#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/Basic/Builtins.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/Rewriters.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ConvertUTF.h"
using namespace clang;
using namespace sema;
using llvm::makeArrayRef;
ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings) {
StringLiteral *S = cast<StringLiteral>(Strings[0]);
if (Strings.size() != 1) {
SmallString<128> StrBuf;
SmallVector<SourceLocation, 8> StrLocs;
for (Expr *E : Strings) {
S = cast<StringLiteral>(E);
if (!S->isOrdinary()) {
Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
<< S->getSourceRange();
return true;
}
StrBuf += S->getString();
StrLocs.append(S->tokloc_begin(), S->tokloc_end());
}
const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
assert(CAT && "String literal not of constant array type!");
QualType StrTy = Context.getConstantArrayType(
CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ordinary,
false, StrTy, &StrLocs[0],
StrLocs.size());
}
return BuildObjCStringLiteral(AtLocs[0], S);
}
ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
if (CheckObjCString(S))
return true;
QualType Ty = Context.getObjCConstantStringInterface();
if (!Ty.isNull()) {
Ty = Context.getObjCObjectPointerType(Ty);
} else if (getLangOpts().NoConstantCFStrings) {
IdentifierInfo *NSIdent=nullptr;
std::string StringClass(getLangOpts().ObjCConstantStringClass);
if (StringClass.empty())
NSIdent = &Context.Idents.get("NSConstantString");
else
NSIdent = &Context.Idents.get(StringClass);
NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
LookupOrdinaryName);
if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
Context.setObjCConstantStringInterface(StrIF);
Ty = Context.getObjCConstantStringInterface();
Ty = Context.getObjCObjectPointerType(Ty);
} else {
Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
<< NSIdent << S->getSourceRange();
Ty = Context.getObjCIdType();
}
} else {
IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
LookupOrdinaryName);
if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
Context.setObjCConstantStringInterface(StrIF);
Ty = Context.getObjCConstantStringInterface();
Ty = Context.getObjCObjectPointerType(Ty);
} else {
Ty = Context.getObjCNSStringType();
if (Ty.isNull()) {
ObjCInterfaceDecl *NSStringIDecl =
ObjCInterfaceDecl::Create (Context,
Context.getTranslationUnitDecl(),
SourceLocation(), NSIdent,
nullptr, nullptr, SourceLocation());
Ty = Context.getObjCInterfaceType(NSStringIDecl);
Context.setObjCNSStringType(Ty);
}
Ty = Context.getObjCObjectPointerType(Ty);
}
}
return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
}
static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
const ObjCInterfaceDecl *Class,
Selector Sel, const ObjCMethodDecl *Method) {
if (!Method) {
S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
return false;
}
QualType ReturnType = Method->getReturnType();
if (!ReturnType->isObjCObjectPointerType()) {
S.Diag(Loc, diag::err_objc_literal_method_sig)
<< Sel;
S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
<< ReturnType;
return false;
}
return true;
}
static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
Sema::ObjCLiteralKind LiteralKind) {
switch (LiteralKind) {
case Sema::LK_Array:
return NSAPI::ClassId_NSArray;
case Sema::LK_Dictionary:
return NSAPI::ClassId_NSDictionary;
case Sema::LK_Numeric:
return NSAPI::ClassId_NSNumber;
case Sema::LK_String:
return NSAPI::ClassId_NSString;
case Sema::LK_Boxed:
return NSAPI::ClassId_NSValue;
case Sema::LK_Block:
case Sema::LK_None:
break;
}
llvm_unreachable("LiteralKind can't be converted into a ClassKind");
}
static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
SourceLocation Loc,
Sema::ObjCLiteralKind LiteralKind) {
if (!Decl) {
NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
S.Diag(Loc, diag::err_undeclared_objc_literal_class)
<< II->getName() << LiteralKind;
return false;
} else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
S.Diag(Loc, diag::err_undeclared_objc_literal_class)
<< Decl->getName() << LiteralKind;
S.Diag(Decl->getLocation(), diag::note_forward_class);
return false;
}
return true;
}
static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
SourceLocation Loc,
Sema::ObjCLiteralKind LiteralKind) {
NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
Sema::LookupOrdinaryName);
ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
ASTContext &Context = S.Context;
TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
nullptr, nullptr, SourceLocation());
}
if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
ID = nullptr;
}
return ID;
}
static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
QualType NumberType,
bool isLiteral = false,
SourceRange R = SourceRange()) {
Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
if (!Kind) {
if (isLiteral) {
S.Diag(Loc, diag::err_invalid_nsnumber_type)
<< NumberType << R;
}
return nullptr;
}
if (S.NSNumberLiteralMethods[*Kind])
return S.NSNumberLiteralMethods[*Kind];
Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
false);
ASTContext &CX = S.Context;
if (!S.NSNumberDecl) {
S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
Sema::LK_Numeric);
if (!S.NSNumberDecl) {
return nullptr;
}
}
if (S.NSNumberPointer.isNull()) {
QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
}
ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
TypeSourceInfo *ReturnTInfo = nullptr;
Method =
ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
false, false,
false,
false,
true,
false, ObjCMethodDecl::Required,
false);
ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
SourceLocation(), SourceLocation(),
&CX.Idents.get("value"),
NumberType, nullptr,
SC_None, nullptr);
Method->setMethodParams(S.Context, value, None);
}
if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
return nullptr;
S.NSNumberLiteralMethods[*Kind] = Method;
return Method;
}
ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
QualType NumberType = Number->getType();
if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
switch (Char->getKind()) {
case CharacterLiteral::Ascii:
case CharacterLiteral::UTF8:
NumberType = Context.CharTy;
break;
case CharacterLiteral::Wide:
NumberType = Context.getWideCharType();
break;
case CharacterLiteral::UTF16:
NumberType = Context.Char16Ty;
break;
case CharacterLiteral::UTF32:
NumberType = Context.Char32Ty;
break;
}
}
SourceRange NR(Number->getSourceRange());
ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
true, NR);
if (!Method)
return ExprError();
ParmVarDecl *ParamDecl = Method->parameters()[0];
InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
ParamDecl);
ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
SourceLocation(),
Number);
if (ConvertedNumber.isInvalid())
return ExprError();
Number = ConvertedNumber.get();
return MaybeBindToTemporary(
new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
SourceRange(AtLoc, NR.getEnd())));
}
ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
SourceLocation ValueLoc,
bool Value) {
ExprResult Inner;
if (getLangOpts().CPlusPlus) {
Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
} else {
Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
CK_IntegralToBoolean);
}
return BuildObjCNumericLiteral(AtLoc, Inner.get());
}
static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
QualType T,
bool ArrayLiteral = false) {
if (Element->isTypeDependent())
return Element;
ExprResult Result = S.CheckPlaceholderExpr(Element);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
InitializedEntity Entity
= InitializedEntity::InitializeParameter(S.Context, T,
false);
InitializationKind Kind = InitializationKind::CreateCopy(
Element->getBeginLoc(), SourceLocation());
InitializationSequence Seq(S, Entity, Kind, Element);
if (!Seq.Failed())
return Seq.Perform(S, Entity, Kind, Element);
}
Expr *OrigElement = Element;
Result = S.DefaultLvalueConversion(Element);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
if (!Element->getType()->isObjCObjectPointerType() &&
!Element->getType()->isBlockPointerType()) {
bool Recovered = false;
if (isa<IntegerLiteral>(OrigElement) ||
isa<CharacterLiteral>(OrigElement) ||
isa<FloatingLiteral>(OrigElement) ||
isa<ObjCBoolLiteralExpr>(OrigElement) ||
isa<CXXBoolLiteralExpr>(OrigElement)) {
if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
int Which = isa<CharacterLiteral>(OrigElement) ? 1
: (isa<CXXBoolLiteralExpr>(OrigElement) ||
isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
: 3;
S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
<< Which << OrigElement->getSourceRange()
<< FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Result =
S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
Recovered = true;
}
}
else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
if (String->isOrdinary()) {
S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
<< 0 << OrigElement->getSourceRange()
<< FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
if (Result.isInvalid())
return ExprError();
Element = Result.get();
Recovered = true;
}
}
if (!Recovered) {
S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
<< Element->getType();
return ExprError();
}
}
if (ArrayLiteral)
if (ObjCStringLiteral *getString =
dyn_cast<ObjCStringLiteral>(OrigElement)) {
if (StringLiteral *SL = getString->getString()) {
unsigned numConcat = SL->getNumConcatenated();
if (numConcat > 1) {
bool hasMacro = false;
for (unsigned i = 0; i < numConcat ; ++i)
if (SL->getStrTokenLoc(i).isMacroID()) {
hasMacro = true;
break;
}
if (!hasMacro)
S.Diag(Element->getBeginLoc(),
diag::warn_concatenated_nsarray_literal)
<< Element->getType();
}
}
}
return S.PerformCopyInitialization(
InitializedEntity::InitializeParameter(S.Context, T,
false),
Element->getBeginLoc(), Element);
}
ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
if (ValueExpr->isTypeDependent()) {
ObjCBoxedExpr *BoxedExpr =
new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
return BoxedExpr;
}
ObjCMethodDecl *BoxingMethod = nullptr;
QualType BoxedType;
ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
if (RValue.isInvalid()) {
return ExprError();
}
SourceLocation Loc = SR.getBegin();
ValueExpr = RValue.get();
QualType ValueType(ValueExpr->getType());
if (const PointerType *PT = ValueType->getAs<PointerType>()) {
QualType PointeeType = PT->getPointeeType();
if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
if (!NSStringDecl) {
NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_String);
if (!NSStringDecl) {
return ExprError();
}
QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
}
if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
if (CE->getCastKind() == CK_ArrayToPointerDecay)
if (auto *SL =
dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
assert((SL->isOrdinary() || SL->isUTF8()) &&
"unexpected character encoding");
StringRef Str = SL->getString();
const llvm::UTF8 *StrBegin = Str.bytes_begin();
const llvm::UTF8 *StrEnd = Str.bytes_end();
if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
BoxedType = Context.getAttributedType(
AttributedType::getNullabilityAttrKind(
NullabilityKind::NonNull),
NSStringPointer, NSStringPointer);
return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
}
Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
<< NSStringPointer << SL->getSourceRange();
}
if (!StringWithUTF8StringMethod) {
IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
TypeSourceInfo *ReturnTInfo = nullptr;
ObjCMethodDecl *M = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
NSStringPointer, ReturnTInfo, NSStringDecl,
false, false,
false,
false,
true,
false, ObjCMethodDecl::Required,
false);
QualType ConstCharType = Context.CharTy.withConst();
ParmVarDecl *value =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("value"),
Context.getPointerType(ConstCharType),
nullptr,
SC_None, nullptr);
M->setMethodParams(Context, value, None);
BoxingMethod = M;
}
if (!validateBoxingMethod(*this, Loc, NSStringDecl,
stringWithUTF8String, BoxingMethod))
return ExprError();
StringWithUTF8StringMethod = BoxingMethod;
}
BoxingMethod = StringWithUTF8StringMethod;
BoxedType = NSStringPointer;
Optional<NullabilityKind> Nullability =
BoxingMethod->getReturnType()->getNullability(Context);
if (Nullability)
BoxedType = Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
BoxedType);
}
} else if (ValueType->isBuiltinType()) {
if (const CharacterLiteral *Char =
dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
switch (Char->getKind()) {
case CharacterLiteral::Ascii:
case CharacterLiteral::UTF8:
ValueType = Context.CharTy;
break;
case CharacterLiteral::Wide:
ValueType = Context.getWideCharType();
break;
case CharacterLiteral::UTF16:
ValueType = Context.Char16Ty;
break;
case CharacterLiteral::UTF32:
ValueType = Context.Char32Ty;
break;
}
}
BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
BoxedType = NSNumberPointer;
} else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
if (!ET->getDecl()->isComplete()) {
Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
ET->getDecl()->getIntegerType());
BoxedType = NSNumberPointer;
} else if (ValueType->isObjCBoxableRecordType()) {
if (!NSValueDecl) {
NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Boxed);
if (!NSValueDecl) {
return ExprError();
}
QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
}
if (!ValueWithBytesObjCTypeMethod) {
IdentifierInfo *II[] = {
&Context.Idents.get("valueWithBytes"),
&Context.Idents.get("objCType")
};
Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
TypeSourceInfo *ReturnTInfo = nullptr;
ObjCMethodDecl *M = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
NSValuePointer, ReturnTInfo, NSValueDecl,
false,
false,
false,
false,
true,
false, ObjCMethodDecl::Required,
false);
SmallVector<ParmVarDecl *, 2> Params;
ParmVarDecl *bytes =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("bytes"),
Context.VoidPtrTy.withConst(),
nullptr,
SC_None, nullptr);
Params.push_back(bytes);
QualType ConstCharType = Context.CharTy.withConst();
ParmVarDecl *type =
ParmVarDecl::Create(Context, M,
SourceLocation(), SourceLocation(),
&Context.Idents.get("type"),
Context.getPointerType(ConstCharType),
nullptr,
SC_None, nullptr);
Params.push_back(type);
M->setMethodParams(Context, Params, None);
BoxingMethod = M;
}
if (!validateBoxingMethod(*this, Loc, NSValueDecl,
ValueWithBytesObjCType, BoxingMethod))
return ExprError();
ValueWithBytesObjCTypeMethod = BoxingMethod;
}
if (!ValueType.isTriviallyCopyableType(Context)) {
Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
BoxingMethod = ValueWithBytesObjCTypeMethod;
BoxedType = NSValuePointer;
}
if (!BoxingMethod) {
Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
<< ValueType << ValueExpr->getSourceRange();
return ExprError();
}
DiagnoseUseOfDecl(BoxingMethod, Loc);
ExprResult ConvertedValueExpr;
if (ValueType->isObjCBoxableRecordType()) {
InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
ValueExpr);
} else {
ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
ParamDecl);
ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
ValueExpr);
}
if (ConvertedValueExpr.isInvalid())
return ExprError();
ValueExpr = ConvertedValueExpr.get();
ObjCBoxedExpr *BoxedExpr =
new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
BoxingMethod, SR);
return MaybeBindToTemporary(BoxedExpr);
}
ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod) {
assert(!LangOpts.isSubscriptPointerArithmetic());
assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
"base or index cannot have dependent type here");
ExprResult Result = CheckPlaceholderExpr(IndexExpr);
if (Result.isInvalid())
return ExprError();
IndexExpr = Result.get();
Result = DefaultLvalueConversion(BaseExpr);
if (Result.isInvalid())
return ExprError();
BaseExpr = Result.get();
return new (Context) ObjCSubscriptRefExpr(
BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
getterMethod, setterMethod, RB);
}
ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
SourceLocation Loc = SR.getBegin();
if (!NSArrayDecl) {
NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Array);
if (!NSArrayDecl) {
return ExprError();
}
}
QualType IdT = Context.getObjCIdType();
if (!ArrayWithObjectsMethod) {
Selector
Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
if (!Method && getLangOpts().DebuggerObjCLiteral) {
TypeSourceInfo *ReturnTInfo = nullptr;
Method = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Context.getTranslationUnitDecl(), false ,
false ,
false, false,
true, false,
ObjCMethodDecl::Required, false);
SmallVector<ParmVarDecl *, 2> Params;
ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("objects"),
Context.getPointerType(IdT),
nullptr,
SC_None, nullptr);
Params.push_back(objects);
ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("cnt"),
Context.UnsignedLongTy,
nullptr, SC_None,
nullptr);
Params.push_back(cnt);
Method->setMethodParams(Context, Params, None);
}
if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
return ExprError();
QualType T = Method->parameters()[0]->getType();
const PointerType *PtrT = T->getAs<PointerType>();
if (!PtrT ||
!Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[0]->getLocation(),
diag::note_objc_literal_method_param)
<< 0 << T
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
if (!Method->parameters()[1]->getType()->isIntegerType()) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[1]->getLocation(),
diag::note_objc_literal_method_param)
<< 1
<< Method->parameters()[1]->getType()
<< "integral";
return ExprError();
}
ArrayWithObjectsMethod = Method;
}
QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Expr **ElementsBuffer = Elements.data();
for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
ElementsBuffer[I],
RequiredType, true);
if (Converted.isInvalid())
return ExprError();
ElementsBuffer[I] = Converted.get();
}
QualType Ty
= Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(NSArrayDecl));
return MaybeBindToTemporary(
ObjCArrayLiteral::Create(Context, Elements, Ty,
ArrayWithObjectsMethod, SR));
}
static void
CheckObjCDictionaryLiteralDuplicateKeys(Sema &S,
ObjCDictionaryLiteral *Literal) {
if (Literal->isValueDependent() || Literal->isTypeDependent())
return;
struct APSIntCompare {
bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
return llvm::APSInt::compareValues(LHS, RHS) < 0;
}
};
llvm::DenseMap<StringRef, SourceLocation> StringKeys;
std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
auto Pair = Map.insert({Key, Loc});
if (!Pair.second) {
S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
}
};
for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; ++Idx) {
Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
StringRef Bytes = StrLit->getString()->getBytes();
SourceLocation Loc = StrLit->getExprLoc();
checkOneKey(StringKeys, Bytes, Loc);
}
if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) {
Expr *Boxed = BE->getSubExpr();
SourceLocation Loc = BE->getExprLoc();
if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) {
checkOneKey(StringKeys, Str->getBytes(), Loc);
continue;
}
Expr::EvalResult Result;
if (Boxed->EvaluateAsInt(Result, S.getASTContext(),
Expr::SE_AllowSideEffects)) {
checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
}
}
}
}
ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements) {
SourceLocation Loc = SR.getBegin();
if (!NSDictionaryDecl) {
NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
Sema::LK_Dictionary);
if (!NSDictionaryDecl) {
return ExprError();
}
}
QualType IdT = Context.getObjCIdType();
if (!DictionaryWithObjectsMethod) {
Selector Sel = NSAPIObj->getNSDictionarySelector(
NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
if (!Method && getLangOpts().DebuggerObjCLiteral) {
Method = ObjCMethodDecl::Create(
Context, SourceLocation(), SourceLocation(), Sel, IdT,
nullptr , Context.getTranslationUnitDecl(),
false , false ,
false,
false,
true, false,
ObjCMethodDecl::Required, false);
SmallVector<ParmVarDecl *, 3> Params;
ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("objects"),
Context.getPointerType(IdT),
nullptr, SC_None,
nullptr);
Params.push_back(objects);
ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("keys"),
Context.getPointerType(IdT),
nullptr, SC_None,
nullptr);
Params.push_back(keys);
ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
SourceLocation(),
SourceLocation(),
&Context.Idents.get("cnt"),
Context.UnsignedLongTy,
nullptr, SC_None,
nullptr);
Params.push_back(cnt);
Method->setMethodParams(Context, Params, None);
}
if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
Method))
return ExprError();
QualType ValueT = Method->parameters()[0]->getType();
const PointerType *PtrValue = ValueT->getAs<PointerType>();
if (!PtrValue ||
!Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[0]->getLocation(),
diag::note_objc_literal_method_param)
<< 0 << ValueT
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
QualType KeyT = Method->parameters()[1]->getType();
const PointerType *PtrKey = KeyT->getAs<PointerType>();
if (!PtrKey ||
!Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
IdT)) {
bool err = true;
if (PtrKey) {
if (QIDNSCopying.isNull()) {
if (ObjCProtocolDecl *NSCopyingPDecl =
LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
QIDNSCopying =
Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
llvm::makeArrayRef(
(ObjCProtocolDecl**) PQ,
1),
false);
QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
}
}
if (!QIDNSCopying.isNull())
err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
QIDNSCopying);
}
if (err) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[1]->getLocation(),
diag::note_objc_literal_method_param)
<< 1 << KeyT
<< Context.getPointerType(IdT.withConst());
return ExprError();
}
}
QualType CountType = Method->parameters()[2]->getType();
if (!CountType->isIntegerType()) {
Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
<< Sel;
Diag(Method->parameters()[2]->getLocation(),
diag::note_objc_literal_method_param)
<< 2 << CountType
<< "integral";
return ExprError();
}
DictionaryWithObjectsMethod = Method;
}
QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
bool HasPackExpansions = false;
for (ObjCDictionaryElement &Element : Elements) {
ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
KeyT);
if (Key.isInvalid())
return ExprError();
ExprResult Value
= CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
if (Value.isInvalid())
return ExprError();
Element.Key = Key.get();
Element.Value = Value.get();
if (Element.EllipsisLoc.isInvalid())
continue;
if (!Element.Key->containsUnexpandedParameterPack() &&
!Element.Value->containsUnexpandedParameterPack()) {
Diag(Element.EllipsisLoc,
diag::err_pack_expansion_without_parameter_packs)
<< SourceRange(Element.Key->getBeginLoc(),
Element.Value->getEndLoc());
return ExprError();
}
HasPackExpansions = true;
}
QualType Ty = Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(NSDictionaryDecl));
auto *Literal =
ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
DictionaryWithObjectsMethod, SR);
CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
return MaybeBindToTemporary(Literal);
}
ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc) {
QualType EncodedType = EncodedTypeInfo->getType();
QualType StrTy;
if (EncodedType->isDependentType())
StrTy = Context.DependentTy;
else {
if (!EncodedType->getAsArrayTypeUnsafe() && !EncodedType->isVoidType()) if (RequireCompleteType(AtLoc, EncodedType,
diag::err_incomplete_type_objc_at_encode,
EncodedTypeInfo->getTypeLoc()))
return ExprError();
std::string Str;
QualType NotEncodedT;
Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
if (!NotEncodedT.isNull())
Diag(AtLoc, diag::warn_incomplete_encoded_type)
<< EncodedType << NotEncodedT;
StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
}
return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
}
ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType ty,
SourceLocation RParenLoc) {
TypeSourceInfo *TInfo;
QualType EncodedType = GetTypeFromParser(ty, &TInfo);
if (!TInfo)
TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
getLocForEndOfToken(LParenLoc));
return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
}
static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
ObjCMethodDecl *Method,
ObjCMethodList &MethList) {
ObjCMethodList *M = &MethList;
bool Warned = false;
for (M = M->getNext(); M; M=M->getNext()) {
ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
if (MatchingMethodDecl == Method ||
isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
MatchingMethodDecl->getSelector() != Method->getSelector())
continue;
if (!S.MatchTwoMethodDeclarations(Method,
MatchingMethodDecl, Sema::MMS_loose)) {
if (!Warned) {
Warned = true;
S.Diag(AtLoc, diag::warn_multiple_selectors)
<< Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
<< FixItHint::CreateInsertion(RParenLoc, ")");
S.Diag(Method->getLocation(), diag::note_method_declared_at)
<< Method->getDeclName();
}
S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
<< MatchingMethodDecl->getDeclName();
}
}
return Warned;
}
static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
ObjCMethodDecl *Method,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors) {
if (!WarnMultipleSelectors ||
S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
return;
bool Warned = false;
for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
e = S.MethodPool.end(); b != e; b++) {
ObjCMethodList &InstMethList = b->second.first;
if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Method, InstMethList))
Warned = true;
ObjCMethodList &ClsMethList = b->second.second;
if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Method, ClsMethList) || Warned)
return;
}
}
static ObjCMethodDecl *LookupDirectMethodInMethodList(Sema &S, Selector Sel,
ObjCMethodList &MethList,
bool &onlyDirect,
bool &anyDirect) {
(void)Sel;
ObjCMethodList *M = &MethList;
ObjCMethodDecl *DirectMethod = nullptr;
for (; M; M = M->getNext()) {
ObjCMethodDecl *Method = M->getMethod();
if (!Method)
continue;
assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
if (Method->isDirectMethod()) {
anyDirect = true;
DirectMethod = Method;
} else
onlyDirect = false;
}
return DirectMethod;
}
static ObjCMethodDecl *LookupDirectMethodInGlobalPool(Sema &S, Selector Sel,
bool &onlyDirect,
bool &anyDirect) {
auto Iter = S.MethodPool.find(Sel);
if (Iter == S.MethodPool.end())
return nullptr;
ObjCMethodDecl *DirectInstance = LookupDirectMethodInMethodList(
S, Sel, Iter->second.first, onlyDirect, anyDirect);
ObjCMethodDecl *DirectClass = LookupDirectMethodInMethodList(
S, Sel, Iter->second.second, onlyDirect, anyDirect);
return DirectInstance ? DirectInstance : DirectClass;
}
static ObjCMethodDecl *findMethodInCurrentClass(Sema &S, Selector Sel) {
auto *CurMD = S.getCurMethodDecl();
if (!CurMD)
return nullptr;
ObjCInterfaceDecl *IFace = CurMD->getClassInterface();
if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, true))
return MD;
if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, true))
return MD;
if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, false))
return MD;
if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, false))
return MD;
return nullptr;
}
ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors) {
ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
SourceRange(LParenLoc, RParenLoc));
if (!Method)
Method = LookupFactoryMethodInGlobalPool(Sel,
SourceRange(LParenLoc, RParenLoc));
if (!Method) {
if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
Selector MatchedSel = OM->getSelector();
SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
RParenLoc.getLocWithOffset(-1));
Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
<< Sel << MatchedSel
<< FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
} else
Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
} else {
DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
WarnMultipleSelectors);
bool onlyDirect = true;
bool anyDirect = false;
ObjCMethodDecl *GlobalDirectMethod =
LookupDirectMethodInGlobalPool(*this, Sel, onlyDirect, anyDirect);
if (onlyDirect) {
Diag(AtLoc, diag::err_direct_selector_expression)
<< Method->getSelector();
Diag(Method->getLocation(), diag::note_direct_method_declared_at)
<< Method->getDeclName();
} else if (anyDirect) {
ObjCMethodDecl *LikelyTargetMethod = findMethodInCurrentClass(*this, Sel);
if (LikelyTargetMethod && LikelyTargetMethod->isDirectMethod()) {
Diag(AtLoc, diag::warn_potentially_direct_selector_expression) << Sel;
Diag(LikelyTargetMethod->getLocation(),
diag::note_direct_method_declared_at)
<< LikelyTargetMethod->getDeclName();
} else if (!LikelyTargetMethod) {
Diag(AtLoc, diag::warn_strict_potentially_direct_selector_expression)
<< Sel;
Diag(GlobalDirectMethod->getLocation(),
diag::note_direct_method_declared_at)
<< GlobalDirectMethod->getDeclName();
}
}
}
if (Method &&
Method->getImplementationControl() != ObjCMethodDecl::Optional &&
!getSourceManager().isInSystemHeader(Method->getLocation()))
ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
if (getLangOpts().ObjCAutoRefCount) {
switch (Sel.getMethodFamily()) {
case OMF_retain:
case OMF_release:
case OMF_autorelease:
case OMF_retainCount:
case OMF_dealloc:
Diag(AtLoc, diag::err_arc_illegal_selector) <<
Sel << SourceRange(LParenLoc, RParenLoc);
break;
case OMF_None:
case OMF_alloc:
case OMF_copy:
case OMF_finalize:
case OMF_init:
case OMF_mutableCopy:
case OMF_new:
case OMF_self:
case OMF_initialize:
case OMF_performSelector:
break;
}
}
QualType Ty = Context.getObjCSelType();
return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
}
ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc) {
ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
if (!PDecl) {
Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
return true;
}
if (PDecl->isNonRuntimeProtocol())
Diag(ProtoLoc, diag::err_objc_non_runtime_protocol_in_protocol_expr)
<< PDecl;
if (!PDecl->hasDefinition()) {
Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
} else {
PDecl = PDecl->getDefinition();
}
QualType Ty = Context.getObjCProtoType();
if (Ty.isNull())
return true;
Ty = Context.getObjCObjectPointerType(Ty);
return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
}
ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
DeclContext *DC = getFunctionLevelDeclContext();
ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
if (!method)
return nullptr;
tryCaptureVariable(method->getSelfDecl(), Loc);
return method;
}
static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
QualType origType = T;
if (auto nullability = AttributedType::stripOuterNullability(T)) {
if (T == Context.getObjCInstanceType()) {
return Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*nullability),
Context.getObjCIdType(),
Context.getObjCIdType());
}
return origType;
}
if (T == Context.getObjCInstanceType())
return Context.getObjCIdType();
return origType;
}
static QualType getBaseMessageSendResultType(Sema &S,
QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage,
bool isSuperMessage) {
assert(Method && "Must have a method");
if (!Method->hasRelatedResultType())
return Method->getSendResultType(ReceiverType);
ASTContext &Context = S.Context;
auto transferNullability = [&](QualType type) -> QualType {
if (auto nullability = Method->getSendResultType(ReceiverType)
->getNullability(Context)){
(void)AttributedType::stripOuterNullability(type);
return Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*nullability),
type,
type);
}
return type;
};
if (Method->isInstanceMethod() && isClassMessage)
return stripObjCInstanceType(Context,
Method->getSendResultType(ReceiverType));
if (isSuperMessage) {
if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
return transferNullability(
Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(Class)));
}
}
if (ReceiverType->getAsObjCInterfaceType())
return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
if (ReceiverType->isObjCClassType() ||
ReceiverType->isObjCQualifiedClassType())
return stripObjCInstanceType(Context,
Method->getSendResultType(ReceiverType));
return transferNullability(ReceiverType);
}
QualType Sema::getMessageSendResultType(const Expr *Receiver,
QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage,
bool isSuperMessage) {
QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
Method,
isClassMessage,
isSuperMessage);
if (isClassMessage) {
if (Receiver && Receiver->isObjCSelfExpr()) {
assert(ReceiverType->isObjCClassType() && "expected a Class self");
QualType T = Method->getSendResultType(ReceiverType);
AttributedType::stripOuterNullability(T);
if (T == Context.getObjCInstanceType()) {
const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
cast<ImplicitParamDecl>(
cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
->getDeclContext());
assert(MD->isClassMethod() && "expected a class method");
QualType NewResultType = Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(MD->getClassInterface()));
if (auto Nullability = resultType->getNullability(Context))
NewResultType = Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*Nullability),
NewResultType, NewResultType);
return NewResultType;
}
}
return resultType;
}
if (!resultType->canHaveNullability())
return resultType;
unsigned receiverNullabilityIdx = 0;
if (Optional<NullabilityKind> nullability =
ReceiverType->getNullability(Context)) {
if (*nullability == NullabilityKind::NullableResult)
nullability = NullabilityKind::Nullable;
receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
}
unsigned resultNullabilityIdx = 0;
if (Optional<NullabilityKind> nullability =
resultType->getNullability(Context)) {
if (*nullability == NullabilityKind::NullableResult)
nullability = NullabilityKind::Nullable;
resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
}
static const uint8_t None = 0;
static const uint8_t NonNull = 1;
static const uint8_t Nullable = 2;
static const uint8_t Unspecified = 3;
static const uint8_t nullabilityMap[4][4] = {
{ None, None, Nullable, None },
{ None, NonNull, Nullable, Unspecified },
{ Nullable, Nullable, Nullable, Nullable },
{ None, Unspecified, Nullable, Unspecified }
};
unsigned newResultNullabilityIdx
= nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
if (newResultNullabilityIdx == resultNullabilityIdx)
return resultType;
do {
if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
resultType = attributed->getModifiedType();
} else {
resultType = resultType.getDesugaredType(Context);
}
} while (resultType->getNullability(Context));
if (newResultNullabilityIdx > 0) {
auto newNullability
= static_cast<NullabilityKind>(newResultNullabilityIdx-1);
return Context.getAttributedType(
AttributedType::getNullabilityAttrKind(newNullability),
resultType, resultType);
}
return resultType;
}
static const ObjCMethodDecl *
findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
QualType instancetype) {
if (MD->getReturnType() == instancetype)
return MD;
if (const ObjCImplDecl *impl =
dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
const ObjCContainerDecl *iface;
if (const ObjCCategoryImplDecl *catImpl =
dyn_cast<ObjCCategoryImplDecl>(impl)) {
iface = catImpl->getCategoryDecl();
} else {
iface = impl->getClassInterface();
}
const ObjCMethodDecl *ifaceMD =
iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
}
SmallVector<const ObjCMethodDecl *, 4> overrides;
MD->getOverriddenMethods(overrides);
for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
if (const ObjCMethodDecl *result =
findExplicitInstancetypeDeclarer(overrides[i], instancetype))
return result;
}
return nullptr;
}
void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
if (!MD || !MD->hasRelatedResultType() ||
Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
return;
if (const ObjCMethodDecl *overridden =
findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
SourceRange range = overridden->getReturnTypeSourceRange();
SourceLocation loc = range.getBegin();
if (loc.isInvalid())
loc = overridden->getLocation();
Diag(loc, diag::note_related_result_type_explicit)
<< 1 << range;
return;
}
if (ObjCMethodFamily family = MD->getMethodFamily())
Diag(MD->getLocation(), diag::note_related_result_type_family)
<< 1
<< family;
}
void Sema::EmitRelatedResultTypeNote(const Expr *E) {
E = E->IgnoreParenImpCasts();
const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
if (!MsgSend)
return;
const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
if (!Method)
return;
if (!Method->hasRelatedResultType())
return;
if (Context.hasSameUnqualifiedType(
Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
return;
if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Context.getObjCInstanceType()))
return;
Diag(Method->getLocation(), diag::note_related_result_type_inferred)
<< Method->isInstanceMethod() << Method->getSelector()
<< MsgSend->getType();
}
bool Sema::CheckMessageArgumentTypes(
const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
ExprValueKind &VK) {
SourceLocation SelLoc;
if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
SelLoc = SelectorLocs.front();
else
SelLoc = lbrac;
if (!Method) {
for (unsigned i = 0, e = Args.size(); i != e; i++) {
if (Args[i]->isTypeDependent())
continue;
ExprResult result;
if (getLangOpts().DebuggerSupport) {
QualType paramTy; result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
} else {
result = DefaultArgumentPromotion(Args[i]);
}
if (result.isInvalid())
return true;
Args[i] = result.get();
}
unsigned DiagID;
if (getLangOpts().ObjCAutoRefCount)
DiagID = diag::err_arc_method_not_found;
else
DiagID = isClassMessage ? diag::warn_class_method_not_found
: diag::warn_inst_method_not_found;
if (!getLangOpts().DebuggerSupport) {
const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
if (OMD && !OMD->isInvalidDecl()) {
if (getLangOpts().ObjCAutoRefCount)
DiagID = diag::err_method_not_found_with_typo;
else
DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
: diag::warn_instance_method_not_found_with_typo;
Selector MatchedSel = OMD->getSelector();
SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
if (MatchedSel.isUnarySelector())
Diag(SelLoc, DiagID)
<< Sel<< isClassMessage << MatchedSel
<< FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
else
Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
}
else
Diag(SelLoc, DiagID)
<< Sel << isClassMessage << SourceRange(SelectorLocs.front(),
SelectorLocs.back());
if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) {
Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
if (!RecRange.isInvalid())
if (ThisClass->lookupClassMethod(Sel))
Diag(RecRange.getBegin(), diag::note_receiver_expr_here)
<< FixItHint::CreateReplacement(RecRange,
ThisClass->getNameAsString());
}
}
}
if (getLangOpts().DebuggerSupport) {
ReturnType = Context.UnknownAnyTy;
} else {
ReturnType = Context.getObjCIdType();
}
VK = VK_PRValue;
return false;
}
ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
isClassMessage, isSuperMessage);
VK = Expr::getValueKindForType(Method->getReturnType());
unsigned NumNamedArgs = Sel.getNumArgs();
if (Method->param_size() > Sel.getNumArgs())
NumNamedArgs = Method->param_size();
if (Args.size() < NumNamedArgs) {
Diag(SelLoc, diag::err_typecheck_call_too_few_args)
<< 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
return false;
}
Optional<ArrayRef<QualType>> typeArgs
= ReceiverType->getObjCSubstitutions(Method->getDeclContext());
bool IsError = false;
for (unsigned i = 0; i < NumNamedArgs; i++) {
if (Args[i]->isTypeDependent())
continue;
Expr *argExpr = Args[i];
ParmVarDecl *param = Method->parameters()[i];
assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
if (param->hasAttr<NoEscapeAttr>() &&
param->getType()->isBlockPointerType())
if (auto *BE = dyn_cast<BlockExpr>(
argExpr->IgnoreParenNoopCasts(Context)))
BE->getBlockDecl()->setDoesNotEscape();
if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
!param->hasAttr<CFConsumedAttr>())
argExpr = stripARCUnbridgedCast(argExpr);
if (param->getType() == Context.UnknownAnyTy) {
QualType paramType;
ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
if (argE.isInvalid()) {
IsError = true;
} else {
Args[i] = argE.get();
param->setType(paramType);
}
continue;
}
QualType origParamType = param->getType();
QualType paramType = param->getType();
if (typeArgs)
paramType = paramType.substObjCTypeArgs(
Context,
*typeArgs,
ObjCSubstitutionContext::Parameter);
if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
paramType,
diag::err_call_incomplete_argument, argExpr))
return true;
InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context, param, paramType);
ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
if (ArgE.isInvalid())
IsError = true;
else {
Args[i] = ArgE.getAs<Expr>();
if (typeArgs && Args[i]->isPRValue() && paramType->isBlockPointerType() &&
Args[i]->getType()->isBlockPointerType() &&
origParamType->isObjCObjectPointerType()) {
ExprResult arg = Args[i];
maybeExtendBlockObject(arg);
Args[i] = arg.get();
}
}
}
if (Method->isVariadic()) {
for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
if (Args[i]->isTypeDependent())
continue;
ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
nullptr);
IsError |= Arg.isInvalid();
Args[i] = Arg.get();
}
} else {
if (Args.size() != NumNamedArgs) {
Diag(Args[NumNamedArgs]->getBeginLoc(),
diag::err_typecheck_call_too_many_args)
<< 2 << NumNamedArgs << static_cast<unsigned>(Args.size())
<< Method->getSourceRange()
<< SourceRange(Args[NumNamedArgs]->getBeginLoc(),
Args.back()->getEndLoc());
}
}
DiagnoseSentinelCalls(Method, SelLoc, Args);
IsError |= CheckObjCMethodCall(
Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
return IsError;
}
bool Sema::isSelfExpr(Expr *RExpr) {
ObjCMethodDecl *Method =
dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
return isSelfExpr(RExpr, Method);
}
bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
if (!method) return false;
receiver = receiver->IgnoreParenLValueCasts();
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
if (DRE->getDecl() == method->getSelfDecl())
return true;
return false;
}
ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
bool isInstance) {
const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
if (ObjCInterfaceDecl *iface = objType->getInterface()) {
if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
return method;
if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
return method;
}
for (const auto *I : objType->quals())
if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
return method;
return nullptr;
}
ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool Instance)
{
ObjCMethodDecl *MD = nullptr;
for (const auto *PROTO : OPT->quals()) {
if ((MD = PROTO->lookupMethod(Sel, Instance))) {
return MD;
}
}
return nullptr;
}
ExprResult Sema::
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr, SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super) {
const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
ObjCInterfaceDecl *IFace = IFaceT->getDecl();
if (!MemberName.isIdentifier()) {
Diag(MemberLoc, diag::err_invalid_property_name)
<< MemberName << QualType(OPT, 0);
return ExprError();
}
IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
SourceRange BaseRange = Super? SourceRange(SuperLoc)
: BaseExpr->getSourceRange();
if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
diag::err_property_not_found_forward_class,
MemberName, BaseRange))
return ExprError();
if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
if (DiagnoseUseOfDecl(PD, MemberLoc))
return ExprError();
if (Super)
return new (Context)
ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
else
return new (Context)
ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, MemberLoc, BaseExpr);
}
for (const auto *I : OPT->quals())
if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
if (DiagnoseUseOfDecl(PD, MemberLoc))
return ExprError();
if (Super)
return new (Context) ObjCPropertyRefExpr(
PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
SuperLoc, SuperType);
else
return new (Context)
ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, MemberLoc, BaseExpr);
}
Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
if (!Getter)
Getter = LookupMethodInQualifiedType(Sel, OPT, true);
if (!Getter)
Getter = IFace->lookupPrivateMethod(Sel);
if (Getter) {
if (DiagnoseUseOfDecl(Getter, MemberLoc))
return ExprError();
}
Selector SetterSel =
SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
PP.getSelectorTable(), Member);
ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
if (!Setter)
Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
if (!Setter) {
Setter = IFace->lookupPrivateMethod(SetterSel);
}
if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
return ExprError();
if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
!IFace->FindPropertyDeclaration(
Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
if (!(PDecl->getPropertyAttributes() &
ObjCPropertyAttribute::kind_setter))
Diag(MemberLoc,
diag::warn_property_access_suggest)
<< MemberName << QualType(OPT, 0) << PDecl->getName()
<< FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
}
}
if (Getter || Setter) {
if (Super)
return new (Context)
ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
else
return new (Context)
ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, MemberLoc, BaseExpr);
}
DeclFilterCCC<ObjCPropertyDecl> CCC{};
if (TypoCorrection Corrected = CorrectTypo(
DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
DeclarationName TypoResult = Corrected.getCorrection();
if (TypoResult.isIdentifier() &&
TypoResult.getAsIdentifierInfo() == Member) {
NamedDecl *ChosenDecl =
Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
Diag(MemberLoc, diag::err_class_property_found) << MemberName
<< OPT->getInterfaceDecl()->getName()
<< FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
OPT->getInterfaceDecl()->getName());
return ExprError();
}
} else {
diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
<< MemberName << QualType(OPT, 0));
return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
TypoResult, MemberLoc,
SuperLoc, SuperType, Super);
}
}
ObjCInterfaceDecl *ClassDeclared;
if (ObjCIvarDecl *Ivar =
IFace->lookupInstanceVariable(Member, ClassDeclared)) {
QualType T = Ivar->getType();
if (const ObjCObjectPointerType * OBJPT =
T->getAsObjCInterfacePointerType()) {
if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
diag::err_property_not_as_forward_class,
MemberName, BaseExpr))
return ExprError();
}
Diag(MemberLoc,
diag::err_ivar_access_using_property_syntax_suggest)
<< MemberName << QualType(OPT, 0) << Ivar->getDeclName()
<< FixItHint::CreateReplacement(OpLoc, "->");
return ExprError();
}
Diag(MemberLoc, diag::err_property_not_found)
<< MemberName << QualType(OPT, 0);
if (Setter)
Diag(Setter->getLocation(), diag::note_getter_unavailable)
<< MemberName << BaseExpr->getSourceRange();
return ExprError();
}
ExprResult Sema::
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc) {
IdentifierInfo *receiverNamePtr = &receiverName;
ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
receiverNameLoc);
QualType SuperType;
if (!IFace) {
if (receiverNamePtr->isStr("super")) {
if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
if (auto classDecl = CurMethod->getClassInterface()) {
SuperType = QualType(classDecl->getSuperClassType(), 0);
if (CurMethod->isInstanceMethod()) {
if (SuperType.isNull()) {
Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
<< CurMethod->getClassInterface()->getIdentifier();
return ExprError();
}
QualType T = Context.getObjCObjectPointerType(SuperType);
return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
nullptr,
SourceLocation(),
&propertyName,
propertyNameLoc,
receiverNameLoc, T, true);
}
IFace = CurMethod->getClassInterface()->getSuperClass();
}
}
}
if (!IFace) {
Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
<< tok::l_paren;
return ExprError();
}
}
Selector GetterSel;
Selector SetterSel;
if (auto PD = IFace->FindPropertyDeclaration(
&propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
GetterSel = PD->getGetterName();
SetterSel = PD->getSetterName();
} else {
GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
SetterSel = SelectorTable::constructSetterSelector(
PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
}
ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
if (!Getter)
Getter = IFace->lookupPrivateClassMethod(GetterSel);
if (Getter) {
if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
return ExprError();
}
ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
if (!Setter) {
Setter = IFace->lookupPrivateClassMethod(SetterSel);
}
if (!Setter)
Setter = IFace->getCategoryClassMethod(SetterSel);
if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
return ExprError();
if (Getter || Setter) {
if (!SuperType.isNull())
return new (Context)
ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
SuperType);
return new (Context) ObjCPropertyRefExpr(
Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
propertyNameLoc, receiverNameLoc, IFace);
}
return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
<< &propertyName << Context.getObjCInterfaceType(IFace));
}
namespace {
class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
public:
ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
if (Method && Method->getClassInterface())
WantObjCSuper = Method->getClassInterface()->getSuperClass();
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
candidate.isKeyword("super");
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
}
};
}
Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType) {
ReceiverType = nullptr;
if (IsSuper && S->isInObjcMethodScope())
return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
LookupName(Result, S);
switch (Result.getResultKind()) {
case LookupResult::NotFound:
if (ObjCMethodDecl *Method = getCurMethodDecl()) {
if (!Method->getClassInterface()) {
return ObjCInstanceMessage;
}
ObjCInterfaceDecl *ClassDeclared;
if (Method->getClassInterface()->lookupInstanceVariable(Name,
ClassDeclared))
return ObjCInstanceMessage;
}
break;
case LookupResult::NotFoundInCurrentInstantiation:
case LookupResult::FoundOverloaded:
case LookupResult::FoundUnresolvedValue:
case LookupResult::Ambiguous:
Result.suppressDiagnostics();
return ObjCInstanceMessage;
case LookupResult::Found: {
if (HasTrailingDot)
return ObjCInstanceMessage;
NamedDecl *ND = Result.getFoundDecl();
QualType T;
if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
T = Context.getObjCInterfaceType(Class);
else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
T = Context.getTypeDeclType(Type);
DiagnoseUseOfDecl(Type, NameLoc);
}
else
return ObjCInstanceMessage;
TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
ReceiverType = CreateParsedType(T, TSInfo);
return ObjCClassMessage;
}
}
ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
if (TypoCorrection Corrected = CorrectTypo(
Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
if (Corrected.isKeyword()) {
diagnoseTypo(Corrected,
PDiag(diag::err_unknown_receiver_suggest) << Name);
return ObjCSuperMessage;
} else if (ObjCInterfaceDecl *Class =
Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
diagnoseTypo(Corrected,
PDiag(diag::err_unknown_receiver_suggest) << Name);
QualType T = Context.getObjCInterfaceType(Class);
TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
ReceiverType = CreateParsedType(T, TSInfo);
return ObjCClassMessage;
}
}
return ObjCInstanceMessage;
}
ExprResult Sema::ActOnSuperMessage(Scope *S,
SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args) {
ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
if (!Method) {
Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
return ExprError();
}
ObjCInterfaceDecl *Class = Method->getClassInterface();
if (!Class) {
Diag(SuperLoc, diag::err_no_super_class_message)
<< Method->getDeclName();
return ExprError();
}
QualType SuperTy(Class->getSuperClassType(), 0);
if (SuperTy.isNull()) {
Diag(SuperLoc, diag::err_root_class_cannot_use_super)
<< Class->getIdentifier();
return ExprError();
}
if (Method->getSelector() == Sel)
getCurFunction()->ObjCShouldCallSuper = false;
if (Method->isInstanceMethod()) {
SuperTy = Context.getObjCObjectPointerType(SuperTy);
return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
Sel, nullptr,
LBracLoc, SelectorLocs, RBracLoc, Args);
}
return BuildClassMessage(nullptr,
SuperTy,
SuperLoc, Sel, nullptr,
LBracLoc, SelectorLocs, RBracLoc, Args);
}
ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args) {
TypeSourceInfo *receiverTypeInfo = nullptr;
if (!ReceiverType.isNull())
receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
return BuildClassMessage(receiverTypeInfo, ReceiverType,
isSuperReceiver ? Loc : SourceLocation(),
Sel, Method, Loc, Loc, Loc, Args,
true);
}
static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
unsigned DiagID,
bool (*refactor)(const ObjCMessageExpr *,
const NSAPI &, edit::Commit &)) {
SourceLocation MsgLoc = Msg->getExprLoc();
if (S.Diags.isIgnored(DiagID, MsgLoc))
return;
SourceManager &SM = S.SourceMgr;
edit::Commit ECommit(SM, S.LangOpts);
if (refactor(Msg,*S.NSAPIObj, ECommit)) {
auto Builder = S.Diag(MsgLoc, DiagID)
<< Msg->getSelector() << Msg->getSourceRange();
if (!ECommit.isCommitable())
return;
for (edit::Commit::edit_iterator
I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
const edit::Commit::Edit &Edit = *I;
switch (Edit.Kind) {
case edit::Commit::Act_Insert:
Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
Edit.Text,
Edit.BeforePrev));
break;
case edit::Commit::Act_InsertFromRange:
Builder.AddFixItHint(
FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
Edit.getInsertFromRange(SM),
Edit.BeforePrev));
break;
case edit::Commit::Act_Remove:
Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
break;
}
}
}
}
static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
edit::rewriteObjCRedundantCallWithLiteral);
}
static void checkFoundationAPI(Sema &S, SourceLocation Loc,
const ObjCMethodDecl *Method,
ArrayRef<Expr *> Args, QualType ReceiverType,
bool IsClassObjectCall) {
if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
Args.empty())
return;
const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
if (!SE)
return;
ObjCMethodDecl *ImpliedMethod;
if (!IsClassObjectCall) {
const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
if (!OPT || !OPT->getInterfaceDecl())
return;
ImpliedMethod =
OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
if (!ImpliedMethod)
ImpliedMethod =
OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
} else {
const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
if (!IT)
return;
ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
if (!ImpliedMethod)
ImpliedMethod =
IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
}
if (!ImpliedMethod)
return;
QualType Ret = ImpliedMethod->getReturnType();
if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
<< Method->getSelector()
<< (!Ret->isRecordType()
? 2
: Ret->isUnionType() ? 1 : 0);
S.Diag(ImpliedMethod->getBeginLoc(),
diag::note_objc_unsafe_perform_selector_method_declared_here)
<< ImpliedMethod->getSelector() << Ret;
}
}
static void
DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
ObjCMethodDecl *Method,
Selector Sel,
Expr **Args, unsigned NumArgs) {
unsigned Idx = 0;
bool Format = false;
ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Idx = 0;
Format = true;
}
else if (Method) {
for (const auto *I : Method->specific_attrs<FormatAttr>()) {
if (S.GetFormatNSStringIdx(I, Idx)) {
Format = true;
break;
}
}
}
if (!Format || NumArgs <= Idx)
return;
Expr *FormatExpr = Args[Idx];
if (ObjCStringLiteral *OSL =
dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
StringLiteral *FormatString = OSL->getString();
if (S.FormatStringHasSArg(FormatString)) {
S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
<< "%s" << 0 << 0;
if (Method)
S.Diag(Method->getLocation(), diag::note_method_declared_at)
<< Method->getDeclName();
}
}
}
ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg ArgsIn,
bool isImplicit) {
SourceLocation Loc = SuperLoc.isValid()? SuperLoc
: ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
if (LBracLoc.isInvalid()) {
Diag(Loc, diag::err_missing_open_square_message_send)
<< FixItHint::CreateInsertion(Loc, "[");
LBracLoc = Loc;
}
ArrayRef<SourceLocation> SelectorSlotLocs;
if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
SelectorSlotLocs = SelectorLocs;
else
SelectorSlotLocs = Loc;
SourceLocation SelLoc = SelectorSlotLocs.front();
if (ReceiverType->isDependentType()) {
unsigned NumArgs = ArgsIn.size();
Expr **Args = ArgsIn.data();
assert(SuperLoc.isInvalid() && "Message to super with dependent type");
return ObjCMessageExpr::Create(
Context, ReceiverType, VK_PRValue, LBracLoc, ReceiverTypeInfo, Sel,
SelectorLocs, nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
isImplicit);
}
ObjCInterfaceDecl *Class = nullptr;
const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
if (!ClassType || !(Class = ClassType->getInterface())) {
Diag(Loc, diag::err_invalid_receiver_class_message)
<< ReceiverType;
return ExprError();
}
assert(Class && "We don't know which class we're messaging?");
if (!getLangOpts().CPlusPlus)
(void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
if (!Method) {
SourceRange TypeRange
= SuperLoc.isValid()? SourceRange(SuperLoc)
: ReceiverTypeInfo->getTypeLoc().getSourceRange();
if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
(getLangOpts().ObjCAutoRefCount
? diag::err_arc_receiver_forward_class
: diag::warn_receiver_forward_class),
TypeRange)) {
Method = LookupFactoryMethodInGlobalPool(Sel,
SourceRange(LBracLoc, RBracLoc));
if (Method && !getLangOpts().ObjCAutoRefCount)
Diag(Method->getLocation(), diag::note_method_sent_forward_class)
<< Method->getDeclName();
}
if (!Method)
Method = Class->lookupClassMethod(Sel);
if (!Method)
Method = Class->lookupPrivateClassMethod(Sel);
if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
nullptr, false, false, Class))
return ExprError();
}
QualType ReturnType;
ExprValueKind VK = VK_PRValue;
unsigned NumArgs = ArgsIn.size();
Expr **Args = ArgsIn.data();
if (CheckMessageArgumentTypes(nullptr, ReceiverType,
MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
Method, true, SuperLoc.isValid(), LBracLoc,
RBracLoc, SourceRange(), ReturnType, VK))
return ExprError();
if (Method && !Method->getReturnType()->isVoidType() &&
RequireCompleteType(LBracLoc, Method->getReturnType(),
diag::err_illegal_message_expr_incomplete_type))
return ExprError();
if (Method && Method->isDirectMethod() && SuperLoc.isValid()) {
Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
<< FixItHint::CreateReplacement(
SuperLoc, getLangOpts().ObjCAutoRefCount
? "self"
: Method->getClassInterface()->getName());
Diag(Method->getLocation(), diag::note_direct_method_declared_at)
<< Method->getDeclName();
}
if (Method && Method->getMethodFamily() == OMF_initialize) {
if (!SuperLoc.isValid()) {
const ObjCInterfaceDecl *ID =
dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
if (ID == Class) {
Diag(Loc, diag::warn_direct_initialize_call);
Diag(Method->getLocation(), diag::note_method_declared_at)
<< Method->getDeclName();
}
}
else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
if (CurMeth->getMethodFamily() != OMF_initialize) {
Diag(Loc, diag::warn_direct_super_initialize_call);
Diag(Method->getLocation(), diag::note_method_declared_at)
<< Method->getDeclName();
Diag(CurMeth->getLocation(), diag::note_method_declared_at)
<< CurMeth->getDeclName();
}
}
}
DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
ObjCMessageExpr *Result;
if (SuperLoc.isValid())
Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
SuperLoc, false,
ReceiverType, Sel, SelectorLocs,
Method, makeArrayRef(Args, NumArgs),
RBracLoc, isImplicit);
else {
Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
ReceiverTypeInfo, Sel, SelectorLocs,
Method, makeArrayRef(Args, NumArgs),
RBracLoc, isImplicit);
if (!isImplicit)
checkCocoaAPI(*this, Result);
}
if (Method)
checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
ReceiverType, true);
return MaybeBindToTemporary(Result);
}
ExprResult Sema::ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args) {
TypeSourceInfo *ReceiverTypeInfo;
QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
if (ReceiverType.isNull())
return ExprError();
if (!ReceiverTypeInfo)
ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
SourceLocation(), Sel,
nullptr, LBracLoc, SelectorLocs, RBracLoc,
Args);
}
ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args) {
return BuildInstanceMessage(Receiver, ReceiverType,
!Receiver ? Loc : SourceLocation(),
Sel, Method, Loc, Loc, Loc, Args,
true);
}
static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
if (!S.NSAPIObj)
return false;
const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
if (!Protocol)
return false;
const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
Sema::LookupOrdinaryName))) {
for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
return true;
}
}
return false;
}
ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg ArgsIn,
bool isImplicit) {
assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
"SuperLoc must be valid so we can "
"use it instead.");
SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
SourceRange RecRange =
SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
ArrayRef<SourceLocation> SelectorSlotLocs;
if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
SelectorSlotLocs = SelectorLocs;
else
SelectorSlotLocs = Loc;
SourceLocation SelLoc = SelectorSlotLocs.front();
if (LBracLoc.isInvalid()) {
Diag(Loc, diag::err_missing_open_square_message_send)
<< FixItHint::CreateInsertion(Loc, "[");
LBracLoc = Loc;
}
if (Receiver) {
if (Receiver->hasPlaceholderType()) {
ExprResult Result;
if (Receiver->getType() == Context.UnknownAnyTy)
Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
else
Result = CheckPlaceholderExpr(Receiver);
if (Result.isInvalid()) return ExprError();
Receiver = Result.get();
}
if (Receiver->isTypeDependent()) {
unsigned NumArgs = ArgsIn.size();
Expr **Args = ArgsIn.data();
assert(SuperLoc.isInvalid() && "Message to super with dependent type");
return ObjCMessageExpr::Create(
Context, Context.DependentTy, VK_PRValue, LBracLoc, Receiver, Sel,
SelectorLocs, nullptr, makeArrayRef(Args, NumArgs),
RBracLoc, isImplicit);
}
ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
if (Result.isInvalid())
return ExprError();
Receiver = Result.get();
ReceiverType = Receiver->getType();
if (ReceiverType->isObjCRetainableType()) {
} else if (!getLangOpts().ObjCAutoRefCount &&
!Context.getObjCIdType().isNull() &&
(ReceiverType->isPointerType() ||
ReceiverType->isIntegerType())) {
Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
if (ReceiverType->isPointerType()) {
Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
CK_CPointerToObjCPointerCast).get();
} else {
bool IsNull = Receiver->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNull);
CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Kind).get();
}
ReceiverType = Receiver->getType();
} else if (getLangOpts().CPlusPlus) {
if (RequireCompleteType(Loc, Receiver->getType(),
diag::err_incomplete_receiver_type))
return ExprError();
ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
if (result.isUsable()) {
Receiver = result.get();
ReceiverType = Receiver->getType();
}
}
}
if (!Method) {
const ObjCObjectType *typeBound = nullptr;
bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
typeBound);
if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
(Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
SmallVector<ObjCMethodDecl*, 4> Methods;
CollectMultipleMethodsInGlobalPool(Sel, Methods, true,
true, typeBound);
if (!Methods.empty()) {
Method = Methods[0];
if (ObjCMethodDecl *BestMethod =
SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Method = BestMethod;
if (!AreMultipleMethodsInGlobalPool(Sel, Method,
SourceRange(LBracLoc, RBracLoc),
receiverIsIdLike, Methods))
DiagnoseUseOfDecl(Method, SelectorSlotLocs);
}
} else if (ReceiverType->isObjCClassOrClassKindOfType() ||
ReceiverType->isObjCQualifiedClassType()) {
if (!ReceiverType->isObjCClassOrClassKindOfType()) {
const ObjCObjectPointerType *QClassTy
= ReceiverType->getAsObjCQualifiedClassType();
Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
if (!Method) {
Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
Diag(SelLoc, diag::warn_instance_method_on_class_found)
<< Method->getSelector() << Sel;
Diag(Method->getLocation(), diag::note_method_declared_at)
<< Method->getDeclName();
}
}
} else {
if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
Method = ClassDecl->lookupClassMethod(Sel);
if (!Method)
Method = ClassDecl->lookupPrivateClassMethod(Sel);
if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
return ExprError();
}
}
if (!Method) {
if (!Receiver || !isSelfExpr(Receiver)) {
SmallVector<ObjCMethodDecl*, 4> Methods;
CollectMultipleMethodsInGlobalPool(Sel, Methods,
false,
true);
if (!Methods.empty()) {
Method = Methods[0];
if (Method->isInstanceMethod()) {
if (const ObjCInterfaceDecl *ID =
dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
if (ID->getSuperClass())
Diag(SelLoc, diag::warn_root_inst_method_not_found)
<< Sel << SourceRange(LBracLoc, RBracLoc);
}
}
if (ObjCMethodDecl *BestMethod =
SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
Methods))
Method = BestMethod;
}
}
}
}
} else {
ObjCInterfaceDecl *ClassDecl = nullptr;
if (const ObjCObjectPointerType *QIdTy
= ReceiverType->getAsObjCQualifiedIdType()) {
Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
if (!Method)
Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
return ExprError();
} else if (const ObjCObjectPointerType *OCIType
= ReceiverType->getAsObjCInterfacePointerType()) {
ClassDecl = OCIType->getInterfaceDecl();
const ObjCInterfaceDecl *forwardClass = nullptr;
if (RequireCompleteType(Loc, OCIType->getPointeeType(),
getLangOpts().ObjCAutoRefCount
? diag::err_arc_receiver_forward_instance
: diag::warn_receiver_forward_instance,
RecRange)) {
if (getLangOpts().ObjCAutoRefCount)
return ExprError();
forwardClass = OCIType->getInterfaceDecl();
Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
diag::note_receiver_is_id);
Method = nullptr;
} else {
Method = ClassDecl->lookupInstanceMethod(Sel);
}
if (!Method)
Method = LookupMethodInQualifiedType(Sel, OCIType, true);
if (!Method) {
Method = ClassDecl->lookupPrivateMethod(Sel);
if (!Method && getLangOpts().ObjCAutoRefCount) {
Diag(SelLoc, diag::err_arc_may_not_respond)
<< OCIType->getPointeeType() << Sel << RecRange
<< SourceRange(SelectorLocs.front(), SelectorLocs.back());
return ExprError();
}
if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
if (OCIType->qual_empty()) {
SmallVector<ObjCMethodDecl*, 4> Methods;
CollectMultipleMethodsInGlobalPool(Sel, Methods,
true,
false);
if (!Methods.empty()) {
Method = Methods[0];
if (ObjCMethodDecl *BestMethod =
SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
Methods))
Method = BestMethod;
AreMultipleMethodsInGlobalPool(Sel, Method,
SourceRange(LBracLoc, RBracLoc),
true,
Methods);
}
if (Method && !forwardClass)
Diag(SelLoc, diag::warn_maynot_respond)
<< OCIType->getInterfaceDecl()->getIdentifier()
<< Sel << RecRange;
}
}
}
if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
return ExprError();
} else {
Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
return ExprError();
}
}
}
FunctionScopeInfo *DIFunctionScopeInfo =
(Method && Method->getMethodFamily() == OMF_init)
? getEnclosingFunction() : nullptr;
if (Method && Method->isDirectMethod()) {
if (ReceiverType->isObjCIdType() && !isImplicit) {
Diag(Receiver->getExprLoc(),
diag::err_messaging_unqualified_id_with_direct_method);
Diag(Method->getLocation(), diag::note_direct_method_declared_at)
<< Method->getDeclName();
}
if (ReceiverType->isObjCClassType() && !isImplicit &&
!(Receiver->isObjCSelfExpr() && getLangOpts().ObjCAutoRefCount)) {
{
auto Builder = Diag(Receiver->getExprLoc(),
diag::err_messaging_class_with_direct_method);
if (Receiver->isObjCSelfExpr()) {
Builder.AddFixItHint(FixItHint::CreateReplacement(
RecRange, Method->getClassInterface()->getName()));
}
}
Diag(Method->getLocation(), diag::note_direct_method_declared_at)
<< Method->getDeclName();
}
if (SuperLoc.isValid()) {
{
auto Builder =
Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
if (ReceiverType->isObjCClassType()) {
Builder.AddFixItHint(FixItHint::CreateReplacement(
SuperLoc, Method->getClassInterface()->getName()));
} else {
Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
}
}
Diag(Method->getLocation(), diag::note_direct_method_declared_at)
<< Method->getDeclName();
}
} else if (ReceiverType->isObjCIdType() && !isImplicit) {
Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
}
if (DIFunctionScopeInfo &&
DIFunctionScopeInfo->ObjCIsDesignatedInit &&
(SuperLoc.isValid() || isSelfExpr(Receiver))) {
bool isDesignatedInitChain = false;
if (SuperLoc.isValid()) {
if (const ObjCObjectPointerType *
OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
if (!ID->declaresOrInheritsDesignatedInitializers() ||
ID->isDesignatedInitializer(Sel)) {
isDesignatedInitChain = true;
DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
}
}
}
}
if (!isDesignatedInitChain) {
const ObjCMethodDecl *InitMethod = nullptr;
bool isDesignated =
getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
assert(isDesignated && InitMethod);
(void)isDesignated;
Diag(SelLoc, SuperLoc.isValid() ?
diag::warn_objc_designated_init_non_designated_init_call :
diag::warn_objc_designated_init_non_super_designated_init_call);
Diag(InitMethod->getLocation(),
diag::note_objc_designated_init_marked_here);
}
}
if (DIFunctionScopeInfo &&
DIFunctionScopeInfo->ObjCIsSecondaryInit &&
(SuperLoc.isValid() || isSelfExpr(Receiver))) {
if (SuperLoc.isValid()) {
Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
} else {
DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
}
}
unsigned NumArgs = ArgsIn.size();
Expr **Args = ArgsIn.data();
QualType ReturnType;
ExprValueKind VK = VK_PRValue;
bool ClassMessage = (ReceiverType->isObjCClassType() ||
ReceiverType->isObjCQualifiedClassType());
if (CheckMessageArgumentTypes(Receiver, ReceiverType,
MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
Method, ClassMessage, SuperLoc.isValid(),
LBracLoc, RBracLoc, RecRange, ReturnType, VK))
return ExprError();
if (Method && !Method->getReturnType()->isVoidType() &&
RequireCompleteType(LBracLoc, Method->getReturnType(),
diag::err_illegal_message_expr_incomplete_type))
return ExprError();
if (getLangOpts().ObjCAutoRefCount) {
ObjCMethodFamily family =
(Method ? Method->getMethodFamily() : Sel.getMethodFamily());
switch (family) {
case OMF_init:
if (Method)
checkInitMethod(Method, ReceiverType);
break;
case OMF_None:
case OMF_alloc:
case OMF_copy:
case OMF_finalize:
case OMF_mutableCopy:
case OMF_new:
case OMF_self:
case OMF_initialize:
break;
case OMF_dealloc:
case OMF_retain:
case OMF_release:
case OMF_autorelease:
case OMF_retainCount:
Diag(SelLoc, diag::err_arc_illegal_explicit_message)
<< Sel << RecRange;
break;
case OMF_performSelector:
if (Method && NumArgs >= 1) {
if (const auto *SelExp =
dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
Selector ArgSel = SelExp->getSelector();
ObjCMethodDecl *SelMethod =
LookupInstanceMethodInGlobalPool(ArgSel,
SelExp->getSourceRange());
if (!SelMethod)
SelMethod =
LookupFactoryMethodInGlobalPool(ArgSel,
SelExp->getSourceRange());
if (SelMethod) {
ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
switch (SelFamily) {
case OMF_alloc:
case OMF_copy:
case OMF_mutableCopy:
case OMF_new:
case OMF_init:
if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
Diag(SelLoc,
diag::err_arc_perform_selector_retains);
Diag(SelMethod->getLocation(), diag::note_method_declared_at)
<< SelMethod->getDeclName();
}
break;
default:
if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
Diag(SelLoc,
diag::err_arc_perform_selector_retains);
Diag(SelMethod->getLocation(), diag::note_method_declared_at)
<< SelMethod->getDeclName();
}
break;
}
}
} else {
Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Diag(Args[0]->getExprLoc(), diag::note_used_here);
}
}
break;
}
}
DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
ObjCMessageExpr *Result;
if (SuperLoc.isValid())
Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
SuperLoc, true,
ReceiverType, Sel, SelectorLocs, Method,
makeArrayRef(Args, NumArgs), RBracLoc,
isImplicit);
else {
Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Receiver, Sel, SelectorLocs, Method,
makeArrayRef(Args, NumArgs), RBracLoc,
isImplicit);
if (!isImplicit)
checkCocoaAPI(*this, Result);
}
if (Method) {
bool IsClassObjectCall = ClassMessage;
if (Receiver && isSelfExpr(Receiver)) {
if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
if (OPT->getObjectType()->isObjCClass()) {
if (const auto *CurMeth = getCurMethodDecl()) {
IsClassObjectCall = true;
ReceiverType =
Context.getObjCInterfaceType(CurMeth->getClassInterface());
}
}
}
}
checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
ReceiverType, IsClassObjectCall);
}
if (getLangOpts().ObjCAutoRefCount) {
if (Result->getMethodFamily() == OMF_init &&
(SuperLoc.isValid() || isSelfExpr(Receiver))) {
ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
if (method && method->getMethodFamily() == OMF_init) {
Result->setDelegateInitCall(true);
return Result;
}
}
checkRetainCycles(Result);
}
if (getLangOpts().ObjCWeak) {
if (!isImplicit && Method) {
if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
bool IsWeak =
Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
if (!IsWeak && Sel.isUnarySelector())
IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
if (IsWeak && !isUnevaluatedContext() &&
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
getCurFunction()->recordUseOfWeak(Result, Prop);
}
}
}
CheckObjCCircularContainer(Result);
return MaybeBindToTemporary(Result);
}
static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
if (ObjCSelectorExpr *OSE =
dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
Selector Sel = OSE->getSelector();
SourceLocation Loc = OSE->getAtLoc();
auto Pos = S.ReferencedSelectors.find(Sel);
if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
S.ReferencedSelectors.erase(Pos);
}
}
ExprResult Sema::ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args) {
if (!Receiver)
return ExprError();
if (isa<ParenListExpr>(Receiver)) {
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
if (Result.isInvalid()) return ExprError();
Receiver = Result.get();
}
if (RespondsToSelectorSel.isNull()) {
IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
}
if (Sel == RespondsToSelectorSel)
RemoveSelectorFromWarningCache(*this, Args[0]);
return BuildInstanceMessage(Receiver, Receiver->getType(),
SourceLocation(), Sel,
nullptr, LBracLoc, SelectorLocs,
RBracLoc, Args);
}
enum ARCConversionTypeClass {
ACTC_none,
ACTC_retainable,
ACTC_indirectRetainable,
ACTC_voidPtr,
ACTC_coreFoundation
};
static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
return (ACTC == ACTC_retainable ||
ACTC == ACTC_coreFoundation ||
ACTC == ACTC_voidPtr);
}
static bool isAnyCLike(ARCConversionTypeClass ACTC) {
return ACTC == ACTC_none ||
ACTC == ACTC_voidPtr ||
ACTC == ACTC_coreFoundation;
}
static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
bool isIndirect = false;
if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
type = ref->getPointeeType();
isIndirect = true;
}
while (true) {
if (const PointerType *ptr = type->getAs<PointerType>()) {
type = ptr->getPointeeType();
if (!isIndirect) {
if (type->isVoidType()) return ACTC_voidPtr;
if (type->isRecordType()) return ACTC_coreFoundation;
}
} else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
} else {
break;
}
isIndirect = true;
}
if (isIndirect) {
if (type->isObjCARCBridgableType())
return ACTC_indirectRetainable;
return ACTC_none;
}
if (type->isObjCARCBridgableType())
return ACTC_retainable;
return ACTC_none;
}
namespace {
enum ACCResult {
ACC_invalid,
ACC_bottom,
ACC_plusZero,
ACC_plusOne
};
ACCResult merge(ACCResult left, ACCResult right) {
if (left == right) return left;
if (left == ACC_bottom) return right;
if (right == ACC_bottom) return left;
return ACC_invalid;
}
class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
typedef StmtVisitor<ARCCastChecker, ACCResult> super;
ASTContext &Context;
ARCConversionTypeClass SourceClass;
ARCConversionTypeClass TargetClass;
bool Diagnose;
static bool isCFType(QualType type) {
return type->isCARCBridgableType();
}
public:
ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
ARCConversionTypeClass target, bool diagnose)
: Context(Context), SourceClass(source), TargetClass(target),
Diagnose(diagnose) {}
using super::Visit;
ACCResult Visit(Expr *e) {
return super::Visit(e->IgnoreParens());
}
ACCResult VisitStmt(Stmt *s) {
return ACC_invalid;
}
ACCResult VisitExpr(Expr *e) {
if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
return ACC_bottom;
return ACC_invalid;
}
ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
if (isAnyRetainable(TargetClass)) return ACC_bottom;
return ACC_invalid;
}
ACCResult VisitCastExpr(CastExpr *e) {
switch (e->getCastKind()) {
case CK_NullToPointer:
return ACC_bottom;
case CK_NoOp:
case CK_LValueToRValue:
case CK_BitCast:
case CK_CPointerToObjCPointerCast:
case CK_BlockPointerToObjCPointerCast:
case CK_AnyPointerToBlockPointerCast:
return Visit(e->getSubExpr());
default:
return ACC_invalid;
}
}
ACCResult VisitUnaryExtension(UnaryOperator *e) {
return Visit(e->getSubExpr());
}
ACCResult VisitBinComma(BinaryOperator *e) {
return Visit(e->getRHS());
}
ACCResult VisitConditionalOperator(ConditionalOperator *e) {
ACCResult left = Visit(e->getTrueExpr());
if (left == ACC_invalid) return ACC_invalid;
return merge(left, Visit(e->getFalseExpr()));
}
ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
return Visit(e->getResultExpr());
}
ACCResult VisitStmtExpr(StmtExpr *e) {
return Visit(e->getSubStmt()->body_back());
}
ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
if (isAnyRetainable(TargetClass) &&
isAnyRetainable(SourceClass) &&
var &&
!var->hasDefinition(Context) &&
var->getType().isConstQualified()) {
if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
return ACC_bottom;
return ACC_plusZero;
}
return ACC_invalid;
}
ACCResult VisitCallExpr(CallExpr *e) {
if (FunctionDecl *fn = e->getDirectCallee())
if (ACCResult result = checkCallToFunction(fn))
return result;
return super::VisitCallExpr(e);
}
ACCResult checkCallToFunction(FunctionDecl *fn) {
if (!isCFType(fn->getReturnType()))
return ACC_invalid;
if (!isAnyRetainable(TargetClass))
return ACC_invalid;
if (fn->hasAttr<CFReturnsNotRetainedAttr>())
return ACC_plusZero;
if (fn->hasAttr<CFReturnsRetainedAttr>())
return Diagnose ? ACC_plusOne
: ACC_invalid;
unsigned builtinID = fn->getBuiltinID();
if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
return ACC_bottom;
if (!fn->hasAttr<CFAuditedTransferAttr>())
return ACC_invalid;
if (ento::coreFoundation::followsCreateRule(fn))
return Diagnose ? ACC_plusOne
: ACC_invalid;
return ACC_plusZero;
}
ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
return checkCallToMethod(e->getMethodDecl());
}
ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
ObjCMethodDecl *method;
if (e->isExplicitProperty())
method = e->getExplicitProperty()->getGetterMethodDecl();
else
method = e->getImplicitPropertyGetter();
return checkCallToMethod(method);
}
ACCResult checkCallToMethod(ObjCMethodDecl *method) {
if (!method) return ACC_invalid;
if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
return ACC_invalid;
if (method->hasAttr<CFReturnsNotRetainedAttr>())
return ACC_plusZero;
if (method->hasAttr<CFReturnsRetainedAttr>())
return ACC_plusOne;
switch (method->getSelector().getMethodFamily()) {
case OMF_alloc:
case OMF_copy:
case OMF_mutableCopy:
case OMF_new:
return ACC_plusOne;
default:
return ACC_plusZero;
}
}
};
}
bool Sema::isKnownName(StringRef name) {
if (name.empty())
return false;
LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Sema::LookupOrdinaryName);
return LookupName(R, TUScope, false);
}
template <typename DiagBuilderT>
static void addFixitForObjCARCConversion(
Sema &S, DiagBuilderT &DiagB, Sema::CheckedConversionKind CCK,
SourceLocation afterLParen, QualType castType, Expr *castExpr,
Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) {
switch (CCK) {
case Sema::CCK_ImplicitConversion:
case Sema::CCK_ForBuiltinOverloadedOp:
case Sema::CCK_CStyleCast:
case Sema::CCK_OtherCast:
break;
case Sema::CCK_FunctionalCast:
return;
}
if (CFBridgeName) {
if (CCK == Sema::CCK_OtherCast) {
if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
SourceRange range(NCE->getOperatorLoc(),
NCE->getAngleBrackets().getEnd());
SmallString<32> BridgeCall;
SourceManager &SM = S.getSourceManager();
char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
BridgeCall += ' ';
BridgeCall += CFBridgeName;
DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
}
return;
}
Expr *castedE = castExpr;
if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
castedE = CCE->getSubExpr();
castedE = castedE->IgnoreImpCasts();
SourceRange range = castedE->getSourceRange();
SmallString<32> BridgeCall;
SourceManager &SM = S.getSourceManager();
char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
BridgeCall += ' ';
BridgeCall += CFBridgeName;
if (isa<ParenExpr>(castedE)) {
DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
BridgeCall));
} else {
BridgeCall += '(';
DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
BridgeCall));
DiagB.AddFixItHint(FixItHint::CreateInsertion(
S.getLocForEndOfToken(range.getEnd()),
")"));
}
return;
}
if (CCK == Sema::CCK_CStyleCast) {
DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
} else if (CCK == Sema::CCK_OtherCast) {
if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
std::string castCode = "(";
castCode += bridgeKeyword;
castCode += castType.getAsString();
castCode += ")";
SourceRange Range(NCE->getOperatorLoc(),
NCE->getAngleBrackets().getEnd());
DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
}
} else {
std::string castCode = "(";
castCode += bridgeKeyword;
castCode += castType.getAsString();
castCode += ")";
Expr *castedE = castExpr->IgnoreImpCasts();
SourceRange range = castedE->getSourceRange();
if (isa<ParenExpr>(castedE)) {
DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
castCode));
} else {
castCode += "(";
DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
castCode));
DiagB.AddFixItHint(FixItHint::CreateInsertion(
S.getLocForEndOfToken(range.getEnd()),
")"));
}
}
}
template <typename T>
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
TypedefNameDecl *TDNDecl = TD->getDecl();
QualType QT = TDNDecl->getUnderlyingType();
if (QT->isPointerType()) {
QT = QT->getPointeeType();
if (const RecordType *RT = QT->getAs<RecordType>()) {
for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
if (auto *attr = Redecl->getAttr<T>())
return attr;
}
}
}
return nullptr;
}
static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
TypedefNameDecl *&TDNDecl) {
while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
TDNDecl = TD->getDecl();
if (ObjCBridgeRelatedAttr *ObjCBAttr =
getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
return ObjCBAttr;
T = TDNDecl->getUnderlyingType();
}
return nullptr;
}
static void
diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
QualType castType, ARCConversionTypeClass castACTC,
Expr *castExpr, Expr *realCast,
ARCConversionTypeClass exprACTC,
Sema::CheckedConversionKind CCK) {
SourceLocation loc =
(castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
if (S.makeUnavailableInSystemHeader(loc,
UnavailableAttr::IR_ARCForbiddenConversion))
return;
QualType castExprType = castExpr->getType();
TypedefNameDecl *TDNDecl = nullptr;
if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
(exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
return;
unsigned srcKind = 0;
switch (exprACTC) {
case ACTC_none:
case ACTC_coreFoundation:
case ACTC_voidPtr:
srcKind = (castExprType->isPointerType() ? 1 : 0);
break;
case ACTC_retainable:
srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
break;
case ACTC_indirectRetainable:
srcKind = 4;
break;
}
SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
S.Diag(loc, diag::err_arc_cast_requires_bridge)
<< convKindForDiag
<< 2 << castExprType
<< unsigned(castType->isBlockPointerType()) << castType
<< castRange
<< castExpr->getSourceRange();
bool br = S.isKnownName("CFBridgingRelease");
ACCResult CreateRule =
ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
if (CreateRule != ACC_plusOne)
{
auto DiagB = (CCK != Sema::CCK_OtherCast)
? S.Diag(noteLoc, diag::note_arc_bridge)
: S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
castType, castExpr, realCast, "__bridge ",
nullptr);
}
if (CreateRule != ACC_plusZero)
{
auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer)
<< castExprType
: S.Diag(br ? castExpr->getExprLoc() : noteLoc,
diag::note_arc_bridge_transfer)
<< castExprType << br;
addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
castType, castExpr, realCast, "__bridge_transfer ",
br ? "CFBridgingRelease" : nullptr);
}
return;
}
if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
bool br = S.isKnownName("CFBridgingRetain");
S.Diag(loc, diag::err_arc_cast_requires_bridge)
<< convKindForDiag
<< unsigned(castExprType->isBlockPointerType()) << castExprType
<< 2 << castType
<< castRange
<< castExpr->getSourceRange();
ACCResult CreateRule =
ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
if (CreateRule != ACC_plusOne)
{
auto DiagB = (CCK != Sema::CCK_OtherCast)
? S.Diag(noteLoc, diag::note_arc_bridge)
: S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
castType, castExpr, realCast, "__bridge ",
nullptr);
}
if (CreateRule != ACC_plusZero)
{
auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained)
<< castType
: S.Diag(br ? castExpr->getExprLoc() : noteLoc,
diag::note_arc_bridge_retained)
<< castType << br;
addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
castType, castExpr, realCast, "__bridge_retained ",
br ? "CFBridgingRetain" : nullptr);
}
return;
}
S.Diag(loc, diag::err_arc_mismatched_cast)
<< !convKindForDiag
<< srcKind << castExprType << castType
<< castRange << castExpr->getSourceRange();
}
template <typename TB>
static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
bool &HadTheAttribute, bool warn) {
QualType T = castExpr->getType();
HadTheAttribute = false;
while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
TypedefNameDecl *TDNDecl = TD->getDecl();
if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
HadTheAttribute = true;
if (Parm->isStr("id"))
return true;
LookupResult R(S, DeclarationName(Parm), SourceLocation(),
Sema::LookupOrdinaryName);
if (S.LookupName(R, S.TUScope)) {
NamedDecl *Target = R.getFoundDecl();
if (Target && isa<ObjCInterfaceDecl>(Target)) {
ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
if (const ObjCObjectPointerType *InterfacePointerType =
castType->getAsObjCInterfacePointerType()) {
ObjCInterfaceDecl *CastClass
= InterfacePointerType->getObjectType()->getInterface();
if ((CastClass == ExprClass) ||
(CastClass && CastClass->isSuperClassOf(ExprClass)))
return true;
if (warn)
S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
<< T << Target->getName() << castType->getPointeeType();
return false;
} else if (castType->isObjCIdType() ||
(S.Context.ObjCObjectAdoptsQTypeProtocols(
castType, ExprClass)))
return true;
else {
if (warn) {
S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
<< T << Target->getName() << castType;
S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
S.Diag(Target->getBeginLoc(), diag::note_declared_at);
}
return false;
}
}
} else if (!castType->isObjCIdType()) {
S.Diag(castExpr->getBeginLoc(),
diag::err_objc_cf_bridged_not_interface)
<< castExpr->getType() << Parm;
S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
}
return true;
}
return false;
}
T = TDNDecl->getUnderlyingType();
}
return true;
}
template <typename TB>
static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
bool &HadTheAttribute, bool warn) {
QualType T = castType;
HadTheAttribute = false;
while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
TypedefNameDecl *TDNDecl = TD->getDecl();
if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
HadTheAttribute = true;
if (Parm->isStr("id"))
return true;
NamedDecl *Target = nullptr;
LookupResult R(S, DeclarationName(Parm), SourceLocation(),
Sema::LookupOrdinaryName);
if (S.LookupName(R, S.TUScope)) {
Target = R.getFoundDecl();
if (Target && isa<ObjCInterfaceDecl>(Target)) {
ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
if (const ObjCObjectPointerType *InterfacePointerType =
castExpr->getType()->getAsObjCInterfacePointerType()) {
ObjCInterfaceDecl *ExprClass
= InterfacePointerType->getObjectType()->getInterface();
if ((CastClass == ExprClass) ||
(ExprClass && CastClass->isSuperClassOf(ExprClass)))
return true;
if (warn) {
S.Diag(castExpr->getBeginLoc(),
diag::warn_objc_invalid_bridge_to_cf)
<< castExpr->getType()->getPointeeType() << T;
S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
}
return false;
} else if (castExpr->getType()->isObjCIdType() ||
(S.Context.QIdProtocolsAdoptObjCObjectProtocols(
castExpr->getType(), CastClass)))
return true;
else {
if (warn) {
S.Diag(castExpr->getBeginLoc(),
diag::warn_objc_invalid_bridge_to_cf)
<< castExpr->getType() << castType;
S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
S.Diag(Target->getBeginLoc(), diag::note_declared_at);
}
return false;
}
}
}
S.Diag(castExpr->getBeginLoc(),
diag::err_objc_ns_bridged_invalid_cfobject)
<< castExpr->getType() << castType;
S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
if (Target)
S.Diag(Target->getBeginLoc(), diag::note_declared_at);
return true;
}
return false;
}
T = TDNDecl->getUnderlyingType();
}
return true;
}
void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
if (!getLangOpts().ObjC)
return;
ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
bool HasObjCBridgeAttr;
bool ObjCBridgeAttrWillNotWarn =
CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
false);
if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
return;
bool HasObjCBridgeMutableAttr;
bool ObjCBridgeMutableAttrWillNotWarn =
CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
HasObjCBridgeMutableAttr, false);
if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
return;
if (HasObjCBridgeAttr)
CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
true);
else if (HasObjCBridgeMutableAttr)
CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
HasObjCBridgeMutableAttr, true);
}
else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
bool HasObjCBridgeAttr;
bool ObjCBridgeAttrWillNotWarn =
CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
false);
if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
return;
bool HasObjCBridgeMutableAttr;
bool ObjCBridgeMutableAttrWillNotWarn =
CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
HasObjCBridgeMutableAttr, false);
if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
return;
if (HasObjCBridgeAttr)
CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
true);
else if (HasObjCBridgeMutableAttr)
CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
HasObjCBridgeMutableAttr, true);
}
}
void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
QualType SrcType = castExpr->getType();
if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
if (PRE->isExplicitProperty()) {
if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
SrcType = PDecl->getType();
}
else if (PRE->isImplicitProperty()) {
if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
SrcType = Getter->getReturnType();
}
}
ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
return;
CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
castExpr);
}
bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind) {
if (!getLangOpts().ObjC)
return false;
ARCConversionTypeClass exprACTC =
classifyTypeForARCConversion(castExpr->getType());
ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
(castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
CheckTollFreeBridgeCast(castType, castExpr);
Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
: CK_CPointerToObjCPointerCast;
return true;
}
return false;
}
bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose) {
QualType T = CfToNs ? SrcType : DestType;
ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
if (!ObjCBAttr)
return false;
IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
if (!RCId)
return false;
NamedDecl *Target = nullptr;
LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
Sema::LookupOrdinaryName);
if (!LookupName(R, TUScope)) {
if (Diagnose) {
Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
<< SrcType << DestType;
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
}
return false;
}
Target = R.getFoundDecl();
if (Target && isa<ObjCInterfaceDecl>(Target))
RelatedClass = cast<ObjCInterfaceDecl>(Target);
else {
if (Diagnose) {
Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
<< SrcType << DestType;
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
if (Target)
Diag(Target->getBeginLoc(), diag::note_declared_at);
}
return false;
}
if (CfToNs && CMId) {
Selector Sel = Context.Selectors.getUnarySelector(CMId);
ClassMethod = RelatedClass->lookupMethod(Sel, false);
if (!ClassMethod) {
if (Diagnose) {
Diag(Loc, diag::err_objc_bridged_related_known_method)
<< SrcType << DestType << Sel << false;
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
}
return false;
}
}
if (!CfToNs && IMId) {
Selector Sel = Context.Selectors.getNullarySelector(IMId);
InstanceMethod = RelatedClass->lookupMethod(Sel, true);
if (!InstanceMethod) {
if (Diagnose) {
Diag(Loc, diag::err_objc_bridged_related_known_method)
<< SrcType << DestType << Sel << true;
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
}
return false;
}
}
return true;
}
bool
Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose) {
ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
if (!CfToNs && !NsToCf)
return false;
ObjCInterfaceDecl *RelatedClass;
ObjCMethodDecl *ClassMethod = nullptr;
ObjCMethodDecl *InstanceMethod = nullptr;
TypedefNameDecl *TDNDecl = nullptr;
if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
ClassMethod, InstanceMethod, TDNDecl,
CfToNs, Diagnose))
return false;
if (CfToNs) {
if (ClassMethod) {
if (Diagnose) {
std::string ExpressionString = "[";
ExpressionString += RelatedClass->getNameAsString();
ExpressionString += " ";
ExpressionString += ClassMethod->getSelector().getAsString();
SourceLocation SrcExprEndLoc =
getLocForEndOfToken(SrcExpr->getEndLoc());
Diag(Loc, diag::err_objc_bridged_related_known_method)
<< SrcType << DestType << ClassMethod->getSelector() << false
<< FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
ExpressionString)
<< FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
Expr *args[] = { SrcExpr };
ExprResult msg = BuildClassMessageImplicit(receiverType, false,
ClassMethod->getLocation(),
ClassMethod->getSelector(), ClassMethod,
MultiExprArg(args, 1));
SrcExpr = msg.get();
}
return true;
}
}
else {
if (InstanceMethod) {
if (Diagnose) {
std::string ExpressionString;
SourceLocation SrcExprEndLoc =
getLocForEndOfToken(SrcExpr->getEndLoc());
if (InstanceMethod->isPropertyAccessor())
if (const ObjCPropertyDecl *PDecl =
InstanceMethod->findPropertyDecl()) {
ExpressionString = ".";
ExpressionString += PDecl->getNameAsString();
Diag(Loc, diag::err_objc_bridged_related_known_method)
<< SrcType << DestType << InstanceMethod->getSelector() << true
<< FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
}
if (ExpressionString.empty()) {
ExpressionString = " ";
ExpressionString += InstanceMethod->getSelector().getAsString();
ExpressionString += "]";
Diag(Loc, diag::err_objc_bridged_related_known_method)
<< SrcType << DestType << InstanceMethod->getSelector() << true
<< FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
<< FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
}
Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
ExprResult msg =
BuildInstanceMessageImplicit(SrcExpr, SrcType,
InstanceMethod->getLocation(),
InstanceMethod->getSelector(),
InstanceMethod, None);
SrcExpr = msg.get();
}
return true;
}
}
return false;
}
Sema::ARCConversionResult
Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
Expr *&castExpr, CheckedConversionKind CCK,
bool Diagnose, bool DiagnoseCFAudited,
BinaryOperatorKind Opc) {
QualType castExprType = castExpr->getType();
QualType effCastType = castType;
if (const ReferenceType *ref = castType->getAs<ReferenceType>())
effCastType = ref->getPointeeType();
ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
if (exprACTC == castACTC) {
if (castACTC == ACTC_retainable &&
(CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
castType != castExprType) {
const Type *DT = castType.getTypePtr();
QualType QDT = castType;
if (const ParenType *PT = dyn_cast<ParenType>(DT))
QDT = PT->desugar();
else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
QDT = TP->desugar();
else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
QDT = AT->desugar();
if (QDT != castType &&
QDT.getObjCLifetime() != Qualifiers::OCL_None) {
if (Diagnose) {
SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
: castExpr->getExprLoc());
Diag(loc, diag::err_arc_nolifetime_behavior);
}
return ACR_error;
}
}
return ACR_okay;
}
if (!getLangOpts().ObjCAutoRefCount)
return ACR_okay;
if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
if (castACTC == ACTC_none && castType->isIntegralType(Context))
return ACR_okay;
if (exprACTC == ACTC_indirectRetainable &&
(castACTC == ACTC_voidPtr ||
(castACTC == ACTC_coreFoundation && isCast(CCK))))
return ACR_okay;
if (castACTC == ACTC_indirectRetainable &&
(exprACTC == ACTC_voidPtr || exprACTC == ACTC_coreFoundation) &&
isCast(CCK))
return ACR_okay;
switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
case ACC_invalid:
break;
case ACC_bottom:
case ACC_plusZero:
return ACR_okay;
case ACC_plusOne:
castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
CK_ARCConsumeObject, castExpr, nullptr,
VK_PRValue, FPOptionsOverride());
Cleanup.setExprNeedsCleanups(true);
return ACR_okay;
}
if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
return ACR_unbridged;
if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
CheckConversionToObjCLiteral(castType, castExpr, Diagnose))
return ACR_error;
if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
castACTC != ACTC_coreFoundation) &&
!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
(Opc == BO_NE || Opc == BO_EQ))) {
if (Diagnose)
diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
castExpr, exprACTC, CCK);
return ACR_error;
}
return ACR_okay;
}
void Sema::diagnoseARCUnbridgedCast(Expr *e) {
assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
SourceRange castRange;
QualType castType;
CheckedConversionKind CCK;
if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
castType = cast->getTypeAsWritten();
CCK = CCK_CStyleCast;
} else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
castType = cast->getTypeAsWritten();
CCK = CCK_OtherCast;
} else {
llvm_unreachable("Unexpected ImplicitCastExpr");
}
ARCConversionTypeClass castACTC =
classifyTypeForARCConversion(castType.getNonReferenceType());
Expr *castExpr = realCast->getSubExpr();
assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
castExpr, realCast, ACTC_retainable, CCK);
}
Expr *Sema::stripARCUnbridgedCast(Expr *e) {
assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
} else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
assert(uo->getOpcode() == UO_Extension);
Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
sub->getValueKind(), sub->getObjectKind(),
uo->getOperatorLoc(), false,
CurFPFeatureOverrides());
} else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
assert(!gse->isResultDependent());
unsigned n = gse->getNumAssocs();
SmallVector<Expr *, 4> subExprs;
SmallVector<TypeSourceInfo *, 4> subTypes;
subExprs.reserve(n);
subTypes.reserve(n);
for (const GenericSelectionExpr::Association assoc : gse->associations()) {
subTypes.push_back(assoc.getTypeSourceInfo());
Expr *sub = assoc.getAssociationExpr();
if (assoc.isSelected())
sub = stripARCUnbridgedCast(sub);
subExprs.push_back(sub);
}
return GenericSelectionExpr::Create(
Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
gse->containsUnexpandedParameterPack(), gse->getResultIndex());
} else {
assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
return cast<ImplicitCastExpr>(e)->getSubExpr();
}
}
bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType exprType) {
QualType canCastType =
Context.getCanonicalType(castType).getUnqualifiedType();
QualType canExprType =
Context.getCanonicalType(exprType).getUnqualifiedType();
if (isa<ObjCObjectPointerType>(canCastType) &&
castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
canExprType->isObjCObjectPointerType()) {
if (const ObjCObjectPointerType *ObjT =
canExprType->getAs<ObjCObjectPointerType>())
if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
return !ObjI->isArcWeakrefUnavailable();
}
return true;
}
static Expr *maybeUndoReclaimObject(Expr *e) {
Expr *curExpr = e, *prevExpr = nullptr;
while (true) {
if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
prevExpr = curExpr;
curExpr = pe->getSubExpr();
continue;
}
if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
if (!prevExpr)
return ice->getSubExpr();
if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
pe->setSubExpr(ice->getSubExpr());
else
cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
return e;
}
prevExpr = curExpr;
curExpr = ce->getSubExpr();
continue;
}
break;
}
return e;
}
ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr) {
ExprResult SubResult = UsualUnaryConversions(SubExpr);
if (SubResult.isInvalid()) return ExprError();
SubExpr = SubResult.get();
QualType T = TSInfo->getType();
QualType FromType = SubExpr->getType();
CastKind CK;
bool MustConsume = false;
if (T->isDependentType() || SubExpr->isTypeDependent()) {
CK = CK_Dependent;
} else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
: CK_CPointerToObjCPointerCast);
switch (Kind) {
case OBC_Bridge:
break;
case OBC_BridgeRetained: {
bool br = isKnownName("CFBridgingRelease");
Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
<< 2
<< FromType
<< (T->isBlockPointerType()? 1 : 0)
<< T
<< SubExpr->getSourceRange()
<< Kind;
Diag(BridgeKeywordLoc, diag::note_arc_bridge)
<< FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
<< FromType << br
<< FixItHint::CreateReplacement(BridgeKeywordLoc,
br ? "CFBridgingRelease "
: "__bridge_transfer ");
Kind = OBC_Bridge;
break;
}
case OBC_BridgeTransfer:
MustConsume = true;
break;
}
} else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
CK = CK_BitCast;
switch (Kind) {
case OBC_Bridge:
SubExpr = maybeUndoReclaimObject(SubExpr);
break;
case OBC_BridgeRetained:
SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject,
SubExpr, nullptr, VK_PRValue,
FPOptionsOverride());
break;
case OBC_BridgeTransfer: {
bool br = isKnownName("CFBridgingRetain");
Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
<< (FromType->isBlockPointerType()? 1 : 0)
<< FromType
<< 2
<< T
<< SubExpr->getSourceRange()
<< Kind;
Diag(BridgeKeywordLoc, diag::note_arc_bridge)
<< FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
<< T << br
<< FixItHint::CreateReplacement(BridgeKeywordLoc,
br ? "CFBridgingRetain " : "__bridge_retained");
Kind = OBC_Bridge;
break;
}
}
} else {
Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
<< FromType << T << Kind
<< SubExpr->getSourceRange()
<< TSInfo->getTypeLoc().getSourceRange();
return ExprError();
}
Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
BridgeKeywordLoc,
TSInfo, SubExpr);
if (MustConsume) {
Cleanup.setExprNeedsCleanups(true);
Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
nullptr, VK_PRValue, FPOptionsOverride());
}
return Result;
}
ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr) {
TypeSourceInfo *TSInfo = nullptr;
QualType T = GetTypeFromParser(Type, &TSInfo);
if (Kind == OBC_Bridge)
CheckTollFreeBridgeCast(T, SubExpr);
if (!TSInfo)
TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
SubExpr);
}