Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGObjCMac.cpp
35233 views
//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This provides Objective-C code generation targeting the Apple runtime.9//10//===----------------------------------------------------------------------===//1112#include "CGBlocks.h"13#include "CGCleanup.h"14#include "CGObjCRuntime.h"15#include "CGRecordLayout.h"16#include "CodeGenFunction.h"17#include "CodeGenModule.h"18#include "clang/AST/ASTContext.h"19#include "clang/AST/Attr.h"20#include "clang/AST/Decl.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/Mangle.h"23#include "clang/AST/RecordLayout.h"24#include "clang/AST/StmtObjC.h"25#include "clang/Basic/CodeGenOptions.h"26#include "clang/Basic/LangOptions.h"27#include "clang/CodeGen/CGFunctionInfo.h"28#include "clang/CodeGen/ConstantInitBuilder.h"29#include "llvm/ADT/CachedHashString.h"30#include "llvm/ADT/DenseSet.h"31#include "llvm/ADT/SetVector.h"32#include "llvm/ADT/SmallPtrSet.h"33#include "llvm/ADT/SmallString.h"34#include "llvm/ADT/UniqueVector.h"35#include "llvm/IR/DataLayout.h"36#include "llvm/IR/InlineAsm.h"37#include "llvm/IR/IntrinsicInst.h"38#include "llvm/IR/LLVMContext.h"39#include "llvm/IR/Module.h"40#include "llvm/Support/ScopedPrinter.h"41#include "llvm/Support/raw_ostream.h"42#include <cstdio>4344using namespace clang;45using namespace CodeGen;4647namespace {4849// FIXME: We should find a nicer way to make the labels for metadata, string50// concatenation is lame.5152class ObjCCommonTypesHelper {53protected:54llvm::LLVMContext &VMContext;5556private:57// The types of these functions don't really matter because we58// should always bitcast before calling them.5960/// id objc_msgSend (id, SEL, ...)61///62/// The default messenger, used for sends whose ABI is unchanged from63/// the all-integer/pointer case.64llvm::FunctionCallee getMessageSendFn() const {65// Add the non-lazy-bind attribute, since objc_msgSend is likely to66// be called a lot.67llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };68return CGM.CreateRuntimeFunction(69llvm::FunctionType::get(ObjectPtrTy, params, true), "objc_msgSend",70llvm::AttributeList::get(CGM.getLLVMContext(),71llvm::AttributeList::FunctionIndex,72llvm::Attribute::NonLazyBind));73}7475/// void objc_msgSend_stret (id, SEL, ...)76///77/// The messenger used when the return value is an aggregate returned78/// by indirect reference in the first argument, and therefore the79/// self and selector parameters are shifted over by one.80llvm::FunctionCallee getMessageSendStretFn() const {81llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };82return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,83params, true),84"objc_msgSend_stret");85}8687/// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)88///89/// The messenger used when the return value is returned on the x8790/// floating-point stack; without a special entrypoint, the nil case91/// would be unbalanced.92llvm::FunctionCallee getMessageSendFpretFn() const {93llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };94return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,95params, true),96"objc_msgSend_fpret");97}9899/// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)100///101/// The messenger used when the return value is returned in two values on the102/// x87 floating point stack; without a special entrypoint, the nil case103/// would be unbalanced. Only used on 64-bit X86.104llvm::FunctionCallee getMessageSendFp2retFn() const {105llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };106llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);107llvm::Type *resultType =108llvm::StructType::get(longDoubleType, longDoubleType);109110return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,111params, true),112"objc_msgSend_fp2ret");113}114115/// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)116///117/// The messenger used for super calls, which have different dispatch118/// semantics. The class passed is the superclass of the current119/// class.120llvm::FunctionCallee getMessageSendSuperFn() const {121llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };122return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,123params, true),124"objc_msgSendSuper");125}126127/// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)128///129/// A slightly different messenger used for super calls. The class130/// passed is the current class.131llvm::FunctionCallee getMessageSendSuperFn2() const {132llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };133return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,134params, true),135"objc_msgSendSuper2");136}137138/// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,139/// SEL op, ...)140///141/// The messenger used for super calls which return an aggregate indirectly.142llvm::FunctionCallee getMessageSendSuperStretFn() const {143llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };144return CGM.CreateRuntimeFunction(145llvm::FunctionType::get(CGM.VoidTy, params, true),146"objc_msgSendSuper_stret");147}148149/// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,150/// SEL op, ...)151///152/// objc_msgSendSuper_stret with the super2 semantics.153llvm::FunctionCallee getMessageSendSuperStretFn2() const {154llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };155return CGM.CreateRuntimeFunction(156llvm::FunctionType::get(CGM.VoidTy, params, true),157"objc_msgSendSuper2_stret");158}159160llvm::FunctionCallee getMessageSendSuperFpretFn() const {161// There is no objc_msgSendSuper_fpret? How can that work?162return getMessageSendSuperFn();163}164165llvm::FunctionCallee getMessageSendSuperFpretFn2() const {166// There is no objc_msgSendSuper_fpret? How can that work?167return getMessageSendSuperFn2();168}169170protected:171CodeGen::CodeGenModule &CGM;172173public:174llvm::IntegerType *ShortTy, *IntTy, *LongTy;175llvm::PointerType *Int8PtrTy, *Int8PtrPtrTy;176llvm::PointerType *Int8PtrProgramASTy;177llvm::Type *IvarOffsetVarTy;178179/// ObjectPtrTy - LLVM type for object handles (typeof(id))180llvm::PointerType *ObjectPtrTy;181182/// PtrObjectPtrTy - LLVM type for id *183llvm::PointerType *PtrObjectPtrTy;184185/// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))186llvm::PointerType *SelectorPtrTy;187188private:189/// ProtocolPtrTy - LLVM type for external protocol handles190/// (typeof(Protocol))191llvm::Type *ExternalProtocolPtrTy;192193public:194llvm::Type *getExternalProtocolPtrTy() {195if (!ExternalProtocolPtrTy) {196// FIXME: It would be nice to unify this with the opaque type, so that the197// IR comes out a bit cleaner.198CodeGen::CodeGenTypes &Types = CGM.getTypes();199ASTContext &Ctx = CGM.getContext();200llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());201ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);202}203204return ExternalProtocolPtrTy;205}206207// SuperCTy - clang type for struct objc_super.208QualType SuperCTy;209// SuperPtrCTy - clang type for struct objc_super *.210QualType SuperPtrCTy;211212/// SuperTy - LLVM type for struct objc_super.213llvm::StructType *SuperTy;214/// SuperPtrTy - LLVM type for struct objc_super *.215llvm::PointerType *SuperPtrTy;216217/// PropertyTy - LLVM type for struct objc_property (struct _prop_t218/// in GCC parlance).219llvm::StructType *PropertyTy;220221/// PropertyListTy - LLVM type for struct objc_property_list222/// (_prop_list_t in GCC parlance).223llvm::StructType *PropertyListTy;224/// PropertyListPtrTy - LLVM type for struct objc_property_list*.225llvm::PointerType *PropertyListPtrTy;226227// MethodTy - LLVM type for struct objc_method.228llvm::StructType *MethodTy;229230/// CacheTy - LLVM type for struct objc_cache.231llvm::Type *CacheTy;232/// CachePtrTy - LLVM type for struct objc_cache *.233llvm::PointerType *CachePtrTy;234235llvm::FunctionCallee getGetPropertyFn() {236CodeGen::CodeGenTypes &Types = CGM.getTypes();237ASTContext &Ctx = CGM.getContext();238// id objc_getProperty (id, SEL, ptrdiff_t, bool)239CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());240CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());241CanQualType Params[] = {242IdType, SelType,243Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(), Ctx.BoolTy};244llvm::FunctionType *FTy =245Types.GetFunctionType(246Types.arrangeBuiltinFunctionDeclaration(IdType, Params));247return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");248}249250llvm::FunctionCallee getSetPropertyFn() {251CodeGen::CodeGenTypes &Types = CGM.getTypes();252ASTContext &Ctx = CGM.getContext();253// void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)254CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());255CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());256CanQualType Params[] = {257IdType,258SelType,259Ctx.getPointerDiffType()->getCanonicalTypeUnqualified(),260IdType,261Ctx.BoolTy,262Ctx.BoolTy};263llvm::FunctionType *FTy =264Types.GetFunctionType(265Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));266return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");267}268269llvm::FunctionCallee getOptimizedSetPropertyFn(bool atomic, bool copy) {270CodeGen::CodeGenTypes &Types = CGM.getTypes();271ASTContext &Ctx = CGM.getContext();272// void objc_setProperty_atomic(id self, SEL _cmd,273// id newValue, ptrdiff_t offset);274// void objc_setProperty_nonatomic(id self, SEL _cmd,275// id newValue, ptrdiff_t offset);276// void objc_setProperty_atomic_copy(id self, SEL _cmd,277// id newValue, ptrdiff_t offset);278// void objc_setProperty_nonatomic_copy(id self, SEL _cmd,279// id newValue, ptrdiff_t offset);280281SmallVector<CanQualType,4> Params;282CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());283CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());284Params.push_back(IdType);285Params.push_back(SelType);286Params.push_back(IdType);287Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());288llvm::FunctionType *FTy =289Types.GetFunctionType(290Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));291const char *name;292if (atomic && copy)293name = "objc_setProperty_atomic_copy";294else if (atomic && !copy)295name = "objc_setProperty_atomic";296else if (!atomic && copy)297name = "objc_setProperty_nonatomic_copy";298else299name = "objc_setProperty_nonatomic";300301return CGM.CreateRuntimeFunction(FTy, name);302}303304llvm::FunctionCallee getCopyStructFn() {305CodeGen::CodeGenTypes &Types = CGM.getTypes();306ASTContext &Ctx = CGM.getContext();307// void objc_copyStruct (void *, const void *, size_t, bool, bool)308SmallVector<CanQualType,5> Params;309Params.push_back(Ctx.VoidPtrTy);310Params.push_back(Ctx.VoidPtrTy);311Params.push_back(Ctx.getSizeType());312Params.push_back(Ctx.BoolTy);313Params.push_back(Ctx.BoolTy);314llvm::FunctionType *FTy =315Types.GetFunctionType(316Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));317return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");318}319320/// This routine declares and returns address of:321/// void objc_copyCppObjectAtomic(322/// void *dest, const void *src,323/// void (*copyHelper) (void *dest, const void *source));324llvm::FunctionCallee getCppAtomicObjectFunction() {325CodeGen::CodeGenTypes &Types = CGM.getTypes();326ASTContext &Ctx = CGM.getContext();327/// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);328SmallVector<CanQualType,3> Params;329Params.push_back(Ctx.VoidPtrTy);330Params.push_back(Ctx.VoidPtrTy);331Params.push_back(Ctx.VoidPtrTy);332llvm::FunctionType *FTy =333Types.GetFunctionType(334Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));335return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");336}337338llvm::FunctionCallee getEnumerationMutationFn() {339CodeGen::CodeGenTypes &Types = CGM.getTypes();340ASTContext &Ctx = CGM.getContext();341// void objc_enumerationMutation (id)342SmallVector<CanQualType,1> Params;343Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));344llvm::FunctionType *FTy =345Types.GetFunctionType(346Types.arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Params));347return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");348}349350llvm::FunctionCallee getLookUpClassFn() {351CodeGen::CodeGenTypes &Types = CGM.getTypes();352ASTContext &Ctx = CGM.getContext();353// Class objc_lookUpClass (const char *)354SmallVector<CanQualType,1> Params;355Params.push_back(356Ctx.getCanonicalType(Ctx.getPointerType(Ctx.CharTy.withConst())));357llvm::FunctionType *FTy =358Types.GetFunctionType(Types.arrangeBuiltinFunctionDeclaration(359Ctx.getCanonicalType(Ctx.getObjCClassType()),360Params));361return CGM.CreateRuntimeFunction(FTy, "objc_lookUpClass");362}363364/// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.365llvm::FunctionCallee getGcReadWeakFn() {366// id objc_read_weak (id *)367llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };368llvm::FunctionType *FTy =369llvm::FunctionType::get(ObjectPtrTy, args, false);370return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");371}372373/// GcAssignWeakFn -- LLVM objc_assign_weak function.374llvm::FunctionCallee getGcAssignWeakFn() {375// id objc_assign_weak (id, id *)376llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };377llvm::FunctionType *FTy =378llvm::FunctionType::get(ObjectPtrTy, args, false);379return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");380}381382/// GcAssignGlobalFn -- LLVM objc_assign_global function.383llvm::FunctionCallee getGcAssignGlobalFn() {384// id objc_assign_global(id, id *)385llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };386llvm::FunctionType *FTy =387llvm::FunctionType::get(ObjectPtrTy, args, false);388return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");389}390391/// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.392llvm::FunctionCallee getGcAssignThreadLocalFn() {393// id objc_assign_threadlocal(id src, id * dest)394llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };395llvm::FunctionType *FTy =396llvm::FunctionType::get(ObjectPtrTy, args, false);397return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");398}399400/// GcAssignIvarFn -- LLVM objc_assign_ivar function.401llvm::FunctionCallee getGcAssignIvarFn() {402// id objc_assign_ivar(id, id *, ptrdiff_t)403llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),404CGM.PtrDiffTy };405llvm::FunctionType *FTy =406llvm::FunctionType::get(ObjectPtrTy, args, false);407return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");408}409410/// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.411llvm::FunctionCallee GcMemmoveCollectableFn() {412// void *objc_memmove_collectable(void *dst, const void *src, size_t size)413llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };414llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);415return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");416}417418/// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.419llvm::FunctionCallee getGcAssignStrongCastFn() {420// id objc_assign_strongCast(id, id *)421llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };422llvm::FunctionType *FTy =423llvm::FunctionType::get(ObjectPtrTy, args, false);424return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");425}426427/// ExceptionThrowFn - LLVM objc_exception_throw function.428llvm::FunctionCallee getExceptionThrowFn() {429// void objc_exception_throw(id)430llvm::Type *args[] = { ObjectPtrTy };431llvm::FunctionType *FTy =432llvm::FunctionType::get(CGM.VoidTy, args, false);433return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");434}435436/// ExceptionRethrowFn - LLVM objc_exception_rethrow function.437llvm::FunctionCallee getExceptionRethrowFn() {438// void objc_exception_rethrow(void)439llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);440return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");441}442443/// SyncEnterFn - LLVM object_sync_enter function.444llvm::FunctionCallee getSyncEnterFn() {445// int objc_sync_enter (id)446llvm::Type *args[] = { ObjectPtrTy };447llvm::FunctionType *FTy =448llvm::FunctionType::get(CGM.IntTy, args, false);449return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");450}451452/// SyncExitFn - LLVM object_sync_exit function.453llvm::FunctionCallee getSyncExitFn() {454// int objc_sync_exit (id)455llvm::Type *args[] = { ObjectPtrTy };456llvm::FunctionType *FTy =457llvm::FunctionType::get(CGM.IntTy, args, false);458return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");459}460461llvm::FunctionCallee getSendFn(bool IsSuper) const {462return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();463}464465llvm::FunctionCallee getSendFn2(bool IsSuper) const {466return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();467}468469llvm::FunctionCallee getSendStretFn(bool IsSuper) const {470return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();471}472473llvm::FunctionCallee getSendStretFn2(bool IsSuper) const {474return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();475}476477llvm::FunctionCallee getSendFpretFn(bool IsSuper) const {478return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();479}480481llvm::FunctionCallee getSendFpretFn2(bool IsSuper) const {482return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();483}484485llvm::FunctionCallee getSendFp2retFn(bool IsSuper) const {486return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();487}488489llvm::FunctionCallee getSendFp2RetFn2(bool IsSuper) const {490return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();491}492493ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);494};495496/// ObjCTypesHelper - Helper class that encapsulates lazy497/// construction of varies types used during ObjC generation.498class ObjCTypesHelper : public ObjCCommonTypesHelper {499public:500/// SymtabTy - LLVM type for struct objc_symtab.501llvm::StructType *SymtabTy;502/// SymtabPtrTy - LLVM type for struct objc_symtab *.503llvm::PointerType *SymtabPtrTy;504/// ModuleTy - LLVM type for struct objc_module.505llvm::StructType *ModuleTy;506507/// ProtocolTy - LLVM type for struct objc_protocol.508llvm::StructType *ProtocolTy;509/// ProtocolPtrTy - LLVM type for struct objc_protocol *.510llvm::PointerType *ProtocolPtrTy;511/// ProtocolExtensionTy - LLVM type for struct512/// objc_protocol_extension.513llvm::StructType *ProtocolExtensionTy;514/// ProtocolExtensionTy - LLVM type for struct515/// objc_protocol_extension *.516llvm::PointerType *ProtocolExtensionPtrTy;517/// MethodDescriptionTy - LLVM type for struct518/// objc_method_description.519llvm::StructType *MethodDescriptionTy;520/// MethodDescriptionListTy - LLVM type for struct521/// objc_method_description_list.522llvm::StructType *MethodDescriptionListTy;523/// MethodDescriptionListPtrTy - LLVM type for struct524/// objc_method_description_list *.525llvm::PointerType *MethodDescriptionListPtrTy;526/// ProtocolListTy - LLVM type for struct objc_property_list.527llvm::StructType *ProtocolListTy;528/// ProtocolListPtrTy - LLVM type for struct objc_property_list*.529llvm::PointerType *ProtocolListPtrTy;530/// CategoryTy - LLVM type for struct objc_category.531llvm::StructType *CategoryTy;532/// ClassTy - LLVM type for struct objc_class.533llvm::StructType *ClassTy;534/// ClassPtrTy - LLVM type for struct objc_class *.535llvm::PointerType *ClassPtrTy;536/// ClassExtensionTy - LLVM type for struct objc_class_ext.537llvm::StructType *ClassExtensionTy;538/// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.539llvm::PointerType *ClassExtensionPtrTy;540// IvarTy - LLVM type for struct objc_ivar.541llvm::StructType *IvarTy;542/// IvarListTy - LLVM type for struct objc_ivar_list.543llvm::StructType *IvarListTy;544/// IvarListPtrTy - LLVM type for struct objc_ivar_list *.545llvm::PointerType *IvarListPtrTy;546/// MethodListTy - LLVM type for struct objc_method_list.547llvm::StructType *MethodListTy;548/// MethodListPtrTy - LLVM type for struct objc_method_list *.549llvm::PointerType *MethodListPtrTy;550551/// ExceptionDataTy - LLVM type for struct _objc_exception_data.552llvm::StructType *ExceptionDataTy;553554/// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.555llvm::FunctionCallee getExceptionTryEnterFn() {556llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };557return CGM.CreateRuntimeFunction(558llvm::FunctionType::get(CGM.VoidTy, params, false),559"objc_exception_try_enter");560}561562/// ExceptionTryExitFn - LLVM objc_exception_try_exit function.563llvm::FunctionCallee getExceptionTryExitFn() {564llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };565return CGM.CreateRuntimeFunction(566llvm::FunctionType::get(CGM.VoidTy, params, false),567"objc_exception_try_exit");568}569570/// ExceptionExtractFn - LLVM objc_exception_extract function.571llvm::FunctionCallee getExceptionExtractFn() {572llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };573return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,574params, false),575"objc_exception_extract");576}577578/// ExceptionMatchFn - LLVM objc_exception_match function.579llvm::FunctionCallee getExceptionMatchFn() {580llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };581return CGM.CreateRuntimeFunction(582llvm::FunctionType::get(CGM.Int32Ty, params, false),583"objc_exception_match");584}585586/// SetJmpFn - LLVM _setjmp function.587llvm::FunctionCallee getSetJmpFn() {588// This is specifically the prototype for x86.589llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };590return CGM.CreateRuntimeFunction(591llvm::FunctionType::get(CGM.Int32Ty, params, false), "_setjmp",592llvm::AttributeList::get(CGM.getLLVMContext(),593llvm::AttributeList::FunctionIndex,594llvm::Attribute::NonLazyBind));595}596597public:598ObjCTypesHelper(CodeGen::CodeGenModule &cgm);599};600601/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's602/// modern abi603class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {604public:605// MethodListnfABITy - LLVM for struct _method_list_t606llvm::StructType *MethodListnfABITy;607608// MethodListnfABIPtrTy - LLVM for struct _method_list_t*609llvm::PointerType *MethodListnfABIPtrTy;610611// ProtocolnfABITy = LLVM for struct _protocol_t612llvm::StructType *ProtocolnfABITy;613614// ProtocolnfABIPtrTy = LLVM for struct _protocol_t*615llvm::PointerType *ProtocolnfABIPtrTy;616617// ProtocolListnfABITy - LLVM for struct _objc_protocol_list618llvm::StructType *ProtocolListnfABITy;619620// ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*621llvm::PointerType *ProtocolListnfABIPtrTy;622623// ClassnfABITy - LLVM for struct _class_t624llvm::StructType *ClassnfABITy;625626// ClassnfABIPtrTy - LLVM for struct _class_t*627llvm::PointerType *ClassnfABIPtrTy;628629// IvarnfABITy - LLVM for struct _ivar_t630llvm::StructType *IvarnfABITy;631632// IvarListnfABITy - LLVM for struct _ivar_list_t633llvm::StructType *IvarListnfABITy;634635// IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*636llvm::PointerType *IvarListnfABIPtrTy;637638// ClassRonfABITy - LLVM for struct _class_ro_t639llvm::StructType *ClassRonfABITy;640641// ImpnfABITy - LLVM for id (*)(id, SEL, ...)642llvm::PointerType *ImpnfABITy;643644// CategorynfABITy - LLVM for struct _category_t645llvm::StructType *CategorynfABITy;646647// New types for nonfragile abi messaging.648649// MessageRefTy - LLVM for:650// struct _message_ref_t {651// IMP messenger;652// SEL name;653// };654llvm::StructType *MessageRefTy;655// MessageRefCTy - clang type for struct _message_ref_t656QualType MessageRefCTy;657658// MessageRefPtrTy - LLVM for struct _message_ref_t*659llvm::Type *MessageRefPtrTy;660// MessageRefCPtrTy - clang type for struct _message_ref_t*661QualType MessageRefCPtrTy;662663// SuperMessageRefTy - LLVM for:664// struct _super_message_ref_t {665// SUPER_IMP messenger;666// SEL name;667// };668llvm::StructType *SuperMessageRefTy;669670// SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*671llvm::PointerType *SuperMessageRefPtrTy;672673llvm::FunctionCallee getMessageSendFixupFn() {674// id objc_msgSend_fixup(id, struct message_ref_t*, ...)675llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };676return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,677params, true),678"objc_msgSend_fixup");679}680681llvm::FunctionCallee getMessageSendFpretFixupFn() {682// id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)683llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };684return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,685params, true),686"objc_msgSend_fpret_fixup");687}688689llvm::FunctionCallee getMessageSendStretFixupFn() {690// id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)691llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };692return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,693params, true),694"objc_msgSend_stret_fixup");695}696697llvm::FunctionCallee getMessageSendSuper2FixupFn() {698// id objc_msgSendSuper2_fixup (struct objc_super *,699// struct _super_message_ref_t*, ...)700llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };701return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,702params, true),703"objc_msgSendSuper2_fixup");704}705706llvm::FunctionCallee getMessageSendSuper2StretFixupFn() {707// id objc_msgSendSuper2_stret_fixup(struct objc_super *,708// struct _super_message_ref_t*, ...)709llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };710return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,711params, true),712"objc_msgSendSuper2_stret_fixup");713}714715llvm::FunctionCallee getObjCEndCatchFn() {716return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),717"objc_end_catch");718}719720llvm::FunctionCallee getObjCBeginCatchFn() {721llvm::Type *params[] = { Int8PtrTy };722return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,723params, false),724"objc_begin_catch");725}726727/// Class objc_loadClassref (void *)728///729/// Loads from a classref. For Objective-C stub classes, this invokes the730/// initialization callback stored inside the stub. For all other classes731/// this simply dereferences the pointer.732llvm::FunctionCallee getLoadClassrefFn() const {733// Add the non-lazy-bind attribute, since objc_loadClassref is likely to734// be called a lot.735//736// Also it is safe to make it readnone, since we never load or store the737// classref except by calling this function.738llvm::Type *params[] = { Int8PtrPtrTy };739llvm::LLVMContext &C = CGM.getLLVMContext();740llvm::AttributeSet AS = llvm::AttributeSet::get(C, {741llvm::Attribute::get(C, llvm::Attribute::NonLazyBind),742llvm::Attribute::getWithMemoryEffects(C, llvm::MemoryEffects::none()),743llvm::Attribute::get(C, llvm::Attribute::NoUnwind),744});745llvm::FunctionCallee F = CGM.CreateRuntimeFunction(746llvm::FunctionType::get(ClassnfABIPtrTy, params, false),747"objc_loadClassref",748llvm::AttributeList::get(CGM.getLLVMContext(),749llvm::AttributeList::FunctionIndex, AS));750if (!CGM.getTriple().isOSBinFormatCOFF())751cast<llvm::Function>(F.getCallee())->setLinkage(752llvm::Function::ExternalWeakLinkage);753754return F;755}756757llvm::StructType *EHTypeTy;758llvm::Type *EHTypePtrTy;759760ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);761};762763enum class ObjCLabelType {764ClassName,765MethodVarName,766MethodVarType,767PropertyName,768};769770class CGObjCCommonMac : public CodeGen::CGObjCRuntime {771public:772class SKIP_SCAN {773public:774unsigned skip;775unsigned scan;776SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)777: skip(_skip), scan(_scan) {}778};779780/// opcode for captured block variables layout 'instructions'.781/// In the following descriptions, 'I' is the value of the immediate field.782/// (field following the opcode).783///784enum BLOCK_LAYOUT_OPCODE {785/// An operator which affects how the following layout should be786/// interpreted.787/// I == 0: Halt interpretation and treat everything else as788/// a non-pointer. Note that this instruction is equal789/// to '\0'.790/// I != 0: Currently unused.791BLOCK_LAYOUT_OPERATOR = 0,792793/// The next I+1 bytes do not contain a value of object pointer type.794/// Note that this can leave the stream unaligned, meaning that795/// subsequent word-size instructions do not begin at a multiple of796/// the pointer size.797BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,798799/// The next I+1 words do not contain a value of object pointer type.800/// This is simply an optimized version of BLOCK_LAYOUT_BYTES for801/// when the required skip quantity is a multiple of the pointer size.802BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,803804/// The next I+1 words are __strong pointers to Objective-C805/// objects or blocks.806BLOCK_LAYOUT_STRONG = 3,807808/// The next I+1 words are pointers to __block variables.809BLOCK_LAYOUT_BYREF = 4,810811/// The next I+1 words are __weak pointers to Objective-C812/// objects or blocks.813BLOCK_LAYOUT_WEAK = 5,814815/// The next I+1 words are __unsafe_unretained pointers to816/// Objective-C objects or blocks.817BLOCK_LAYOUT_UNRETAINED = 6818819/// The next I+1 words are block or object pointers with some820/// as-yet-unspecified ownership semantics. If we add more821/// flavors of ownership semantics, values will be taken from822/// this range.823///824/// This is included so that older tools can at least continue825/// processing the layout past such things.826//BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,827828/// All other opcodes are reserved. Halt interpretation and829/// treat everything else as opaque.830};831832class RUN_SKIP {833public:834enum BLOCK_LAYOUT_OPCODE opcode;835CharUnits block_var_bytepos;836CharUnits block_var_size;837RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,838CharUnits BytePos = CharUnits::Zero(),839CharUnits Size = CharUnits::Zero())840: opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}841842// Allow sorting based on byte pos.843bool operator<(const RUN_SKIP &b) const {844return block_var_bytepos < b.block_var_bytepos;845}846};847848protected:849llvm::LLVMContext &VMContext;850// FIXME! May not be needing this after all.851unsigned ObjCABI;852853// arc/mrr layout of captured block literal variables.854SmallVector<RUN_SKIP, 16> RunSkipBlockVars;855856/// LazySymbols - Symbols to generate a lazy reference for. See857/// DefinedSymbols and FinishModule().858llvm::SetVector<IdentifierInfo*> LazySymbols;859860/// DefinedSymbols - External symbols which are defined by this861/// module. The symbols in this list and LazySymbols are used to add862/// special linker symbols which ensure that Objective-C modules are863/// linked properly.864llvm::SetVector<IdentifierInfo*> DefinedSymbols;865866/// ClassNames - uniqued class names.867llvm::StringMap<llvm::GlobalVariable*> ClassNames;868869/// MethodVarNames - uniqued method variable names.870llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;871872/// DefinedCategoryNames - list of category names in form Class_Category.873llvm::SmallSetVector<llvm::CachedHashString, 16> DefinedCategoryNames;874875/// MethodVarTypes - uniqued method type signatures. We have to use876/// a StringMap here because have no other unique reference.877llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;878879/// MethodDefinitions - map of methods which have been defined in880/// this translation unit.881llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;882883/// DirectMethodDefinitions - map of direct methods which have been defined in884/// this translation unit.885llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> DirectMethodDefinitions;886887/// PropertyNames - uniqued method variable names.888llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;889890/// ClassReferences - uniqued class references.891llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;892893/// SelectorReferences - uniqued selector references.894llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;895896/// Protocols - Protocols for which an objc_protocol structure has897/// been emitted. Forward declarations are handled by creating an898/// empty structure whose initializer is filled in when/if defined.899llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;900901/// DefinedProtocols - Protocols which have actually been902/// defined. We should not need this, see FIXME in GenerateProtocol.903llvm::DenseSet<IdentifierInfo*> DefinedProtocols;904905/// DefinedClasses - List of defined classes.906SmallVector<llvm::GlobalValue*, 16> DefinedClasses;907908/// ImplementedClasses - List of @implemented classes.909SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;910911/// DefinedNonLazyClasses - List of defined "non-lazy" classes.912SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;913914/// DefinedCategories - List of defined categories.915SmallVector<llvm::GlobalValue*, 16> DefinedCategories;916917/// DefinedStubCategories - List of defined categories on class stubs.918SmallVector<llvm::GlobalValue*, 16> DefinedStubCategories;919920/// DefinedNonLazyCategories - List of defined "non-lazy" categories.921SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;922923/// Cached reference to the class for constant strings. This value has type924/// int * but is actually an Obj-C class pointer.925llvm::WeakTrackingVH ConstantStringClassRef;926927/// The LLVM type corresponding to NSConstantString.928llvm::StructType *NSConstantStringType = nullptr;929930llvm::StringMap<llvm::GlobalVariable *> NSConstantStringMap;931932/// GetMethodVarName - Return a unique constant for the given933/// selector's name. The return value has type char *.934llvm::Constant *GetMethodVarName(Selector Sel);935llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);936937/// GetMethodVarType - Return a unique constant for the given938/// method's type encoding string. The return value has type char *.939940// FIXME: This is a horrible name.941llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,942bool Extended = false);943llvm::Constant *GetMethodVarType(const FieldDecl *D);944945/// GetPropertyName - Return a unique constant for the given946/// name. The return value has type char *.947llvm::Constant *GetPropertyName(IdentifierInfo *Ident);948949// FIXME: This can be dropped once string functions are unified.950llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,951const Decl *Container);952953/// GetClassName - Return a unique constant for the given selector's954/// runtime name (which may change via use of objc_runtime_name attribute on955/// class or protocol definition. The return value has type char *.956llvm::Constant *GetClassName(StringRef RuntimeName);957958llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);959960/// BuildIvarLayout - Builds ivar layout bitmap for the class961/// implementation for the __strong or __weak case.962///963/// \param hasMRCWeakIvars - Whether we are compiling in MRC and there964/// are any weak ivars defined directly in the class. Meaningless unless965/// building a weak layout. Does not guarantee that the layout will966/// actually have any entries, because the ivar might be under-aligned.967llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,968CharUnits beginOffset,969CharUnits endOffset,970bool forStrongLayout,971bool hasMRCWeakIvars);972973llvm::Constant *BuildStrongIvarLayout(const ObjCImplementationDecl *OI,974CharUnits beginOffset,975CharUnits endOffset) {976return BuildIvarLayout(OI, beginOffset, endOffset, true, false);977}978979llvm::Constant *BuildWeakIvarLayout(const ObjCImplementationDecl *OI,980CharUnits beginOffset,981CharUnits endOffset,982bool hasMRCWeakIvars) {983return BuildIvarLayout(OI, beginOffset, endOffset, false, hasMRCWeakIvars);984}985986Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);987988void UpdateRunSkipBlockVars(bool IsByref,989Qualifiers::ObjCLifetime LifeTime,990CharUnits FieldOffset,991CharUnits FieldSize);992993void BuildRCBlockVarRecordLayout(const RecordType *RT,994CharUnits BytePos, bool &HasUnion,995bool ByrefLayout=false);996997void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,998const RecordDecl *RD,999ArrayRef<const FieldDecl*> RecFields,1000CharUnits BytePos, bool &HasUnion,1001bool ByrefLayout);10021003uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);10041005llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);10061007/// GetIvarLayoutName - Returns a unique constant for the given1008/// ivar layout bitmap.1009llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,1010const ObjCCommonTypesHelper &ObjCTypes);10111012/// EmitPropertyList - Emit the given property list. The return1013/// value has type PropertyListPtrTy.1014llvm::Constant *EmitPropertyList(Twine Name,1015const Decl *Container,1016const ObjCContainerDecl *OCD,1017const ObjCCommonTypesHelper &ObjCTypes,1018bool IsClassProperty);10191020/// EmitProtocolMethodTypes - Generate the array of extended method type1021/// strings. The return value has type Int8PtrPtrTy.1022llvm::Constant *EmitProtocolMethodTypes(Twine Name,1023ArrayRef<llvm::Constant*> MethodTypes,1024const ObjCCommonTypesHelper &ObjCTypes);10251026/// GetProtocolRef - Return a reference to the internal protocol1027/// description, creating an empty one if it has not been1028/// defined. The return value has type ProtocolPtrTy.1029llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);10301031/// Return a reference to the given Class using runtime calls rather than1032/// by a symbol reference.1033llvm::Value *EmitClassRefViaRuntime(CodeGenFunction &CGF,1034const ObjCInterfaceDecl *ID,1035ObjCCommonTypesHelper &ObjCTypes);10361037std::string GetSectionName(StringRef Section, StringRef MachOAttributes);10381039public:1040/// CreateMetadataVar - Create a global variable with internal1041/// linkage for use by the Objective-C runtime.1042///1043/// This is a convenience wrapper which not only creates the1044/// variable, but also sets the section and alignment and adds the1045/// global to the "llvm.used" list.1046///1047/// \param Name - The variable name.1048/// \param Init - The variable initializer; this is also used to1049/// define the type of the variable.1050/// \param Section - The section the variable should go into, or empty.1051/// \param Align - The alignment for the variable, or 0.1052/// \param AddToUsed - Whether the variable should be added to1053/// "llvm.used".1054llvm::GlobalVariable *CreateMetadataVar(Twine Name,1055ConstantStructBuilder &Init,1056StringRef Section, CharUnits Align,1057bool AddToUsed);1058llvm::GlobalVariable *CreateMetadataVar(Twine Name,1059llvm::Constant *Init,1060StringRef Section, CharUnits Align,1061bool AddToUsed);10621063llvm::GlobalVariable *CreateCStringLiteral(StringRef Name,1064ObjCLabelType LabelType,1065bool ForceNonFragileABI = false,1066bool NullTerminate = true);10671068protected:1069CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,1070ReturnValueSlot Return,1071QualType ResultType,1072Selector Sel,1073llvm::Value *Arg0,1074QualType Arg0Ty,1075bool IsSuper,1076const CallArgList &CallArgs,1077const ObjCMethodDecl *OMD,1078const ObjCInterfaceDecl *ClassReceiver,1079const ObjCCommonTypesHelper &ObjCTypes);10801081/// EmitImageInfo - Emit the image info marker used to encode some module1082/// level information.1083void EmitImageInfo();10841085public:1086CGObjCCommonMac(CodeGen::CodeGenModule &cgm)1087: CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) {}10881089bool isNonFragileABI() const {1090return ObjCABI == 2;1091}10921093ConstantAddress GenerateConstantString(const StringLiteral *SL) override;1094ConstantAddress GenerateConstantNSString(const StringLiteral *SL);10951096llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,1097const ObjCContainerDecl *CD=nullptr) override;10981099llvm::Function *GenerateDirectMethod(const ObjCMethodDecl *OMD,1100const ObjCContainerDecl *CD);11011102void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,1103const ObjCMethodDecl *OMD,1104const ObjCContainerDecl *CD) override;11051106void GenerateProtocol(const ObjCProtocolDecl *PD) override;11071108/// GetOrEmitProtocolRef - Get a forward reference to the protocol1109/// object for the given declaration, emitting it if needed. These1110/// forward references will be filled in with empty bodies if no1111/// definition is seen. The return value has type ProtocolPtrTy.1112virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;11131114virtual llvm::Constant *getNSConstantStringClassRef() = 0;11151116llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,1117const CGBlockInfo &blockInfo) override;1118llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,1119const CGBlockInfo &blockInfo) override;1120std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM,1121const CGBlockInfo &blockInfo) override;11221123llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,1124QualType T) override;11251126private:1127void fillRunSkipBlockVars(CodeGenModule &CGM, const CGBlockInfo &blockInfo);1128};11291130namespace {11311132enum class MethodListType {1133CategoryInstanceMethods,1134CategoryClassMethods,1135InstanceMethods,1136ClassMethods,1137ProtocolInstanceMethods,1138ProtocolClassMethods,1139OptionalProtocolInstanceMethods,1140OptionalProtocolClassMethods,1141};11421143/// A convenience class for splitting the methods of a protocol into1144/// the four interesting groups.1145class ProtocolMethodLists {1146public:1147enum Kind {1148RequiredInstanceMethods,1149RequiredClassMethods,1150OptionalInstanceMethods,1151OptionalClassMethods1152};1153enum {1154NumProtocolMethodLists = 41155};11561157static MethodListType getMethodListKind(Kind kind) {1158switch (kind) {1159case RequiredInstanceMethods:1160return MethodListType::ProtocolInstanceMethods;1161case RequiredClassMethods:1162return MethodListType::ProtocolClassMethods;1163case OptionalInstanceMethods:1164return MethodListType::OptionalProtocolInstanceMethods;1165case OptionalClassMethods:1166return MethodListType::OptionalProtocolClassMethods;1167}1168llvm_unreachable("bad kind");1169}11701171SmallVector<const ObjCMethodDecl *, 4> Methods[NumProtocolMethodLists];11721173static ProtocolMethodLists get(const ObjCProtocolDecl *PD) {1174ProtocolMethodLists result;11751176for (auto *MD : PD->methods()) {1177size_t index = (2 * size_t(MD->isOptional()))1178+ (size_t(MD->isClassMethod()));1179result.Methods[index].push_back(MD);1180}11811182return result;1183}11841185template <class Self>1186SmallVector<llvm::Constant*, 8> emitExtendedTypesArray(Self *self) const {1187// In both ABIs, the method types list is parallel with the1188// concatenation of the methods arrays in the following order:1189// instance methods1190// class methods1191// optional instance methods1192// optional class methods1193SmallVector<llvm::Constant*, 8> result;11941195// Methods is already in the correct order for both ABIs.1196for (auto &list : Methods) {1197for (auto MD : list) {1198result.push_back(self->GetMethodVarType(MD, true));1199}1200}12011202return result;1203}12041205template <class Self>1206llvm::Constant *emitMethodList(Self *self, const ObjCProtocolDecl *PD,1207Kind kind) const {1208return self->emitMethodList(PD->getObjCRuntimeNameAsString(),1209getMethodListKind(kind), Methods[kind]);1210}1211};12121213} // end anonymous namespace12141215class CGObjCMac : public CGObjCCommonMac {1216private:1217friend ProtocolMethodLists;12181219ObjCTypesHelper ObjCTypes;12201221/// EmitModuleInfo - Another marker encoding module level1222/// information.1223void EmitModuleInfo();12241225/// EmitModuleSymols - Emit module symbols, the list of defined1226/// classes and categories. The result has type SymtabPtrTy.1227llvm::Constant *EmitModuleSymbols();12281229/// FinishModule - Write out global data structures at the end of1230/// processing a translation unit.1231void FinishModule();12321233/// EmitClassExtension - Generate the class extension structure used1234/// to store the weak ivar layout and properties. The return value1235/// has type ClassExtensionPtrTy.1236llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID,1237CharUnits instanceSize,1238bool hasMRCWeakIvars,1239bool isMetaclass);12401241/// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,1242/// for the given class.1243llvm::Value *EmitClassRef(CodeGenFunction &CGF,1244const ObjCInterfaceDecl *ID);12451246llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,1247IdentifierInfo *II);12481249llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;12501251/// EmitSuperClassRef - Emits reference to class's main metadata class.1252llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);12531254/// EmitIvarList - Emit the ivar list for the given1255/// implementation. If ForClass is true the list of class ivars1256/// (i.e. metaclass ivars) is emitted, otherwise the list of1257/// interface ivars will be emitted. The return value has type1258/// IvarListPtrTy.1259llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,1260bool ForClass);12611262/// EmitMetaClass - Emit a forward reference to the class structure1263/// for the metaclass of the given interface. The return value has1264/// type ClassPtrTy.1265llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);12661267/// EmitMetaClass - Emit a class structure for the metaclass of the1268/// given implementation. The return value has type ClassPtrTy.1269llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,1270llvm::Constant *Protocols,1271ArrayRef<const ObjCMethodDecl *> Methods);12721273void emitMethodConstant(ConstantArrayBuilder &builder,1274const ObjCMethodDecl *MD);12751276void emitMethodDescriptionConstant(ConstantArrayBuilder &builder,1277const ObjCMethodDecl *MD);12781279/// EmitMethodList - Emit the method list for the given1280/// implementation. The return value has type MethodListPtrTy.1281llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,1282ArrayRef<const ObjCMethodDecl *> Methods);12831284/// GetOrEmitProtocol - Get the protocol object for the given1285/// declaration, emitting it if necessary. The return value has type1286/// ProtocolPtrTy.1287llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;12881289/// GetOrEmitProtocolRef - Get a forward reference to the protocol1290/// object for the given declaration, emitting it if needed. These1291/// forward references will be filled in with empty bodies if no1292/// definition is seen. The return value has type ProtocolPtrTy.1293llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;12941295/// EmitProtocolExtension - Generate the protocol extension1296/// structure used to store optional instance and class methods, and1297/// protocol properties. The return value has type1298/// ProtocolExtensionPtrTy.1299llvm::Constant *1300EmitProtocolExtension(const ObjCProtocolDecl *PD,1301const ProtocolMethodLists &methodLists);13021303/// EmitProtocolList - Generate the list of referenced1304/// protocols. The return value has type ProtocolListPtrTy.1305llvm::Constant *EmitProtocolList(Twine Name,1306ObjCProtocolDecl::protocol_iterator begin,1307ObjCProtocolDecl::protocol_iterator end);13081309/// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,1310/// for the given selector.1311llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);1312ConstantAddress EmitSelectorAddr(Selector Sel);13131314public:1315CGObjCMac(CodeGen::CodeGenModule &cgm);13161317llvm::Constant *getNSConstantStringClassRef() override;13181319llvm::Function *ModuleInitFunction() override;13201321CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,1322ReturnValueSlot Return,1323QualType ResultType,1324Selector Sel, llvm::Value *Receiver,1325const CallArgList &CallArgs,1326const ObjCInterfaceDecl *Class,1327const ObjCMethodDecl *Method) override;13281329CodeGen::RValue1330GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,1331ReturnValueSlot Return, QualType ResultType,1332Selector Sel, const ObjCInterfaceDecl *Class,1333bool isCategoryImpl, llvm::Value *Receiver,1334bool IsClassMessage, const CallArgList &CallArgs,1335const ObjCMethodDecl *Method) override;13361337llvm::Value *GetClass(CodeGenFunction &CGF,1338const ObjCInterfaceDecl *ID) override;13391340llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;1341Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;13421343/// The NeXT/Apple runtimes do not support typed selectors; just emit an1344/// untyped one.1345llvm::Value *GetSelector(CodeGenFunction &CGF,1346const ObjCMethodDecl *Method) override;13471348llvm::Constant *GetEHType(QualType T) override;13491350void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;13511352void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;13531354void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}13551356llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,1357const ObjCProtocolDecl *PD) override;13581359llvm::FunctionCallee GetPropertyGetFunction() override;1360llvm::FunctionCallee GetPropertySetFunction() override;1361llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,1362bool copy) override;1363llvm::FunctionCallee GetGetStructFunction() override;1364llvm::FunctionCallee GetSetStructFunction() override;1365llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;1366llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;1367llvm::FunctionCallee EnumerationMutationFunction() override;13681369void EmitTryStmt(CodeGen::CodeGenFunction &CGF,1370const ObjCAtTryStmt &S) override;1371void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,1372const ObjCAtSynchronizedStmt &S) override;1373void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);1374void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,1375bool ClearInsertionPoint=true) override;1376llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,1377Address AddrWeakObj) override;1378void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,1379llvm::Value *src, Address dst) override;1380void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,1381llvm::Value *src, Address dest,1382bool threadlocal = false) override;1383void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,1384llvm::Value *src, Address dest,1385llvm::Value *ivarOffset) override;1386void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,1387llvm::Value *src, Address dest) override;1388void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,1389Address dest, Address src,1390llvm::Value *size) override;13911392LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,1393llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,1394unsigned CVRQualifiers) override;1395llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,1396const ObjCInterfaceDecl *Interface,1397const ObjCIvarDecl *Ivar) override;1398};13991400class CGObjCNonFragileABIMac : public CGObjCCommonMac {1401private:1402friend ProtocolMethodLists;1403ObjCNonFragileABITypesHelper ObjCTypes;1404llvm::GlobalVariable* ObjCEmptyCacheVar;1405llvm::Constant* ObjCEmptyVtableVar;14061407/// SuperClassReferences - uniqued super class references.1408llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;14091410/// MetaClassReferences - uniqued meta class references.1411llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;14121413/// EHTypeReferences - uniqued class ehtype references.1414llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;14151416/// VTableDispatchMethods - List of methods for which we generate1417/// vtable-based message dispatch.1418llvm::DenseSet<Selector> VTableDispatchMethods;14191420/// DefinedMetaClasses - List of defined meta-classes.1421std::vector<llvm::GlobalValue*> DefinedMetaClasses;14221423/// isVTableDispatchedSelector - Returns true if SEL is a1424/// vtable-based selector.1425bool isVTableDispatchedSelector(Selector Sel);14261427/// FinishNonFragileABIModule - Write out global data structures at the end of1428/// processing a translation unit.1429void FinishNonFragileABIModule();14301431/// AddModuleClassList - Add the given list of class pointers to the1432/// module with the provided symbol and section names.1433void AddModuleClassList(ArrayRef<llvm::GlobalValue *> Container,1434StringRef SymbolName, StringRef SectionName);14351436llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,1437unsigned InstanceStart,1438unsigned InstanceSize,1439const ObjCImplementationDecl *ID);1440llvm::GlobalVariable *BuildClassObject(const ObjCInterfaceDecl *CI,1441bool isMetaclass,1442llvm::Constant *IsAGV,1443llvm::Constant *SuperClassGV,1444llvm::Constant *ClassRoGV,1445bool HiddenVisibility);14461447void emitMethodConstant(ConstantArrayBuilder &builder,1448const ObjCMethodDecl *MD,1449bool forProtocol);14501451/// Emit the method list for the given implementation. The return value1452/// has type MethodListnfABITy.1453llvm::Constant *emitMethodList(Twine Name, MethodListType MLT,1454ArrayRef<const ObjCMethodDecl *> Methods);14551456/// EmitIvarList - Emit the ivar list for the given1457/// implementation. If ForClass is true the list of class ivars1458/// (i.e. metaclass ivars) is emitted, otherwise the list of1459/// interface ivars will be emitted. The return value has type1460/// IvarListnfABIPtrTy.1461llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);14621463llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,1464const ObjCIvarDecl *Ivar,1465unsigned long int offset);14661467/// GetOrEmitProtocol - Get the protocol object for the given1468/// declaration, emitting it if necessary. The return value has type1469/// ProtocolPtrTy.1470llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;14711472/// GetOrEmitProtocolRef - Get a forward reference to the protocol1473/// object for the given declaration, emitting it if needed. These1474/// forward references will be filled in with empty bodies if no1475/// definition is seen. The return value has type ProtocolPtrTy.1476llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;14771478/// EmitProtocolList - Generate the list of referenced1479/// protocols. The return value has type ProtocolListPtrTy.1480llvm::Constant *EmitProtocolList(Twine Name,1481ObjCProtocolDecl::protocol_iterator begin,1482ObjCProtocolDecl::protocol_iterator end);14831484CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,1485ReturnValueSlot Return,1486QualType ResultType,1487Selector Sel,1488llvm::Value *Receiver,1489QualType Arg0Ty,1490bool IsSuper,1491const CallArgList &CallArgs,1492const ObjCMethodDecl *Method);14931494/// GetClassGlobal - Return the global variable for the Objective-C1495/// class of the given name.1496llvm::Constant *GetClassGlobal(StringRef Name,1497ForDefinition_t IsForDefinition,1498bool Weak = false, bool DLLImport = false);1499llvm::Constant *GetClassGlobal(const ObjCInterfaceDecl *ID,1500bool isMetaclass,1501ForDefinition_t isForDefinition);15021503llvm::Constant *GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID);15041505llvm::Value *EmitLoadOfClassRef(CodeGenFunction &CGF,1506const ObjCInterfaceDecl *ID,1507llvm::GlobalVariable *Entry);15081509/// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,1510/// for the given class reference.1511llvm::Value *EmitClassRef(CodeGenFunction &CGF,1512const ObjCInterfaceDecl *ID);15131514llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,1515IdentifierInfo *II,1516const ObjCInterfaceDecl *ID);15171518llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;15191520/// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,1521/// for the given super class reference.1522llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,1523const ObjCInterfaceDecl *ID);15241525/// EmitMetaClassRef - Return a Value * of the address of _class_t1526/// meta-data1527llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,1528const ObjCInterfaceDecl *ID, bool Weak);15291530/// ObjCIvarOffsetVariable - Returns the ivar offset variable for1531/// the given ivar.1532///1533llvm::GlobalVariable * ObjCIvarOffsetVariable(1534const ObjCInterfaceDecl *ID,1535const ObjCIvarDecl *Ivar);15361537/// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,1538/// for the given selector.1539llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel);1540ConstantAddress EmitSelectorAddr(Selector Sel);15411542/// GetInterfaceEHType - Get the cached ehtype for the given Objective-C1543/// interface. The return value has type EHTypePtrTy.1544llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,1545ForDefinition_t IsForDefinition);15461547StringRef getMetaclassSymbolPrefix() const { return "OBJC_METACLASS_$_"; }15481549StringRef getClassSymbolPrefix() const { return "OBJC_CLASS_$_"; }15501551void GetClassSizeInfo(const ObjCImplementationDecl *OID,1552uint32_t &InstanceStart,1553uint32_t &InstanceSize);15541555// Shamelessly stolen from Analysis/CFRefCount.cpp1556Selector GetNullarySelector(const char* name) const {1557const IdentifierInfo *II = &CGM.getContext().Idents.get(name);1558return CGM.getContext().Selectors.getSelector(0, &II);1559}15601561Selector GetUnarySelector(const char* name) const {1562const IdentifierInfo *II = &CGM.getContext().Idents.get(name);1563return CGM.getContext().Selectors.getSelector(1, &II);1564}15651566/// ImplementationIsNonLazy - Check whether the given category or1567/// class implementation is "non-lazy".1568bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;15691570bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,1571const ObjCIvarDecl *IV) {1572// Annotate the load as an invariant load iff inside an instance method1573// and ivar belongs to instance method's class and one of its super class.1574// This check is needed because the ivar offset is a lazily1575// initialised value that may depend on objc_msgSend to perform a fixup on1576// the first message dispatch.1577//1578// An additional opportunity to mark the load as invariant arises when the1579// base of the ivar access is a parameter to an Objective C method.1580// However, because the parameters are not available in the current1581// interface, we cannot perform this check.1582//1583// Note that for direct methods, because objc_msgSend is skipped,1584// and that the method may be inlined, this optimization actually1585// can't be performed.1586if (const ObjCMethodDecl *MD =1587dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))1588if (MD->isInstanceMethod() && !MD->isDirectMethod())1589if (const ObjCInterfaceDecl *ID = MD->getClassInterface())1590return IV->getContainingInterface()->isSuperClassOf(ID);1591return false;1592}15931594bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {1595// Test a class by checking its superclasses up to1596// its base class if it has one.1597for (; ID; ID = ID->getSuperClass()) {1598// The layout of base class NSObject1599// is guaranteed to be statically known1600if (ID->getIdentifier()->getName() == "NSObject")1601return true;16021603// If we cannot see the @implementation of a class,1604// we cannot statically know the class layout.1605if (!ID->getImplementation())1606return false;1607}1608return false;1609}16101611public:1612CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);16131614llvm::Constant *getNSConstantStringClassRef() override;16151616llvm::Function *ModuleInitFunction() override;16171618CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,1619ReturnValueSlot Return,1620QualType ResultType, Selector Sel,1621llvm::Value *Receiver,1622const CallArgList &CallArgs,1623const ObjCInterfaceDecl *Class,1624const ObjCMethodDecl *Method) override;16251626CodeGen::RValue1627GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,1628ReturnValueSlot Return, QualType ResultType,1629Selector Sel, const ObjCInterfaceDecl *Class,1630bool isCategoryImpl, llvm::Value *Receiver,1631bool IsClassMessage, const CallArgList &CallArgs,1632const ObjCMethodDecl *Method) override;16331634llvm::Value *GetClass(CodeGenFunction &CGF,1635const ObjCInterfaceDecl *ID) override;16361637llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override1638{ return EmitSelector(CGF, Sel); }1639Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override1640{ return EmitSelectorAddr(Sel); }16411642/// The NeXT/Apple runtimes do not support typed selectors; just emit an1643/// untyped one.1644llvm::Value *GetSelector(CodeGenFunction &CGF,1645const ObjCMethodDecl *Method) override1646{ return EmitSelector(CGF, Method->getSelector()); }16471648void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;16491650void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;16511652void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}16531654llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,1655const ObjCProtocolDecl *PD) override;16561657llvm::Constant *GetEHType(QualType T) override;16581659llvm::FunctionCallee GetPropertyGetFunction() override {1660return ObjCTypes.getGetPropertyFn();1661}1662llvm::FunctionCallee GetPropertySetFunction() override {1663return ObjCTypes.getSetPropertyFn();1664}16651666llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,1667bool copy) override {1668return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);1669}16701671llvm::FunctionCallee GetSetStructFunction() override {1672return ObjCTypes.getCopyStructFn();1673}16741675llvm::FunctionCallee GetGetStructFunction() override {1676return ObjCTypes.getCopyStructFn();1677}16781679llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {1680return ObjCTypes.getCppAtomicObjectFunction();1681}16821683llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {1684return ObjCTypes.getCppAtomicObjectFunction();1685}16861687llvm::FunctionCallee EnumerationMutationFunction() override {1688return ObjCTypes.getEnumerationMutationFn();1689}16901691void EmitTryStmt(CodeGen::CodeGenFunction &CGF,1692const ObjCAtTryStmt &S) override;1693void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,1694const ObjCAtSynchronizedStmt &S) override;1695void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,1696bool ClearInsertionPoint=true) override;1697llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,1698Address AddrWeakObj) override;1699void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,1700llvm::Value *src, Address edst) override;1701void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,1702llvm::Value *src, Address dest,1703bool threadlocal = false) override;1704void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,1705llvm::Value *src, Address dest,1706llvm::Value *ivarOffset) override;1707void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,1708llvm::Value *src, Address dest) override;1709void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,1710Address dest, Address src,1711llvm::Value *size) override;1712LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,1713llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,1714unsigned CVRQualifiers) override;1715llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,1716const ObjCInterfaceDecl *Interface,1717const ObjCIvarDecl *Ivar) override;1718};17191720/// A helper class for performing the null-initialization of a return1721/// value.1722struct NullReturnState {1723llvm::BasicBlock *NullBB = nullptr;1724NullReturnState() = default;17251726/// Perform a null-check of the given receiver.1727void init(CodeGenFunction &CGF, llvm::Value *receiver) {1728// Make blocks for the null-receiver and call edges.1729NullBB = CGF.createBasicBlock("msgSend.null-receiver");1730llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");17311732// Check for a null receiver and, if there is one, jump to the1733// null-receiver block. There's no point in trying to avoid it:1734// we're always going to put *something* there, because otherwise1735// we shouldn't have done this null-check in the first place.1736llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);1737CGF.Builder.CreateCondBr(isNull, NullBB, callBB);17381739// Otherwise, start performing the call.1740CGF.EmitBlock(callBB);1741}17421743/// Complete the null-return operation. It is valid to call this1744/// regardless of whether 'init' has been called.1745RValue complete(CodeGenFunction &CGF,1746ReturnValueSlot returnSlot,1747RValue result,1748QualType resultType,1749const CallArgList &CallArgs,1750const ObjCMethodDecl *Method) {1751// If we never had to do a null-check, just use the raw result.1752if (!NullBB) return result;17531754// The continuation block. This will be left null if we don't have an1755// IP, which can happen if the method we're calling is marked noreturn.1756llvm::BasicBlock *contBB = nullptr;17571758// Finish the call path.1759llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();1760if (callBB) {1761contBB = CGF.createBasicBlock("msgSend.cont");1762CGF.Builder.CreateBr(contBB);1763}17641765// Okay, start emitting the null-receiver block.1766CGF.EmitBlock(NullBB);17671768// Destroy any consumed arguments we've got.1769if (Method) {1770CGObjCRuntime::destroyCalleeDestroyedArguments(CGF, Method, CallArgs);1771}17721773// The phi code below assumes that we haven't needed any control flow yet.1774assert(CGF.Builder.GetInsertBlock() == NullBB);17751776// If we've got a void return, just jump to the continuation block.1777if (result.isScalar() && resultType->isVoidType()) {1778// No jumps required if the message-send was noreturn.1779if (contBB) CGF.EmitBlock(contBB);1780return result;1781}17821783// If we've got a scalar return, build a phi.1784if (result.isScalar()) {1785// Derive the null-initialization value.1786llvm::Value *null =1787CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(resultType), resultType);17881789// If no join is necessary, just flow out.1790if (!contBB) return RValue::get(null);17911792// Otherwise, build a phi.1793CGF.EmitBlock(contBB);1794llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);1795phi->addIncoming(result.getScalarVal(), callBB);1796phi->addIncoming(null, NullBB);1797return RValue::get(phi);1798}17991800// If we've got an aggregate return, null the buffer out.1801// FIXME: maybe we should be doing things differently for all the1802// cases where the ABI has us returning (1) non-agg values in1803// memory or (2) agg values in registers.1804if (result.isAggregate()) {1805assert(result.isAggregate() && "null init of non-aggregate result?");1806if (!returnSlot.isUnused())1807CGF.EmitNullInitialization(result.getAggregateAddress(), resultType);1808if (contBB) CGF.EmitBlock(contBB);1809return result;1810}18111812// Complex types.1813CGF.EmitBlock(contBB);1814CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();18151816// Find the scalar type and its zero value.1817llvm::Type *scalarTy = callResult.first->getType();1818llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);18191820// Build phis for both coordinates.1821llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);1822real->addIncoming(callResult.first, callBB);1823real->addIncoming(scalarZero, NullBB);1824llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);1825imag->addIncoming(callResult.second, callBB);1826imag->addIncoming(scalarZero, NullBB);1827return RValue::getComplex(real, imag);1828}1829};18301831} // end anonymous namespace18321833/* *** Helper Functions *** */18341835/// getConstantGEP() - Help routine to construct simple GEPs.1836static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,1837llvm::GlobalVariable *C, unsigned idx0,1838unsigned idx1) {1839llvm::Value *Idxs[] = {1840llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),1841llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)1842};1843return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);1844}18451846/// hasObjCExceptionAttribute - Return true if this class or any super1847/// class has the __objc_exception__ attribute.1848static bool hasObjCExceptionAttribute(ASTContext &Context,1849const ObjCInterfaceDecl *OID) {1850if (OID->hasAttr<ObjCExceptionAttr>())1851return true;1852if (const ObjCInterfaceDecl *Super = OID->getSuperClass())1853return hasObjCExceptionAttribute(Context, Super);1854return false;1855}18561857static llvm::GlobalValue::LinkageTypes1858getLinkageTypeForObjCMetadata(CodeGenModule &CGM, StringRef Section) {1859if (CGM.getTriple().isOSBinFormatMachO() &&1860(Section.empty() || Section.starts_with("__DATA")))1861return llvm::GlobalValue::InternalLinkage;1862return llvm::GlobalValue::PrivateLinkage;1863}18641865/// A helper function to create an internal or private global variable.1866static llvm::GlobalVariable *1867finishAndCreateGlobal(ConstantInitBuilder::StructBuilder &Builder,1868const llvm::Twine &Name, CodeGenModule &CGM) {1869std::string SectionName;1870if (CGM.getTriple().isOSBinFormatMachO())1871SectionName = "__DATA, __objc_const";1872auto *GV = Builder.finishAndCreateGlobal(1873Name, CGM.getPointerAlign(), /*constant*/ false,1874getLinkageTypeForObjCMetadata(CGM, SectionName));1875GV->setSection(SectionName);1876return GV;1877}18781879/* *** CGObjCMac Public Interface *** */18801881CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),1882ObjCTypes(cgm) {1883ObjCABI = 1;1884EmitImageInfo();1885}18861887/// GetClass - Return a reference to the class for the given interface1888/// decl.1889llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,1890const ObjCInterfaceDecl *ID) {1891return EmitClassRef(CGF, ID);1892}18931894/// GetSelector - Return the pointer to the unique'd string for this selector.1895llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel) {1896return EmitSelector(CGF, Sel);1897}1898Address CGObjCMac::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {1899return EmitSelectorAddr(Sel);1900}1901llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl1902*Method) {1903return EmitSelector(CGF, Method->getSelector());1904}19051906llvm::Constant *CGObjCMac::GetEHType(QualType T) {1907if (T->isObjCIdType() ||1908T->isObjCQualifiedIdType()) {1909return CGM.GetAddrOfRTTIDescriptor(1910CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);1911}1912if (T->isObjCClassType() ||1913T->isObjCQualifiedClassType()) {1914return CGM.GetAddrOfRTTIDescriptor(1915CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);1916}1917if (T->isObjCObjectPointerType())1918return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);19191920llvm_unreachable("asking for catch type for ObjC type in fragile runtime");1921}19221923/// Generate a constant CFString object.1924/*1925struct __builtin_CFString {1926const int *isa; // point to __CFConstantStringClassReference1927int flags;1928const char *str;1929long length;1930};1931*/19321933/// or Generate a constant NSString object.1934/*1935struct __builtin_NSString {1936const int *isa; // point to __NSConstantStringClassReference1937const char *str;1938unsigned int length;1939};1940*/19411942ConstantAddress1943CGObjCCommonMac::GenerateConstantString(const StringLiteral *SL) {1944return (!CGM.getLangOpts().NoConstantCFStrings1945? CGM.GetAddrOfConstantCFString(SL)1946: GenerateConstantNSString(SL));1947}19481949static llvm::StringMapEntry<llvm::GlobalVariable *> &1950GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,1951const StringLiteral *Literal, unsigned &StringLength) {1952StringRef String = Literal->getString();1953StringLength = String.size();1954return *Map.insert(std::make_pair(String, nullptr)).first;1955}19561957llvm::Constant *CGObjCMac::getNSConstantStringClassRef() {1958if (llvm::Value *V = ConstantStringClassRef)1959return cast<llvm::Constant>(V);19601961auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;1962std::string str =1963StringClass.empty() ? "_NSConstantStringClassReference"1964: "_" + StringClass + "ClassReference";19651966llvm::Type *PTy = llvm::ArrayType::get(CGM.IntTy, 0);1967auto GV = CGM.CreateRuntimeVariable(PTy, str);1968ConstantStringClassRef = GV;1969return GV;1970}19711972llvm::Constant *CGObjCNonFragileABIMac::getNSConstantStringClassRef() {1973if (llvm::Value *V = ConstantStringClassRef)1974return cast<llvm::Constant>(V);19751976auto &StringClass = CGM.getLangOpts().ObjCConstantStringClass;1977std::string str =1978StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"1979: "OBJC_CLASS_$_" + StringClass;1980llvm::Constant *GV = GetClassGlobal(str, NotForDefinition);1981ConstantStringClassRef = GV;1982return GV;1983}19841985ConstantAddress1986CGObjCCommonMac::GenerateConstantNSString(const StringLiteral *Literal) {1987unsigned StringLength = 0;1988llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =1989GetConstantStringEntry(NSConstantStringMap, Literal, StringLength);19901991if (auto *C = Entry.second)1992return ConstantAddress(1993C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment()));19941995// If we don't already have it, get _NSConstantStringClassReference.1996llvm::Constant *Class = getNSConstantStringClassRef();19971998// If we don't already have it, construct the type for a constant NSString.1999if (!NSConstantStringType) {2000NSConstantStringType =2001llvm::StructType::create({CGM.UnqualPtrTy, CGM.Int8PtrTy, CGM.IntTy},2002"struct.__builtin_NSString");2003}20042005ConstantInitBuilder Builder(CGM);2006auto Fields = Builder.beginStruct(NSConstantStringType);20072008// Class pointer.2009Fields.add(Class);20102011// String pointer.2012llvm::Constant *C =2013llvm::ConstantDataArray::getString(VMContext, Entry.first());20142015llvm::GlobalValue::LinkageTypes Linkage = llvm::GlobalValue::PrivateLinkage;2016bool isConstant = !CGM.getLangOpts().WritableStrings;20172018auto *GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), isConstant,2019Linkage, C, ".str");2020GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);2021// Don't enforce the target's minimum global alignment, since the only use2022// of the string is via this class initializer.2023GV->setAlignment(llvm::Align(1));2024Fields.add(GV);20252026// String length.2027Fields.addInt(CGM.IntTy, StringLength);20282029// The struct.2030CharUnits Alignment = CGM.getPointerAlign();2031GV = Fields.finishAndCreateGlobal("_unnamed_nsstring_", Alignment,2032/*constant*/ true,2033llvm::GlobalVariable::PrivateLinkage);2034const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";2035const char *NSStringNonFragileABISection =2036"__DATA,__objc_stringobj,regular,no_dead_strip";2037// FIXME. Fix section.2038GV->setSection(CGM.getLangOpts().ObjCRuntime.isNonFragile()2039? NSStringNonFragileABISection2040: NSStringSection);2041Entry.second = GV;20422043return ConstantAddress(GV, GV->getValueType(), Alignment);2044}20452046enum {2047kCFTaggedObjectID_Integer = (1 << 1) + 12048};20492050/// Generates a message send where the super is the receiver. This is2051/// a message send to self with special delivery semantics indicating2052/// which class's method should be called.2053CodeGen::RValue2054CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,2055ReturnValueSlot Return,2056QualType ResultType,2057Selector Sel,2058const ObjCInterfaceDecl *Class,2059bool isCategoryImpl,2060llvm::Value *Receiver,2061bool IsClassMessage,2062const CodeGen::CallArgList &CallArgs,2063const ObjCMethodDecl *Method) {2064// Create and init a super structure; this is a (receiver, class)2065// pair we will pass to objc_msgSendSuper.2066RawAddress ObjCSuper = CGF.CreateTempAlloca(2067ObjCTypes.SuperTy, CGF.getPointerAlign(), "objc_super");2068llvm::Value *ReceiverAsObject =2069CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);2070CGF.Builder.CreateStore(ReceiverAsObject,2071CGF.Builder.CreateStructGEP(ObjCSuper, 0));20722073// If this is a class message the metaclass is passed as the target.2074llvm::Type *ClassTyPtr = llvm::PointerType::getUnqual(ObjCTypes.ClassTy);2075llvm::Value *Target;2076if (IsClassMessage) {2077if (isCategoryImpl) {2078// Message sent to 'super' in a class method defined in a category2079// implementation requires an odd treatment.2080// If we are in a class method, we must retrieve the2081// _metaclass_ for the current class, pointed at by2082// the class's "isa" pointer. The following assumes that2083// isa" is the first ivar in a class (which it must be).2084Target = EmitClassRef(CGF, Class->getSuperClass());2085Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);2086Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, Target,2087CGF.getPointerAlign());2088} else {2089llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);2090llvm::Value *SuperPtr =2091CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);2092llvm::Value *Super = CGF.Builder.CreateAlignedLoad(ClassTyPtr, SuperPtr,2093CGF.getPointerAlign());2094Target = Super;2095}2096} else if (isCategoryImpl)2097Target = EmitClassRef(CGF, Class->getSuperClass());2098else {2099llvm::Value *ClassPtr = EmitSuperClassRef(Class);2100ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);2101Target = CGF.Builder.CreateAlignedLoad(ClassTyPtr, ClassPtr,2102CGF.getPointerAlign());2103}2104// FIXME: We shouldn't need to do this cast, rectify the ASTContext and2105// ObjCTypes types.2106llvm::Type *ClassTy =2107CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());2108Target = CGF.Builder.CreateBitCast(Target, ClassTy);2109CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1));2110return EmitMessageSend(CGF, Return, ResultType, Sel, ObjCSuper.getPointer(),2111ObjCTypes.SuperPtrCTy, true, CallArgs, Method, Class,2112ObjCTypes);2113}21142115/// Generate code for a message send expression.2116CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,2117ReturnValueSlot Return,2118QualType ResultType,2119Selector Sel,2120llvm::Value *Receiver,2121const CallArgList &CallArgs,2122const ObjCInterfaceDecl *Class,2123const ObjCMethodDecl *Method) {2124return EmitMessageSend(CGF, Return, ResultType, Sel, Receiver,2125CGF.getContext().getObjCIdType(), false, CallArgs,2126Method, Class, ObjCTypes);2127}21282129CodeGen::RValue2130CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,2131ReturnValueSlot Return,2132QualType ResultType,2133Selector Sel,2134llvm::Value *Arg0,2135QualType Arg0Ty,2136bool IsSuper,2137const CallArgList &CallArgs,2138const ObjCMethodDecl *Method,2139const ObjCInterfaceDecl *ClassReceiver,2140const ObjCCommonTypesHelper &ObjCTypes) {2141CodeGenTypes &Types = CGM.getTypes();2142auto selTy = CGF.getContext().getObjCSelType();2143llvm::Value *SelValue = llvm::UndefValue::get(Types.ConvertType(selTy));21442145CallArgList ActualArgs;2146if (!IsSuper)2147Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);2148ActualArgs.add(RValue::get(Arg0), Arg0Ty);2149if (!Method || !Method->isDirectMethod())2150ActualArgs.add(RValue::get(SelValue), selTy);2151ActualArgs.addFrom(CallArgs);21522153// If we're calling a method, use the formal signature.2154MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);21552156if (Method)2157assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==2158CGM.getContext().getCanonicalType(ResultType) &&2159"Result type mismatch!");21602161bool ReceiverCanBeNull =2162canMessageReceiverBeNull(CGF, Method, IsSuper, ClassReceiver, Arg0);21632164bool RequiresNullCheck = false;2165bool RequiresSelValue = true;21662167llvm::FunctionCallee Fn = nullptr;2168if (Method && Method->isDirectMethod()) {2169assert(!IsSuper);2170Fn = GenerateDirectMethod(Method, Method->getClassInterface());2171// Direct methods will synthesize the proper `_cmd` internally,2172// so just don't bother with setting the `_cmd` argument.2173RequiresSelValue = false;2174} else if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {2175if (ReceiverCanBeNull) RequiresNullCheck = true;2176Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)2177: ObjCTypes.getSendStretFn(IsSuper);2178} else if (CGM.ReturnTypeUsesFPRet(ResultType)) {2179Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)2180: ObjCTypes.getSendFpretFn(IsSuper);2181} else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {2182Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)2183: ObjCTypes.getSendFp2retFn(IsSuper);2184} else {2185// arm64 uses objc_msgSend for stret methods and yet null receiver check2186// must be made for it.2187if (ReceiverCanBeNull && CGM.ReturnTypeUsesSRet(MSI.CallInfo))2188RequiresNullCheck = true;2189Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)2190: ObjCTypes.getSendFn(IsSuper);2191}21922193// Cast function to proper signature2194llvm::Constant *BitcastFn = cast<llvm::Constant>(2195CGF.Builder.CreateBitCast(Fn.getCallee(), MSI.MessengerType));21962197// We don't need to emit a null check to zero out an indirect result if the2198// result is ignored.2199if (Return.isUnused())2200RequiresNullCheck = false;22012202// Emit a null-check if there's a consumed argument other than the receiver.2203if (!RequiresNullCheck && Method && Method->hasParamDestroyedInCallee())2204RequiresNullCheck = true;22052206NullReturnState nullReturn;2207if (RequiresNullCheck) {2208nullReturn.init(CGF, Arg0);2209}22102211// If a selector value needs to be passed, emit the load before the call.2212if (RequiresSelValue) {2213SelValue = GetSelector(CGF, Sel);2214ActualArgs[1] = CallArg(RValue::get(SelValue), selTy);2215}22162217llvm::CallBase *CallSite;2218CGCallee Callee = CGCallee::forDirect(BitcastFn);2219RValue rvalue = CGF.EmitCall(MSI.CallInfo, Callee, Return, ActualArgs,2220&CallSite);22212222// Mark the call as noreturn if the method is marked noreturn and the2223// receiver cannot be null.2224if (Method && Method->hasAttr<NoReturnAttr>() && !ReceiverCanBeNull) {2225CallSite->setDoesNotReturn();2226}22272228return nullReturn.complete(CGF, Return, rvalue, ResultType, CallArgs,2229RequiresNullCheck ? Method : nullptr);2230}22312232static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT,2233bool pointee = false) {2234// Note that GC qualification applies recursively to C pointer types2235// that aren't otherwise decorated. This is weird, but it's probably2236// an intentional workaround to the unreliable placement of GC qualifiers.2237if (FQT.isObjCGCStrong())2238return Qualifiers::Strong;22392240if (FQT.isObjCGCWeak())2241return Qualifiers::Weak;22422243if (auto ownership = FQT.getObjCLifetime()) {2244// Ownership does not apply recursively to C pointer types.2245if (pointee) return Qualifiers::GCNone;2246switch (ownership) {2247case Qualifiers::OCL_Weak: return Qualifiers::Weak;2248case Qualifiers::OCL_Strong: return Qualifiers::Strong;2249case Qualifiers::OCL_ExplicitNone: return Qualifiers::GCNone;2250case Qualifiers::OCL_Autoreleasing: llvm_unreachable("autoreleasing ivar?");2251case Qualifiers::OCL_None: llvm_unreachable("known nonzero");2252}2253llvm_unreachable("bad objc ownership");2254}22552256// Treat unqualified retainable pointers as strong.2257if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())2258return Qualifiers::Strong;22592260// Walk into C pointer types, but only in GC.2261if (Ctx.getLangOpts().getGC() != LangOptions::NonGC) {2262if (const PointerType *PT = FQT->getAs<PointerType>())2263return GetGCAttrTypeForType(Ctx, PT->getPointeeType(), /*pointee*/ true);2264}22652266return Qualifiers::GCNone;2267}22682269namespace {2270struct IvarInfo {2271CharUnits Offset;2272uint64_t SizeInWords;2273IvarInfo(CharUnits offset, uint64_t sizeInWords)2274: Offset(offset), SizeInWords(sizeInWords) {}22752276// Allow sorting based on byte pos.2277bool operator<(const IvarInfo &other) const {2278return Offset < other.Offset;2279}2280};22812282/// A helper class for building GC layout strings.2283class IvarLayoutBuilder {2284CodeGenModule &CGM;22852286/// The start of the layout. Offsets will be relative to this value,2287/// and entries less than this value will be silently discarded.2288CharUnits InstanceBegin;22892290/// The end of the layout. Offsets will never exceed this value.2291CharUnits InstanceEnd;22922293/// Whether we're generating the strong layout or the weak layout.2294bool ForStrongLayout;22952296/// Whether the offsets in IvarsInfo might be out-of-order.2297bool IsDisordered = false;22982299llvm::SmallVector<IvarInfo, 8> IvarsInfo;23002301public:2302IvarLayoutBuilder(CodeGenModule &CGM, CharUnits instanceBegin,2303CharUnits instanceEnd, bool forStrongLayout)2304: CGM(CGM), InstanceBegin(instanceBegin), InstanceEnd(instanceEnd),2305ForStrongLayout(forStrongLayout) {2306}23072308void visitRecord(const RecordType *RT, CharUnits offset);23092310template <class Iterator, class GetOffsetFn>2311void visitAggregate(Iterator begin, Iterator end,2312CharUnits aggrOffset,2313const GetOffsetFn &getOffset);23142315void visitField(const FieldDecl *field, CharUnits offset);23162317/// Add the layout of a block implementation.2318void visitBlock(const CGBlockInfo &blockInfo);23192320/// Is there any information for an interesting bitmap?2321bool hasBitmapData() const { return !IvarsInfo.empty(); }23222323llvm::Constant *buildBitmap(CGObjCCommonMac &CGObjC,2324llvm::SmallVectorImpl<unsigned char> &buffer);23252326static void dump(ArrayRef<unsigned char> buffer) {2327const unsigned char *s = buffer.data();2328for (unsigned i = 0, e = buffer.size(); i < e; i++)2329if (!(s[i] & 0xf0))2330printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");2331else2332printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");2333printf("\n");2334}2335};2336} // end anonymous namespace23372338llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,2339const CGBlockInfo &blockInfo) {23402341llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);2342if (CGM.getLangOpts().getGC() == LangOptions::NonGC)2343return nullPtr;23442345IvarLayoutBuilder builder(CGM, CharUnits::Zero(), blockInfo.BlockSize,2346/*for strong layout*/ true);23472348builder.visitBlock(blockInfo);23492350if (!builder.hasBitmapData())2351return nullPtr;23522353llvm::SmallVector<unsigned char, 32> buffer;2354llvm::Constant *C = builder.buildBitmap(*this, buffer);2355if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {2356printf("\n block variable layout for block: ");2357builder.dump(buffer);2358}23592360return C;2361}23622363void IvarLayoutBuilder::visitBlock(const CGBlockInfo &blockInfo) {2364// __isa is the first field in block descriptor and must assume by runtime's2365// convention that it is GC'able.2366IvarsInfo.push_back(IvarInfo(CharUnits::Zero(), 1));23672368const BlockDecl *blockDecl = blockInfo.getBlockDecl();23692370// Ignore the optional 'this' capture: C++ objects are not assumed2371// to be GC'ed.23722373CharUnits lastFieldOffset;23742375// Walk the captured variables.2376for (const auto &CI : blockDecl->captures()) {2377const VarDecl *variable = CI.getVariable();2378QualType type = variable->getType();23792380const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);23812382// Ignore constant captures.2383if (capture.isConstant()) continue;23842385CharUnits fieldOffset = capture.getOffset();23862387// Block fields are not necessarily ordered; if we detect that we're2388// adding them out-of-order, make sure we sort later.2389if (fieldOffset < lastFieldOffset)2390IsDisordered = true;2391lastFieldOffset = fieldOffset;23922393// __block variables are passed by their descriptor address.2394if (CI.isByRef()) {2395IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));2396continue;2397}23982399assert(!type->isArrayType() && "array variable should not be caught");2400if (const RecordType *record = type->getAs<RecordType>()) {2401visitRecord(record, fieldOffset);2402continue;2403}24042405Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);24062407if (GCAttr == Qualifiers::Strong) {2408assert(CGM.getContext().getTypeSize(type) ==2409CGM.getTarget().getPointerWidth(LangAS::Default));2410IvarsInfo.push_back(IvarInfo(fieldOffset, /*size in words*/ 1));2411}2412}2413}24142415/// getBlockCaptureLifetime - This routine returns life time of the captured2416/// block variable for the purpose of block layout meta-data generation. FQT is2417/// the type of the variable captured in the block.2418Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,2419bool ByrefLayout) {2420// If it has an ownership qualifier, we're done.2421if (auto lifetime = FQT.getObjCLifetime())2422return lifetime;24232424// If it doesn't, and this is ARC, it has no ownership.2425if (CGM.getLangOpts().ObjCAutoRefCount)2426return Qualifiers::OCL_None;24272428// In MRC, retainable pointers are owned by non-__block variables.2429if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())2430return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;24312432return Qualifiers::OCL_None;2433}24342435void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,2436Qualifiers::ObjCLifetime LifeTime,2437CharUnits FieldOffset,2438CharUnits FieldSize) {2439// __block variables are passed by their descriptor address.2440if (IsByref)2441RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,2442FieldSize));2443else if (LifeTime == Qualifiers::OCL_Strong)2444RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,2445FieldSize));2446else if (LifeTime == Qualifiers::OCL_Weak)2447RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,2448FieldSize));2449else if (LifeTime == Qualifiers::OCL_ExplicitNone)2450RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,2451FieldSize));2452else2453RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,2454FieldOffset,2455FieldSize));2456}24572458void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,2459const RecordDecl *RD,2460ArrayRef<const FieldDecl*> RecFields,2461CharUnits BytePos, bool &HasUnion,2462bool ByrefLayout) {2463bool IsUnion = (RD && RD->isUnion());2464CharUnits MaxUnionSize = CharUnits::Zero();2465const FieldDecl *MaxField = nullptr;2466const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;2467CharUnits MaxFieldOffset = CharUnits::Zero();2468CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();24692470if (RecFields.empty())2471return;2472unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();24732474for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {2475const FieldDecl *Field = RecFields[i];2476// Note that 'i' here is actually the field index inside RD of Field,2477// although this dependency is hidden.2478const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);2479CharUnits FieldOffset =2480CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));24812482// Skip over unnamed or bitfields2483if (!Field->getIdentifier() || Field->isBitField()) {2484LastFieldBitfieldOrUnnamed = Field;2485LastBitfieldOrUnnamedOffset = FieldOffset;2486continue;2487}24882489LastFieldBitfieldOrUnnamed = nullptr;2490QualType FQT = Field->getType();2491if (FQT->isRecordType() || FQT->isUnionType()) {2492if (FQT->isUnionType())2493HasUnion = true;24942495BuildRCBlockVarRecordLayout(FQT->castAs<RecordType>(),2496BytePos + FieldOffset, HasUnion);2497continue;2498}24992500if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {2501auto *CArray = cast<ConstantArrayType>(Array);2502uint64_t ElCount = CArray->getZExtSize();2503assert(CArray && "only array with known element size is supported");2504FQT = CArray->getElementType();2505while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {2506auto *CArray = cast<ConstantArrayType>(Array);2507ElCount *= CArray->getZExtSize();2508FQT = CArray->getElementType();2509}2510if (FQT->isRecordType() && ElCount) {2511int OldIndex = RunSkipBlockVars.size() - 1;2512auto *RT = FQT->castAs<RecordType>();2513BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset, HasUnion);25142515// Replicate layout information for each array element. Note that2516// one element is already done.2517uint64_t ElIx = 1;2518for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {2519CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);2520for (int i = OldIndex+1; i <= FirstIndex; ++i)2521RunSkipBlockVars.push_back(2522RUN_SKIP(RunSkipBlockVars[i].opcode,2523RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,2524RunSkipBlockVars[i].block_var_size));2525}2526continue;2527}2528}2529CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());2530if (IsUnion) {2531CharUnits UnionIvarSize = FieldSize;2532if (UnionIvarSize > MaxUnionSize) {2533MaxUnionSize = UnionIvarSize;2534MaxField = Field;2535MaxFieldOffset = FieldOffset;2536}2537} else {2538UpdateRunSkipBlockVars(false,2539getBlockCaptureLifetime(FQT, ByrefLayout),2540BytePos + FieldOffset,2541FieldSize);2542}2543}25442545if (LastFieldBitfieldOrUnnamed) {2546if (LastFieldBitfieldOrUnnamed->isBitField()) {2547// Last field was a bitfield. Must update the info.2548uint64_t BitFieldSize2549= LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());2550unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +2551((BitFieldSize % ByteSizeInBits) != 0);2552CharUnits Size = CharUnits::fromQuantity(UnsSize);2553Size += LastBitfieldOrUnnamedOffset;2554UpdateRunSkipBlockVars(false,2555getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),2556ByrefLayout),2557BytePos + LastBitfieldOrUnnamedOffset,2558Size);2559} else {2560assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");2561// Last field was unnamed. Must update skip info.2562CharUnits FieldSize2563= CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());2564UpdateRunSkipBlockVars(false,2565getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),2566ByrefLayout),2567BytePos + LastBitfieldOrUnnamedOffset,2568FieldSize);2569}2570}25712572if (MaxField)2573UpdateRunSkipBlockVars(false,2574getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),2575BytePos + MaxFieldOffset,2576MaxUnionSize);2577}25782579void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,2580CharUnits BytePos,2581bool &HasUnion,2582bool ByrefLayout) {2583const RecordDecl *RD = RT->getDecl();2584SmallVector<const FieldDecl*, 16> Fields(RD->fields());2585llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));2586const llvm::StructLayout *RecLayout =2587CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));25882589BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);2590}25912592/// InlineLayoutInstruction - This routine produce an inline instruction for the2593/// block variable layout if it can. If not, it returns 0. Rules are as follow:2594/// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,2595/// an inline layout of value 0x0000000000000xyz is interpreted as follows:2596/// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by2597/// y captured object of BLOCK_LAYOUT_BYREF. Followed by2598/// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero2599/// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no2600/// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.2601uint64_t CGObjCCommonMac::InlineLayoutInstruction(2602SmallVectorImpl<unsigned char> &Layout) {2603uint64_t Result = 0;2604if (Layout.size() <= 3) {2605unsigned size = Layout.size();2606unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;2607unsigned char inst;2608enum BLOCK_LAYOUT_OPCODE opcode ;2609switch (size) {2610case 3:2611inst = Layout[0];2612opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2613if (opcode == BLOCK_LAYOUT_STRONG)2614strong_word_count = (inst & 0xF)+1;2615else2616return 0;2617inst = Layout[1];2618opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2619if (opcode == BLOCK_LAYOUT_BYREF)2620byref_word_count = (inst & 0xF)+1;2621else2622return 0;2623inst = Layout[2];2624opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2625if (opcode == BLOCK_LAYOUT_WEAK)2626weak_word_count = (inst & 0xF)+1;2627else2628return 0;2629break;26302631case 2:2632inst = Layout[0];2633opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2634if (opcode == BLOCK_LAYOUT_STRONG) {2635strong_word_count = (inst & 0xF)+1;2636inst = Layout[1];2637opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2638if (opcode == BLOCK_LAYOUT_BYREF)2639byref_word_count = (inst & 0xF)+1;2640else if (opcode == BLOCK_LAYOUT_WEAK)2641weak_word_count = (inst & 0xF)+1;2642else2643return 0;2644}2645else if (opcode == BLOCK_LAYOUT_BYREF) {2646byref_word_count = (inst & 0xF)+1;2647inst = Layout[1];2648opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2649if (opcode == BLOCK_LAYOUT_WEAK)2650weak_word_count = (inst & 0xF)+1;2651else2652return 0;2653}2654else2655return 0;2656break;26572658case 1:2659inst = Layout[0];2660opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2661if (opcode == BLOCK_LAYOUT_STRONG)2662strong_word_count = (inst & 0xF)+1;2663else if (opcode == BLOCK_LAYOUT_BYREF)2664byref_word_count = (inst & 0xF)+1;2665else if (opcode == BLOCK_LAYOUT_WEAK)2666weak_word_count = (inst & 0xF)+1;2667else2668return 0;2669break;26702671default:2672return 0;2673}26742675// Cannot inline when any of the word counts is 15. Because this is one less2676// than the actual work count (so 15 means 16 actual word counts),2677// and we can only display 0 thru 15 word counts.2678if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)2679return 0;26802681unsigned count =2682(strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);26832684if (size == count) {2685if (strong_word_count)2686Result = strong_word_count;2687Result <<= 4;2688if (byref_word_count)2689Result += byref_word_count;2690Result <<= 4;2691if (weak_word_count)2692Result += weak_word_count;2693}2694}2695return Result;2696}26972698llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {2699llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);2700if (RunSkipBlockVars.empty())2701return nullPtr;2702unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(LangAS::Default);2703unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();2704unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;27052706// Sort on byte position; captures might not be allocated in order,2707// and unions can do funny things.2708llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());2709SmallVector<unsigned char, 16> Layout;27102711unsigned size = RunSkipBlockVars.size();2712for (unsigned i = 0; i < size; i++) {2713enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;2714CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;2715CharUnits end_byte_pos = start_byte_pos;2716unsigned j = i+1;2717while (j < size) {2718if (opcode == RunSkipBlockVars[j].opcode) {2719end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;2720i++;2721}2722else2723break;2724}2725CharUnits size_in_bytes =2726end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;2727if (j < size) {2728CharUnits gap =2729RunSkipBlockVars[j].block_var_bytepos -2730RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;2731size_in_bytes += gap;2732}2733CharUnits residue_in_bytes = CharUnits::Zero();2734if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {2735residue_in_bytes = size_in_bytes % WordSizeInBytes;2736size_in_bytes -= residue_in_bytes;2737opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;2738}27392740unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;2741while (size_in_words >= 16) {2742// Note that value in imm. is one less that the actual2743// value. So, 0xf means 16 words follow!2744unsigned char inst = (opcode << 4) | 0xf;2745Layout.push_back(inst);2746size_in_words -= 16;2747}2748if (size_in_words > 0) {2749// Note that value in imm. is one less that the actual2750// value. So, we subtract 1 away!2751unsigned char inst = (opcode << 4) | (size_in_words-1);2752Layout.push_back(inst);2753}2754if (residue_in_bytes > CharUnits::Zero()) {2755unsigned char inst =2756(BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);2757Layout.push_back(inst);2758}2759}27602761while (!Layout.empty()) {2762unsigned char inst = Layout.back();2763enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2764if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)2765Layout.pop_back();2766else2767break;2768}27692770uint64_t Result = InlineLayoutInstruction(Layout);2771if (Result != 0) {2772// Block variable layout instruction has been inlined.2773if (CGM.getLangOpts().ObjCGCBitmapPrint) {2774if (ComputeByrefLayout)2775printf("\n Inline BYREF variable layout: ");2776else2777printf("\n Inline block variable layout: ");2778printf("0x0%" PRIx64 "", Result);2779if (auto numStrong = (Result & 0xF00) >> 8)2780printf(", BL_STRONG:%d", (int) numStrong);2781if (auto numByref = (Result & 0x0F0) >> 4)2782printf(", BL_BYREF:%d", (int) numByref);2783if (auto numWeak = (Result & 0x00F) >> 0)2784printf(", BL_WEAK:%d", (int) numWeak);2785printf(", BL_OPERATOR:0\n");2786}2787return llvm::ConstantInt::get(CGM.IntPtrTy, Result);2788}27892790unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;2791Layout.push_back(inst);2792std::string BitMap;2793for (unsigned i = 0, e = Layout.size(); i != e; i++)2794BitMap += Layout[i];27952796if (CGM.getLangOpts().ObjCGCBitmapPrint) {2797if (ComputeByrefLayout)2798printf("\n Byref variable layout: ");2799else2800printf("\n Block variable layout: ");2801for (unsigned i = 0, e = BitMap.size(); i != e; i++) {2802unsigned char inst = BitMap[i];2803enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);2804unsigned delta = 1;2805switch (opcode) {2806case BLOCK_LAYOUT_OPERATOR:2807printf("BL_OPERATOR:");2808delta = 0;2809break;2810case BLOCK_LAYOUT_NON_OBJECT_BYTES:2811printf("BL_NON_OBJECT_BYTES:");2812break;2813case BLOCK_LAYOUT_NON_OBJECT_WORDS:2814printf("BL_NON_OBJECT_WORD:");2815break;2816case BLOCK_LAYOUT_STRONG:2817printf("BL_STRONG:");2818break;2819case BLOCK_LAYOUT_BYREF:2820printf("BL_BYREF:");2821break;2822case BLOCK_LAYOUT_WEAK:2823printf("BL_WEAK:");2824break;2825case BLOCK_LAYOUT_UNRETAINED:2826printf("BL_UNRETAINED:");2827break;2828}2829// Actual value of word count is one more that what is in the imm.2830// field of the instruction2831printf("%d", (inst & 0xf) + delta);2832if (i < e-1)2833printf(", ");2834else2835printf("\n");2836}2837}28382839auto *Entry = CreateCStringLiteral(BitMap, ObjCLabelType::ClassName,2840/*ForceNonFragileABI=*/true,2841/*NullTerminate=*/false);2842return getConstantGEP(VMContext, Entry, 0, 0);2843}28442845static std::string getBlockLayoutInfoString(2846const SmallVectorImpl<CGObjCCommonMac::RUN_SKIP> &RunSkipBlockVars,2847bool HasCopyDisposeHelpers) {2848std::string Str;2849for (const CGObjCCommonMac::RUN_SKIP &R : RunSkipBlockVars) {2850if (R.opcode == CGObjCCommonMac::BLOCK_LAYOUT_UNRETAINED) {2851// Copy/dispose helpers don't have any information about2852// __unsafe_unretained captures, so unconditionally concatenate a string.2853Str += "u";2854} else if (HasCopyDisposeHelpers) {2855// Information about __strong, __weak, or byref captures has already been2856// encoded into the names of the copy/dispose helpers. We have to add a2857// string here only when the copy/dispose helpers aren't generated (which2858// happens when the block is non-escaping).2859continue;2860} else {2861switch (R.opcode) {2862case CGObjCCommonMac::BLOCK_LAYOUT_STRONG:2863Str += "s";2864break;2865case CGObjCCommonMac::BLOCK_LAYOUT_BYREF:2866Str += "r";2867break;2868case CGObjCCommonMac::BLOCK_LAYOUT_WEAK:2869Str += "w";2870break;2871default:2872continue;2873}2874}2875Str += llvm::to_string(R.block_var_bytepos.getQuantity());2876Str += "l" + llvm::to_string(R.block_var_size.getQuantity());2877}2878return Str;2879}28802881void CGObjCCommonMac::fillRunSkipBlockVars(CodeGenModule &CGM,2882const CGBlockInfo &blockInfo) {2883assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);28842885RunSkipBlockVars.clear();2886bool hasUnion = false;28872888unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(LangAS::Default);2889unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();2890unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;28912892const BlockDecl *blockDecl = blockInfo.getBlockDecl();28932894// Calculate the basic layout of the block structure.2895const llvm::StructLayout *layout =2896CGM.getDataLayout().getStructLayout(blockInfo.StructureType);28972898// Ignore the optional 'this' capture: C++ objects are not assumed2899// to be GC'ed.2900if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())2901UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,2902blockInfo.BlockHeaderForcedGapOffset,2903blockInfo.BlockHeaderForcedGapSize);2904// Walk the captured variables.2905for (const auto &CI : blockDecl->captures()) {2906const VarDecl *variable = CI.getVariable();2907QualType type = variable->getType();29082909const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);29102911// Ignore constant captures.2912if (capture.isConstant()) continue;29132914CharUnits fieldOffset =2915CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));29162917assert(!type->isArrayType() && "array variable should not be caught");2918if (!CI.isByRef())2919if (const RecordType *record = type->getAs<RecordType>()) {2920BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);2921continue;2922}2923CharUnits fieldSize;2924if (CI.isByRef())2925fieldSize = CharUnits::fromQuantity(WordSizeInBytes);2926else2927fieldSize = CGM.getContext().getTypeSizeInChars(type);2928UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),2929fieldOffset, fieldSize);2930}2931}29322933llvm::Constant *2934CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,2935const CGBlockInfo &blockInfo) {2936fillRunSkipBlockVars(CGM, blockInfo);2937return getBitmapBlockLayout(false);2938}29392940std::string CGObjCCommonMac::getRCBlockLayoutStr(CodeGenModule &CGM,2941const CGBlockInfo &blockInfo) {2942fillRunSkipBlockVars(CGM, blockInfo);2943return getBlockLayoutInfoString(RunSkipBlockVars, blockInfo.NeedsCopyDispose);2944}29452946llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,2947QualType T) {2948assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);2949assert(!T->isArrayType() && "__block array variable should not be caught");2950CharUnits fieldOffset;2951RunSkipBlockVars.clear();2952bool hasUnion = false;2953if (const RecordType *record = T->getAs<RecordType>()) {2954BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);2955llvm::Constant *Result = getBitmapBlockLayout(true);2956if (isa<llvm::ConstantInt>(Result))2957Result = llvm::ConstantExpr::getIntToPtr(Result, CGM.Int8PtrTy);2958return Result;2959}2960llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);2961return nullPtr;2962}29632964llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,2965const ObjCProtocolDecl *PD) {2966// FIXME: I don't understand why gcc generates this, or where it is2967// resolved. Investigate. Its also wasteful to look this up over and over.2968LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));29692970return GetProtocolRef(PD);2971}29722973void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {2974// FIXME: We shouldn't need this, the protocol decl should contain enough2975// information to tell us whether this was a declaration or a definition.2976DefinedProtocols.insert(PD->getIdentifier());29772978// If we have generated a forward reference to this protocol, emit2979// it now. Otherwise do nothing, the protocol objects are lazily2980// emitted.2981if (Protocols.count(PD->getIdentifier()))2982GetOrEmitProtocol(PD);2983}29842985llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {2986if (DefinedProtocols.count(PD->getIdentifier()))2987return GetOrEmitProtocol(PD);29882989return GetOrEmitProtocolRef(PD);2990}29912992llvm::Value *CGObjCCommonMac::EmitClassRefViaRuntime(2993CodeGenFunction &CGF,2994const ObjCInterfaceDecl *ID,2995ObjCCommonTypesHelper &ObjCTypes) {2996llvm::FunctionCallee lookUpClassFn = ObjCTypes.getLookUpClassFn();29972998llvm::Value *className = CGF.CGM2999.GetAddrOfConstantCString(std::string(3000ID->getObjCRuntimeNameAsString()))3001.getPointer();3002ASTContext &ctx = CGF.CGM.getContext();3003className =3004CGF.Builder.CreateBitCast(className,3005CGF.ConvertType(3006ctx.getPointerType(ctx.CharTy.withConst())));3007llvm::CallInst *call = CGF.Builder.CreateCall(lookUpClassFn, className);3008call->setDoesNotThrow();3009return call;3010}30113012/*3013// Objective-C 1.0 extensions3014struct _objc_protocol {3015struct _objc_protocol_extension *isa;3016char *protocol_name;3017struct _objc_protocol_list *protocol_list;3018struct _objc__method_prototype_list *instance_methods;3019struct _objc__method_prototype_list *class_methods3020};30213022See EmitProtocolExtension().3023*/3024llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {3025llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];30263027// Early exit if a defining object has already been generated.3028if (Entry && Entry->hasInitializer())3029return Entry;30303031// Use the protocol definition, if there is one.3032if (const ObjCProtocolDecl *Def = PD->getDefinition())3033PD = Def;30343035// FIXME: I don't understand why gcc generates this, or where it is3036// resolved. Investigate. Its also wasteful to look this up over and over.3037LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));30383039// Construct method lists.3040auto methodLists = ProtocolMethodLists::get(PD);30413042ConstantInitBuilder builder(CGM);3043auto values = builder.beginStruct(ObjCTypes.ProtocolTy);3044values.add(EmitProtocolExtension(PD, methodLists));3045values.add(GetClassName(PD->getObjCRuntimeNameAsString()));3046values.add(EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),3047PD->protocol_begin(), PD->protocol_end()));3048values.add(methodLists.emitMethodList(this, PD,3049ProtocolMethodLists::RequiredInstanceMethods));3050values.add(methodLists.emitMethodList(this, PD,3051ProtocolMethodLists::RequiredClassMethods));30523053if (Entry) {3054// Already created, update the initializer.3055assert(Entry->hasPrivateLinkage());3056values.finishAndSetAsInitializer(Entry);3057} else {3058Entry = values.finishAndCreateGlobal("OBJC_PROTOCOL_" + PD->getName(),3059CGM.getPointerAlign(),3060/*constant*/ false,3061llvm::GlobalValue::PrivateLinkage);3062Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");30633064Protocols[PD->getIdentifier()] = Entry;3065}3066CGM.addCompilerUsedGlobal(Entry);30673068return Entry;3069}30703071llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {3072llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];30733074if (!Entry) {3075// We use the initializer as a marker of whether this is a forward3076// reference or not. At module finalization we add the empty3077// contents for protocols which were referenced but never defined.3078Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,3079false, llvm::GlobalValue::PrivateLinkage,3080nullptr, "OBJC_PROTOCOL_" + PD->getName());3081Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");3082// FIXME: Is this necessary? Why only for protocol?3083Entry->setAlignment(llvm::Align(4));3084}30853086return Entry;3087}30883089/*3090struct _objc_protocol_extension {3091uint32_t size;3092struct objc_method_description_list *optional_instance_methods;3093struct objc_method_description_list *optional_class_methods;3094struct objc_property_list *instance_properties;3095const char ** extendedMethodTypes;3096struct objc_property_list *class_properties;3097};3098*/3099llvm::Constant *3100CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,3101const ProtocolMethodLists &methodLists) {3102auto optInstanceMethods =3103methodLists.emitMethodList(this, PD,3104ProtocolMethodLists::OptionalInstanceMethods);3105auto optClassMethods =3106methodLists.emitMethodList(this, PD,3107ProtocolMethodLists::OptionalClassMethods);31083109auto extendedMethodTypes =3110EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),3111methodLists.emitExtendedTypesArray(this),3112ObjCTypes);31133114auto instanceProperties =3115EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,3116ObjCTypes, false);3117auto classProperties =3118EmitPropertyList("OBJC_$_CLASS_PROP_PROTO_LIST_" + PD->getName(), nullptr,3119PD, ObjCTypes, true);31203121// Return null if no extension bits are used.3122if (optInstanceMethods->isNullValue() &&3123optClassMethods->isNullValue() &&3124extendedMethodTypes->isNullValue() &&3125instanceProperties->isNullValue() &&3126classProperties->isNullValue()) {3127return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);3128}31293130uint64_t size =3131CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);31323133ConstantInitBuilder builder(CGM);3134auto values = builder.beginStruct(ObjCTypes.ProtocolExtensionTy);3135values.addInt(ObjCTypes.IntTy, size);3136values.add(optInstanceMethods);3137values.add(optClassMethods);3138values.add(instanceProperties);3139values.add(extendedMethodTypes);3140values.add(classProperties);31413142// No special section, but goes in llvm.used3143return CreateMetadataVar("_OBJC_PROTOCOLEXT_" + PD->getName(), values,3144StringRef(), CGM.getPointerAlign(), true);3145}31463147/*3148struct objc_protocol_list {3149struct objc_protocol_list *next;3150long count;3151Protocol *list[];3152};3153*/3154llvm::Constant *3155CGObjCMac::EmitProtocolList(Twine name,3156ObjCProtocolDecl::protocol_iterator begin,3157ObjCProtocolDecl::protocol_iterator end) {3158// Just return null for empty protocol lists3159auto PDs = GetRuntimeProtocolList(begin, end);3160if (PDs.empty())3161return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);31623163ConstantInitBuilder builder(CGM);3164auto values = builder.beginStruct();31653166// This field is only used by the runtime.3167values.addNullPointer(ObjCTypes.ProtocolListPtrTy);31683169// Reserve a slot for the count.3170auto countSlot = values.addPlaceholder();31713172auto refsArray = values.beginArray(ObjCTypes.ProtocolPtrTy);3173for (const auto *Proto : PDs)3174refsArray.add(GetProtocolRef(Proto));31753176auto count = refsArray.size();31773178// This list is null terminated.3179refsArray.addNullPointer(ObjCTypes.ProtocolPtrTy);31803181refsArray.finishAndAddTo(values);3182values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);31833184StringRef section;3185if (CGM.getTriple().isOSBinFormatMachO())3186section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";31873188llvm::GlobalVariable *GV =3189CreateMetadataVar(name, values, section, CGM.getPointerAlign(), false);3190return GV;3191}31923193static void3194PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,3195SmallVectorImpl<const ObjCPropertyDecl *> &Properties,3196const ObjCProtocolDecl *Proto,3197bool IsClassProperty) {3198for (const auto *PD : Proto->properties()) {3199if (IsClassProperty != PD->isClassProperty())3200continue;3201if (!PropertySet.insert(PD->getIdentifier()).second)3202continue;3203Properties.push_back(PD);3204}32053206for (const auto *P : Proto->protocols())3207PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);3208}32093210/*3211struct _objc_property {3212const char * const name;3213const char * const attributes;3214};32153216struct _objc_property_list {3217uint32_t entsize; // sizeof (struct _objc_property)3218uint32_t prop_count;3219struct _objc_property[prop_count];3220};3221*/3222llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,3223const Decl *Container,3224const ObjCContainerDecl *OCD,3225const ObjCCommonTypesHelper &ObjCTypes,3226bool IsClassProperty) {3227if (IsClassProperty) {3228// Make this entry NULL for OS X with deployment target < 10.11, for iOS3229// with deployment target < 9.0.3230const llvm::Triple &Triple = CGM.getTarget().getTriple();3231if ((Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 11)) ||3232(Triple.isiOS() && Triple.isOSVersionLT(9)))3233return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);3234}32353236SmallVector<const ObjCPropertyDecl *, 16> Properties;3237llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;32383239if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))3240for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())3241for (auto *PD : ClassExt->properties()) {3242if (IsClassProperty != PD->isClassProperty())3243continue;3244if (PD->isDirectProperty())3245continue;3246PropertySet.insert(PD->getIdentifier());3247Properties.push_back(PD);3248}32493250for (const auto *PD : OCD->properties()) {3251if (IsClassProperty != PD->isClassProperty())3252continue;3253// Don't emit duplicate metadata for properties that were already in a3254// class extension.3255if (!PropertySet.insert(PD->getIdentifier()).second)3256continue;3257if (PD->isDirectProperty())3258continue;3259Properties.push_back(PD);3260}32613262if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {3263for (const auto *P : OID->all_referenced_protocols())3264PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);3265}3266else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {3267for (const auto *P : CD->protocols())3268PushProtocolProperties(PropertySet, Properties, P, IsClassProperty);3269}32703271// Return null for empty list.3272if (Properties.empty())3273return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);32743275unsigned propertySize =3276CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);32773278ConstantInitBuilder builder(CGM);3279auto values = builder.beginStruct();3280values.addInt(ObjCTypes.IntTy, propertySize);3281values.addInt(ObjCTypes.IntTy, Properties.size());3282auto propertiesArray = values.beginArray(ObjCTypes.PropertyTy);3283for (auto PD : Properties) {3284auto property = propertiesArray.beginStruct(ObjCTypes.PropertyTy);3285property.add(GetPropertyName(PD->getIdentifier()));3286property.add(GetPropertyTypeString(PD, Container));3287property.finishAndAddTo(propertiesArray);3288}3289propertiesArray.finishAndAddTo(values);32903291StringRef Section;3292if (CGM.getTriple().isOSBinFormatMachO())3293Section = (ObjCABI == 2) ? "__DATA, __objc_const"3294: "__OBJC,__property,regular,no_dead_strip";32953296llvm::GlobalVariable *GV =3297CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);3298return GV;3299}33003301llvm::Constant *3302CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,3303ArrayRef<llvm::Constant*> MethodTypes,3304const ObjCCommonTypesHelper &ObjCTypes) {3305// Return null for empty list.3306if (MethodTypes.empty())3307return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);33083309llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,3310MethodTypes.size());3311llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);33123313StringRef Section;3314if (CGM.getTriple().isOSBinFormatMachO() && ObjCABI == 2)3315Section = "__DATA, __objc_const";33163317llvm::GlobalVariable *GV =3318CreateMetadataVar(Name, Init, Section, CGM.getPointerAlign(), true);3319return GV;3320}33213322/*3323struct _objc_category {3324char *category_name;3325char *class_name;3326struct _objc_method_list *instance_methods;3327struct _objc_method_list *class_methods;3328struct _objc_protocol_list *protocols;3329uint32_t size; // sizeof(struct _objc_category)3330struct _objc_property_list *instance_properties;3331struct _objc_property_list *class_properties;3332};3333*/3334void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {3335unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);33363337// FIXME: This is poor design, the OCD should have a pointer to the category3338// decl. Additionally, note that Category can be null for the @implementation3339// w/o an @interface case. Sema should just create one for us as it does for3340// @implementation so everyone else can live life under a clear blue sky.3341const ObjCInterfaceDecl *Interface = OCD->getClassInterface();3342const ObjCCategoryDecl *Category =3343Interface->FindCategoryDeclaration(OCD->getIdentifier());33443345SmallString<256> ExtName;3346llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'3347<< OCD->getName();33483349ConstantInitBuilder Builder(CGM);3350auto Values = Builder.beginStruct(ObjCTypes.CategoryTy);33513352enum {3353InstanceMethods,3354ClassMethods,3355NumMethodLists3356};3357SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];3358for (const auto *MD : OCD->methods()) {3359if (!MD->isDirectMethod())3360Methods[unsigned(MD->isClassMethod())].push_back(MD);3361}33623363Values.add(GetClassName(OCD->getName()));3364Values.add(GetClassName(Interface->getObjCRuntimeNameAsString()));3365LazySymbols.insert(Interface->getIdentifier());33663367Values.add(emitMethodList(ExtName, MethodListType::CategoryInstanceMethods,3368Methods[InstanceMethods]));3369Values.add(emitMethodList(ExtName, MethodListType::CategoryClassMethods,3370Methods[ClassMethods]));3371if (Category) {3372Values.add(3373EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),3374Category->protocol_begin(), Category->protocol_end()));3375} else {3376Values.addNullPointer(ObjCTypes.ProtocolListPtrTy);3377}3378Values.addInt(ObjCTypes.IntTy, Size);33793380// If there is no category @interface then there can be no properties.3381if (Category) {3382Values.add(EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(),3383OCD, Category, ObjCTypes, false));3384Values.add(EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(),3385OCD, Category, ObjCTypes, true));3386} else {3387Values.addNullPointer(ObjCTypes.PropertyListPtrTy);3388Values.addNullPointer(ObjCTypes.PropertyListPtrTy);3389}33903391llvm::GlobalVariable *GV =3392CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Values,3393"__OBJC,__category,regular,no_dead_strip",3394CGM.getPointerAlign(), true);3395DefinedCategories.push_back(GV);3396DefinedCategoryNames.insert(llvm::CachedHashString(ExtName));3397// method definition entries must be clear for next implementation.3398MethodDefinitions.clear();3399}34003401enum FragileClassFlags {3402/// Apparently: is not a meta-class.3403FragileABI_Class_Factory = 0x00001,34043405/// Is a meta-class.3406FragileABI_Class_Meta = 0x00002,34073408/// Has a non-trivial constructor or destructor.3409FragileABI_Class_HasCXXStructors = 0x02000,34103411/// Has hidden visibility.3412FragileABI_Class_Hidden = 0x20000,34133414/// Class implementation was compiled under ARC.3415FragileABI_Class_CompiledByARC = 0x04000000,34163417/// Class implementation was compiled under MRC and has MRC weak ivars.3418/// Exclusive with CompiledByARC.3419FragileABI_Class_HasMRCWeakIvars = 0x08000000,3420};34213422enum NonFragileClassFlags {3423/// Is a meta-class.3424NonFragileABI_Class_Meta = 0x00001,34253426/// Is a root class.3427NonFragileABI_Class_Root = 0x00002,34283429/// Has a non-trivial constructor or destructor.3430NonFragileABI_Class_HasCXXStructors = 0x00004,34313432/// Has hidden visibility.3433NonFragileABI_Class_Hidden = 0x00010,34343435/// Has the exception attribute.3436NonFragileABI_Class_Exception = 0x00020,34373438/// (Obsolete) ARC-specific: this class has a .release_ivars method3439NonFragileABI_Class_HasIvarReleaser = 0x00040,34403441/// Class implementation was compiled under ARC.3442NonFragileABI_Class_CompiledByARC = 0x00080,34433444/// Class has non-trivial destructors, but zero-initialization is okay.3445NonFragileABI_Class_HasCXXDestructorOnly = 0x00100,34463447/// Class implementation was compiled under MRC and has MRC weak ivars.3448/// Exclusive with CompiledByARC.3449NonFragileABI_Class_HasMRCWeakIvars = 0x00200,3450};34513452static bool hasWeakMember(QualType type) {3453if (type.getObjCLifetime() == Qualifiers::OCL_Weak) {3454return true;3455}34563457if (auto recType = type->getAs<RecordType>()) {3458for (auto *field : recType->getDecl()->fields()) {3459if (hasWeakMember(field->getType()))3460return true;3461}3462}34633464return false;3465}34663467/// For compatibility, we only want to set the "HasMRCWeakIvars" flag3468/// (and actually fill in a layout string) if we really do have any3469/// __weak ivars.3470static bool hasMRCWeakIvars(CodeGenModule &CGM,3471const ObjCImplementationDecl *ID) {3472if (!CGM.getLangOpts().ObjCWeak) return false;3473assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);34743475for (const ObjCIvarDecl *ivar =3476ID->getClassInterface()->all_declared_ivar_begin();3477ivar; ivar = ivar->getNextIvar()) {3478if (hasWeakMember(ivar->getType()))3479return true;3480}34813482return false;3483}34843485/*3486struct _objc_class {3487Class isa;3488Class super_class;3489const char *name;3490long version;3491long info;3492long instance_size;3493struct _objc_ivar_list *ivars;3494struct _objc_method_list *methods;3495struct _objc_cache *cache;3496struct _objc_protocol_list *protocols;3497// Objective-C 1.0 extensions (<rdr://4585769>)3498const char *ivar_layout;3499struct _objc_class_ext *ext;3500};35013502See EmitClassExtension();3503*/3504void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {3505IdentifierInfo *RuntimeName =3506&CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());3507DefinedSymbols.insert(RuntimeName);35083509std::string ClassName = ID->getNameAsString();3510// FIXME: Gross3511ObjCInterfaceDecl *Interface =3512const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());3513llvm::Constant *Protocols =3514EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),3515Interface->all_referenced_protocol_begin(),3516Interface->all_referenced_protocol_end());3517unsigned Flags = FragileABI_Class_Factory;3518if (ID->hasNonZeroConstructors() || ID->hasDestructors())3519Flags |= FragileABI_Class_HasCXXStructors;35203521bool hasMRCWeak = false;35223523if (CGM.getLangOpts().ObjCAutoRefCount)3524Flags |= FragileABI_Class_CompiledByARC;3525else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))3526Flags |= FragileABI_Class_HasMRCWeakIvars;35273528CharUnits Size =3529CGM.getContext().getASTObjCImplementationLayout(ID).getSize();35303531// FIXME: Set CXX-structors flag.3532if (ID->getClassInterface()->getVisibility() == HiddenVisibility)3533Flags |= FragileABI_Class_Hidden;35343535enum {3536InstanceMethods,3537ClassMethods,3538NumMethodLists3539};3540SmallVector<const ObjCMethodDecl *, 16> Methods[NumMethodLists];3541for (const auto *MD : ID->methods()) {3542if (!MD->isDirectMethod())3543Methods[unsigned(MD->isClassMethod())].push_back(MD);3544}35453546for (const auto *PID : ID->property_impls()) {3547if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {3548if (PID->getPropertyDecl()->isDirectProperty())3549continue;3550if (ObjCMethodDecl *MD = PID->getGetterMethodDecl())3551if (GetMethodDefinition(MD))3552Methods[InstanceMethods].push_back(MD);3553if (ObjCMethodDecl *MD = PID->getSetterMethodDecl())3554if (GetMethodDefinition(MD))3555Methods[InstanceMethods].push_back(MD);3556}3557}35583559ConstantInitBuilder builder(CGM);3560auto values = builder.beginStruct(ObjCTypes.ClassTy);3561values.add(EmitMetaClass(ID, Protocols, Methods[ClassMethods]));3562if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {3563// Record a reference to the super class.3564LazySymbols.insert(Super->getIdentifier());35653566values.add(GetClassName(Super->getObjCRuntimeNameAsString()));3567} else {3568values.addNullPointer(ObjCTypes.ClassPtrTy);3569}3570values.add(GetClassName(ID->getObjCRuntimeNameAsString()));3571// Version is always 0.3572values.addInt(ObjCTypes.LongTy, 0);3573values.addInt(ObjCTypes.LongTy, Flags);3574values.addInt(ObjCTypes.LongTy, Size.getQuantity());3575values.add(EmitIvarList(ID, false));3576values.add(emitMethodList(ID->getName(), MethodListType::InstanceMethods,3577Methods[InstanceMethods]));3578// cache is always NULL.3579values.addNullPointer(ObjCTypes.CachePtrTy);3580values.add(Protocols);3581values.add(BuildStrongIvarLayout(ID, CharUnits::Zero(), Size));3582values.add(EmitClassExtension(ID, Size, hasMRCWeak,3583/*isMetaclass*/ false));35843585std::string Name("OBJC_CLASS_");3586Name += ClassName;3587const char *Section = "__OBJC,__class,regular,no_dead_strip";3588// Check for a forward reference.3589llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);3590if (GV) {3591assert(GV->getValueType() == ObjCTypes.ClassTy &&3592"Forward metaclass reference has incorrect type.");3593values.finishAndSetAsInitializer(GV);3594GV->setSection(Section);3595GV->setAlignment(CGM.getPointerAlign().getAsAlign());3596CGM.addCompilerUsedGlobal(GV);3597} else3598GV = CreateMetadataVar(Name, values, Section, CGM.getPointerAlign(), true);3599DefinedClasses.push_back(GV);3600ImplementedClasses.push_back(Interface);3601// method definition entries must be clear for next implementation.3602MethodDefinitions.clear();3603}36043605llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,3606llvm::Constant *Protocols,3607ArrayRef<const ObjCMethodDecl*> Methods) {3608unsigned Flags = FragileABI_Class_Meta;3609unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);36103611if (ID->getClassInterface()->getVisibility() == HiddenVisibility)3612Flags |= FragileABI_Class_Hidden;36133614ConstantInitBuilder builder(CGM);3615auto values = builder.beginStruct(ObjCTypes.ClassTy);3616// The isa for the metaclass is the root of the hierarchy.3617const ObjCInterfaceDecl *Root = ID->getClassInterface();3618while (const ObjCInterfaceDecl *Super = Root->getSuperClass())3619Root = Super;3620values.add(GetClassName(Root->getObjCRuntimeNameAsString()));3621// The super class for the metaclass is emitted as the name of the3622// super class. The runtime fixes this up to point to the3623// *metaclass* for the super class.3624if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {3625values.add(GetClassName(Super->getObjCRuntimeNameAsString()));3626} else {3627values.addNullPointer(ObjCTypes.ClassPtrTy);3628}3629values.add(GetClassName(ID->getObjCRuntimeNameAsString()));3630// Version is always 0.3631values.addInt(ObjCTypes.LongTy, 0);3632values.addInt(ObjCTypes.LongTy, Flags);3633values.addInt(ObjCTypes.LongTy, Size);3634values.add(EmitIvarList(ID, true));3635values.add(emitMethodList(ID->getName(), MethodListType::ClassMethods,3636Methods));3637// cache is always NULL.3638values.addNullPointer(ObjCTypes.CachePtrTy);3639values.add(Protocols);3640// ivar_layout for metaclass is always NULL.3641values.addNullPointer(ObjCTypes.Int8PtrTy);3642// The class extension is used to store class properties for metaclasses.3643values.add(EmitClassExtension(ID, CharUnits::Zero(), false/*hasMRCWeak*/,3644/*isMetaclass*/true));36453646std::string Name("OBJC_METACLASS_");3647Name += ID->getName();36483649// Check for a forward reference.3650llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);3651if (GV) {3652assert(GV->getValueType() == ObjCTypes.ClassTy &&3653"Forward metaclass reference has incorrect type.");3654values.finishAndSetAsInitializer(GV);3655} else {3656GV = values.finishAndCreateGlobal(Name, CGM.getPointerAlign(),3657/*constant*/ false,3658llvm::GlobalValue::PrivateLinkage);3659}3660GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");3661CGM.addCompilerUsedGlobal(GV);36623663return GV;3664}36653666llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {3667std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();36683669// FIXME: Should we look these up somewhere other than the module. Its a bit3670// silly since we only generate these while processing an implementation, so3671// exactly one pointer would work if know when we entered/exitted an3672// implementation block.36733674// Check for an existing forward reference.3675// Previously, metaclass with internal linkage may have been defined.3676// pass 'true' as 2nd argument so it is returned.3677llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);3678if (!GV)3679GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,3680llvm::GlobalValue::PrivateLinkage, nullptr,3681Name);36823683assert(GV->getValueType() == ObjCTypes.ClassTy &&3684"Forward metaclass reference has incorrect type.");3685return GV;3686}36873688llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {3689std::string Name = "OBJC_CLASS_" + ID->getNameAsString();3690llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);36913692if (!GV)3693GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,3694llvm::GlobalValue::PrivateLinkage, nullptr,3695Name);36963697assert(GV->getValueType() == ObjCTypes.ClassTy &&3698"Forward class metadata reference has incorrect type.");3699return GV;3700}37013702/*3703Emit a "class extension", which in this specific context means extra3704data that doesn't fit in the normal fragile-ABI class structure, and3705has nothing to do with the language concept of a class extension.37063707struct objc_class_ext {3708uint32_t size;3709const char *weak_ivar_layout;3710struct _objc_property_list *properties;3711};3712*/3713llvm::Constant *3714CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID,3715CharUnits InstanceSize, bool hasMRCWeakIvars,3716bool isMetaclass) {3717// Weak ivar layout.3718llvm::Constant *layout;3719if (isMetaclass) {3720layout = llvm::ConstantPointerNull::get(CGM.Int8PtrTy);3721} else {3722layout = BuildWeakIvarLayout(ID, CharUnits::Zero(), InstanceSize,3723hasMRCWeakIvars);3724}37253726// Properties.3727llvm::Constant *propertyList =3728EmitPropertyList((isMetaclass ? Twine("_OBJC_$_CLASS_PROP_LIST_")3729: Twine("_OBJC_$_PROP_LIST_"))3730+ ID->getName(),3731ID, ID->getClassInterface(), ObjCTypes, isMetaclass);37323733// Return null if no extension bits are used.3734if (layout->isNullValue() && propertyList->isNullValue()) {3735return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);3736}37373738uint64_t size =3739CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);37403741ConstantInitBuilder builder(CGM);3742auto values = builder.beginStruct(ObjCTypes.ClassExtensionTy);3743values.addInt(ObjCTypes.IntTy, size);3744values.add(layout);3745values.add(propertyList);37463747return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), values,3748"__OBJC,__class_ext,regular,no_dead_strip",3749CGM.getPointerAlign(), true);3750}37513752/*3753struct objc_ivar {3754char *ivar_name;3755char *ivar_type;3756int ivar_offset;3757};37583759struct objc_ivar_list {3760int ivar_count;3761struct objc_ivar list[count];3762};3763*/3764llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,3765bool ForClass) {3766// When emitting the root class GCC emits ivar entries for the3767// actual class structure. It is not clear if we need to follow this3768// behavior; for now lets try and get away with not doing it. If so,3769// the cleanest solution would be to make up an ObjCInterfaceDecl3770// for the class.3771if (ForClass)3772return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);37733774const ObjCInterfaceDecl *OID = ID->getClassInterface();37753776ConstantInitBuilder builder(CGM);3777auto ivarList = builder.beginStruct();3778auto countSlot = ivarList.addPlaceholder();3779auto ivars = ivarList.beginArray(ObjCTypes.IvarTy);37803781for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();3782IVD; IVD = IVD->getNextIvar()) {3783// Ignore unnamed bit-fields.3784if (!IVD->getDeclName())3785continue;37863787auto ivar = ivars.beginStruct(ObjCTypes.IvarTy);3788ivar.add(GetMethodVarName(IVD->getIdentifier()));3789ivar.add(GetMethodVarType(IVD));3790ivar.addInt(ObjCTypes.IntTy, ComputeIvarBaseOffset(CGM, OID, IVD));3791ivar.finishAndAddTo(ivars);3792}37933794// Return null for empty list.3795auto count = ivars.size();3796if (count == 0) {3797ivars.abandon();3798ivarList.abandon();3799return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);3800}38013802ivars.finishAndAddTo(ivarList);3803ivarList.fillPlaceholderWithInt(countSlot, ObjCTypes.IntTy, count);38043805llvm::GlobalVariable *GV;3806GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), ivarList,3807"__OBJC,__instance_vars,regular,no_dead_strip",3808CGM.getPointerAlign(), true);3809return GV;3810}38113812/// Build a struct objc_method_description constant for the given method.3813///3814/// struct objc_method_description {3815/// SEL method_name;3816/// char *method_types;3817/// };3818void CGObjCMac::emitMethodDescriptionConstant(ConstantArrayBuilder &builder,3819const ObjCMethodDecl *MD) {3820auto description = builder.beginStruct(ObjCTypes.MethodDescriptionTy);3821description.add(GetMethodVarName(MD->getSelector()));3822description.add(GetMethodVarType(MD));3823description.finishAndAddTo(builder);3824}38253826/// Build a struct objc_method constant for the given method.3827///3828/// struct objc_method {3829/// SEL method_name;3830/// char *method_types;3831/// void *method;3832/// };3833void CGObjCMac::emitMethodConstant(ConstantArrayBuilder &builder,3834const ObjCMethodDecl *MD) {3835llvm::Function *fn = GetMethodDefinition(MD);3836assert(fn && "no definition registered for method");38373838auto method = builder.beginStruct(ObjCTypes.MethodTy);3839method.add(GetMethodVarName(MD->getSelector()));3840method.add(GetMethodVarType(MD));3841method.add(fn);3842method.finishAndAddTo(builder);3843}38443845/// Build a struct objc_method_list or struct objc_method_description_list,3846/// as appropriate.3847///3848/// struct objc_method_list {3849/// struct objc_method_list *obsolete;3850/// int count;3851/// struct objc_method methods_list[count];3852/// };3853///3854/// struct objc_method_description_list {3855/// int count;3856/// struct objc_method_description list[count];3857/// };3858llvm::Constant *CGObjCMac::emitMethodList(Twine name, MethodListType MLT,3859ArrayRef<const ObjCMethodDecl *> methods) {3860StringRef prefix;3861StringRef section;3862bool forProtocol = false;3863switch (MLT) {3864case MethodListType::CategoryInstanceMethods:3865prefix = "OBJC_CATEGORY_INSTANCE_METHODS_";3866section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";3867forProtocol = false;3868break;3869case MethodListType::CategoryClassMethods:3870prefix = "OBJC_CATEGORY_CLASS_METHODS_";3871section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";3872forProtocol = false;3873break;3874case MethodListType::InstanceMethods:3875prefix = "OBJC_INSTANCE_METHODS_";3876section = "__OBJC,__inst_meth,regular,no_dead_strip";3877forProtocol = false;3878break;3879case MethodListType::ClassMethods:3880prefix = "OBJC_CLASS_METHODS_";3881section = "__OBJC,__cls_meth,regular,no_dead_strip";3882forProtocol = false;3883break;3884case MethodListType::ProtocolInstanceMethods:3885prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_";3886section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";3887forProtocol = true;3888break;3889case MethodListType::ProtocolClassMethods:3890prefix = "OBJC_PROTOCOL_CLASS_METHODS_";3891section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";3892forProtocol = true;3893break;3894case MethodListType::OptionalProtocolInstanceMethods:3895prefix = "OBJC_PROTOCOL_INSTANCE_METHODS_OPT_";3896section = "__OBJC,__cat_inst_meth,regular,no_dead_strip";3897forProtocol = true;3898break;3899case MethodListType::OptionalProtocolClassMethods:3900prefix = "OBJC_PROTOCOL_CLASS_METHODS_OPT_";3901section = "__OBJC,__cat_cls_meth,regular,no_dead_strip";3902forProtocol = true;3903break;3904}39053906// Return null for empty list.3907if (methods.empty())3908return llvm::Constant::getNullValue(forProtocol3909? ObjCTypes.MethodDescriptionListPtrTy3910: ObjCTypes.MethodListPtrTy);39113912// For protocols, this is an objc_method_description_list, which has3913// a slightly different structure.3914if (forProtocol) {3915ConstantInitBuilder builder(CGM);3916auto values = builder.beginStruct();3917values.addInt(ObjCTypes.IntTy, methods.size());3918auto methodArray = values.beginArray(ObjCTypes.MethodDescriptionTy);3919for (auto MD : methods) {3920emitMethodDescriptionConstant(methodArray, MD);3921}3922methodArray.finishAndAddTo(values);39233924llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,3925CGM.getPointerAlign(), true);3926return GV;3927}39283929// Otherwise, it's an objc_method_list.3930ConstantInitBuilder builder(CGM);3931auto values = builder.beginStruct();3932values.addNullPointer(ObjCTypes.Int8PtrTy);3933values.addInt(ObjCTypes.IntTy, methods.size());3934auto methodArray = values.beginArray(ObjCTypes.MethodTy);3935for (auto MD : methods) {3936if (!MD->isDirectMethod())3937emitMethodConstant(methodArray, MD);3938}3939methodArray.finishAndAddTo(values);39403941llvm::GlobalVariable *GV = CreateMetadataVar(prefix + name, values, section,3942CGM.getPointerAlign(), true);3943return GV;3944}39453946llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,3947const ObjCContainerDecl *CD) {3948llvm::Function *Method;39493950if (OMD->isDirectMethod()) {3951Method = GenerateDirectMethod(OMD, CD);3952} else {3953auto Name = getSymbolNameForMethod(OMD);39543955CodeGenTypes &Types = CGM.getTypes();3956llvm::FunctionType *MethodTy =3957Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));3958Method =3959llvm::Function::Create(MethodTy, llvm::GlobalValue::InternalLinkage,3960Name, &CGM.getModule());3961}39623963MethodDefinitions.insert(std::make_pair(OMD, Method));39643965return Method;3966}39673968llvm::Function *3969CGObjCCommonMac::GenerateDirectMethod(const ObjCMethodDecl *OMD,3970const ObjCContainerDecl *CD) {3971auto *COMD = OMD->getCanonicalDecl();3972auto I = DirectMethodDefinitions.find(COMD);3973llvm::Function *OldFn = nullptr, *Fn = nullptr;39743975if (I != DirectMethodDefinitions.end()) {3976// Objective-C allows for the declaration and implementation types3977// to differ slightly.3978//3979// If we're being asked for the Function associated for a method3980// implementation, a previous value might have been cached3981// based on the type of the canonical declaration.3982//3983// If these do not match, then we'll replace this function with3984// a new one that has the proper type below.3985if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())3986return I->second;3987OldFn = I->second;3988}39893990CodeGenTypes &Types = CGM.getTypes();3991llvm::FunctionType *MethodTy =3992Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));39933994if (OldFn) {3995Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,3996"", &CGM.getModule());3997Fn->takeName(OldFn);3998OldFn->replaceAllUsesWith(Fn);3999OldFn->eraseFromParent();40004001// Replace the cached function in the map.4002I->second = Fn;4003} else {4004auto Name = getSymbolNameForMethod(OMD, /*include category*/ false);40054006Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage,4007Name, &CGM.getModule());4008DirectMethodDefinitions.insert(std::make_pair(COMD, Fn));4009}40104011return Fn;4012}40134014void CGObjCCommonMac::GenerateDirectMethodPrologue(4015CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,4016const ObjCContainerDecl *CD) {4017auto &Builder = CGF.Builder;4018bool ReceiverCanBeNull = true;4019auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());4020auto selfValue = Builder.CreateLoad(selfAddr);40214022// Generate:4023//4024// /* for class methods only to force class lazy initialization */4025// self = [self self];4026//4027// /* unless the receiver is never NULL */4028// if (self == nil) {4029// return (ReturnType){ };4030// }4031//4032// _cmd = @selector(...)4033// ...40344035if (OMD->isClassMethod()) {4036const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);4037assert(OID &&4038"GenerateDirectMethod() should be called with the Class Interface");4039Selector SelfSel = GetNullarySelector("self", CGM.getContext());4040auto ResultType = CGF.getContext().getObjCIdType();4041RValue result;4042CallArgList Args;40434044// TODO: If this method is inlined, the caller might know that `self` is4045// already initialized; for example, it might be an ordinary Objective-C4046// method which always receives an initialized `self`, or it might have just4047// forced initialization on its own.4048//4049// We should find a way to eliminate this unnecessary initialization in such4050// cases in LLVM.4051result = GeneratePossiblySpecializedMessageSend(4052CGF, ReturnValueSlot(), ResultType, SelfSel, selfValue, Args, OID,4053nullptr, true);4054Builder.CreateStore(result.getScalarVal(), selfAddr);40554056// Nullable `Class` expressions cannot be messaged with a direct method4057// so the only reason why the receive can be null would be because4058// of weak linking.4059ReceiverCanBeNull = isWeakLinkedClass(OID);4060}40614062if (ReceiverCanBeNull) {4063llvm::BasicBlock *SelfIsNilBlock =4064CGF.createBasicBlock("objc_direct_method.self_is_nil");4065llvm::BasicBlock *ContBlock =4066CGF.createBasicBlock("objc_direct_method.cont");40674068// if (self == nil) {4069auto selfTy = cast<llvm::PointerType>(selfValue->getType());4070auto Zero = llvm::ConstantPointerNull::get(selfTy);40714072llvm::MDBuilder MDHelper(CGM.getLLVMContext());4073Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero), SelfIsNilBlock,4074ContBlock, MDHelper.createUnlikelyBranchWeights());40754076CGF.EmitBlock(SelfIsNilBlock);40774078// return (ReturnType){ };4079auto retTy = OMD->getReturnType();4080Builder.SetInsertPoint(SelfIsNilBlock);4081if (!retTy->isVoidType()) {4082CGF.EmitNullInitialization(CGF.ReturnValue, retTy);4083}4084CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);4085// }40864087// rest of the body4088CGF.EmitBlock(ContBlock);4089Builder.SetInsertPoint(ContBlock);4090}40914092// only synthesize _cmd if it's referenced4093if (OMD->getCmdDecl()->isUsed()) {4094// `_cmd` is not a parameter to direct methods, so storage must be4095// explicitly declared for it.4096CGF.EmitVarDecl(*OMD->getCmdDecl());4097Builder.CreateStore(GetSelector(CGF, OMD),4098CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));4099}4100}41014102llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,4103ConstantStructBuilder &Init,4104StringRef Section,4105CharUnits Align,4106bool AddToUsed) {4107llvm::GlobalValue::LinkageTypes LT =4108getLinkageTypeForObjCMetadata(CGM, Section);4109llvm::GlobalVariable *GV =4110Init.finishAndCreateGlobal(Name, Align, /*constant*/ false, LT);4111if (!Section.empty())4112GV->setSection(Section);4113if (AddToUsed)4114CGM.addCompilerUsedGlobal(GV);4115return GV;4116}41174118llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,4119llvm::Constant *Init,4120StringRef Section,4121CharUnits Align,4122bool AddToUsed) {4123llvm::Type *Ty = Init->getType();4124llvm::GlobalValue::LinkageTypes LT =4125getLinkageTypeForObjCMetadata(CGM, Section);4126llvm::GlobalVariable *GV =4127new llvm::GlobalVariable(CGM.getModule(), Ty, false, LT, Init, Name);4128if (!Section.empty())4129GV->setSection(Section);4130GV->setAlignment(Align.getAsAlign());4131if (AddToUsed)4132CGM.addCompilerUsedGlobal(GV);4133return GV;4134}41354136llvm::GlobalVariable *4137CGObjCCommonMac::CreateCStringLiteral(StringRef Name, ObjCLabelType Type,4138bool ForceNonFragileABI,4139bool NullTerminate) {4140StringRef Label;4141switch (Type) {4142case ObjCLabelType::ClassName: Label = "OBJC_CLASS_NAME_"; break;4143case ObjCLabelType::MethodVarName: Label = "OBJC_METH_VAR_NAME_"; break;4144case ObjCLabelType::MethodVarType: Label = "OBJC_METH_VAR_TYPE_"; break;4145case ObjCLabelType::PropertyName: Label = "OBJC_PROP_NAME_ATTR_"; break;4146}41474148bool NonFragile = ForceNonFragileABI || isNonFragileABI();41494150StringRef Section;4151switch (Type) {4152case ObjCLabelType::ClassName:4153Section = NonFragile ? "__TEXT,__objc_classname,cstring_literals"4154: "__TEXT,__cstring,cstring_literals";4155break;4156case ObjCLabelType::MethodVarName:4157Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"4158: "__TEXT,__cstring,cstring_literals";4159break;4160case ObjCLabelType::MethodVarType:4161Section = NonFragile ? "__TEXT,__objc_methtype,cstring_literals"4162: "__TEXT,__cstring,cstring_literals";4163break;4164case ObjCLabelType::PropertyName:4165Section = NonFragile ? "__TEXT,__objc_methname,cstring_literals"4166: "__TEXT,__cstring,cstring_literals";4167break;4168}41694170llvm::Constant *Value =4171llvm::ConstantDataArray::getString(VMContext, Name, NullTerminate);4172llvm::GlobalVariable *GV =4173new llvm::GlobalVariable(CGM.getModule(), Value->getType(),4174/*isConstant=*/true,4175llvm::GlobalValue::PrivateLinkage, Value, Label);4176if (CGM.getTriple().isOSBinFormatMachO())4177GV->setSection(Section);4178GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);4179GV->setAlignment(CharUnits::One().getAsAlign());4180CGM.addCompilerUsedGlobal(GV);41814182return GV;4183}41844185llvm::Function *CGObjCMac::ModuleInitFunction() {4186// Abuse this interface function as a place to finalize.4187FinishModule();4188return nullptr;4189}41904191llvm::FunctionCallee CGObjCMac::GetPropertyGetFunction() {4192return ObjCTypes.getGetPropertyFn();4193}41944195llvm::FunctionCallee CGObjCMac::GetPropertySetFunction() {4196return ObjCTypes.getSetPropertyFn();4197}41984199llvm::FunctionCallee CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,4200bool copy) {4201return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);4202}42034204llvm::FunctionCallee CGObjCMac::GetGetStructFunction() {4205return ObjCTypes.getCopyStructFn();4206}42074208llvm::FunctionCallee CGObjCMac::GetSetStructFunction() {4209return ObjCTypes.getCopyStructFn();4210}42114212llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectGetFunction() {4213return ObjCTypes.getCppAtomicObjectFunction();4214}42154216llvm::FunctionCallee CGObjCMac::GetCppAtomicObjectSetFunction() {4217return ObjCTypes.getCppAtomicObjectFunction();4218}42194220llvm::FunctionCallee CGObjCMac::EnumerationMutationFunction() {4221return ObjCTypes.getEnumerationMutationFn();4222}42234224void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {4225return EmitTryOrSynchronizedStmt(CGF, S);4226}42274228void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,4229const ObjCAtSynchronizedStmt &S) {4230return EmitTryOrSynchronizedStmt(CGF, S);4231}42324233namespace {4234struct PerformFragileFinally final : EHScopeStack::Cleanup {4235const Stmt &S;4236Address SyncArgSlot;4237Address CallTryExitVar;4238Address ExceptionData;4239ObjCTypesHelper &ObjCTypes;4240PerformFragileFinally(const Stmt *S,4241Address SyncArgSlot,4242Address CallTryExitVar,4243Address ExceptionData,4244ObjCTypesHelper *ObjCTypes)4245: S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),4246ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}42474248void Emit(CodeGenFunction &CGF, Flags flags) override {4249// Check whether we need to call objc_exception_try_exit.4250// In optimized code, this branch will always be folded.4251llvm::BasicBlock *FinallyCallExit =4252CGF.createBasicBlock("finally.call_exit");4253llvm::BasicBlock *FinallyNoCallExit =4254CGF.createBasicBlock("finally.no_call_exit");4255CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),4256FinallyCallExit, FinallyNoCallExit);42574258CGF.EmitBlock(FinallyCallExit);4259CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),4260ExceptionData.emitRawPointer(CGF));42614262CGF.EmitBlock(FinallyNoCallExit);42634264if (isa<ObjCAtTryStmt>(S)) {4265if (const ObjCAtFinallyStmt* FinallyStmt =4266cast<ObjCAtTryStmt>(S).getFinallyStmt()) {4267// Don't try to do the @finally if this is an EH cleanup.4268if (flags.isForEHCleanup()) return;42694270// Save the current cleanup destination in case there's4271// control flow inside the finally statement.4272llvm::Value *CurCleanupDest =4273CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());42744275CGF.EmitStmt(FinallyStmt->getFinallyBody());42764277if (CGF.HaveInsertPoint()) {4278CGF.Builder.CreateStore(CurCleanupDest,4279CGF.getNormalCleanupDestSlot());4280} else {4281// Currently, the end of the cleanup must always exist.4282CGF.EnsureInsertPoint();4283}4284}4285} else {4286// Emit objc_sync_exit(expr); as finally's sole statement for4287// @synchronized.4288llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);4289CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);4290}4291}4292};42934294class FragileHazards {4295CodeGenFunction &CGF;4296SmallVector<llvm::Value*, 20> Locals;4297llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;42984299llvm::InlineAsm *ReadHazard;4300llvm::InlineAsm *WriteHazard;43014302llvm::FunctionType *GetAsmFnType();43034304void collectLocals();4305void emitReadHazard(CGBuilderTy &Builder);43064307public:4308FragileHazards(CodeGenFunction &CGF);43094310void emitWriteHazard();4311void emitHazardsInNewBlocks();4312};4313} // end anonymous namespace43144315/// Create the fragile-ABI read and write hazards based on the current4316/// state of the function, which is presumed to be immediately prior4317/// to a @try block. These hazards are used to maintain correct4318/// semantics in the face of optimization and the fragile ABI's4319/// cavalier use of setjmp/longjmp.4320FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {4321collectLocals();43224323if (Locals.empty()) return;43244325// Collect all the blocks in the function.4326for (llvm::Function::iterator4327I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)4328BlocksBeforeTry.insert(&*I);43294330llvm::FunctionType *AsmFnTy = GetAsmFnType();43314332// Create a read hazard for the allocas. This inhibits dead-store4333// optimizations and forces the values to memory. This hazard is4334// inserted before any 'throwing' calls in the protected scope to4335// reflect the possibility that the variables might be read from the4336// catch block if the call throws.4337{4338std::string Constraint;4339for (unsigned I = 0, E = Locals.size(); I != E; ++I) {4340if (I) Constraint += ',';4341Constraint += "*m";4342}43434344ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);4345}43464347// Create a write hazard for the allocas. This inhibits folding4348// loads across the hazard. This hazard is inserted at the4349// beginning of the catch path to reflect the possibility that the4350// variables might have been written within the protected scope.4351{4352std::string Constraint;4353for (unsigned I = 0, E = Locals.size(); I != E; ++I) {4354if (I) Constraint += ',';4355Constraint += "=*m";4356}43574358WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);4359}4360}43614362/// Emit a write hazard at the current location.4363void FragileHazards::emitWriteHazard() {4364if (Locals.empty()) return;43654366llvm::CallInst *Call = CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);4367for (auto Pair : llvm::enumerate(Locals))4368Call->addParamAttr(Pair.index(), llvm::Attribute::get(4369CGF.getLLVMContext(), llvm::Attribute::ElementType,4370cast<llvm::AllocaInst>(Pair.value())->getAllocatedType()));4371}43724373void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {4374assert(!Locals.empty());4375llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);4376call->setDoesNotThrow();4377call->setCallingConv(CGF.getRuntimeCC());4378for (auto Pair : llvm::enumerate(Locals))4379call->addParamAttr(Pair.index(), llvm::Attribute::get(4380Builder.getContext(), llvm::Attribute::ElementType,4381cast<llvm::AllocaInst>(Pair.value())->getAllocatedType()));4382}43834384/// Emit read hazards in all the protected blocks, i.e. all the blocks4385/// which have been inserted since the beginning of the try.4386void FragileHazards::emitHazardsInNewBlocks() {4387if (Locals.empty()) return;43884389CGBuilderTy Builder(CGF, CGF.getLLVMContext());43904391// Iterate through all blocks, skipping those prior to the try.4392for (llvm::Function::iterator4393FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {4394llvm::BasicBlock &BB = *FI;4395if (BlocksBeforeTry.count(&BB)) continue;43964397// Walk through all the calls in the block.4398for (llvm::BasicBlock::iterator4399BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {4400llvm::Instruction &I = *BI;44014402// Ignore instructions that aren't non-intrinsic calls.4403// These are the only calls that can possibly call longjmp.4404if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I))4405continue;4406if (isa<llvm::IntrinsicInst>(I))4407continue;44084409// Ignore call sites marked nounwind. This may be questionable,4410// since 'nounwind' doesn't necessarily mean 'does not call longjmp'.4411if (cast<llvm::CallBase>(I).doesNotThrow())4412continue;44134414// Insert a read hazard before the call. This will ensure that4415// any writes to the locals are performed before making the4416// call. If the call throws, then this is sufficient to4417// guarantee correctness as long as it doesn't also write to any4418// locals.4419Builder.SetInsertPoint(&BB, BI);4420emitReadHazard(Builder);4421}4422}4423}44244425static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, Address V) {4426if (V.isValid())4427if (llvm::Value *Ptr = V.getBasePointer())4428S.insert(Ptr);4429}44304431void FragileHazards::collectLocals() {4432// Compute a set of allocas to ignore.4433llvm::DenseSet<llvm::Value*> AllocasToIgnore;4434addIfPresent(AllocasToIgnore, CGF.ReturnValue);4435addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);44364437// Collect all the allocas currently in the function. This is4438// probably way too aggressive.4439llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();4440for (llvm::BasicBlock::iterator4441I = Entry.begin(), E = Entry.end(); I != E; ++I)4442if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))4443Locals.push_back(&*I);4444}44454446llvm::FunctionType *FragileHazards::GetAsmFnType() {4447SmallVector<llvm::Type *, 16> tys(Locals.size());4448for (unsigned i = 0, e = Locals.size(); i != e; ++i)4449tys[i] = Locals[i]->getType();4450return llvm::FunctionType::get(CGF.VoidTy, tys, false);4451}44524453/*44544455Objective-C setjmp-longjmp (sjlj) Exception Handling4456--44574458A catch buffer is a setjmp buffer plus:4459- a pointer to the exception that was caught4460- a pointer to the previous exception data buffer4461- two pointers of reserved storage4462Therefore catch buffers form a stack, with a pointer to the top4463of the stack kept in thread-local storage.44644465objc_exception_try_enter pushes a catch buffer onto the EH stack.4466objc_exception_try_exit pops the given catch buffer, which is4467required to be the top of the EH stack.4468objc_exception_throw pops the top of the EH stack, writes the4469thrown exception into the appropriate field, and longjmps4470to the setjmp buffer. It crashes the process (with a printf4471and an abort()) if there are no catch buffers on the stack.4472objc_exception_extract just reads the exception pointer out of the4473catch buffer.44744475There's no reason an implementation couldn't use a light-weight4476setjmp here --- something like __builtin_setjmp, but API-compatible4477with the heavyweight setjmp. This will be more important if we ever4478want to implement correct ObjC/C++ exception interactions for the4479fragile ABI.44804481Note that for this use of setjmp/longjmp to be correct in the presence of4482optimization, we use inline assembly on the set of local variables to force4483flushing locals to memory immediately before any protected calls and to4484inhibit optimizing locals across the setjmp->catch edge.44854486The basic framework for a @try-catch-finally is as follows:4487{4488objc_exception_data d;4489id _rethrow = null;4490bool _call_try_exit = true;44914492objc_exception_try_enter(&d);4493if (!setjmp(d.jmp_buf)) {4494... try body ...4495} else {4496// exception path4497id _caught = objc_exception_extract(&d);44984499// enter new try scope for handlers4500if (!setjmp(d.jmp_buf)) {4501... match exception and execute catch blocks ...45024503// fell off end, rethrow.4504_rethrow = _caught;4505... jump-through-finally to finally_rethrow ...4506} else {4507// exception in catch block4508_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 ...45144515finally:4516if (_call_try_exit)4517objc_exception_try_exit(&d);45184519... finally block ....4520... dispatch to finally destination ...45214522finally_rethrow:4523objc_exception_throw(_rethrow);45244525finally_end:4526}45274528This framework differs slightly from the one gcc uses, in that gcc4529uses _rethrow to determine if objc_exception_try_exit should be called4530and if the object should be rethrown. This breaks in the face of4531throwing nil and introduces unnecessary branches.45324533We specialize this framework for a few particular circumstances:45344535- If there are no catch blocks, then we avoid emitting the second4536exception handling context.45374538- If there is a catch-all catch block (i.e. @catch(...) or @catch(id4539e)) we avoid emitting the code to rethrow an uncaught exception.45404541- FIXME: If there is no @finally block we can do a few more4542simplifications.45434544Rethrows and Jumps-Through-Finally4545--45464547'@throw;' is supported by pushing the currently-caught exception4548onto ObjCEHStack while the @catch blocks are emitted.45494550Branches through the @finally block are handled with an ordinary4551normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC4552exceptions are not compatible with C++ exceptions, and this is4553hardly the only place where this will go wrong.45544555@synchronized(expr) { stmt; } is emitted as if it were:4556id synch_value = expr;4557objc_sync_enter(synch_value);4558@try { stmt; } @finally { objc_sync_exit(synch_value); }4559*/45604561void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,4562const Stmt &S) {4563bool isTry = isa<ObjCAtTryStmt>(S);45644565// A destination for the fall-through edges of the catch handlers to4566// jump to.4567CodeGenFunction::JumpDest FinallyEnd =4568CGF.getJumpDestInCurrentScope("finally.end");45694570// A destination for the rethrow edge of the catch handlers to jump4571// to.4572CodeGenFunction::JumpDest FinallyRethrow =4573CGF.getJumpDestInCurrentScope("finally.rethrow");45744575// For @synchronized, call objc_sync_enter(sync.expr). The4576// evaluation of the expression must occur before we enter the4577// @synchronized. We can't avoid a temp here because we need the4578// value to be preserved. If the backend ever does liveness4579// correctly after setjmp, this will be unnecessary.4580Address SyncArgSlot = Address::invalid();4581if (!isTry) {4582llvm::Value *SyncArg =4583CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());4584SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);4585CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);45864587SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(),4588CGF.getPointerAlign(), "sync.arg");4589CGF.Builder.CreateStore(SyncArg, SyncArgSlot);4590}45914592// Allocate memory for the setjmp buffer. This needs to be kept4593// live throughout the try and catch blocks.4594Address ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,4595CGF.getPointerAlign(),4596"exceptiondata.ptr");45974598// Create the fragile hazards. Note that this will not capture any4599// of the allocas required for exception processing, but will4600// capture the current basic block (which extends all the way to the4601// setjmp call) as "before the @try".4602FragileHazards Hazards(CGF);46034604// Create a flag indicating whether the cleanup needs to call4605// objc_exception_try_exit. This is true except when4606// - no catches match and we're branching through the cleanup4607// just to rethrow the exception, or4608// - 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 this4610// variable in a place that dominates the branch through the cleanup4611// without passing through any setjmps.4612Address CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),4613CharUnits::One(),4614"_call_try_exit");46154616// A slot containing the exception to rethrow. Only needed when we4617// have both a @catch and a @finally.4618Address PropagatingExnVar = Address::invalid();46194620// Push a normal cleanup to leave the try scope.4621CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,4622SyncArgSlot,4623CallTryExitVar,4624ExceptionData,4625&ObjCTypes);46264627// Enter a try block:4628// - Call objc_exception_try_enter to push ExceptionData on top of4629// the EH stack.4630CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),4631ExceptionData.emitRawPointer(CGF));46324633// - Call setjmp on the exception data buffer.4634llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);4635llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };4636llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(4637ObjCTypes.ExceptionDataTy, ExceptionData.emitRawPointer(CGF), GEPIndexes,4638"setjmp_buffer");4639llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(4640ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");4641SetJmpResult->setCanReturnTwice();46424643// If setjmp returned 0, enter the protected block; otherwise,4644// branch to the handler.4645llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");4646llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");4647llvm::Value *DidCatch =4648CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");4649CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);46504651// Emit the protected block.4652CGF.EmitBlock(TryBlock);4653CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);4654CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()4655: cast<ObjCAtSynchronizedStmt>(S).getSynchBody());46564657CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();46584659// Emit the exception handler block.4660CGF.EmitBlock(TryHandler);46614662// Don't optimize loads of the in-scope locals across this point.4663Hazards.emitWriteHazard();46644665// For a @synchronized (or a @try with no catches), just branch4666// through the cleanup to the rethrow block.4667if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {4668// Tell the cleanup not to re-pop the exit.4669CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);4670CGF.EmitBranchThroughCleanup(FinallyRethrow);46714672// Otherwise, we have to match against the caught exceptions.4673} else {4674// Retrieve the exception object. We may emit multiple blocks but4675// nothing can cross this so the value is already in SSA form.4676llvm::CallInst *Caught = CGF.EmitNounwindRuntimeCall(4677ObjCTypes.getExceptionExtractFn(), ExceptionData.emitRawPointer(CGF),4678"caught");46794680// Push the exception to rethrow onto the EH value stack for the4681// benefit of any @throws in the handlers.4682CGF.ObjCEHValueStack.push_back(Caught);46834684const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);46854686bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);46874688llvm::BasicBlock *CatchBlock = nullptr;4689llvm::BasicBlock *CatchHandler = nullptr;4690if (HasFinally) {4691// Save the currently-propagating exception before4692// objc_exception_try_enter clears the exception slot.4693PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),4694CGF.getPointerAlign(),4695"propagating_exception");4696CGF.Builder.CreateStore(Caught, PropagatingExnVar);46974698// Enter a new exception try block (in case a @catch block4699// throws an exception).4700CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),4701ExceptionData.emitRawPointer(CGF));47024703llvm::CallInst *SetJmpResult =4704CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),4705SetJmpBuffer, "setjmp.result");4706SetJmpResult->setCanReturnTwice();47074708llvm::Value *Threw =4709CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");47104711CatchBlock = CGF.createBasicBlock("catch");4712CatchHandler = CGF.createBasicBlock("catch_for_catch");4713CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);47144715CGF.EmitBlock(CatchBlock);4716}47174718CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);47194720// Handle catch list. As a special case we check if everything is4721// matched and avoid generating code for falling off the end if4722// so.4723bool AllMatched = false;4724for (const ObjCAtCatchStmt *CatchStmt : AtTryStmt->catch_stmts()) {4725const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();4726const ObjCObjectPointerType *OPT = nullptr;47274728// catch(...) always matches.4729if (!CatchParam) {4730AllMatched = true;4731} else {4732OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();47334734// catch(id e) always matches under this ABI, since only4735// ObjC exceptions end up here in the first place.4736// FIXME: For the time being we also match id<X>; this should4737// be rejected by Sema instead.4738if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))4739AllMatched = true;4740}47414742// If this is a catch-all, we don't need to test anything.4743if (AllMatched) {4744CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);47454746if (CatchParam) {4747CGF.EmitAutoVarDecl(*CatchParam);4748assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");47494750// These types work out because ConvertType(id) == i8*.4751EmitInitOfCatchParam(CGF, Caught, CatchParam);4752}47534754CGF.EmitStmt(CatchStmt->getCatchBody());47554756// The scope of the catch variable ends right here.4757CatchVarCleanups.ForceCleanup();47584759CGF.EmitBranchThroughCleanup(FinallyEnd);4760break;4761}47624763assert(OPT && "Unexpected non-object pointer type in @catch");4764const ObjCObjectType *ObjTy = OPT->getObjectType();47654766// FIXME: @catch (Class c) ?4767ObjCInterfaceDecl *IDecl = ObjTy->getInterface();4768assert(IDecl && "Catch parameter must have Objective-C type!");47694770// Check if the @catch block matches the exception object.4771llvm::Value *Class = EmitClassRef(CGF, IDecl);47724773llvm::Value *matchArgs[] = { Class, Caught };4774llvm::CallInst *Match =4775CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),4776matchArgs, "match");47774778llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");4779llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");47804781CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),4782MatchedBlock, NextCatchBlock);47834784// Emit the @catch block.4785CGF.EmitBlock(MatchedBlock);47864787// Collect any cleanups for the catch variable. The scope lasts until4788// the end of the catch body.4789CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);47904791CGF.EmitAutoVarDecl(*CatchParam);4792assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");47934794// Initialize the catch variable.4795llvm::Value *Tmp =4796CGF.Builder.CreateBitCast(Caught,4797CGF.ConvertType(CatchParam->getType()));4798EmitInitOfCatchParam(CGF, Tmp, CatchParam);47994800CGF.EmitStmt(CatchStmt->getCatchBody());48014802// We're done with the catch variable.4803CatchVarCleanups.ForceCleanup();48044805CGF.EmitBranchThroughCleanup(FinallyEnd);48064807CGF.EmitBlock(NextCatchBlock);4808}48094810CGF.ObjCEHValueStack.pop_back();48114812// If nothing wanted anything to do with the caught exception,4813// kill the extract call.4814if (Caught->use_empty())4815Caught->eraseFromParent();48164817if (!AllMatched)4818CGF.EmitBranchThroughCleanup(FinallyRethrow);48194820if (HasFinally) {4821// Emit the exception handler for the @catch blocks.4822CGF.EmitBlock(CatchHandler);48234824// In theory we might now need a write hazard, but actually it's4825// unnecessary because there's no local-accessing code between4826// the try's write hazard and here.4827//Hazards.emitWriteHazard();48284829// Extract the new exception and save it to the4830// propagating-exception slot.4831assert(PropagatingExnVar.isValid());4832llvm::CallInst *NewCaught = CGF.EmitNounwindRuntimeCall(4833ObjCTypes.getExceptionExtractFn(), ExceptionData.emitRawPointer(CGF),4834"caught");4835CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);48364837// Don't pop the catch handler; the throw already did.4838CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);4839CGF.EmitBranchThroughCleanup(FinallyRethrow);4840}4841}48424843// Insert read hazards as required in the new blocks.4844Hazards.emitHazardsInNewBlocks();48454846// Pop the cleanup.4847CGF.Builder.restoreIP(TryFallthroughIP);4848if (CGF.HaveInsertPoint())4849CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);4850CGF.PopCleanupBlock();4851CGF.EmitBlock(FinallyEnd.getBlock(), true);48524853// Emit the rethrow block.4854CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();4855CGF.EmitBlock(FinallyRethrow.getBlock(), true);4856if (CGF.HaveInsertPoint()) {4857// If we have a propagating-exception variable, check it.4858llvm::Value *PropagatingExn;4859if (PropagatingExnVar.isValid()) {4860PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);48614862// Otherwise, just look in the buffer for the exception to throw.4863} else {4864llvm::CallInst *Caught = CGF.EmitNounwindRuntimeCall(4865ObjCTypes.getExceptionExtractFn(), ExceptionData.emitRawPointer(CGF));4866PropagatingExn = Caught;4867}48684869CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),4870PropagatingExn);4871CGF.Builder.CreateUnreachable();4872}48734874CGF.Builder.restoreIP(SavedIP);4875}48764877void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,4878const ObjCAtThrowStmt &S,4879bool ClearInsertionPoint) {4880llvm::Value *ExceptionAsObject;48814882if (const Expr *ThrowExpr = S.getThrowExpr()) {4883llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);4884ExceptionAsObject =4885CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);4886} else {4887assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&4888"Unexpected rethrow outside @catch block.");4889ExceptionAsObject = CGF.ObjCEHValueStack.back();4890}48914892CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)4893->setDoesNotReturn();4894CGF.Builder.CreateUnreachable();48954896// Clear the insertion point to indicate we are in unreachable code.4897if (ClearInsertionPoint)4898CGF.Builder.ClearInsertionPoint();4899}49004901/// EmitObjCWeakRead - Code gen for loading value of a __weak4902/// object: objc_read_weak (id *src)4903///4904llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,4905Address AddrWeakObj) {4906llvm::Type* DestTy = AddrWeakObj.getElementType();4907llvm::Value *AddrWeakObjVal = CGF.Builder.CreateBitCast(4908AddrWeakObj.emitRawPointer(CGF), ObjCTypes.PtrObjectPtrTy);4909llvm::Value *read_weak =4910CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),4911AddrWeakObjVal, "weakread");4912read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);4913return read_weak;4914}49154916/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.4917/// objc_assign_weak (id src, id *dst)4918///4919void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,4920llvm::Value *src, Address dst) {4921llvm::Type * SrcTy = src->getType();4922if (!isa<llvm::PointerType>(SrcTy)) {4923unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);4924assert(Size <= 8 && "does not support size > 8");4925src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)4926: CGF.Builder.CreateBitCast(src, CGM.Int64Ty);4927src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);4928}4929src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);4930llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),4931ObjCTypes.PtrObjectPtrTy);4932llvm::Value *args[] = { src, dstVal };4933CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),4934args, "weakassign");4935}49364937/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.4938/// objc_assign_global (id src, id *dst)4939///4940void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,4941llvm::Value *src, Address dst,4942bool threadlocal) {4943llvm::Type * SrcTy = src->getType();4944if (!isa<llvm::PointerType>(SrcTy)) {4945unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);4946assert(Size <= 8 && "does not support size > 8");4947src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)4948: CGF.Builder.CreateBitCast(src, CGM.Int64Ty);4949src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);4950}4951src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);4952llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),4953ObjCTypes.PtrObjectPtrTy);4954llvm::Value *args[] = {src, dstVal};4955if (!threadlocal)4956CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),4957args, "globalassign");4958else4959CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),4960args, "threadlocalassign");4961}49624963/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.4964/// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)4965///4966void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,4967llvm::Value *src, Address dst,4968llvm::Value *ivarOffset) {4969assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");4970llvm::Type * SrcTy = src->getType();4971if (!isa<llvm::PointerType>(SrcTy)) {4972unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);4973assert(Size <= 8 && "does not support size > 8");4974src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)4975: CGF.Builder.CreateBitCast(src, CGM.Int64Ty);4976src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);4977}4978src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);4979llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),4980ObjCTypes.PtrObjectPtrTy);4981llvm::Value *args[] = {src, dstVal, ivarOffset};4982CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);4983}49844985/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.4986/// objc_assign_strongCast (id src, id *dst)4987///4988void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,4989llvm::Value *src, Address dst) {4990llvm::Type * SrcTy = src->getType();4991if (!isa<llvm::PointerType>(SrcTy)) {4992unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);4993assert(Size <= 8 && "does not support size > 8");4994src = (Size == 4) ? CGF.Builder.CreateBitCast(src, CGM.Int32Ty)4995: CGF.Builder.CreateBitCast(src, CGM.Int64Ty);4996src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);4997}4998src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);4999llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),5000ObjCTypes.PtrObjectPtrTy);5001llvm::Value *args[] = {src, dstVal};5002CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),5003args, "strongassign");5004}50055006void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,5007Address DestPtr, Address SrcPtr,5008llvm::Value *size) {5009llvm::Value *args[] = {DestPtr.emitRawPointer(CGF),5010SrcPtr.emitRawPointer(CGF), size};5011CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);5012}50135014/// EmitObjCValueForIvar - Code Gen for ivar reference.5015///5016LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,5017QualType ObjectTy,5018llvm::Value *BaseValue,5019const ObjCIvarDecl *Ivar,5020unsigned CVRQualifiers) {5021const ObjCInterfaceDecl *ID =5022ObjectTy->castAs<ObjCObjectType>()->getInterface();5023return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,5024EmitIvarOffset(CGF, ID, Ivar));5025}50265027llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,5028const ObjCInterfaceDecl *Interface,5029const ObjCIvarDecl *Ivar) {5030uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);5031return llvm::ConstantInt::get(5032CGM.getTypes().ConvertType(CGM.getContext().LongTy),5033Offset);5034}50355036/* *** Private Interface *** */50375038std::string CGObjCCommonMac::GetSectionName(StringRef Section,5039StringRef MachOAttributes) {5040switch (CGM.getTriple().getObjectFormat()) {5041case llvm::Triple::UnknownObjectFormat:5042llvm_unreachable("unexpected object file format");5043case llvm::Triple::MachO: {5044if (MachOAttributes.empty())5045return ("__DATA," + Section).str();5046return ("__DATA," + Section + "," + MachOAttributes).str();5047}5048case llvm::Triple::ELF:5049assert(Section.starts_with("__") && "expected the name to begin with __");5050return Section.substr(2).str();5051case llvm::Triple::COFF:5052assert(Section.starts_with("__") && "expected the name to begin with __");5053return ("." + Section.substr(2) + "$B").str();5054case llvm::Triple::Wasm:5055case llvm::Triple::GOFF:5056case llvm::Triple::SPIRV:5057case llvm::Triple::XCOFF:5058case llvm::Triple::DXContainer:5059llvm::report_fatal_error(5060"Objective-C support is unimplemented for object file format");5061}50625063llvm_unreachable("Unhandled llvm::Triple::ObjectFormatType enum");5064}50655066/// EmitImageInfo - Emit the image info marker used to encode some module5067/// level information.5068///5069/// See: <rdr://4810609&4810587&4810587>5070/// struct IMAGE_INFO {5071/// unsigned version;5072/// unsigned flags;5073/// };5074enum ImageInfoFlags {5075eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.5076eImageInfo_GarbageCollected = (1 << 1),5077eImageInfo_GCOnly = (1 << 2),5078eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.50795080// A flag indicating that the module has no instances of a @synthesize of a5081// superclass variable. This flag used to be consumed by the runtime to work5082// around miscompile by gcc.5083eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.5084eImageInfo_ImageIsSimulated = (1 << 5),5085eImageInfo_ClassProperties = (1 << 6)5086};50875088void CGObjCCommonMac::EmitImageInfo() {5089unsigned version = 0; // Version is unused?5090std::string Section =5091(ObjCABI == 1)5092? "__OBJC,__image_info,regular"5093: GetSectionName("__objc_imageinfo", "regular,no_dead_strip");50945095// Generate module-level named metadata to convey this information to the5096// linker and code-gen.5097llvm::Module &Mod = CGM.getModule();50985099// Add the ObjC ABI version to the module flags.5100Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);5101Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",5102version);5103Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",5104llvm::MDString::get(VMContext, Section));51055106auto Int8Ty = llvm::Type::getInt8Ty(VMContext);5107if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {5108// Non-GC overrides those files which specify GC.5109Mod.addModuleFlag(llvm::Module::Error,5110"Objective-C Garbage Collection",5111llvm::ConstantInt::get(Int8Ty,0));5112} else {5113// Add the ObjC garbage collection value.5114Mod.addModuleFlag(llvm::Module::Error,5115"Objective-C Garbage Collection",5116llvm::ConstantInt::get(Int8Ty,5117(uint8_t)eImageInfo_GarbageCollected));51185119if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {5120// Add the ObjC GC Only value.5121Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",5122eImageInfo_GCOnly);51235124// Require that GC be specified and set to eImageInfo_GarbageCollected.5125llvm::Metadata *Ops[2] = {5126llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),5127llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(5128Int8Ty, eImageInfo_GarbageCollected))};5129Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",5130llvm::MDNode::get(VMContext, Ops));5131}5132}51335134// Indicate whether we're compiling this to run on a simulator.5135if (CGM.getTarget().getTriple().isSimulatorEnvironment())5136Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",5137eImageInfo_ImageIsSimulated);51385139// Indicate whether we are generating class properties.5140Mod.addModuleFlag(llvm::Module::Error, "Objective-C Class Properties",5141eImageInfo_ClassProperties);5142}51435144// struct objc_module {5145// unsigned long version;5146// unsigned long size;5147// const char *name;5148// Symtab symtab;5149// };51505151// FIXME: Get from somewhere5152static const int ModuleVersion = 7;51535154void CGObjCMac::EmitModuleInfo() {5155uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);51565157ConstantInitBuilder builder(CGM);5158auto values = builder.beginStruct(ObjCTypes.ModuleTy);5159values.addInt(ObjCTypes.LongTy, ModuleVersion);5160values.addInt(ObjCTypes.LongTy, Size);5161// This used to be the filename, now it is unused. <rdr://4327263>5162values.add(GetClassName(StringRef("")));5163values.add(EmitModuleSymbols());5164CreateMetadataVar("OBJC_MODULES", values,5165"__OBJC,__module_info,regular,no_dead_strip",5166CGM.getPointerAlign(), true);5167}51685169llvm::Constant *CGObjCMac::EmitModuleSymbols() {5170unsigned NumClasses = DefinedClasses.size();5171unsigned NumCategories = DefinedCategories.size();51725173// Return null if no symbols were defined.5174if (!NumClasses && !NumCategories)5175return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);51765177ConstantInitBuilder builder(CGM);5178auto values = builder.beginStruct();5179values.addInt(ObjCTypes.LongTy, 0);5180values.addNullPointer(ObjCTypes.SelectorPtrTy);5181values.addInt(ObjCTypes.ShortTy, NumClasses);5182values.addInt(ObjCTypes.ShortTy, NumCategories);51835184// The runtime expects exactly the list of defined classes followed5185// by the list of defined categories, in a single array.5186auto array = values.beginArray(ObjCTypes.Int8PtrTy);5187for (unsigned i=0; i<NumClasses; i++) {5188const ObjCInterfaceDecl *ID = ImplementedClasses[i];5189assert(ID);5190if (ObjCImplementationDecl *IMP = ID->getImplementation())5191// We are implementing a weak imported interface. Give it external linkage5192if (ID->isWeakImported() && !IMP->isWeakImported())5193DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);51945195array.add(DefinedClasses[i]);5196}5197for (unsigned i=0; i<NumCategories; i++)5198array.add(DefinedCategories[i]);51995200array.finishAndAddTo(values);52015202llvm::GlobalVariable *GV = CreateMetadataVar(5203"OBJC_SYMBOLS", values, "__OBJC,__symbols,regular,no_dead_strip",5204CGM.getPointerAlign(), true);5205return GV;5206}52075208llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,5209IdentifierInfo *II) {5210LazySymbols.insert(II);52115212llvm::GlobalVariable *&Entry = ClassReferences[II];52135214if (!Entry) {5215Entry =5216CreateMetadataVar("OBJC_CLASS_REFERENCES_", GetClassName(II->getName()),5217"__OBJC,__cls_refs,literal_pointers,no_dead_strip",5218CGM.getPointerAlign(), true);5219}52205221return CGF.Builder.CreateAlignedLoad(Entry->getValueType(), Entry,5222CGF.getPointerAlign());5223}52245225llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,5226const ObjCInterfaceDecl *ID) {5227// If the class has the objc_runtime_visible attribute, we need to5228// use the Objective-C runtime to get the class.5229if (ID->hasAttr<ObjCRuntimeVisibleAttr>())5230return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);52315232IdentifierInfo *RuntimeName =5233&CGM.getContext().Idents.get(ID->getObjCRuntimeNameAsString());5234return EmitClassRefFromId(CGF, RuntimeName);5235}52365237llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {5238IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");5239return EmitClassRefFromId(CGF, II);5240}52415242llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel) {5243return CGF.Builder.CreateLoad(EmitSelectorAddr(Sel));5244}52455246ConstantAddress CGObjCMac::EmitSelectorAddr(Selector Sel) {5247CharUnits Align = CGM.getPointerAlign();52485249llvm::GlobalVariable *&Entry = SelectorReferences[Sel];5250if (!Entry) {5251Entry = CreateMetadataVar(5252"OBJC_SELECTOR_REFERENCES_", GetMethodVarName(Sel),5253"__OBJC,__message_refs,literal_pointers,no_dead_strip", Align, true);5254Entry->setExternallyInitialized(true);5255}52565257return ConstantAddress(Entry, ObjCTypes.SelectorPtrTy, Align);5258}52595260llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {5261llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];5262if (!Entry)5263Entry = CreateCStringLiteral(RuntimeName, ObjCLabelType::ClassName);5264return getConstantGEP(VMContext, Entry, 0, 0);5265}52665267llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {5268return MethodDefinitions.lookup(MD);5269}52705271/// GetIvarLayoutName - Returns a unique constant for the given5272/// ivar layout bitmap.5273llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,5274const ObjCCommonTypesHelper &ObjCTypes) {5275return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);5276}52775278void IvarLayoutBuilder::visitRecord(const RecordType *RT,5279CharUnits offset) {5280const RecordDecl *RD = RT->getDecl();52815282// If this is a union, remember that we had one, because it might mess5283// up the ordering of layout entries.5284if (RD->isUnion())5285IsDisordered = true;52865287const ASTRecordLayout *recLayout = nullptr;5288visitAggregate(RD->field_begin(), RD->field_end(), offset,5289[&](const FieldDecl *field) -> CharUnits {5290if (!recLayout)5291recLayout = &CGM.getContext().getASTRecordLayout(RD);5292auto offsetInBits = recLayout->getFieldOffset(field->getFieldIndex());5293return CGM.getContext().toCharUnitsFromBits(offsetInBits);5294});5295}52965297template <class Iterator, class GetOffsetFn>5298void IvarLayoutBuilder::visitAggregate(Iterator begin, Iterator end,5299CharUnits aggregateOffset,5300const GetOffsetFn &getOffset) {5301for (; begin != end; ++begin) {5302auto field = *begin;53035304// Skip over bitfields.5305if (field->isBitField()) {5306continue;5307}53085309// Compute the offset of the field within the aggregate.5310CharUnits fieldOffset = aggregateOffset + getOffset(field);53115312visitField(field, fieldOffset);5313}5314}53155316/// Collect layout information for the given fields into IvarsInfo.5317void IvarLayoutBuilder::visitField(const FieldDecl *field,5318CharUnits fieldOffset) {5319QualType fieldType = field->getType();53205321// Drill down into arrays.5322uint64_t numElts = 1;5323if (auto arrayType = CGM.getContext().getAsIncompleteArrayType(fieldType)) {5324numElts = 0;5325fieldType = arrayType->getElementType();5326}5327// Unlike incomplete arrays, constant arrays can be nested.5328while (auto arrayType = CGM.getContext().getAsConstantArrayType(fieldType)) {5329numElts *= arrayType->getZExtSize();5330fieldType = arrayType->getElementType();5331}53325333assert(!fieldType->isArrayType() && "ivar of non-constant array type?");53345335// If we ended up with a zero-sized array, we've done what we can do within5336// the limits of this layout encoding.5337if (numElts == 0) return;53385339// Recurse if the base element type is a record type.5340if (auto recType = fieldType->getAs<RecordType>()) {5341size_t oldEnd = IvarsInfo.size();53425343visitRecord(recType, fieldOffset);53445345// If we have an array, replicate the first entry's layout information.5346auto numEltEntries = IvarsInfo.size() - oldEnd;5347if (numElts != 1 && numEltEntries != 0) {5348CharUnits eltSize = CGM.getContext().getTypeSizeInChars(recType);5349for (uint64_t eltIndex = 1; eltIndex != numElts; ++eltIndex) {5350// Copy the last numEltEntries onto the end of the array, adjusting5351// each for the element size.5352for (size_t i = 0; i != numEltEntries; ++i) {5353auto firstEntry = IvarsInfo[oldEnd + i];5354IvarsInfo.push_back(IvarInfo(firstEntry.Offset + eltIndex * eltSize,5355firstEntry.SizeInWords));5356}5357}5358}53595360return;5361}53625363// Classify the element type.5364Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), fieldType);53655366// If it matches what we're looking for, add an entry.5367if ((ForStrongLayout && GCAttr == Qualifiers::Strong)5368|| (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {5369assert(CGM.getContext().getTypeSizeInChars(fieldType)5370== CGM.getPointerSize());5371IvarsInfo.push_back(IvarInfo(fieldOffset, numElts));5372}5373}53745375/// buildBitmap - This routine does the horsework of taking the offsets of5376/// strong/weak references and creating a bitmap. The bitmap is also5377/// returned in the given buffer, suitable for being passed to \c dump().5378llvm::Constant *IvarLayoutBuilder::buildBitmap(CGObjCCommonMac &CGObjC,5379llvm::SmallVectorImpl<unsigned char> &buffer) {5380// The bitmap is a series of skip/scan instructions, aligned to word5381// boundaries. The skip is performed first.5382const unsigned char MaxNibble = 0xF;5383const unsigned char SkipMask = 0xF0, SkipShift = 4;5384const unsigned char ScanMask = 0x0F, ScanShift = 0;53855386assert(!IvarsInfo.empty() && "generating bitmap for no data");53875388// Sort the ivar info on byte position in case we encounterred a5389// union nested in the ivar list.5390if (IsDisordered) {5391// This isn't a stable sort, but our algorithm should handle it fine.5392llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());5393} else {5394assert(llvm::is_sorted(IvarsInfo));5395}5396assert(IvarsInfo.back().Offset < InstanceEnd);53975398assert(buffer.empty());53995400// Skip the next N words.5401auto skip = [&](unsigned numWords) {5402assert(numWords > 0);54035404// Try to merge into the previous byte. Since scans happen second, we5405// can't do this if it includes a scan.5406if (!buffer.empty() && !(buffer.back() & ScanMask)) {5407unsigned lastSkip = buffer.back() >> SkipShift;5408if (lastSkip < MaxNibble) {5409unsigned claimed = std::min(MaxNibble - lastSkip, numWords);5410numWords -= claimed;5411lastSkip += claimed;5412buffer.back() = (lastSkip << SkipShift);5413}5414}54155416while (numWords >= MaxNibble) {5417buffer.push_back(MaxNibble << SkipShift);5418numWords -= MaxNibble;5419}5420if (numWords) {5421buffer.push_back(numWords << SkipShift);5422}5423};54245425// Scan the next N words.5426auto scan = [&](unsigned numWords) {5427assert(numWords > 0);54285429// Try to merge into the previous byte. Since scans happen second, we can5430// do this even if it includes a skip.5431if (!buffer.empty()) {5432unsigned lastScan = (buffer.back() & ScanMask) >> ScanShift;5433if (lastScan < MaxNibble) {5434unsigned claimed = std::min(MaxNibble - lastScan, numWords);5435numWords -= claimed;5436lastScan += claimed;5437buffer.back() = (buffer.back() & SkipMask) | (lastScan << ScanShift);5438}5439}54405441while (numWords >= MaxNibble) {5442buffer.push_back(MaxNibble << ScanShift);5443numWords -= MaxNibble;5444}5445if (numWords) {5446buffer.push_back(numWords << ScanShift);5447}5448};54495450// One past the end of the last scan.5451unsigned endOfLastScanInWords = 0;5452const CharUnits WordSize = CGM.getPointerSize();54535454// Consider all the scan requests.5455for (auto &request : IvarsInfo) {5456CharUnits beginOfScan = request.Offset - InstanceBegin;54575458// Ignore scan requests that don't start at an even multiple of the5459// word size. We can't encode them.5460if ((beginOfScan % WordSize) != 0) continue;54615462// Ignore scan requests that start before the instance start.5463// This assumes that scans never span that boundary. The boundary5464// isn't the true start of the ivars, because in the fragile-ARC case5465// it's rounded up to word alignment, but the test above should leave5466// us ignoring that possibility.5467if (beginOfScan.isNegative()) {5468assert(request.Offset + request.SizeInWords * WordSize <= InstanceBegin);5469continue;5470}54715472unsigned beginOfScanInWords = beginOfScan / WordSize;5473unsigned endOfScanInWords = beginOfScanInWords + request.SizeInWords;54745475// If the scan starts some number of words after the last one ended,5476// skip forward.5477if (beginOfScanInWords > endOfLastScanInWords) {5478skip(beginOfScanInWords - endOfLastScanInWords);54795480// Otherwise, start scanning where the last left off.5481} else {5482beginOfScanInWords = endOfLastScanInWords;54835484// If that leaves us with nothing to scan, ignore this request.5485if (beginOfScanInWords >= endOfScanInWords) continue;5486}54875488// Scan to the end of the request.5489assert(beginOfScanInWords < endOfScanInWords);5490scan(endOfScanInWords - beginOfScanInWords);5491endOfLastScanInWords = endOfScanInWords;5492}54935494if (buffer.empty())5495return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);54965497// For GC layouts, emit a skip to the end of the allocation so that we5498// have precise information about the entire thing. This isn't useful5499// or necessary for the ARC-style layout strings.5500if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {5501unsigned lastOffsetInWords =5502(InstanceEnd - InstanceBegin + WordSize - CharUnits::One()) / WordSize;5503if (lastOffsetInWords > endOfLastScanInWords) {5504skip(lastOffsetInWords - endOfLastScanInWords);5505}5506}55075508// Null terminate the string.5509buffer.push_back(0);55105511auto *Entry = CGObjC.CreateCStringLiteral(5512reinterpret_cast<char *>(buffer.data()), ObjCLabelType::ClassName);5513return getConstantGEP(CGM.getLLVMContext(), Entry, 0, 0);5514}55155516/// BuildIvarLayout - Builds ivar layout bitmap for the class5517/// implementation for the __strong or __weak case.5518/// The layout map displays which words in ivar list must be skipped5519/// 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 count5521/// of words to skip and right nibble is count of words to scan. So, each5522/// nibble represents up to 15 workds to skip or scan. Skipping the rest is5523/// represented by a 0x00 byte which also ends the string.5524/// 1. when ForStrongLayout is true, following ivars are scanned:5525/// - id, Class5526/// - object *5527/// - __strong anything5528///5529/// 2. When ForStrongLayout is false, following ivars are scanned:5530/// - __weak anything5531///5532llvm::Constant *5533CGObjCCommonMac::BuildIvarLayout(const ObjCImplementationDecl *OMD,5534CharUnits beginOffset, CharUnits endOffset,5535bool ForStrongLayout, bool HasMRCWeakIvars) {5536// If this is MRC, and we're either building a strong layout or there5537// are no weak ivars, bail out early.5538llvm::Type *PtrTy = CGM.Int8PtrTy;5539if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&5540!CGM.getLangOpts().ObjCAutoRefCount &&5541(ForStrongLayout || !HasMRCWeakIvars))5542return llvm::Constant::getNullValue(PtrTy);55435544const ObjCInterfaceDecl *OI = OMD->getClassInterface();5545SmallVector<const ObjCIvarDecl*, 32> ivars;55465547// GC layout strings include the complete object layout, possibly5548// inaccurately in the non-fragile ABI; the runtime knows how to fix this5549// up.5550//5551// ARC layout strings only include the class's ivars. In non-fragile5552// runtimes, that means starting at InstanceStart, rounded up to word5553// alignment. In fragile runtimes, there's no InstanceStart, so it means5554// starting at the offset of the first ivar, rounded up to word alignment.5555//5556// MRC weak layout strings follow the ARC style.5557CharUnits baseOffset;5558if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {5559for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();5560IVD; IVD = IVD->getNextIvar())5561ivars.push_back(IVD);55625563if (isNonFragileABI()) {5564baseOffset = beginOffset; // InstanceStart5565} else if (!ivars.empty()) {5566baseOffset =5567CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivars[0]));5568} else {5569baseOffset = CharUnits::Zero();5570}55715572baseOffset = baseOffset.alignTo(CGM.getPointerAlign());5573}5574else {5575CGM.getContext().DeepCollectObjCIvars(OI, true, ivars);55765577baseOffset = CharUnits::Zero();5578}55795580if (ivars.empty())5581return llvm::Constant::getNullValue(PtrTy);55825583IvarLayoutBuilder builder(CGM, baseOffset, endOffset, ForStrongLayout);55845585builder.visitAggregate(ivars.begin(), ivars.end(), CharUnits::Zero(),5586[&](const ObjCIvarDecl *ivar) -> CharUnits {5587return CharUnits::fromQuantity(ComputeIvarBaseOffset(CGM, OMD, ivar));5588});55895590if (!builder.hasBitmapData())5591return llvm::Constant::getNullValue(PtrTy);55925593llvm::SmallVector<unsigned char, 4> buffer;5594llvm::Constant *C = builder.buildBitmap(*this, buffer);55955596if (CGM.getLangOpts().ObjCGCBitmapPrint && !buffer.empty()) {5597printf("\n%s ivar layout for class '%s': ",5598ForStrongLayout ? "strong" : "weak",5599OMD->getClassInterface()->getName().str().c_str());5600builder.dump(buffer);5601}5602return C;5603}56045605llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {5606llvm::GlobalVariable *&Entry = MethodVarNames[Sel];5607// FIXME: Avoid std::string in "Sel.getAsString()"5608if (!Entry)5609Entry = CreateCStringLiteral(Sel.getAsString(), ObjCLabelType::MethodVarName);5610return getConstantGEP(VMContext, Entry, 0, 0);5611}56125613// FIXME: Merge into a single cstring creation function.5614llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {5615return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));5616}56175618llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {5619std::string TypeStr;5620CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);56215622llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];5623if (!Entry)5624Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);5625return getConstantGEP(VMContext, Entry, 0, 0);5626}56275628llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,5629bool Extended) {5630std::string TypeStr =5631CGM.getContext().getObjCEncodingForMethodDecl(D, Extended);56325633llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];5634if (!Entry)5635Entry = CreateCStringLiteral(TypeStr, ObjCLabelType::MethodVarType);5636return getConstantGEP(VMContext, Entry, 0, 0);5637}56385639// FIXME: Merge into a single cstring creation function.5640llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {5641llvm::GlobalVariable *&Entry = PropertyNames[Ident];5642if (!Entry)5643Entry = CreateCStringLiteral(Ident->getName(), ObjCLabelType::PropertyName);5644return getConstantGEP(VMContext, Entry, 0, 0);5645}56465647// FIXME: Merge into a single cstring creation function.5648// FIXME: This Decl should be more precise.5649llvm::Constant *5650CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,5651const Decl *Container) {5652std::string TypeStr =5653CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);5654return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));5655}56565657void CGObjCMac::FinishModule() {5658EmitModuleInfo();56595660// Emit the dummy bodies for any protocols which were referenced but5661// never defined.5662for (auto &entry : Protocols) {5663llvm::GlobalVariable *global = entry.second;5664if (global->hasInitializer())5665continue;56665667ConstantInitBuilder builder(CGM);5668auto values = builder.beginStruct(ObjCTypes.ProtocolTy);5669values.addNullPointer(ObjCTypes.ProtocolExtensionPtrTy);5670values.add(GetClassName(entry.first->getName()));5671values.addNullPointer(ObjCTypes.ProtocolListPtrTy);5672values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);5673values.addNullPointer(ObjCTypes.MethodDescriptionListPtrTy);5674values.finishAndSetAsInitializer(global);5675CGM.addCompilerUsedGlobal(global);5676}56775678// Add assembler directives to add lazy undefined symbol references5679// for classes which are referenced but not defined. This is5680// important for correct linker interaction.5681//5682// FIXME: It would be nice if we had an LLVM construct for this.5683if ((!LazySymbols.empty() || !DefinedSymbols.empty()) &&5684CGM.getTriple().isOSBinFormatMachO()) {5685SmallString<256> Asm;5686Asm += CGM.getModule().getModuleInlineAsm();5687if (!Asm.empty() && Asm.back() != '\n')5688Asm += '\n';56895690llvm::raw_svector_ostream OS(Asm);5691for (const auto *Sym : DefinedSymbols)5692OS << "\t.objc_class_name_" << Sym->getName() << "=0\n"5693<< "\t.globl .objc_class_name_" << Sym->getName() << "\n";5694for (const auto *Sym : LazySymbols)5695OS << "\t.lazy_reference .objc_class_name_" << Sym->getName() << "\n";5696for (const auto &Category : DefinedCategoryNames)5697OS << "\t.objc_category_name_" << Category << "=0\n"5698<< "\t.globl .objc_category_name_" << Category << "\n";56995700CGM.getModule().setModuleInlineAsm(OS.str());5701}5702}57035704CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)5705: CGObjCCommonMac(cgm), ObjCTypes(cgm), ObjCEmptyCacheVar(nullptr),5706ObjCEmptyVtableVar(nullptr) {5707ObjCABI = 2;5708}57095710/* *** */57115712ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)5713: VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)5714{5715CodeGen::CodeGenTypes &Types = CGM.getTypes();5716ASTContext &Ctx = CGM.getContext();5717unsigned ProgramAS = CGM.getDataLayout().getProgramAddressSpace();57185719ShortTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.ShortTy));5720IntTy = CGM.IntTy;5721LongTy = cast<llvm::IntegerType>(Types.ConvertType(Ctx.LongTy));5722Int8PtrTy = CGM.Int8PtrTy;5723Int8PtrProgramASTy = llvm::PointerType::get(CGM.Int8Ty, ProgramAS);5724Int8PtrPtrTy = CGM.Int8PtrPtrTy;57255726// arm64 targets use "int" ivar offset variables. All others,5727// including OS X x86_64 and Windows x86_64, use "long" ivar offsets.5728if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)5729IvarOffsetVarTy = IntTy;5730else5731IvarOffsetVarTy = LongTy;57325733ObjectPtrTy =5734cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCIdType()));5735PtrObjectPtrTy =5736llvm::PointerType::getUnqual(ObjectPtrTy);5737SelectorPtrTy =5738cast<llvm::PointerType>(Types.ConvertType(Ctx.getObjCSelType()));57395740// I'm not sure I like this. The implicit coordination is a bit5741// gross. We should solve this in a reasonable fashion because this5742// is a pretty common task (match some runtime data structure with5743// an LLVM data structure).57445745// FIXME: This is leaked.5746// FIXME: Merge with rewriter code?57475748// struct _objc_super {5749// id self;5750// Class cls;5751// }5752RecordDecl *RD = RecordDecl::Create(5753Ctx, TagTypeKind::Struct, Ctx.getTranslationUnitDecl(), SourceLocation(),5754SourceLocation(), &Ctx.Idents.get("_objc_super"));5755RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),5756nullptr, Ctx.getObjCIdType(), nullptr, nullptr,5757false, ICIS_NoInit));5758RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),5759nullptr, Ctx.getObjCClassType(), nullptr,5760nullptr, false, ICIS_NoInit));5761RD->completeDefinition();57625763SuperCTy = Ctx.getTagDeclType(RD);5764SuperPtrCTy = Ctx.getPointerType(SuperCTy);57655766SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));5767SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);57685769// struct _prop_t {5770// char *name;5771// char *attributes;5772// }5773PropertyTy = llvm::StructType::create("struct._prop_t", Int8PtrTy, Int8PtrTy);57745775// 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// }5780PropertyListTy = llvm::StructType::create(5781"struct._prop_list_t", IntTy, IntTy, llvm::ArrayType::get(PropertyTy, 0));5782// struct _prop_list_t *5783PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);57845785// struct _objc_method {5786// SEL _cmd;5787// char *method_type;5788// char *_imp;5789// }5790MethodTy = llvm::StructType::create("struct._objc_method", SelectorPtrTy,5791Int8PtrTy, Int8PtrProgramASTy);57925793// struct _objc_cache *5794CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");5795CachePtrTy = llvm::PointerType::getUnqual(CacheTy);5796}57975798ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)5799: ObjCCommonTypesHelper(cgm) {5800// struct _objc_method_description {5801// SEL name;5802// char *types;5803// }5804MethodDescriptionTy = llvm::StructType::create(5805"struct._objc_method_description", SelectorPtrTy, Int8PtrTy);58065807// struct _objc_method_description_list {5808// int count;5809// struct _objc_method_description[1];5810// }5811MethodDescriptionListTy =5812llvm::StructType::create("struct._objc_method_description_list", IntTy,5813llvm::ArrayType::get(MethodDescriptionTy, 0));58145815// struct _objc_method_description_list *5816MethodDescriptionListPtrTy =5817llvm::PointerType::getUnqual(MethodDescriptionListTy);58185819// Protocol description structures58205821// 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// }5829ProtocolExtensionTy = llvm::StructType::create(5830"struct._objc_protocol_extension", IntTy, MethodDescriptionListPtrTy,5831MethodDescriptionListPtrTy, PropertyListPtrTy, Int8PtrPtrTy,5832PropertyListPtrTy);58335834// struct _objc_protocol_extension *5835ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);58365837// Handle recursive construction of Protocol and ProtocolList types58385839ProtocolTy =5840llvm::StructType::create(VMContext, "struct._objc_protocol");58415842ProtocolListTy =5843llvm::StructType::create(VMContext, "struct._objc_protocol_list");5844ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy), LongTy,5845llvm::ArrayType::get(ProtocolTy, 0));58465847// 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// }5854ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,5855llvm::PointerType::getUnqual(ProtocolListTy),5856MethodDescriptionListPtrTy, MethodDescriptionListPtrTy);58575858// struct _objc_protocol_list *5859ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);58605861ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);58625863// Class description structures58645865// struct _objc_ivar {5866// char *ivar_name;5867// char *ivar_type;5868// int ivar_offset;5869// }5870IvarTy = llvm::StructType::create("struct._objc_ivar", Int8PtrTy, Int8PtrTy,5871IntTy);58725873// struct _objc_ivar_list *5874IvarListTy =5875llvm::StructType::create(VMContext, "struct._objc_ivar_list");5876IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);58775878// struct _objc_method_list *5879MethodListTy =5880llvm::StructType::create(VMContext, "struct._objc_method_list");5881MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);58825883// struct _objc_class_extension *5884ClassExtensionTy = llvm::StructType::create(5885"struct._objc_class_extension", IntTy, Int8PtrTy, PropertyListPtrTy);5886ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);58875888ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");58895890// 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// };5904ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),5905llvm::PointerType::getUnqual(ClassTy), Int8PtrTy, LongTy,5906LongTy, LongTy, IvarListPtrTy, MethodListPtrTy, CachePtrTy,5907ProtocolListPtrTy, Int8PtrTy, ClassExtensionPtrTy);59085909ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);59105911// 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 @property5919// struct _objc_property_list *class_properties;5920// }5921CategoryTy = llvm::StructType::create(5922"struct._objc_category", Int8PtrTy, Int8PtrTy, MethodListPtrTy,5923MethodListPtrTy, ProtocolListPtrTy, IntTy, PropertyListPtrTy,5924PropertyListPtrTy);59255926// Global metadata structures59275928// 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// }5935SymtabTy = llvm::StructType::create("struct._objc_symtab", LongTy,5936SelectorPtrTy, ShortTy, ShortTy,5937llvm::ArrayType::get(Int8PtrTy, 0));5938SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);59395940// struct _objc_module {5941// long version;5942// long size; // sizeof(struct _objc_module)5943// char *name;5944// struct _objc_symtab* symtab;5945// }5946ModuleTy = llvm::StructType::create("struct._objc_module", LongTy, LongTy,5947Int8PtrTy, SymtabPtrTy);59485949// FIXME: This is the size of the setjmp buffer and should be target5950// specific. 18 is what's used on 32-bit X86.5951uint64_t SetJmpBufferSize = 18;59525953// Exceptions5954llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);59555956ExceptionDataTy = llvm::StructType::create(5957"struct._objc_exception_data",5958llvm::ArrayType::get(CGM.Int32Ty, SetJmpBufferSize), StackPtrTy);5959}59605961ObjCNonFragileABITypesHelper::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// }5968MethodListnfABITy =5969llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,5970llvm::ArrayType::get(MethodTy, 0));5971// struct method_list_t *5972MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);59735974// struct _protocol_t {5975// id isa; // NULL5976// const char * const protocol_name;5977// const struct _protocol_list_t * protocol_list; // super protocols5978// 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; // = 05985// const char ** extendedMethodTypes;5986// const char *demangledName;5987// const struct _prop_list_t * class_properties;5988// }59895990// Holder for struct _protocol_list_t *5991ProtocolListnfABITy =5992llvm::StructType::create(VMContext, "struct._objc_protocol_list");59935994ProtocolnfABITy = llvm::StructType::create(5995"struct._protocol_t", ObjectPtrTy, Int8PtrTy,5996llvm::PointerType::getUnqual(ProtocolListnfABITy), MethodListnfABIPtrTy,5997MethodListnfABIPtrTy, MethodListnfABIPtrTy, MethodListnfABIPtrTy,5998PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy, Int8PtrTy,5999PropertyListPtrTy);60006001// struct _protocol_t*6002ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);60036004// struct _protocol_list_t {6005// long protocol_count; // Note, this is 32/64 bit6006// struct _protocol_t *[protocol_count];6007// }6008ProtocolListnfABITy->setBody(LongTy,6009llvm::ArrayType::get(ProtocolnfABIPtrTy, 0));60106011// struct _objc_protocol_list*6012ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);60136014// struct _ivar_t {6015// unsigned [long] int *offset; // pointer to ivar offset location6016// char *name;6017// char *type;6018// uint32_t alignment;6019// uint32_t size;6020// }6021IvarnfABITy = llvm::StructType::create(6022"struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),6023Int8PtrTy, Int8PtrTy, IntTy, IntTy);60246025// struct _ivar_list_t {6026// uint32 entsize; // sizeof(struct _ivar_t)6027// uint32 count;6028// struct _iver_t list[count];6029// }6030IvarListnfABITy =6031llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,6032llvm::ArrayType::get(IvarnfABITy, 0));60336034IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);60356036// 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 targets6041// 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// }60496050// FIXME. Add 'reserved' field in 64bit abi mode!6051ClassRonfABITy = llvm::StructType::create(6052"struct._class_ro_t", IntTy, IntTy, IntTy, Int8PtrTy, Int8PtrTy,6053MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, IvarListnfABIPtrTy,6054Int8PtrTy, PropertyListPtrTy);60556056// ImpnfABITy - LLVM for id (*)(id, SEL, ...)6057llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };6058ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)6059->getPointerTo();60606061// 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// }60686069ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");6070ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),6071llvm::PointerType::getUnqual(ClassnfABITy), CachePtrTy,6072llvm::PointerType::getUnqual(ImpnfABITy),6073llvm::PointerType::getUnqual(ClassRonfABITy));60746075// LLVM for struct _class_t *6076ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);60776078// 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// }6088CategorynfABITy = llvm::StructType::create(6089"struct._category_t", Int8PtrTy, ClassnfABIPtrTy, MethodListnfABIPtrTy,6090MethodListnfABIPtrTy, ProtocolListnfABIPtrTy, PropertyListPtrTy,6091PropertyListPtrTy, IntTy);60926093// New types for nonfragile abi messaging.6094CodeGen::CodeGenTypes &Types = CGM.getTypes();6095ASTContext &Ctx = CGM.getContext();60966097// MessageRefTy - LLVM for:6098// struct _message_ref_t {6099// IMP messenger;6100// SEL name;6101// };61026103// First the clang type for struct _message_ref_t6104RecordDecl *RD = RecordDecl::Create(6105Ctx, TagTypeKind::Struct, Ctx.getTranslationUnitDecl(), SourceLocation(),6106SourceLocation(), &Ctx.Idents.get("_message_ref_t"));6107RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),6108nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,6109ICIS_NoInit));6110RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),6111nullptr, Ctx.getObjCSelType(), nullptr, nullptr,6112false, ICIS_NoInit));6113RD->completeDefinition();61146115MessageRefCTy = Ctx.getTagDeclType(RD);6116MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);6117MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));61186119// MessageRefPtrTy - LLVM for struct _message_ref_t*6120MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);61216122// SuperMessageRefTy - LLVM for:6123// struct _super_message_ref_t {6124// SUPER_IMP messenger;6125// SEL name;6126// };6127SuperMessageRefTy = llvm::StructType::create("struct._super_message_ref_t",6128ImpnfABITy, SelectorPtrTy);61296130// SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*6131SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);613261336134// struct objc_typeinfo {6135// const void** vtable; // objc_ehtype_vtable + 26136// const char* name; // c++ typeinfo string6137// Class cls;6138// };6139EHTypeTy = llvm::StructType::create("struct._objc_typeinfo",6140llvm::PointerType::getUnqual(Int8PtrTy),6141Int8PtrTy, ClassnfABIPtrTy);6142EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);6143}61446145llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {6146FinishNonFragileABIModule();61476148return nullptr;6149}61506151void CGObjCNonFragileABIMac::AddModuleClassList(6152ArrayRef<llvm::GlobalValue *> Container, StringRef SymbolName,6153StringRef SectionName) {6154unsigned NumClasses = Container.size();61556156if (!NumClasses)6157return;61586159SmallVector<llvm::Constant*, 8> Symbols(NumClasses);6160for (unsigned i=0; i<NumClasses; i++)6161Symbols[i] = Container[i];61626163llvm::Constant *Init =6164llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,6165Symbols.size()),6166Symbols);61676168// Section name is obtained by calling GetSectionName, which returns6169// sections in the __DATA segment on MachO.6170assert((!CGM.getTriple().isOSBinFormatMachO() ||6171SectionName.starts_with("__DATA")) &&6172"SectionName expected to start with __DATA on MachO");6173llvm::GlobalVariable *GV = new llvm::GlobalVariable(6174CGM.getModule(), Init->getType(), false,6175llvm::GlobalValue::PrivateLinkage, Init, SymbolName);6176GV->setAlignment(CGM.getDataLayout().getABITypeAlign(Init->getType()));6177GV->setSection(SectionName);6178CGM.addCompilerUsedGlobal(GV);6179}61806181void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {6182// nonfragile abi has no module definition.61836184// Build list of all implemented class addresses in array6185// L_OBJC_LABEL_CLASS_$.61866187for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {6188const ObjCInterfaceDecl *ID = ImplementedClasses[i];6189assert(ID);6190if (ObjCImplementationDecl *IMP = ID->getImplementation())6191// We are implementing a weak imported interface. Give it external linkage6192if (ID->isWeakImported() && !IMP->isWeakImported()) {6193DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);6194DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);6195}6196}61976198AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",6199GetSectionName("__objc_classlist",6200"regular,no_dead_strip"));62016202AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",6203GetSectionName("__objc_nlclslist",6204"regular,no_dead_strip"));62056206// Build list of all implemented category addresses in array6207// L_OBJC_LABEL_CATEGORY_$.6208AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",6209GetSectionName("__objc_catlist",6210"regular,no_dead_strip"));6211AddModuleClassList(DefinedStubCategories, "OBJC_LABEL_STUB_CATEGORY_$",6212GetSectionName("__objc_catlist2",6213"regular,no_dead_strip"));6214AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",6215GetSectionName("__objc_nlcatlist",6216"regular,no_dead_strip"));62176218EmitImageInfo();6219}62206221/// isVTableDispatchedSelector - Returns true if SEL is not in the list of6222/// VTableDispatchMethods; false otherwise. What this means is that6223/// except for the 19 selectors in the list, we generate 32bit-style6224/// message dispatch call for all the rest.6225bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {6226// At various points we've experimented with using vtable-based6227// dispatch for all methods.6228switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {6229case CodeGenOptions::Legacy:6230return false;6231case CodeGenOptions::NonLegacy:6232return true;6233case CodeGenOptions::Mixed:6234break;6235}62366237// If so, see whether this selector is in the white-list of things which must6238// use the new dispatch convention. We lazily build a dense set for this.6239if (VTableDispatchMethods.empty()) {6240VTableDispatchMethods.insert(GetNullarySelector("alloc"));6241VTableDispatchMethods.insert(GetNullarySelector("class"));6242VTableDispatchMethods.insert(GetNullarySelector("self"));6243VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));6244VTableDispatchMethods.insert(GetNullarySelector("length"));6245VTableDispatchMethods.insert(GetNullarySelector("count"));62466247// These are vtable-based if GC is disabled.6248// Optimistically use vtable dispatch for hybrid compiles.6249if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {6250VTableDispatchMethods.insert(GetNullarySelector("retain"));6251VTableDispatchMethods.insert(GetNullarySelector("release"));6252VTableDispatchMethods.insert(GetNullarySelector("autorelease"));6253}62546255VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));6256VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));6257VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));6258VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));6259VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));6260VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));6261VTableDispatchMethods.insert(GetUnarySelector("isEqual"));62626263// These are vtable-based if GC is enabled.6264// Optimistically use vtable dispatch for hybrid compiles.6265if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {6266VTableDispatchMethods.insert(GetNullarySelector("hash"));6267VTableDispatchMethods.insert(GetUnarySelector("addObject"));62686269// "countByEnumeratingWithState:objects:count"6270const IdentifierInfo *KeyIdents[] = {6271&CGM.getContext().Idents.get("countByEnumeratingWithState"),6272&CGM.getContext().Idents.get("objects"),6273&CGM.getContext().Idents.get("count")};6274VTableDispatchMethods.insert(6275CGM.getContext().Selectors.getSelector(3, KeyIdents));6276}6277}62786279return VTableDispatchMethods.count(Sel);6280}62816282/// BuildClassRoTInitializer - generate meta-data for:6283/// struct _class_ro_t {6284/// uint32_t const flags;6285/// uint32_t const instanceStart;6286/// uint32_t const instanceSize;6287/// uint32_t const reserved; // only when building for 64bit targets6288/// const uint8_t * const ivarLayout;6289/// const char *const name;6290/// const struct _method_list_t * const baseMethods;6291/// const struct _protocol_list_t *const baseProtocols;6292/// const struct _ivar_list_t *const ivars;6293/// const uint8_t * const weakIvarLayout;6294/// const struct _prop_list_t * const properties;6295/// }6296///6297llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(6298unsigned flags,6299unsigned InstanceStart,6300unsigned InstanceSize,6301const ObjCImplementationDecl *ID) {6302std::string ClassName = std::string(ID->getObjCRuntimeNameAsString());63036304CharUnits beginInstance = CharUnits::fromQuantity(InstanceStart);6305CharUnits endInstance = CharUnits::fromQuantity(InstanceSize);63066307bool hasMRCWeak = false;6308if (CGM.getLangOpts().ObjCAutoRefCount)6309flags |= NonFragileABI_Class_CompiledByARC;6310else if ((hasMRCWeak = hasMRCWeakIvars(CGM, ID)))6311flags |= NonFragileABI_Class_HasMRCWeakIvars;63126313ConstantInitBuilder builder(CGM);6314auto values = builder.beginStruct(ObjCTypes.ClassRonfABITy);63156316values.addInt(ObjCTypes.IntTy, flags);6317values.addInt(ObjCTypes.IntTy, InstanceStart);6318values.addInt(ObjCTypes.IntTy, InstanceSize);6319values.add((flags & NonFragileABI_Class_Meta)6320? GetIvarLayoutName(nullptr, ObjCTypes)6321: BuildStrongIvarLayout(ID, beginInstance, endInstance));6322values.add(GetClassName(ID->getObjCRuntimeNameAsString()));63236324// const struct _method_list_t * const baseMethods;6325SmallVector<const ObjCMethodDecl*, 16> methods;6326if (flags & NonFragileABI_Class_Meta) {6327for (const auto *MD : ID->class_methods())6328if (!MD->isDirectMethod())6329methods.push_back(MD);6330} else {6331for (const auto *MD : ID->instance_methods())6332if (!MD->isDirectMethod())6333methods.push_back(MD);6334}63356336values.add(emitMethodList(ID->getObjCRuntimeNameAsString(),6337(flags & NonFragileABI_Class_Meta)6338? MethodListType::ClassMethods6339: MethodListType::InstanceMethods,6340methods));63416342const ObjCInterfaceDecl *OID = ID->getClassInterface();6343assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");6344values.add(EmitProtocolList("_OBJC_CLASS_PROTOCOLS_$_"6345+ OID->getObjCRuntimeNameAsString(),6346OID->all_referenced_protocol_begin(),6347OID->all_referenced_protocol_end()));63486349if (flags & NonFragileABI_Class_Meta) {6350values.addNullPointer(ObjCTypes.IvarListnfABIPtrTy);6351values.add(GetIvarLayoutName(nullptr, ObjCTypes));6352values.add(EmitPropertyList(6353"_OBJC_$_CLASS_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),6354ID, ID->getClassInterface(), ObjCTypes, true));6355} else {6356values.add(EmitIvarList(ID));6357values.add(BuildWeakIvarLayout(ID, beginInstance, endInstance, hasMRCWeak));6358values.add(EmitPropertyList(6359"_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),6360ID, ID->getClassInterface(), ObjCTypes, false));6361}63626363llvm::SmallString<64> roLabel;6364llvm::raw_svector_ostream(roLabel)6365<< ((flags & NonFragileABI_Class_Meta) ? "_OBJC_METACLASS_RO_$_"6366: "_OBJC_CLASS_RO_$_")6367<< ClassName;63686369return finishAndCreateGlobal(values, roLabel, CGM);6370}63716372/// Build the metaclass object for a class.6373///6374/// struct _class_t {6375/// struct _class_t *isa;6376/// struct _class_t * const superclass;6377/// void *cache;6378/// IMP *vtable;6379/// struct class_ro_t *ro;6380/// }6381///6382llvm::GlobalVariable *6383CGObjCNonFragileABIMac::BuildClassObject(const ObjCInterfaceDecl *CI,6384bool isMetaclass,6385llvm::Constant *IsAGV,6386llvm::Constant *SuperClassGV,6387llvm::Constant *ClassRoGV,6388bool HiddenVisibility) {6389ConstantInitBuilder builder(CGM);6390auto values = builder.beginStruct(ObjCTypes.ClassnfABITy);6391values.add(IsAGV);6392if (SuperClassGV) {6393values.add(SuperClassGV);6394} else {6395values.addNullPointer(ObjCTypes.ClassnfABIPtrTy);6396}6397values.add(ObjCEmptyCacheVar);6398values.add(ObjCEmptyVtableVar);6399values.add(ClassRoGV);64006401llvm::GlobalVariable *GV =6402cast<llvm::GlobalVariable>(GetClassGlobal(CI, isMetaclass, ForDefinition));6403values.finishAndSetAsInitializer(GV);64046405if (CGM.getTriple().isOSBinFormatMachO())6406GV->setSection("__DATA, __objc_data");6407GV->setAlignment(CGM.getDataLayout().getABITypeAlign(ObjCTypes.ClassnfABITy));6408if (!CGM.getTriple().isOSBinFormatCOFF())6409if (HiddenVisibility)6410GV->setVisibility(llvm::GlobalValue::HiddenVisibility);6411return GV;6412}64136414bool CGObjCNonFragileABIMac::ImplementationIsNonLazy(6415const ObjCImplDecl *OD) const {6416return OD->getClassMethod(GetNullarySelector("load")) != nullptr ||6417OD->getClassInterface()->hasAttr<ObjCNonLazyClassAttr>() ||6418OD->hasAttr<ObjCNonLazyClassAttr>();6419}64206421void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,6422uint32_t &InstanceStart,6423uint32_t &InstanceSize) {6424const ASTRecordLayout &RL =6425CGM.getContext().getASTObjCImplementationLayout(OID);64266427// InstanceSize is really instance end.6428InstanceSize = RL.getDataSize().getQuantity();64296430// If there are no fields, the start is the same as the end.6431if (!RL.getFieldCount())6432InstanceStart = InstanceSize;6433else6434InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();6435}64366437static llvm::GlobalValue::DLLStorageClassTypes getStorage(CodeGenModule &CGM,6438StringRef Name) {6439IdentifierInfo &II = CGM.getContext().Idents.get(Name);6440TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();6441DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);64426443const VarDecl *VD = nullptr;6444for (const auto *Result : DC->lookup(&II))6445if ((VD = dyn_cast<VarDecl>(Result)))6446break;64476448if (!VD)6449return llvm::GlobalValue::DLLImportStorageClass;6450if (VD->hasAttr<DLLExportAttr>())6451return llvm::GlobalValue::DLLExportStorageClass;6452if (VD->hasAttr<DLLImportAttr>())6453return llvm::GlobalValue::DLLImportStorageClass;6454return llvm::GlobalValue::DefaultStorageClass;6455}64566457void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {6458if (!ObjCEmptyCacheVar) {6459ObjCEmptyCacheVar =6460new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CacheTy, false,6461llvm::GlobalValue::ExternalLinkage, nullptr,6462"_objc_empty_cache");6463if (CGM.getTriple().isOSBinFormatCOFF())6464ObjCEmptyCacheVar->setDLLStorageClass(getStorage(CGM, "_objc_empty_cache"));64656466// Only OS X with deployment version <10.9 use the empty vtable symbol6467const llvm::Triple &Triple = CGM.getTarget().getTriple();6468if (Triple.isMacOSX() && Triple.isMacOSXVersionLT(10, 9))6469ObjCEmptyVtableVar =6470new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ImpnfABITy, false,6471llvm::GlobalValue::ExternalLinkage, nullptr,6472"_objc_empty_vtable");6473else6474ObjCEmptyVtableVar =6475llvm::ConstantPointerNull::get(ObjCTypes.ImpnfABITy->getPointerTo());6476}64776478// FIXME: Is this correct (that meta class size is never computed)?6479uint32_t InstanceStart =6480CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);6481uint32_t InstanceSize = InstanceStart;6482uint32_t flags = NonFragileABI_Class_Meta;64836484llvm::Constant *SuperClassGV, *IsAGV;64856486const auto *CI = ID->getClassInterface();6487assert(CI && "CGObjCNonFragileABIMac::GenerateClass - class is 0");64886489// Build the flags for the metaclass.6490bool classIsHidden = (CGM.getTriple().isOSBinFormatCOFF())6491? !CI->hasAttr<DLLExportAttr>()6492: CI->getVisibility() == HiddenVisibility;6493if (classIsHidden)6494flags |= NonFragileABI_Class_Hidden;64956496// FIXME: why is this flag set on the metaclass?6497// ObjC metaclasses have no fields and don't really get constructed.6498if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {6499flags |= NonFragileABI_Class_HasCXXStructors;6500if (!ID->hasNonZeroConstructors())6501flags |= NonFragileABI_Class_HasCXXDestructorOnly;6502}65036504if (!CI->getSuperClass()) {6505// class is root6506flags |= NonFragileABI_Class_Root;65076508SuperClassGV = GetClassGlobal(CI, /*metaclass*/ false, NotForDefinition);6509IsAGV = GetClassGlobal(CI, /*metaclass*/ true, NotForDefinition);6510} else {6511// Has a root. Current class is not a root.6512const ObjCInterfaceDecl *Root = ID->getClassInterface();6513while (const ObjCInterfaceDecl *Super = Root->getSuperClass())6514Root = Super;65156516const auto *Super = CI->getSuperClass();6517IsAGV = GetClassGlobal(Root, /*metaclass*/ true, NotForDefinition);6518SuperClassGV = GetClassGlobal(Super, /*metaclass*/ true, NotForDefinition);6519}65206521llvm::GlobalVariable *CLASS_RO_GV =6522BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);65236524llvm::GlobalVariable *MetaTClass =6525BuildClassObject(CI, /*metaclass*/ true,6526IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden);6527CGM.setGVProperties(MetaTClass, CI);6528DefinedMetaClasses.push_back(MetaTClass);65296530// Metadata for the class6531flags = 0;6532if (classIsHidden)6533flags |= NonFragileABI_Class_Hidden;65346535if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {6536flags |= NonFragileABI_Class_HasCXXStructors;65376538// Set a flag to enable a runtime optimization when a class has6539// fields that require destruction but which don't require6540// anything except zero-initialization during construction. This6541// is most notably true of __strong and __weak types, but you can6542// also imagine there being C++ types with non-trivial default6543// constructors that merely set all fields to null.6544if (!ID->hasNonZeroConstructors())6545flags |= NonFragileABI_Class_HasCXXDestructorOnly;6546}65476548if (hasObjCExceptionAttribute(CGM.getContext(), CI))6549flags |= NonFragileABI_Class_Exception;65506551if (!CI->getSuperClass()) {6552flags |= NonFragileABI_Class_Root;6553SuperClassGV = nullptr;6554} else {6555// Has a root. Current class is not a root.6556const auto *Super = CI->getSuperClass();6557SuperClassGV = GetClassGlobal(Super, /*metaclass*/ false, NotForDefinition);6558}65596560GetClassSizeInfo(ID, InstanceStart, InstanceSize);6561CLASS_RO_GV =6562BuildClassRoTInitializer(flags, InstanceStart, InstanceSize, ID);65636564llvm::GlobalVariable *ClassMD =6565BuildClassObject(CI, /*metaclass*/ false,6566MetaTClass, SuperClassGV, CLASS_RO_GV, classIsHidden);6567CGM.setGVProperties(ClassMD, CI);6568DefinedClasses.push_back(ClassMD);6569ImplementedClasses.push_back(CI);65706571// Determine if this class is also "non-lazy".6572if (ImplementationIsNonLazy(ID))6573DefinedNonLazyClasses.push_back(ClassMD);65746575// Force the definition of the EHType if necessary.6576if (flags & NonFragileABI_Class_Exception)6577(void) GetInterfaceEHType(CI, ForDefinition);6578// Make sure method definition entries are all clear for next implementation.6579MethodDefinitions.clear();6580}65816582/// GenerateProtocolRef - This routine is called to generate code for6583/// a protocol reference expression; as in:6584/// @code6585/// @protocol(Proto1);6586/// @endcode6587/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto16588/// which will hold address of the protocol meta-data.6589///6590llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,6591const ObjCProtocolDecl *PD) {65926593// This routine is called for @protocol only. So, we must build definition6594// of protocol's meta-data (not a reference to it!)6595assert(!PD->isNonRuntimeProtocol() &&6596"attempting to get a protocol ref to a static protocol.");6597llvm::Constant *Init = GetOrEmitProtocol(PD);65986599std::string ProtocolName("_OBJC_PROTOCOL_REFERENCE_$_");6600ProtocolName += PD->getObjCRuntimeNameAsString();66016602CharUnits Align = CGF.getPointerAlign();66036604llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);6605if (PTGV)6606return CGF.Builder.CreateAlignedLoad(PTGV->getValueType(), PTGV, Align);6607PTGV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,6608llvm::GlobalValue::WeakAnyLinkage, Init,6609ProtocolName);6610PTGV->setSection(GetSectionName("__objc_protorefs",6611"coalesced,no_dead_strip"));6612PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);6613PTGV->setAlignment(Align.getAsAlign());6614if (!CGM.getTriple().isOSBinFormatMachO())6615PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolName));6616CGM.addUsedGlobal(PTGV);6617return CGF.Builder.CreateAlignedLoad(PTGV->getValueType(), PTGV, Align);6618}66196620/// GenerateCategory - Build metadata for a category implementation.6621/// struct _category_t {6622/// const char * const name;6623/// struct _class_t *const cls;6624/// const struct _method_list_t * const instance_methods;6625/// const struct _method_list_t * const class_methods;6626/// const struct _protocol_list_t * const protocols;6627/// const struct _prop_list_t * const properties;6628/// const struct _prop_list_t * const class_properties;6629/// const uint32_t size;6630/// }6631///6632void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {6633const ObjCInterfaceDecl *Interface = OCD->getClassInterface();6634const char *Prefix = "_OBJC_$_CATEGORY_";66356636llvm::SmallString<64> ExtCatName(Prefix);6637ExtCatName += Interface->getObjCRuntimeNameAsString();6638ExtCatName += "_$_";6639ExtCatName += OCD->getNameAsString();66406641ConstantInitBuilder builder(CGM);6642auto values = builder.beginStruct(ObjCTypes.CategorynfABITy);6643values.add(GetClassName(OCD->getIdentifier()->getName()));6644// meta-class entry symbol6645values.add(GetClassGlobal(Interface, /*metaclass*/ false, NotForDefinition));6646std::string listName =6647(Interface->getObjCRuntimeNameAsString() + "_$_" + OCD->getName()).str();66486649SmallVector<const ObjCMethodDecl *, 16> instanceMethods;6650SmallVector<const ObjCMethodDecl *, 8> classMethods;6651for (const auto *MD : OCD->methods()) {6652if (MD->isDirectMethod())6653continue;6654if (MD->isInstanceMethod()) {6655instanceMethods.push_back(MD);6656} else {6657classMethods.push_back(MD);6658}6659}66606661auto instanceMethodList = emitMethodList(6662listName, MethodListType::CategoryInstanceMethods, instanceMethods);6663auto classMethodList = emitMethodList(6664listName, MethodListType::CategoryClassMethods, classMethods);6665values.add(instanceMethodList);6666values.add(classMethodList);6667// Keep track of whether we have actual metadata to emit.6668bool isEmptyCategory =6669instanceMethodList->isNullValue() && classMethodList->isNullValue();66706671const ObjCCategoryDecl *Category =6672Interface->FindCategoryDeclaration(OCD->getIdentifier());6673if (Category) {6674SmallString<256> ExtName;6675llvm::raw_svector_ostream(ExtName)6676<< Interface->getObjCRuntimeNameAsString() << "_$_" << OCD->getName();6677auto protocolList =6678EmitProtocolList("_OBJC_CATEGORY_PROTOCOLS_$_" +6679Interface->getObjCRuntimeNameAsString() + "_$_" +6680Category->getName(),6681Category->protocol_begin(), Category->protocol_end());6682auto propertyList = EmitPropertyList("_OBJC_$_PROP_LIST_" + ExtName.str(),6683OCD, Category, ObjCTypes, false);6684auto classPropertyList =6685EmitPropertyList("_OBJC_$_CLASS_PROP_LIST_" + ExtName.str(), OCD,6686Category, ObjCTypes, true);6687values.add(protocolList);6688values.add(propertyList);6689values.add(classPropertyList);6690isEmptyCategory &= protocolList->isNullValue() &&6691propertyList->isNullValue() &&6692classPropertyList->isNullValue();6693} else {6694values.addNullPointer(ObjCTypes.ProtocolListnfABIPtrTy);6695values.addNullPointer(ObjCTypes.PropertyListPtrTy);6696values.addNullPointer(ObjCTypes.PropertyListPtrTy);6697}66986699if (isEmptyCategory) {6700// Empty category, don't emit any metadata.6701values.abandon();6702MethodDefinitions.clear();6703return;6704}67056706unsigned Size =6707CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategorynfABITy);6708values.addInt(ObjCTypes.IntTy, Size);67096710llvm::GlobalVariable *GCATV =6711finishAndCreateGlobal(values, ExtCatName.str(), CGM);6712CGM.addCompilerUsedGlobal(GCATV);6713if (Interface->hasAttr<ObjCClassStubAttr>())6714DefinedStubCategories.push_back(GCATV);6715else6716DefinedCategories.push_back(GCATV);67176718// Determine if this category is also "non-lazy".6719if (ImplementationIsNonLazy(OCD))6720DefinedNonLazyCategories.push_back(GCATV);6721// method definition entries must be clear for next implementation.6722MethodDefinitions.clear();6723}67246725/// emitMethodConstant - Return a struct objc_method constant. If6726/// forProtocol is true, the implementation will be null; otherwise,6727/// the method must have a definition registered with the runtime.6728///6729/// struct _objc_method {6730/// SEL _cmd;6731/// char *method_type;6732/// char *_imp;6733/// }6734void CGObjCNonFragileABIMac::emitMethodConstant(ConstantArrayBuilder &builder,6735const ObjCMethodDecl *MD,6736bool forProtocol) {6737auto method = builder.beginStruct(ObjCTypes.MethodTy);6738method.add(GetMethodVarName(MD->getSelector()));6739method.add(GetMethodVarType(MD));67406741if (forProtocol) {6742// Protocol methods have no implementation. So, this entry is always NULL.6743method.addNullPointer(ObjCTypes.Int8PtrProgramASTy);6744} else {6745llvm::Function *fn = GetMethodDefinition(MD);6746assert(fn && "no definition for method?");6747method.add(fn);6748}67496750method.finishAndAddTo(builder);6751}67526753/// Build meta-data for method declarations.6754///6755/// struct _method_list_t {6756/// uint32_t entsize; // sizeof(struct _objc_method)6757/// uint32_t method_count;6758/// struct _objc_method method_list[method_count];6759/// }6760///6761llvm::Constant *6762CGObjCNonFragileABIMac::emitMethodList(Twine name, MethodListType kind,6763ArrayRef<const ObjCMethodDecl *> methods) {6764// Return null for empty list.6765if (methods.empty())6766return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);67676768StringRef prefix;6769bool forProtocol;6770switch (kind) {6771case MethodListType::CategoryInstanceMethods:6772prefix = "_OBJC_$_CATEGORY_INSTANCE_METHODS_";6773forProtocol = false;6774break;6775case MethodListType::CategoryClassMethods:6776prefix = "_OBJC_$_CATEGORY_CLASS_METHODS_";6777forProtocol = false;6778break;6779case MethodListType::InstanceMethods:6780prefix = "_OBJC_$_INSTANCE_METHODS_";6781forProtocol = false;6782break;6783case MethodListType::ClassMethods:6784prefix = "_OBJC_$_CLASS_METHODS_";6785forProtocol = false;6786break;67876788case MethodListType::ProtocolInstanceMethods:6789prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_";6790forProtocol = true;6791break;6792case MethodListType::ProtocolClassMethods:6793prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_";6794forProtocol = true;6795break;6796case MethodListType::OptionalProtocolInstanceMethods:6797prefix = "_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_";6798forProtocol = true;6799break;6800case MethodListType::OptionalProtocolClassMethods:6801prefix = "_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_";6802forProtocol = true;6803break;6804}68056806ConstantInitBuilder builder(CGM);6807auto values = builder.beginStruct();68086809// sizeof(struct _objc_method)6810unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);6811values.addInt(ObjCTypes.IntTy, Size);6812// method_count6813values.addInt(ObjCTypes.IntTy, methods.size());6814auto methodArray = values.beginArray(ObjCTypes.MethodTy);6815for (auto MD : methods)6816emitMethodConstant(methodArray, MD, forProtocol);6817methodArray.finishAndAddTo(values);68186819llvm::GlobalVariable *GV = finishAndCreateGlobal(values, prefix + name, CGM);6820CGM.addCompilerUsedGlobal(GV);6821return GV;6822}68236824/// ObjCIvarOffsetVariable - Returns the ivar offset variable for6825/// the given ivar.6826llvm::GlobalVariable *6827CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,6828const ObjCIvarDecl *Ivar) {6829const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();6830llvm::SmallString<64> Name("OBJC_IVAR_$_");6831Name += Container->getObjCRuntimeNameAsString();6832Name += ".";6833Name += Ivar->getName();6834llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);6835if (!IvarOffsetGV) {6836IvarOffsetGV =6837new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.IvarOffsetVarTy,6838false, llvm::GlobalValue::ExternalLinkage,6839nullptr, Name.str());6840if (CGM.getTriple().isOSBinFormatCOFF()) {6841bool IsPrivateOrPackage =6842Ivar->getAccessControl() == ObjCIvarDecl::Private ||6843Ivar->getAccessControl() == ObjCIvarDecl::Package;68446845const ObjCInterfaceDecl *ContainingID = Ivar->getContainingInterface();68466847if (ContainingID->hasAttr<DLLImportAttr>())6848IvarOffsetGV6849->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);6850else if (ContainingID->hasAttr<DLLExportAttr>() && !IsPrivateOrPackage)6851IvarOffsetGV6852->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);6853}6854}6855return IvarOffsetGV;6856}68576858llvm::Constant *6859CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,6860const ObjCIvarDecl *Ivar,6861unsigned long int Offset) {6862llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);6863IvarOffsetGV->setInitializer(6864llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));6865IvarOffsetGV->setAlignment(6866CGM.getDataLayout().getABITypeAlign(ObjCTypes.IvarOffsetVarTy));68676868if (!CGM.getTriple().isOSBinFormatCOFF()) {6869// FIXME: This matches gcc, but shouldn't the visibility be set on the use6870// as well (i.e., in ObjCIvarOffsetVariable).6871if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||6872Ivar->getAccessControl() == ObjCIvarDecl::Package ||6873ID->getVisibility() == HiddenVisibility)6874IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);6875else6876IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);6877}68786879// If ID's layout is known, then make the global constant. This serves as a6880// useful assertion: we'll never use this variable to calculate ivar offsets,6881// so if the runtime tries to patch it then we should crash.6882if (isClassLayoutKnownStatically(ID))6883IvarOffsetGV->setConstant(true);68846885if (CGM.getTriple().isOSBinFormatMachO())6886IvarOffsetGV->setSection("__DATA, __objc_ivar");6887return IvarOffsetGV;6888}68896890/// EmitIvarList - Emit the ivar list for the given6891/// implementation. The return value has type6892/// IvarListnfABIPtrTy.6893/// struct _ivar_t {6894/// unsigned [long] int *offset; // pointer to ivar offset location6895/// char *name;6896/// char *type;6897/// uint32_t alignment;6898/// uint32_t size;6899/// }6900/// struct _ivar_list_t {6901/// uint32 entsize; // sizeof(struct _ivar_t)6902/// uint32 count;6903/// struct _iver_t list[count];6904/// }6905///69066907llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(6908const ObjCImplementationDecl *ID) {69096910ConstantInitBuilder builder(CGM);6911auto ivarList = builder.beginStruct();6912ivarList.addInt(ObjCTypes.IntTy,6913CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy));6914auto ivarCountSlot = ivarList.addPlaceholder();6915auto ivars = ivarList.beginArray(ObjCTypes.IvarnfABITy);69166917const ObjCInterfaceDecl *OID = ID->getClassInterface();6918assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");69196920// FIXME. Consolidate this with similar code in GenerateClass.69216922for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();6923IVD; IVD = IVD->getNextIvar()) {6924// Ignore unnamed bit-fields.6925if (!IVD->getDeclName())6926continue;69276928auto ivar = ivars.beginStruct(ObjCTypes.IvarnfABITy);6929ivar.add(EmitIvarOffsetVar(ID->getClassInterface(), IVD,6930ComputeIvarBaseOffset(CGM, ID, IVD)));6931ivar.add(GetMethodVarName(IVD->getIdentifier()));6932ivar.add(GetMethodVarType(IVD));6933llvm::Type *FieldTy =6934CGM.getTypes().ConvertTypeForMem(IVD->getType());6935unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);6936unsigned Align = CGM.getContext().getPreferredTypeAlign(6937IVD->getType().getTypePtr()) >> 3;6938Align = llvm::Log2_32(Align);6939ivar.addInt(ObjCTypes.IntTy, Align);6940// NOTE. Size of a bitfield does not match gcc's, because of the6941// way bitfields are treated special in each. But I am told that6942// 'size' for bitfield ivars is ignored by the runtime so it does6943// not matter. If it matters, there is enough info to get the6944// bitfield right!6945ivar.addInt(ObjCTypes.IntTy, Size);6946ivar.finishAndAddTo(ivars);6947}6948// Return null for empty list.6949if (ivars.empty()) {6950ivars.abandon();6951ivarList.abandon();6952return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);6953}69546955auto ivarCount = ivars.size();6956ivars.finishAndAddTo(ivarList);6957ivarList.fillPlaceholderWithInt(ivarCountSlot, ObjCTypes.IntTy, ivarCount);69586959const char *Prefix = "_OBJC_$_INSTANCE_VARIABLES_";6960llvm::GlobalVariable *GV = finishAndCreateGlobal(6961ivarList, Prefix + OID->getObjCRuntimeNameAsString(), CGM);6962CGM.addCompilerUsedGlobal(GV);6963return GV;6964}69656966llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(6967const ObjCProtocolDecl *PD) {6968llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];69696970assert(!PD->isNonRuntimeProtocol() &&6971"attempting to GetOrEmit a non-runtime protocol");6972if (!Entry) {6973// We use the initializer as a marker of whether this is a forward6974// reference or not. At module finalization we add the empty6975// contents for protocols which were referenced but never defined.6976llvm::SmallString<64> Protocol;6977llvm::raw_svector_ostream(Protocol) << "_OBJC_PROTOCOL_$_"6978<< PD->getObjCRuntimeNameAsString();69796980Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,6981false, llvm::GlobalValue::ExternalLinkage,6982nullptr, Protocol);6983if (!CGM.getTriple().isOSBinFormatMachO())6984Entry->setComdat(CGM.getModule().getOrInsertComdat(Protocol));6985}69866987return Entry;6988}69896990/// GetOrEmitProtocol - Generate the protocol meta-data:6991/// @code6992/// struct _protocol_t {6993/// id isa; // NULL6994/// const char * const protocol_name;6995/// const struct _protocol_list_t * protocol_list; // super protocols6996/// const struct method_list_t * const instance_methods;6997/// const struct method_list_t * const class_methods;6998/// const struct method_list_t *optionalInstanceMethods;6999/// const struct method_list_t *optionalClassMethods;7000/// const struct _prop_list_t * properties;7001/// const uint32_t size; // sizeof(struct _protocol_t)7002/// const uint32_t flags; // = 07003/// const char ** extendedMethodTypes;7004/// const char *demangledName;7005/// const struct _prop_list_t * class_properties;7006/// }7007/// @endcode7008///70097010llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(7011const ObjCProtocolDecl *PD) {7012llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];70137014// Early exit if a defining object has already been generated.7015if (Entry && Entry->hasInitializer())7016return Entry;70177018// Use the protocol definition, if there is one.7019assert(PD->hasDefinition() &&7020"emitting protocol metadata without definition");7021PD = PD->getDefinition();70227023auto methodLists = ProtocolMethodLists::get(PD);70247025ConstantInitBuilder builder(CGM);7026auto values = builder.beginStruct(ObjCTypes.ProtocolnfABITy);70277028// isa is NULL7029values.addNullPointer(ObjCTypes.ObjectPtrTy);7030values.add(GetClassName(PD->getObjCRuntimeNameAsString()));7031values.add(EmitProtocolList("_OBJC_$_PROTOCOL_REFS_"7032+ PD->getObjCRuntimeNameAsString(),7033PD->protocol_begin(),7034PD->protocol_end()));7035values.add(methodLists.emitMethodList(this, PD,7036ProtocolMethodLists::RequiredInstanceMethods));7037values.add(methodLists.emitMethodList(this, PD,7038ProtocolMethodLists::RequiredClassMethods));7039values.add(methodLists.emitMethodList(this, PD,7040ProtocolMethodLists::OptionalInstanceMethods));7041values.add(methodLists.emitMethodList(this, PD,7042ProtocolMethodLists::OptionalClassMethods));7043values.add(EmitPropertyList(7044"_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),7045nullptr, PD, ObjCTypes, false));7046uint32_t Size =7047CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);7048values.addInt(ObjCTypes.IntTy, Size);7049values.addInt(ObjCTypes.IntTy, 0);7050values.add(EmitProtocolMethodTypes("_OBJC_$_PROTOCOL_METHOD_TYPES_"7051+ PD->getObjCRuntimeNameAsString(),7052methodLists.emitExtendedTypesArray(this),7053ObjCTypes));70547055// const char *demangledName;7056values.addNullPointer(ObjCTypes.Int8PtrTy);70577058values.add(EmitPropertyList(7059"_OBJC_$_CLASS_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),7060nullptr, PD, ObjCTypes, true));70617062if (Entry) {7063// Already created, fix the linkage and update the initializer.7064Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);7065values.finishAndSetAsInitializer(Entry);7066} else {7067llvm::SmallString<64> symbolName;7068llvm::raw_svector_ostream(symbolName)7069<< "_OBJC_PROTOCOL_$_" << PD->getObjCRuntimeNameAsString();70707071Entry = values.finishAndCreateGlobal(symbolName, CGM.getPointerAlign(),7072/*constant*/ false,7073llvm::GlobalValue::WeakAnyLinkage);7074if (!CGM.getTriple().isOSBinFormatMachO())7075Entry->setComdat(CGM.getModule().getOrInsertComdat(symbolName));70767077Protocols[PD->getIdentifier()] = Entry;7078}7079Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);7080CGM.addUsedGlobal(Entry);70817082// Use this protocol meta-data to build protocol list table in section7083// __DATA, __objc_protolist7084llvm::SmallString<64> ProtocolRef;7085llvm::raw_svector_ostream(ProtocolRef) << "_OBJC_LABEL_PROTOCOL_$_"7086<< PD->getObjCRuntimeNameAsString();70877088llvm::GlobalVariable *PTGV =7089new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,7090false, llvm::GlobalValue::WeakAnyLinkage, Entry,7091ProtocolRef);7092if (!CGM.getTriple().isOSBinFormatMachO())7093PTGV->setComdat(CGM.getModule().getOrInsertComdat(ProtocolRef));7094PTGV->setAlignment(7095CGM.getDataLayout().getABITypeAlign(ObjCTypes.ProtocolnfABIPtrTy));7096PTGV->setSection(GetSectionName("__objc_protolist",7097"coalesced,no_dead_strip"));7098PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);7099CGM.addUsedGlobal(PTGV);7100return Entry;7101}71027103/// EmitProtocolList - Generate protocol list meta-data:7104/// @code7105/// struct _protocol_list_t {7106/// long protocol_count; // Note, this is 32/64 bit7107/// struct _protocol_t[protocol_count];7108/// }7109/// @endcode7110///7111llvm::Constant *7112CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,7113ObjCProtocolDecl::protocol_iterator begin,7114ObjCProtocolDecl::protocol_iterator end) {7115// Just return null for empty protocol lists7116auto Protocols = GetRuntimeProtocolList(begin, end);7117if (Protocols.empty())7118return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);71197120SmallVector<llvm::Constant *, 16> ProtocolRefs;7121ProtocolRefs.reserve(Protocols.size());71227123for (const auto *PD : Protocols)7124ProtocolRefs.push_back(GetProtocolRef(PD));71257126// If all of the protocols in the protocol list are objc_non_runtime_protocol7127// just return null7128if (ProtocolRefs.size() == 0)7129return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);71307131// FIXME: We shouldn't need to do this lookup here, should we?7132SmallString<256> TmpName;7133Name.toVector(TmpName);7134llvm::GlobalVariable *GV =7135CGM.getModule().getGlobalVariable(TmpName.str(), true);7136if (GV)7137return GV;71387139ConstantInitBuilder builder(CGM);7140auto values = builder.beginStruct();7141auto countSlot = values.addPlaceholder();71427143// A null-terminated array of protocols.7144auto array = values.beginArray(ObjCTypes.ProtocolnfABIPtrTy);7145for (auto const &proto : ProtocolRefs)7146array.add(proto);7147auto count = array.size();7148array.addNullPointer(ObjCTypes.ProtocolnfABIPtrTy);71497150array.finishAndAddTo(values);7151values.fillPlaceholderWithInt(countSlot, ObjCTypes.LongTy, count);71527153GV = finishAndCreateGlobal(values, Name, CGM);7154CGM.addCompilerUsedGlobal(GV);7155return GV;7156}71577158/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.7159/// This code gen. amounts to generating code for:7160/// @code7161/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;7162/// @encode7163///7164LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(7165CodeGen::CodeGenFunction &CGF,7166QualType ObjectTy,7167llvm::Value *BaseValue,7168const ObjCIvarDecl *Ivar,7169unsigned CVRQualifiers) {7170ObjCInterfaceDecl *ID = ObjectTy->castAs<ObjCObjectType>()->getInterface();7171llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);7172return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,7173Offset);7174}71757176llvm::Value *7177CGObjCNonFragileABIMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,7178const ObjCInterfaceDecl *Interface,7179const ObjCIvarDecl *Ivar) {7180llvm::Value *IvarOffsetValue;7181if (isClassLayoutKnownStatically(Interface)) {7182IvarOffsetValue = llvm::ConstantInt::get(7183ObjCTypes.IvarOffsetVarTy,7184ComputeIvarBaseOffset(CGM, Interface->getImplementation(), Ivar));7185} else {7186llvm::GlobalVariable *GV = ObjCIvarOffsetVariable(Interface, Ivar);7187IvarOffsetValue =7188CGF.Builder.CreateAlignedLoad(GV->getValueType(), GV,7189CGF.getSizeAlign(), "ivar");7190if (IsIvarOffsetKnownIdempotent(CGF, Ivar))7191cast<llvm::LoadInst>(IvarOffsetValue)7192->setMetadata(llvm::LLVMContext::MD_invariant_load,7193llvm::MDNode::get(VMContext, std::nullopt));7194}71957196// This could be 32bit int or 64bit integer depending on the architecture.7197// Cast it to 64bit integer value, if it is a 32bit integer ivar offset value7198// as this is what caller always expects.7199if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)7200IvarOffsetValue = CGF.Builder.CreateIntCast(7201IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");7202return IvarOffsetValue;7203}72047205static void appendSelectorForMessageRefTable(std::string &buffer,7206Selector selector) {7207if (selector.isUnarySelector()) {7208buffer += selector.getNameForSlot(0);7209return;7210}72117212for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {7213buffer += selector.getNameForSlot(i);7214buffer += '_';7215}7216}72177218/// Emit a "vtable" message send. We emit a weak hidden-visibility7219/// struct, initially containing the selector pointer and a pointer to7220/// a "fixup" variant of the appropriate objc_msgSend. To call, we7221/// load and call the function pointer, passing the address of the7222/// struct as the second parameter. The runtime determines whether7223/// the selector is currently emitted using vtable dispatch; if so, it7224/// substitutes a stub function which simply tail-calls through the7225/// appropriate vtable slot, and if not, it substitues a stub function7226/// which tail-calls objc_msgSend. Both stubs adjust the selector7227/// argument to correctly point to the selector.7228RValue7229CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,7230ReturnValueSlot returnSlot,7231QualType resultType,7232Selector selector,7233llvm::Value *arg0,7234QualType arg0Type,7235bool isSuper,7236const CallArgList &formalArgs,7237const ObjCMethodDecl *method) {7238// Compute the actual arguments.7239CallArgList args;72407241// First argument: the receiver / super-call structure.7242if (!isSuper)7243arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);7244args.add(RValue::get(arg0), arg0Type);72457246// Second argument: a pointer to the message ref structure. Leave7247// the actual argument value blank for now.7248args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);72497250args.insert(args.end(), formalArgs.begin(), formalArgs.end());72517252MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);72537254NullReturnState nullReturn;72557256// Find the function to call and the mangled name for the message7257// ref structure. Using a different mangled name wouldn't actually7258// be a problem; it would just be a waste.7259//7260// The runtime currently never uses vtable dispatch for anything7261// except normal, non-super message-sends.7262// FIXME: don't use this for that.7263llvm::FunctionCallee fn = nullptr;7264std::string messageRefName("_");7265if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {7266if (isSuper) {7267fn = ObjCTypes.getMessageSendSuper2StretFixupFn();7268messageRefName += "objc_msgSendSuper2_stret_fixup";7269} else {7270nullReturn.init(CGF, arg0);7271fn = ObjCTypes.getMessageSendStretFixupFn();7272messageRefName += "objc_msgSend_stret_fixup";7273}7274} else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {7275fn = ObjCTypes.getMessageSendFpretFixupFn();7276messageRefName += "objc_msgSend_fpret_fixup";7277} else {7278if (isSuper) {7279fn = ObjCTypes.getMessageSendSuper2FixupFn();7280messageRefName += "objc_msgSendSuper2_fixup";7281} else {7282fn = ObjCTypes.getMessageSendFixupFn();7283messageRefName += "objc_msgSend_fixup";7284}7285}7286assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");7287messageRefName += '_';72887289// Append the selector name, except use underscores anywhere we7290// would have used colons.7291appendSelectorForMessageRefTable(messageRefName, selector);72927293llvm::GlobalVariable *messageRef7294= CGM.getModule().getGlobalVariable(messageRefName);7295if (!messageRef) {7296// Build the message ref structure.7297ConstantInitBuilder builder(CGM);7298auto values = builder.beginStruct();7299values.add(cast<llvm::Constant>(fn.getCallee()));7300values.add(GetMethodVarName(selector));7301messageRef = values.finishAndCreateGlobal(messageRefName,7302CharUnits::fromQuantity(16),7303/*constant*/ false,7304llvm::GlobalValue::WeakAnyLinkage);7305messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);7306messageRef->setSection(GetSectionName("__objc_msgrefs", "coalesced"));7307}73087309bool requiresnullCheck = false;7310if (CGM.getLangOpts().ObjCAutoRefCount && method)7311for (const auto *ParamDecl : method->parameters()) {7312if (ParamDecl->isDestroyedInCallee()) {7313if (!nullReturn.NullBB)7314nullReturn.init(CGF, arg0);7315requiresnullCheck = true;7316break;7317}7318}73197320Address mref =7321Address(CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy),7322ObjCTypes.MessageRefTy, CGF.getPointerAlign());73237324// Update the message ref argument.7325args[1].setRValue(RValue::get(mref, CGF));73267327// Load the function to call from the message ref table.7328Address calleeAddr = CGF.Builder.CreateStructGEP(mref, 0);7329llvm::Value *calleePtr = CGF.Builder.CreateLoad(calleeAddr, "msgSend_fn");73307331calleePtr = CGF.Builder.CreateBitCast(calleePtr, MSI.MessengerType);7332CGCallee callee(CGCalleeInfo(), calleePtr);73337334RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);7335return nullReturn.complete(CGF, returnSlot, result, resultType, formalArgs,7336requiresnullCheck ? method : nullptr);7337}73387339/// Generate code for a message send expression in the nonfragile abi.7340CodeGen::RValue7341CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,7342ReturnValueSlot Return,7343QualType ResultType,7344Selector Sel,7345llvm::Value *Receiver,7346const CallArgList &CallArgs,7347const ObjCInterfaceDecl *Class,7348const ObjCMethodDecl *Method) {7349return isVTableDispatchedSelector(Sel)7350? EmitVTableMessageSend(CGF, Return, ResultType, Sel,7351Receiver, CGF.getContext().getObjCIdType(),7352false, CallArgs, Method)7353: EmitMessageSend(CGF, Return, ResultType, Sel,7354Receiver, CGF.getContext().getObjCIdType(),7355false, CallArgs, Method, Class, ObjCTypes);7356}73577358llvm::Constant *7359CGObjCNonFragileABIMac::GetClassGlobal(const ObjCInterfaceDecl *ID,7360bool metaclass,7361ForDefinition_t isForDefinition) {7362auto prefix =7363(metaclass ? getMetaclassSymbolPrefix() : getClassSymbolPrefix());7364return GetClassGlobal((prefix + ID->getObjCRuntimeNameAsString()).str(),7365isForDefinition,7366ID->isWeakImported(),7367!isForDefinition7368&& CGM.getTriple().isOSBinFormatCOFF()7369&& ID->hasAttr<DLLImportAttr>());7370}73717372llvm::Constant *7373CGObjCNonFragileABIMac::GetClassGlobal(StringRef Name,7374ForDefinition_t IsForDefinition,7375bool Weak, bool DLLImport) {7376llvm::GlobalValue::LinkageTypes L =7377Weak ? llvm::GlobalValue::ExternalWeakLinkage7378: llvm::GlobalValue::ExternalLinkage;73797380llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);7381if (!GV || GV->getValueType() != ObjCTypes.ClassnfABITy) {7382auto *NewGV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false, L,7383nullptr, Name);73847385if (DLLImport)7386NewGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);73877388if (GV) {7389GV->replaceAllUsesWith(NewGV);7390GV->eraseFromParent();7391}7392GV = NewGV;7393CGM.getModule().insertGlobalVariable(GV);7394}73957396assert(GV->getLinkage() == L);7397return GV;7398}73997400llvm::Constant *7401CGObjCNonFragileABIMac::GetClassGlobalForClassRef(const ObjCInterfaceDecl *ID) {7402llvm::Constant *ClassGV = GetClassGlobal(ID, /*metaclass*/ false,7403NotForDefinition);74047405if (!ID->hasAttr<ObjCClassStubAttr>())7406return ClassGV;74077408ClassGV = llvm::ConstantExpr::getPointerCast(ClassGV, ObjCTypes.Int8PtrTy);74097410// Stub classes are pointer-aligned. Classrefs pointing at stub classes7411// must set the least significant bit set to 1.7412auto *Idx = llvm::ConstantInt::get(CGM.Int32Ty, 1);7413return llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, ClassGV, Idx);7414}74157416llvm::Value *7417CGObjCNonFragileABIMac::EmitLoadOfClassRef(CodeGenFunction &CGF,7418const ObjCInterfaceDecl *ID,7419llvm::GlobalVariable *Entry) {7420if (ID && ID->hasAttr<ObjCClassStubAttr>()) {7421// Classrefs pointing at Objective-C stub classes must be loaded by calling7422// a special runtime function.7423return CGF.EmitRuntimeCall(7424ObjCTypes.getLoadClassrefFn(), Entry, "load_classref_result");7425}74267427CharUnits Align = CGF.getPointerAlign();7428return CGF.Builder.CreateAlignedLoad(Entry->getValueType(), Entry, Align);7429}74307431llvm::Value *7432CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,7433IdentifierInfo *II,7434const ObjCInterfaceDecl *ID) {7435llvm::GlobalVariable *&Entry = ClassReferences[II];74367437if (!Entry) {7438llvm::Constant *ClassGV;7439if (ID) {7440ClassGV = GetClassGlobalForClassRef(ID);7441} else {7442ClassGV = GetClassGlobal((getClassSymbolPrefix() + II->getName()).str(),7443NotForDefinition);7444assert(ClassGV->getType() == ObjCTypes.ClassnfABIPtrTy &&7445"classref was emitted with the wrong type?");7446}74477448std::string SectionName =7449GetSectionName("__objc_classrefs", "regular,no_dead_strip");7450Entry = new llvm::GlobalVariable(7451CGM.getModule(), ClassGV->getType(), false,7452getLinkageTypeForObjCMetadata(CGM, SectionName), ClassGV,7453"OBJC_CLASSLIST_REFERENCES_$_");7454Entry->setAlignment(CGF.getPointerAlign().getAsAlign());7455if (!ID || !ID->hasAttr<ObjCClassStubAttr>())7456Entry->setSection(SectionName);74577458CGM.addCompilerUsedGlobal(Entry);7459}74607461return EmitLoadOfClassRef(CGF, ID, Entry);7462}74637464llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,7465const ObjCInterfaceDecl *ID) {7466// If the class has the objc_runtime_visible attribute, we need to7467// use the Objective-C runtime to get the class.7468if (ID->hasAttr<ObjCRuntimeVisibleAttr>())7469return EmitClassRefViaRuntime(CGF, ID, ObjCTypes);74707471return EmitClassRefFromId(CGF, ID->getIdentifier(), ID);7472}74737474llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(7475CodeGenFunction &CGF) {7476IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");7477return EmitClassRefFromId(CGF, II, nullptr);7478}74797480llvm::Value *7481CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,7482const ObjCInterfaceDecl *ID) {7483llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];74847485if (!Entry) {7486llvm::Constant *ClassGV = GetClassGlobalForClassRef(ID);7487std::string SectionName =7488GetSectionName("__objc_superrefs", "regular,no_dead_strip");7489Entry = new llvm::GlobalVariable(CGM.getModule(), ClassGV->getType(), false,7490llvm::GlobalValue::PrivateLinkage, ClassGV,7491"OBJC_CLASSLIST_SUP_REFS_$_");7492Entry->setAlignment(CGF.getPointerAlign().getAsAlign());7493Entry->setSection(SectionName);7494CGM.addCompilerUsedGlobal(Entry);7495}74967497return EmitLoadOfClassRef(CGF, ID, Entry);7498}74997500/// EmitMetaClassRef - Return a Value * of the address of _class_t7501/// meta-data7502///7503llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,7504const ObjCInterfaceDecl *ID,7505bool Weak) {7506CharUnits Align = CGF.getPointerAlign();7507llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];7508if (!Entry) {7509auto MetaClassGV = GetClassGlobal(ID, /*metaclass*/ true, NotForDefinition);7510std::string SectionName =7511GetSectionName("__objc_superrefs", "regular,no_dead_strip");7512Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,7513false, llvm::GlobalValue::PrivateLinkage,7514MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");7515Entry->setAlignment(Align.getAsAlign());7516Entry->setSection(SectionName);7517CGM.addCompilerUsedGlobal(Entry);7518}75197520return CGF.Builder.CreateAlignedLoad(ObjCTypes.ClassnfABIPtrTy, Entry, Align);7521}75227523/// GetClass - Return a reference to the class for the given interface7524/// decl.7525llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,7526const ObjCInterfaceDecl *ID) {7527if (ID->isWeakImported()) {7528auto ClassGV = GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition);7529(void)ClassGV;7530assert(!isa<llvm::GlobalVariable>(ClassGV) ||7531cast<llvm::GlobalVariable>(ClassGV)->hasExternalWeakLinkage());7532}75337534return EmitClassRef(CGF, ID);7535}75367537/// Generates a message send where the super is the receiver. This is7538/// a message send to self with special delivery semantics indicating7539/// which class's method should be called.7540CodeGen::RValue7541CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,7542ReturnValueSlot Return,7543QualType ResultType,7544Selector Sel,7545const ObjCInterfaceDecl *Class,7546bool isCategoryImpl,7547llvm::Value *Receiver,7548bool IsClassMessage,7549const CodeGen::CallArgList &CallArgs,7550const ObjCMethodDecl *Method) {7551// ...7552// Create and init a super structure; this is a (receiver, class)7553// pair we will pass to objc_msgSendSuper.7554RawAddress ObjCSuper = CGF.CreateTempAlloca(7555ObjCTypes.SuperTy, CGF.getPointerAlign(), "objc_super");75567557llvm::Value *ReceiverAsObject =7558CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);7559CGF.Builder.CreateStore(ReceiverAsObject,7560CGF.Builder.CreateStructGEP(ObjCSuper, 0));75617562// If this is a class message the metaclass is passed as the target.7563llvm::Value *Target;7564if (IsClassMessage)7565Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());7566else7567Target = EmitSuperClassRef(CGF, Class);75687569// FIXME: We shouldn't need to do this cast, rectify the ASTContext and7570// ObjCTypes types.7571llvm::Type *ClassTy =7572CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());7573Target = CGF.Builder.CreateBitCast(Target, ClassTy);7574CGF.Builder.CreateStore(Target, CGF.Builder.CreateStructGEP(ObjCSuper, 1));75757576return (isVTableDispatchedSelector(Sel))7577? EmitVTableMessageSend(CGF, Return, ResultType, Sel,7578ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,7579true, CallArgs, Method)7580: EmitMessageSend(CGF, Return, ResultType, Sel,7581ObjCSuper.getPointer(), ObjCTypes.SuperPtrCTy,7582true, CallArgs, Method, Class, ObjCTypes);7583}75847585llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,7586Selector Sel) {7587Address Addr = EmitSelectorAddr(Sel);75887589llvm::LoadInst* LI = CGF.Builder.CreateLoad(Addr);7590LI->setMetadata(llvm::LLVMContext::MD_invariant_load,7591llvm::MDNode::get(VMContext, std::nullopt));7592return LI;7593}75947595ConstantAddress CGObjCNonFragileABIMac::EmitSelectorAddr(Selector Sel) {7596llvm::GlobalVariable *&Entry = SelectorReferences[Sel];7597CharUnits Align = CGM.getPointerAlign();7598if (!Entry) {7599std::string SectionName =7600GetSectionName("__objc_selrefs", "literal_pointers,no_dead_strip");7601Entry = new llvm::GlobalVariable(7602CGM.getModule(), ObjCTypes.SelectorPtrTy, false,7603getLinkageTypeForObjCMetadata(CGM, SectionName), GetMethodVarName(Sel),7604"OBJC_SELECTOR_REFERENCES_");7605Entry->setExternallyInitialized(true);7606Entry->setSection(SectionName);7607Entry->setAlignment(Align.getAsAlign());7608CGM.addCompilerUsedGlobal(Entry);7609}76107611return ConstantAddress(Entry, ObjCTypes.SelectorPtrTy, Align);7612}76137614/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.7615/// objc_assign_ivar (id src, id *dst, ptrdiff_t)7616///7617void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,7618llvm::Value *src,7619Address dst,7620llvm::Value *ivarOffset) {7621llvm::Type * SrcTy = src->getType();7622if (!isa<llvm::PointerType>(SrcTy)) {7623unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);7624assert(Size <= 8 && "does not support size > 8");7625src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)7626: CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));7627src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);7628}7629src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);7630llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),7631ObjCTypes.PtrObjectPtrTy);7632llvm::Value *args[] = {src, dstVal, ivarOffset};7633CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);7634}76357636/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.7637/// objc_assign_strongCast (id src, id *dst)7638///7639void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(7640CodeGen::CodeGenFunction &CGF,7641llvm::Value *src, Address dst) {7642llvm::Type * SrcTy = src->getType();7643if (!isa<llvm::PointerType>(SrcTy)) {7644unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);7645assert(Size <= 8 && "does not support size > 8");7646src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)7647: CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));7648src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);7649}7650src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);7651llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),7652ObjCTypes.PtrObjectPtrTy);7653llvm::Value *args[] = {src, dstVal};7654CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),7655args, "weakassign");7656}76577658void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(7659CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr,7660llvm::Value *Size) {7661llvm::Value *args[] = {DestPtr.emitRawPointer(CGF),7662SrcPtr.emitRawPointer(CGF), Size};7663CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);7664}76657666/// EmitObjCWeakRead - Code gen for loading value of a __weak7667/// object: objc_read_weak (id *src)7668///7669llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(7670CodeGen::CodeGenFunction &CGF,7671Address AddrWeakObj) {7672llvm::Type *DestTy = AddrWeakObj.getElementType();7673llvm::Value *AddrWeakObjVal = CGF.Builder.CreateBitCast(7674AddrWeakObj.emitRawPointer(CGF), ObjCTypes.PtrObjectPtrTy);7675llvm::Value *read_weak =7676CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),7677AddrWeakObjVal, "weakread");7678read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);7679return read_weak;7680}76817682/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.7683/// objc_assign_weak (id src, id *dst)7684///7685void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,7686llvm::Value *src, Address dst) {7687llvm::Type * SrcTy = src->getType();7688if (!isa<llvm::PointerType>(SrcTy)) {7689unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);7690assert(Size <= 8 && "does not support size > 8");7691src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)7692: CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));7693src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);7694}7695src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);7696llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),7697ObjCTypes.PtrObjectPtrTy);7698llvm::Value *args[] = {src, dstVal};7699CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),7700args, "weakassign");7701}77027703/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.7704/// objc_assign_global (id src, id *dst)7705///7706void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,7707llvm::Value *src, Address dst,7708bool threadlocal) {7709llvm::Type * SrcTy = src->getType();7710if (!isa<llvm::PointerType>(SrcTy)) {7711unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);7712assert(Size <= 8 && "does not support size > 8");7713src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)7714: CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));7715src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);7716}7717src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);7718llvm::Value *dstVal = CGF.Builder.CreateBitCast(dst.emitRawPointer(CGF),7719ObjCTypes.PtrObjectPtrTy);7720llvm::Value *args[] = {src, dstVal};7721if (!threadlocal)7722CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),7723args, "globalassign");7724else7725CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),7726args, "threadlocalassign");7727}77287729void7730CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,7731const ObjCAtSynchronizedStmt &S) {7732EmitAtSynchronizedStmt(CGF, S, ObjCTypes.getSyncEnterFn(),7733ObjCTypes.getSyncExitFn());7734}77357736llvm::Constant *7737CGObjCNonFragileABIMac::GetEHType(QualType T) {7738// There's a particular fixed type info for 'id'.7739if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {7740auto *IDEHType = CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");7741if (!IDEHType) {7742IDEHType =7743new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,7744llvm::GlobalValue::ExternalLinkage, nullptr,7745"OBJC_EHTYPE_id");7746if (CGM.getTriple().isOSBinFormatCOFF())7747IDEHType->setDLLStorageClass(getStorage(CGM, "OBJC_EHTYPE_id"));7748}7749return IDEHType;7750}77517752// All other types should be Objective-C interface pointer types.7753const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();7754assert(PT && "Invalid @catch type.");77557756const ObjCInterfaceType *IT = PT->getInterfaceType();7757assert(IT && "Invalid @catch type.");77587759return GetInterfaceEHType(IT->getDecl(), NotForDefinition);7760}77617762void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,7763const ObjCAtTryStmt &S) {7764EmitTryCatchStmt(CGF, S, ObjCTypes.getObjCBeginCatchFn(),7765ObjCTypes.getObjCEndCatchFn(),7766ObjCTypes.getExceptionRethrowFn());7767}77687769/// EmitThrowStmt - Generate code for a throw statement.7770void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,7771const ObjCAtThrowStmt &S,7772bool ClearInsertionPoint) {7773if (const Expr *ThrowExpr = S.getThrowExpr()) {7774llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);7775Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);7776llvm::CallBase *Call =7777CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception);7778Call->setDoesNotReturn();7779} else {7780llvm::CallBase *Call =7781CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn());7782Call->setDoesNotReturn();7783}77847785CGF.Builder.CreateUnreachable();7786if (ClearInsertionPoint)7787CGF.Builder.ClearInsertionPoint();7788}77897790llvm::Constant *7791CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,7792ForDefinition_t IsForDefinition) {7793llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];7794StringRef ClassName = ID->getObjCRuntimeNameAsString();77957796// If we don't need a definition, return the entry if found or check7797// if we use an external reference.7798if (!IsForDefinition) {7799if (Entry)7800return Entry;78017802// If this type (or a super class) has the __objc_exception__7803// attribute, emit an external reference.7804if (hasObjCExceptionAttribute(CGM.getContext(), ID)) {7805std::string EHTypeName = ("OBJC_EHTYPE_$_" + ClassName).str();7806Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,7807false, llvm::GlobalValue::ExternalLinkage,7808nullptr, EHTypeName);7809CGM.setGVProperties(Entry, ID);7810return Entry;7811}7812}78137814// Otherwise we need to either make a new entry or fill in the initializer.7815assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");78167817std::string VTableName = "objc_ehtype_vtable";7818auto *VTableGV = CGM.getModule().getGlobalVariable(VTableName);7819if (!VTableGV) {7820VTableGV =7821new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy, false,7822llvm::GlobalValue::ExternalLinkage, nullptr,7823VTableName);7824if (CGM.getTriple().isOSBinFormatCOFF())7825VTableGV->setDLLStorageClass(getStorage(CGM, VTableName));7826}78277828llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);7829ConstantInitBuilder builder(CGM);7830auto values = builder.beginStruct(ObjCTypes.EHTypeTy);7831values.add(7832llvm::ConstantExpr::getInBoundsGetElementPtr(VTableGV->getValueType(),7833VTableGV, VTableIdx));7834values.add(GetClassName(ClassName));7835values.add(GetClassGlobal(ID, /*metaclass*/ false, NotForDefinition));78367837llvm::GlobalValue::LinkageTypes L = IsForDefinition7838? llvm::GlobalValue::ExternalLinkage7839: llvm::GlobalValue::WeakAnyLinkage;7840if (Entry) {7841values.finishAndSetAsInitializer(Entry);7842Entry->setAlignment(CGM.getPointerAlign().getAsAlign());7843} else {7844Entry = values.finishAndCreateGlobal("OBJC_EHTYPE_$_" + ClassName,7845CGM.getPointerAlign(),7846/*constant*/ false,7847L);7848if (hasObjCExceptionAttribute(CGM.getContext(), ID))7849CGM.setGVProperties(Entry, ID);7850}7851assert(Entry->getLinkage() == L);78527853if (!CGM.getTriple().isOSBinFormatCOFF())7854if (ID->getVisibility() == HiddenVisibility)7855Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);78567857if (IsForDefinition)7858if (CGM.getTriple().isOSBinFormatMachO())7859Entry->setSection("__DATA,__objc_const");78607861return Entry;7862}78637864/* *** */78657866CodeGen::CGObjCRuntime *7867CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {7868switch (CGM.getLangOpts().ObjCRuntime.getKind()) {7869case ObjCRuntime::FragileMacOSX:7870return new CGObjCMac(CGM);78717872case ObjCRuntime::MacOSX:7873case ObjCRuntime::iOS:7874case ObjCRuntime::WatchOS:7875return new CGObjCNonFragileABIMac(CGM);78767877case ObjCRuntime::GNUstep:7878case ObjCRuntime::GCC:7879case ObjCRuntime::ObjFW:7880llvm_unreachable("these runtimes are not Mac runtimes");7881}7882llvm_unreachable("bad runtime");7883}788478857886