Bug Summary

File:clang/lib/Sema/SemaExprObjC.cpp
Warning:line 1608, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExprObjC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp

1//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective-C expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/SemaInternal.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/ExprObjC.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/AST/TypeLoc.h"
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/Edit/Commit.h"
21#include "clang/Edit/Rewriters.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/Support/ConvertUTF.h"
29
30using namespace clang;
31using namespace sema;
32using llvm::makeArrayRef;
33
34ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 ArrayRef<Expr *> Strings) {
36 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
40 StringLiteral *S = cast<StringLiteral>(Strings[0]);
41
42 // If we have a multi-part string, merge it all together.
43 if (Strings.size() != 1) {
44 // Concatenate objc strings.
45 SmallString<128> StrBuf;
46 SmallVector<SourceLocation, 8> StrLocs;
47
48 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
50
51 // ObjC strings can't be wide or UTF.
52 if (!S->isAscii()) {
53 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
55 return true;
56 }
57
58 // Append the string.
59 StrBuf += S->getString();
60
61 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
63 }
64
65 // Create the aggregate string with the appropriate content and location
66 // information.
67 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!")((CAT && "String literal not of constant array type!"
) ? static_cast<void> (0) : __assert_fail ("CAT && \"String literal not of constant array type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 68, __PRETTY_FUNCTION__))
;
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
74 StrLocs.size());
75 }
76
77 return BuildObjCStringLiteral(AtLocs[0], S);
78}
79
80ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
81 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
83 return true;
84
85 // Initialize the constant string interface lazily. This assumes
86 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
89 QualType Ty = Context.getObjCConstantStringInterface();
90 if (!Ty.isNull()) {
91 Ty = Context.getObjCObjectPointerType(Ty);
92 } else if (getLangOpts().NoConstantCFStrings) {
93 IdentifierInfo *NSIdent=nullptr;
94 std::string StringClass(getLangOpts().ObjCConstantStringClass);
95
96 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
98 else
99 NSIdent = &Context.Idents.get(StringClass);
100
101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
102 LookupOrdinaryName);
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
107 } else {
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
110 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
111 << NSIdent << S->getSourceRange();
112 Ty = Context.getObjCIdType();
113 }
114 } else {
115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
117 LookupOrdinaryName);
118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
121 Ty = Context.getObjCObjectPointerType(Ty);
122 } else {
123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
128 if (Ty.isNull()) {
129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
133 nullptr, nullptr, SourceLocation());
134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
136 }
137 Ty = Context.getObjCObjectPointerType(Ty);
138 }
139 }
140
141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
142}
143
144/// Emits an error if the given method does not exist, or if the return
145/// type is not an Objective-C object.
146static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
149 if (!Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
152 return false;
153 }
154
155 // Make sure the return type is reasonable.
156 QualType ReturnType = Method->getReturnType();
157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
159 << Sel;
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
161 << ReturnType;
162 return false;
163 }
164
165 return true;
166}
167
168/// Maps ObjCLiteralKind to NSClassIdKindKind
169static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
172 case Sema::LK_Array:
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
180 case Sema::LK_Boxed:
181 return NSAPI::ClassId_NSValue;
182
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
185 case Sema::LK_Block:
186 case Sema::LK_None:
187 break;
188 }
189 llvm_unreachable("LiteralKind can't be converted into a ClassKind")::llvm::llvm_unreachable_internal("LiteralKind can't be converted into a ClassKind"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 189)
;
190}
191
192/// Validates ObjCInterfaceDecl availability.
193/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194/// if clang not in a debugger mode.
195static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
196 SourceLocation Loc,
197 Sema::ObjCLiteralKind LiteralKind) {
198 if (!Decl) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
203 return false;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
208 return false;
209 }
210
211 return true;
212}
213
214/// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
215/// Used to create ObjC literals, such as NSDictionary (@{}),
216/// NSArray (@[]) and Boxed Expressions (@())
217static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
218 SourceLocation Loc,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
230 }
231
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
233 ID = nullptr;
234 }
235
236 return ID;
237}
238
239/// Retrieve the NSNumber factory method that should be used to create
240/// an Objective-C literal for the given type.
241static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
242 QualType NumberType,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
247
248 if (!Kind) {
249 if (isLiteral) {
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
251 << NumberType << R;
252 }
253 return nullptr;
254 }
255
256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
259
260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
261 /*Instance=*/false);
262
263 ASTContext &CX = S.Context;
264
265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
269 Sema::LK_Numeric);
270 if (!S.NSNumberDecl) {
271 return nullptr;
272 }
273 }
274
275 if (S.NSNumberPointer.isNull()) {
276 // generate the pointer to NSNumber type.
277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
279 }
280
281 // Look for the appropriate method within NSNumber.
282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
284 // create a stub definition this NSNumber factory method.
285 TypeSourceInfo *ReturnTInfo = nullptr;
286 Method =
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isSynthesizedAccessorStub=*/false,
292 /*isImplicitlyDeclared=*/true,
293 /*isDefined=*/false, ObjCMethodDecl::Required,
294 /*HasRelatedResultType=*/false);
295 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
296 SourceLocation(), SourceLocation(),
297 &CX.Idents.get("value"),
298 NumberType, /*TInfo=*/nullptr,
299 SC_None, nullptr);
300 Method->setMethodParams(S.Context, value, None);
301 }
302
303 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
304 return nullptr;
305
306 // Note: if the parameter type is out-of-line, we'll catch it later in the
307 // implicit conversion.
308
309 S.NSNumberLiteralMethods[*Kind] = Method;
310 return Method;
311}
312
313/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
314/// numeric literal expression. Type of the expression will be "NSNumber *".
315ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
316 // Determine the type of the literal.
317 QualType NumberType = Number->getType();
318 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
319 // In C, character literals have type 'int'. That's not the type we want
320 // to use to determine the Objective-c literal kind.
321 switch (Char->getKind()) {
322 case CharacterLiteral::Ascii:
323 case CharacterLiteral::UTF8:
324 NumberType = Context.CharTy;
325 break;
326
327 case CharacterLiteral::Wide:
328 NumberType = Context.getWideCharType();
329 break;
330
331 case CharacterLiteral::UTF16:
332 NumberType = Context.Char16Ty;
333 break;
334
335 case CharacterLiteral::UTF32:
336 NumberType = Context.Char32Ty;
337 break;
338 }
339 }
340
341 // Look for the appropriate method within NSNumber.
342 // Construct the literal.
343 SourceRange NR(Number->getSourceRange());
344 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
345 true, NR);
346 if (!Method)
347 return ExprError();
348
349 // Convert the number to the type that the parameter expects.
350 ParmVarDecl *ParamDecl = Method->parameters()[0];
351 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
352 ParamDecl);
353 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
354 SourceLocation(),
355 Number);
356 if (ConvertedNumber.isInvalid())
357 return ExprError();
358 Number = ConvertedNumber.get();
359
360 // Use the effective source range of the literal, including the leading '@'.
361 return MaybeBindToTemporary(
362 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
363 SourceRange(AtLoc, NR.getEnd())));
364}
365
366ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
367 SourceLocation ValueLoc,
368 bool Value) {
369 ExprResult Inner;
370 if (getLangOpts().CPlusPlus) {
371 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
372 } else {
373 // C doesn't actually have a way to represent literal values of type
374 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
375 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
376 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
377 CK_IntegralToBoolean);
378 }
379
380 return BuildObjCNumericLiteral(AtLoc, Inner.get());
381}
382
383/// Check that the given expression is a valid element of an Objective-C
384/// collection literal.
385static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
386 QualType T,
387 bool ArrayLiteral = false) {
388 // If the expression is type-dependent, there's nothing for us to do.
389 if (Element->isTypeDependent())
390 return Element;
391
392 ExprResult Result = S.CheckPlaceholderExpr(Element);
393 if (Result.isInvalid())
394 return ExprError();
395 Element = Result.get();
396
397 // In C++, check for an implicit conversion to an Objective-C object pointer
398 // type.
399 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
400 InitializedEntity Entity
401 = InitializedEntity::InitializeParameter(S.Context, T,
402 /*Consumed=*/false);
403 InitializationKind Kind = InitializationKind::CreateCopy(
404 Element->getBeginLoc(), SourceLocation());
405 InitializationSequence Seq(S, Entity, Kind, Element);
406 if (!Seq.Failed())
407 return Seq.Perform(S, Entity, Kind, Element);
408 }
409
410 Expr *OrigElement = Element;
411
412 // Perform lvalue-to-rvalue conversion.
413 Result = S.DefaultLvalueConversion(Element);
414 if (Result.isInvalid())
415 return ExprError();
416 Element = Result.get();
417
418 // Make sure that we have an Objective-C pointer type or block.
419 if (!Element->getType()->isObjCObjectPointerType() &&
420 !Element->getType()->isBlockPointerType()) {
421 bool Recovered = false;
422
423 // If this is potentially an Objective-C numeric literal, add the '@'.
424 if (isa<IntegerLiteral>(OrigElement) ||
425 isa<CharacterLiteral>(OrigElement) ||
426 isa<FloatingLiteral>(OrigElement) ||
427 isa<ObjCBoolLiteralExpr>(OrigElement) ||
428 isa<CXXBoolLiteralExpr>(OrigElement)) {
429 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
430 int Which = isa<CharacterLiteral>(OrigElement) ? 1
431 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
432 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
433 : 3;
434
435 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
436 << Which << OrigElement->getSourceRange()
437 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
438
439 Result =
440 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
441 if (Result.isInvalid())
442 return ExprError();
443
444 Element = Result.get();
445 Recovered = true;
446 }
447 }
448 // If this is potentially an Objective-C string literal, add the '@'.
449 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
450 if (String->isAscii()) {
451 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
452 << 0 << OrigElement->getSourceRange()
453 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
454
455 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
456 if (Result.isInvalid())
457 return ExprError();
458
459 Element = Result.get();
460 Recovered = true;
461 }
462 }
463
464 if (!Recovered) {
465 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
466 << Element->getType();
467 return ExprError();
468 }
469 }
470 if (ArrayLiteral)
471 if (ObjCStringLiteral *getString =
472 dyn_cast<ObjCStringLiteral>(OrigElement)) {
473 if (StringLiteral *SL = getString->getString()) {
474 unsigned numConcat = SL->getNumConcatenated();
475 if (numConcat > 1) {
476 // Only warn if the concatenated string doesn't come from a macro.
477 bool hasMacro = false;
478 for (unsigned i = 0; i < numConcat ; ++i)
479 if (SL->getStrTokenLoc(i).isMacroID()) {
480 hasMacro = true;
481 break;
482 }
483 if (!hasMacro)
484 S.Diag(Element->getBeginLoc(),
485 diag::warn_concatenated_nsarray_literal)
486 << Element->getType();
487 }
488 }
489 }
490
491 // Make sure that the element has the type that the container factory
492 // function expects.
493 return S.PerformCopyInitialization(
494 InitializedEntity::InitializeParameter(S.Context, T,
495 /*Consumed=*/false),
496 Element->getBeginLoc(), Element);
497}
498
499ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
500 if (ValueExpr->isTypeDependent()) {
501 ObjCBoxedExpr *BoxedExpr =
502 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
503 return BoxedExpr;
504 }
505 ObjCMethodDecl *BoxingMethod = nullptr;
506 QualType BoxedType;
507 // Convert the expression to an RValue, so we can check for pointer types...
508 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
509 if (RValue.isInvalid()) {
510 return ExprError();
511 }
512 SourceLocation Loc = SR.getBegin();
513 ValueExpr = RValue.get();
514 QualType ValueType(ValueExpr->getType());
515 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
516 QualType PointeeType = PT->getPointeeType();
517 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
518
519 if (!NSStringDecl) {
520 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
521 Sema::LK_String);
522 if (!NSStringDecl) {
523 return ExprError();
524 }
525 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
526 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
527 }
528
529 // The boxed expression can be emitted as a compile time constant if it is
530 // a string literal whose character encoding is compatible with UTF-8.
531 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
532 if (CE->getCastKind() == CK_ArrayToPointerDecay)
533 if (auto *SL =
534 dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
535 assert((SL->isAscii() || SL->isUTF8()) &&(((SL->isAscii() || SL->isUTF8()) && "unexpected character encoding"
) ? static_cast<void> (0) : __assert_fail ("(SL->isAscii() || SL->isUTF8()) && \"unexpected character encoding\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 536, __PRETTY_FUNCTION__))
536 "unexpected character encoding")(((SL->isAscii() || SL->isUTF8()) && "unexpected character encoding"
) ? static_cast<void> (0) : __assert_fail ("(SL->isAscii() || SL->isUTF8()) && \"unexpected character encoding\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 536, __PRETTY_FUNCTION__))
;
537 StringRef Str = SL->getString();
538 const llvm::UTF8 *StrBegin = Str.bytes_begin();
539 const llvm::UTF8 *StrEnd = Str.bytes_end();
540 // Check that this is a valid UTF-8 string.
541 if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
542 BoxedType = Context.getAttributedType(
543 AttributedType::getNullabilityAttrKind(
544 NullabilityKind::NonNull),
545 NSStringPointer, NSStringPointer);
546 return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
547 }
548
549 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
550 << NSStringPointer << SL->getSourceRange();
551 }
552
553 if (!StringWithUTF8StringMethod) {
554 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
555 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
556
557 // Look for the appropriate method within NSString.
558 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
559 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
560 // Debugger needs to work even if NSString hasn't been defined.
561 TypeSourceInfo *ReturnTInfo = nullptr;
562 ObjCMethodDecl *M = ObjCMethodDecl::Create(
563 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
564 NSStringPointer, ReturnTInfo, NSStringDecl,
565 /*isInstance=*/false, /*isVariadic=*/false,
566 /*isPropertyAccessor=*/false,
567 /*isSynthesizedAccessorStub=*/false,
568 /*isImplicitlyDeclared=*/true,
569 /*isDefined=*/false, ObjCMethodDecl::Required,
570 /*HasRelatedResultType=*/false);
571 QualType ConstCharType = Context.CharTy.withConst();
572 ParmVarDecl *value =
573 ParmVarDecl::Create(Context, M,
574 SourceLocation(), SourceLocation(),
575 &Context.Idents.get("value"),
576 Context.getPointerType(ConstCharType),
577 /*TInfo=*/nullptr,
578 SC_None, nullptr);
579 M->setMethodParams(Context, value, None);
580 BoxingMethod = M;
581 }
582
583 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
584 stringWithUTF8String, BoxingMethod))
585 return ExprError();
586
587 StringWithUTF8StringMethod = BoxingMethod;
588 }
589
590 BoxingMethod = StringWithUTF8StringMethod;
591 BoxedType = NSStringPointer;
592 // Transfer the nullability from method's return type.
593 Optional<NullabilityKind> Nullability =
594 BoxingMethod->getReturnType()->getNullability(Context);
595 if (Nullability)
596 BoxedType = Context.getAttributedType(
597 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
598 BoxedType);
599 }
600 } else if (ValueType->isBuiltinType()) {
601 // The other types we support are numeric, char and BOOL/bool. We could also
602 // provide limited support for structure types, such as NSRange, NSRect, and
603 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
604 // for more details.
605
606 // Check for a top-level character literal.
607 if (const CharacterLiteral *Char =
608 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
609 // In C, character literals have type 'int'. That's not the type we want
610 // to use to determine the Objective-c literal kind.
611 switch (Char->getKind()) {
612 case CharacterLiteral::Ascii:
613 case CharacterLiteral::UTF8:
614 ValueType = Context.CharTy;
615 break;
616
617 case CharacterLiteral::Wide:
618 ValueType = Context.getWideCharType();
619 break;
620
621 case CharacterLiteral::UTF16:
622 ValueType = Context.Char16Ty;
623 break;
624
625 case CharacterLiteral::UTF32:
626 ValueType = Context.Char32Ty;
627 break;
628 }
629 }
630 // FIXME: Do I need to do anything special with BoolTy expressions?
631
632 // Look for the appropriate method within NSNumber.
633 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
634 BoxedType = NSNumberPointer;
635 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
636 if (!ET->getDecl()->isComplete()) {
637 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
638 << ValueType << ValueExpr->getSourceRange();
639 return ExprError();
640 }
641
642 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
643 ET->getDecl()->getIntegerType());
644 BoxedType = NSNumberPointer;
645 } else if (ValueType->isObjCBoxableRecordType()) {
646 // Support for structure types, that marked as objc_boxable
647 // struct __attribute__((objc_boxable)) s { ... };
648
649 // Look up the NSValue class, if we haven't done so already. It's cached
650 // in the Sema instance.
651 if (!NSValueDecl) {
652 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
653 Sema::LK_Boxed);
654 if (!NSValueDecl) {
655 return ExprError();
656 }
657
658 // generate the pointer to NSValue type.
659 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
660 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
661 }
662
663 if (!ValueWithBytesObjCTypeMethod) {
664 IdentifierInfo *II[] = {
665 &Context.Idents.get("valueWithBytes"),
666 &Context.Idents.get("objCType")
667 };
668 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
669
670 // Look for the appropriate method within NSValue.
671 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
672 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
673 // Debugger needs to work even if NSValue hasn't been defined.
674 TypeSourceInfo *ReturnTInfo = nullptr;
675 ObjCMethodDecl *M = ObjCMethodDecl::Create(
676 Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
677 NSValuePointer, ReturnTInfo, NSValueDecl,
678 /*isInstance=*/false,
679 /*isVariadic=*/false,
680 /*isPropertyAccessor=*/false,
681 /*isSynthesizedAccessorStub=*/false,
682 /*isImplicitlyDeclared=*/true,
683 /*isDefined=*/false, ObjCMethodDecl::Required,
684 /*HasRelatedResultType=*/false);
685
686 SmallVector<ParmVarDecl *, 2> Params;
687
688 ParmVarDecl *bytes =
689 ParmVarDecl::Create(Context, M,
690 SourceLocation(), SourceLocation(),
691 &Context.Idents.get("bytes"),
692 Context.VoidPtrTy.withConst(),
693 /*TInfo=*/nullptr,
694 SC_None, nullptr);
695 Params.push_back(bytes);
696
697 QualType ConstCharType = Context.CharTy.withConst();
698 ParmVarDecl *type =
699 ParmVarDecl::Create(Context, M,
700 SourceLocation(), SourceLocation(),
701 &Context.Idents.get("type"),
702 Context.getPointerType(ConstCharType),
703 /*TInfo=*/nullptr,
704 SC_None, nullptr);
705 Params.push_back(type);
706
707 M->setMethodParams(Context, Params, None);
708 BoxingMethod = M;
709 }
710
711 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
712 ValueWithBytesObjCType, BoxingMethod))
713 return ExprError();
714
715 ValueWithBytesObjCTypeMethod = BoxingMethod;
716 }
717
718 if (!ValueType.isTriviallyCopyableType(Context)) {
719 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
720 << ValueType << ValueExpr->getSourceRange();
721 return ExprError();
722 }
723
724 BoxingMethod = ValueWithBytesObjCTypeMethod;
725 BoxedType = NSValuePointer;
726 }
727
728 if (!BoxingMethod) {
729 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
730 << ValueType << ValueExpr->getSourceRange();
731 return ExprError();
732 }
733
734 DiagnoseUseOfDecl(BoxingMethod, Loc);
735
736 ExprResult ConvertedValueExpr;
737 if (ValueType->isObjCBoxableRecordType()) {
738 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
739 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
740 ValueExpr);
741 } else {
742 // Convert the expression to the type that the parameter requires.
743 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
744 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
745 ParamDecl);
746 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
747 ValueExpr);
748 }
749
750 if (ConvertedValueExpr.isInvalid())
751 return ExprError();
752 ValueExpr = ConvertedValueExpr.get();
753
754 ObjCBoxedExpr *BoxedExpr =
755 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
756 BoxingMethod, SR);
757 return MaybeBindToTemporary(BoxedExpr);
758}
759
760/// Build an ObjC subscript pseudo-object expression, given that
761/// that's supported by the runtime.
762ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
763 Expr *IndexExpr,
764 ObjCMethodDecl *getterMethod,
765 ObjCMethodDecl *setterMethod) {
766 assert(!LangOpts.isSubscriptPointerArithmetic())((!LangOpts.isSubscriptPointerArithmetic()) ? static_cast<
void> (0) : __assert_fail ("!LangOpts.isSubscriptPointerArithmetic()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 766, __PRETTY_FUNCTION__))
;
767
768 // We can't get dependent types here; our callers should have
769 // filtered them out.
770 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&(((!BaseExpr->isTypeDependent() && !IndexExpr->
isTypeDependent()) && "base or index cannot have dependent type here"
) ? static_cast<void> (0) : __assert_fail ("(!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && \"base or index cannot have dependent type here\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 771, __PRETTY_FUNCTION__))
771 "base or index cannot have dependent type here")(((!BaseExpr->isTypeDependent() && !IndexExpr->
isTypeDependent()) && "base or index cannot have dependent type here"
) ? static_cast<void> (0) : __assert_fail ("(!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && \"base or index cannot have dependent type here\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 771, __PRETTY_FUNCTION__))
;
772
773 // Filter out placeholders in the index. In theory, overloads could
774 // be preserved here, although that might not actually work correctly.
775 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
776 if (Result.isInvalid())
777 return ExprError();
778 IndexExpr = Result.get();
779
780 // Perform lvalue-to-rvalue conversion on the base.
781 Result = DefaultLvalueConversion(BaseExpr);
782 if (Result.isInvalid())
783 return ExprError();
784 BaseExpr = Result.get();
785
786 // Build the pseudo-object expression.
787 return new (Context) ObjCSubscriptRefExpr(
788 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
789 getterMethod, setterMethod, RB);
790}
791
792ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
793 SourceLocation Loc = SR.getBegin();
794
795 if (!NSArrayDecl) {
796 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
797 Sema::LK_Array);
798 if (!NSArrayDecl) {
799 return ExprError();
800 }
801 }
802
803 // Find the arrayWithObjects:count: method, if we haven't done so already.
804 QualType IdT = Context.getObjCIdType();
805 if (!ArrayWithObjectsMethod) {
806 Selector
807 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
808 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
809 if (!Method && getLangOpts().DebuggerObjCLiteral) {
810 TypeSourceInfo *ReturnTInfo = nullptr;
811 Method = ObjCMethodDecl::Create(
812 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
813 Context.getTranslationUnitDecl(), false /*Instance*/,
814 false /*isVariadic*/,
815 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
816 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
817 ObjCMethodDecl::Required, false);
818 SmallVector<ParmVarDecl *, 2> Params;
819 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
820 SourceLocation(),
821 SourceLocation(),
822 &Context.Idents.get("objects"),
823 Context.getPointerType(IdT),
824 /*TInfo=*/nullptr,
825 SC_None, nullptr);
826 Params.push_back(objects);
827 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
828 SourceLocation(),
829 SourceLocation(),
830 &Context.Idents.get("cnt"),
831 Context.UnsignedLongTy,
832 /*TInfo=*/nullptr, SC_None,
833 nullptr);
834 Params.push_back(cnt);
835 Method->setMethodParams(Context, Params, None);
836 }
837
838 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
839 return ExprError();
840
841 // Dig out the type that all elements should be converted to.
842 QualType T = Method->parameters()[0]->getType();
843 const PointerType *PtrT = T->getAs<PointerType>();
844 if (!PtrT ||
845 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
846 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
847 << Sel;
848 Diag(Method->parameters()[0]->getLocation(),
849 diag::note_objc_literal_method_param)
850 << 0 << T
851 << Context.getPointerType(IdT.withConst());
852 return ExprError();
853 }
854
855 // Check that the 'count' parameter is integral.
856 if (!Method->parameters()[1]->getType()->isIntegerType()) {
857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
858 << Sel;
859 Diag(Method->parameters()[1]->getLocation(),
860 diag::note_objc_literal_method_param)
861 << 1
862 << Method->parameters()[1]->getType()
863 << "integral";
864 return ExprError();
865 }
866
867 // We've found a good +arrayWithObjects:count: method. Save it!
868 ArrayWithObjectsMethod = Method;
869 }
870
871 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
872 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
873
874 // Check that each of the elements provided is valid in a collection literal,
875 // performing conversions as necessary.
876 Expr **ElementsBuffer = Elements.data();
877 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
878 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
879 ElementsBuffer[I],
880 RequiredType, true);
881 if (Converted.isInvalid())
882 return ExprError();
883
884 ElementsBuffer[I] = Converted.get();
885 }
886
887 QualType Ty
888 = Context.getObjCObjectPointerType(
889 Context.getObjCInterfaceType(NSArrayDecl));
890
891 return MaybeBindToTemporary(
892 ObjCArrayLiteral::Create(Context, Elements, Ty,
893 ArrayWithObjectsMethod, SR));
894}
895
896ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
897 MutableArrayRef<ObjCDictionaryElement> Elements) {
898 SourceLocation Loc = SR.getBegin();
899
900 if (!NSDictionaryDecl) {
901 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
902 Sema::LK_Dictionary);
903 if (!NSDictionaryDecl) {
904 return ExprError();
905 }
906 }
907
908 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
909 // so already.
910 QualType IdT = Context.getObjCIdType();
911 if (!DictionaryWithObjectsMethod) {
912 Selector Sel = NSAPIObj->getNSDictionarySelector(
913 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
914 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
915 if (!Method && getLangOpts().DebuggerObjCLiteral) {
916 Method = ObjCMethodDecl::Create(
917 Context, SourceLocation(), SourceLocation(), Sel, IdT,
918 nullptr /*TypeSourceInfo */, Context.getTranslationUnitDecl(),
919 false /*Instance*/, false /*isVariadic*/,
920 /*isPropertyAccessor=*/false,
921 /*isSynthesizedAccessorStub=*/false,
922 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
923 ObjCMethodDecl::Required, false);
924 SmallVector<ParmVarDecl *, 3> Params;
925 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
926 SourceLocation(),
927 SourceLocation(),
928 &Context.Idents.get("objects"),
929 Context.getPointerType(IdT),
930 /*TInfo=*/nullptr, SC_None,
931 nullptr);
932 Params.push_back(objects);
933 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
934 SourceLocation(),
935 SourceLocation(),
936 &Context.Idents.get("keys"),
937 Context.getPointerType(IdT),
938 /*TInfo=*/nullptr, SC_None,
939 nullptr);
940 Params.push_back(keys);
941 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
942 SourceLocation(),
943 SourceLocation(),
944 &Context.Idents.get("cnt"),
945 Context.UnsignedLongTy,
946 /*TInfo=*/nullptr, SC_None,
947 nullptr);
948 Params.push_back(cnt);
949 Method->setMethodParams(Context, Params, None);
950 }
951
952 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
953 Method))
954 return ExprError();
955
956 // Dig out the type that all values should be converted to.
957 QualType ValueT = Method->parameters()[0]->getType();
958 const PointerType *PtrValue = ValueT->getAs<PointerType>();
959 if (!PtrValue ||
960 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
961 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
962 << Sel;
963 Diag(Method->parameters()[0]->getLocation(),
964 diag::note_objc_literal_method_param)
965 << 0 << ValueT
966 << Context.getPointerType(IdT.withConst());
967 return ExprError();
968 }
969
970 // Dig out the type that all keys should be converted to.
971 QualType KeyT = Method->parameters()[1]->getType();
972 const PointerType *PtrKey = KeyT->getAs<PointerType>();
973 if (!PtrKey ||
974 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
975 IdT)) {
976 bool err = true;
977 if (PtrKey) {
978 if (QIDNSCopying.isNull()) {
979 // key argument of selector is id<NSCopying>?
980 if (ObjCProtocolDecl *NSCopyingPDecl =
981 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
982 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
983 QIDNSCopying =
984 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
985 llvm::makeArrayRef(
986 (ObjCProtocolDecl**) PQ,
987 1),
988 false);
989 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
990 }
991 }
992 if (!QIDNSCopying.isNull())
993 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
994 QIDNSCopying);
995 }
996
997 if (err) {
998 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
999 << Sel;
1000 Diag(Method->parameters()[1]->getLocation(),
1001 diag::note_objc_literal_method_param)
1002 << 1 << KeyT
1003 << Context.getPointerType(IdT.withConst());
1004 return ExprError();
1005 }
1006 }
1007
1008 // Check that the 'count' parameter is integral.
1009 QualType CountType = Method->parameters()[2]->getType();
1010 if (!CountType->isIntegerType()) {
1011 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1012 << Sel;
1013 Diag(Method->parameters()[2]->getLocation(),
1014 diag::note_objc_literal_method_param)
1015 << 2 << CountType
1016 << "integral";
1017 return ExprError();
1018 }
1019
1020 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1021 DictionaryWithObjectsMethod = Method;
1022 }
1023
1024 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1025 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1026 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1027 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1028
1029 // Check that each of the keys and values provided is valid in a collection
1030 // literal, performing conversions as necessary.
1031 bool HasPackExpansions = false;
1032 for (ObjCDictionaryElement &Element : Elements) {
1033 // Check the key.
1034 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1035 KeyT);
1036 if (Key.isInvalid())
1037 return ExprError();
1038
1039 // Check the value.
1040 ExprResult Value
1041 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1042 if (Value.isInvalid())
1043 return ExprError();
1044
1045 Element.Key = Key.get();
1046 Element.Value = Value.get();
1047
1048 if (Element.EllipsisLoc.isInvalid())
1049 continue;
1050
1051 if (!Element.Key->containsUnexpandedParameterPack() &&
1052 !Element.Value->containsUnexpandedParameterPack()) {
1053 Diag(Element.EllipsisLoc,
1054 diag::err_pack_expansion_without_parameter_packs)
1055 << SourceRange(Element.Key->getBeginLoc(),
1056 Element.Value->getEndLoc());
1057 return ExprError();
1058 }
1059
1060 HasPackExpansions = true;
1061 }
1062
1063 QualType Ty
1064 = Context.getObjCObjectPointerType(
1065 Context.getObjCInterfaceType(NSDictionaryDecl));
1066 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1067 Context, Elements, HasPackExpansions, Ty,
1068 DictionaryWithObjectsMethod, SR));
1069}
1070
1071ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1072 TypeSourceInfo *EncodedTypeInfo,
1073 SourceLocation RParenLoc) {
1074 QualType EncodedType = EncodedTypeInfo->getType();
1075 QualType StrTy;
1076 if (EncodedType->isDependentType())
1077 StrTy = Context.DependentTy;
1078 else {
1079 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1080 !EncodedType->isVoidType()) // void is handled too.
1081 if (RequireCompleteType(AtLoc, EncodedType,
1082 diag::err_incomplete_type_objc_at_encode,
1083 EncodedTypeInfo->getTypeLoc()))
1084 return ExprError();
1085
1086 std::string Str;
1087 QualType NotEncodedT;
1088 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1089 if (!NotEncodedT.isNull())
1090 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1091 << EncodedType << NotEncodedT;
1092
1093 // The type of @encode is the same as the type of the corresponding string,
1094 // which is an array type.
1095 StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1096 }
1097
1098 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1099}
1100
1101ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1102 SourceLocation EncodeLoc,
1103 SourceLocation LParenLoc,
1104 ParsedType ty,
1105 SourceLocation RParenLoc) {
1106 // FIXME: Preserve type source info ?
1107 TypeSourceInfo *TInfo;
1108 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1109 if (!TInfo)
1110 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1111 getLocForEndOfToken(LParenLoc));
1112
1113 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1114}
1115
1116static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1117 SourceLocation AtLoc,
1118 SourceLocation LParenLoc,
1119 SourceLocation RParenLoc,
1120 ObjCMethodDecl *Method,
1121 ObjCMethodList &MethList) {
1122 ObjCMethodList *M = &MethList;
1123 bool Warned = false;
1124 for (M = M->getNext(); M; M=M->getNext()) {
1125 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1126 if (MatchingMethodDecl == Method ||
1127 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1128 MatchingMethodDecl->getSelector() != Method->getSelector())
1129 continue;
1130 if (!S.MatchTwoMethodDeclarations(Method,
1131 MatchingMethodDecl, Sema::MMS_loose)) {
1132 if (!Warned) {
1133 Warned = true;
1134 S.Diag(AtLoc, diag::warn_multiple_selectors)
1135 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1136 << FixItHint::CreateInsertion(RParenLoc, ")");
1137 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1138 << Method->getDeclName();
1139 }
1140 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1141 << MatchingMethodDecl->getDeclName();
1142 }
1143 }
1144 return Warned;
1145}
1146
1147static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1148 ObjCMethodDecl *Method,
1149 SourceLocation LParenLoc,
1150 SourceLocation RParenLoc,
1151 bool WarnMultipleSelectors) {
1152 if (!WarnMultipleSelectors ||
1153 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1154 return;
1155 bool Warned = false;
1156 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1157 e = S.MethodPool.end(); b != e; b++) {
1158 // first, instance methods
1159 ObjCMethodList &InstMethList = b->second.first;
1160 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1161 Method, InstMethList))
1162 Warned = true;
1163
1164 // second, class methods
1165 ObjCMethodList &ClsMethList = b->second.second;
1166 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1167 Method, ClsMethList) || Warned)
1168 return;
1169 }
1170}
1171
1172ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1173 SourceLocation AtLoc,
1174 SourceLocation SelLoc,
1175 SourceLocation LParenLoc,
1176 SourceLocation RParenLoc,
1177 bool WarnMultipleSelectors) {
1178 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1179 SourceRange(LParenLoc, RParenLoc));
1180 if (!Method)
1181 Method = LookupFactoryMethodInGlobalPool(Sel,
1182 SourceRange(LParenLoc, RParenLoc));
1183 if (!Method) {
1184 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1185 Selector MatchedSel = OM->getSelector();
1186 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1187 RParenLoc.getLocWithOffset(-1));
1188 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1189 << Sel << MatchedSel
1190 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1191
1192 } else
1193 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1194 } else
1195 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1196 WarnMultipleSelectors);
1197
1198 if (Method &&
1199 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1200 !getSourceManager().isInSystemHeader(Method->getLocation()))
1201 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1202
1203 // In ARC, forbid the user from using @selector for
1204 // retain/release/autorelease/dealloc/retainCount.
1205 if (getLangOpts().ObjCAutoRefCount) {
1206 switch (Sel.getMethodFamily()) {
1207 case OMF_retain:
1208 case OMF_release:
1209 case OMF_autorelease:
1210 case OMF_retainCount:
1211 case OMF_dealloc:
1212 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1213 Sel << SourceRange(LParenLoc, RParenLoc);
1214 break;
1215
1216 case OMF_None:
1217 case OMF_alloc:
1218 case OMF_copy:
1219 case OMF_finalize:
1220 case OMF_init:
1221 case OMF_mutableCopy:
1222 case OMF_new:
1223 case OMF_self:
1224 case OMF_initialize:
1225 case OMF_performSelector:
1226 break;
1227 }
1228 }
1229 QualType Ty = Context.getObjCSelType();
1230 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1231}
1232
1233ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1234 SourceLocation AtLoc,
1235 SourceLocation ProtoLoc,
1236 SourceLocation LParenLoc,
1237 SourceLocation ProtoIdLoc,
1238 SourceLocation RParenLoc) {
1239 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1240 if (!PDecl) {
1241 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1242 return true;
1243 }
1244 if (!PDecl->hasDefinition()) {
1245 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1246 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1247 } else {
1248 PDecl = PDecl->getDefinition();
1249 }
1250
1251 QualType Ty = Context.getObjCProtoType();
1252 if (Ty.isNull())
1253 return true;
1254 Ty = Context.getObjCObjectPointerType(Ty);
1255 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1256}
1257
1258/// Try to capture an implicit reference to 'self'.
1259ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1260 DeclContext *DC = getFunctionLevelDeclContext();
1261
1262 // If we're not in an ObjC method, error out. Note that, unlike the
1263 // C++ case, we don't require an instance method --- class methods
1264 // still have a 'self', and we really do still need to capture it!
1265 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1266 if (!method)
1267 return nullptr;
1268
1269 tryCaptureVariable(method->getSelfDecl(), Loc);
1270
1271 return method;
1272}
1273
1274static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1275 QualType origType = T;
1276 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1277 if (T == Context.getObjCInstanceType()) {
1278 return Context.getAttributedType(
1279 AttributedType::getNullabilityAttrKind(*nullability),
1280 Context.getObjCIdType(),
1281 Context.getObjCIdType());
1282 }
1283
1284 return origType;
1285 }
1286
1287 if (T == Context.getObjCInstanceType())
1288 return Context.getObjCIdType();
1289
1290 return origType;
1291}
1292
1293/// Determine the result type of a message send based on the receiver type,
1294/// method, and the kind of message send.
1295///
1296/// This is the "base" result type, which will still need to be adjusted
1297/// to account for nullability.
1298static QualType getBaseMessageSendResultType(Sema &S,
1299 QualType ReceiverType,
1300 ObjCMethodDecl *Method,
1301 bool isClassMessage,
1302 bool isSuperMessage) {
1303 assert(Method && "Must have a method")((Method && "Must have a method") ? static_cast<void
> (0) : __assert_fail ("Method && \"Must have a method\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 1303, __PRETTY_FUNCTION__))
;
1304 if (!Method->hasRelatedResultType())
1305 return Method->getSendResultType(ReceiverType);
1306
1307 ASTContext &Context = S.Context;
1308
1309 // Local function that transfers the nullability of the method's
1310 // result type to the returned result.
1311 auto transferNullability = [&](QualType type) -> QualType {
1312 // If the method's result type has nullability, extract it.
1313 if (auto nullability = Method->getSendResultType(ReceiverType)
1314 ->getNullability(Context)){
1315 // Strip off any outer nullability sugar from the provided type.
1316 (void)AttributedType::stripOuterNullability(type);
1317
1318 // Form a new attributed type using the method result type's nullability.
1319 return Context.getAttributedType(
1320 AttributedType::getNullabilityAttrKind(*nullability),
1321 type,
1322 type);
1323 }
1324
1325 return type;
1326 };
1327
1328 // If a method has a related return type:
1329 // - if the method found is an instance method, but the message send
1330 // was a class message send, T is the declared return type of the method
1331 // found
1332 if (Method->isInstanceMethod() && isClassMessage)
1333 return stripObjCInstanceType(Context,
1334 Method->getSendResultType(ReceiverType));
1335
1336 // - if the receiver is super, T is a pointer to the class of the
1337 // enclosing method definition
1338 if (isSuperMessage) {
1339 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1340 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1341 return transferNullability(
1342 Context.getObjCObjectPointerType(
1343 Context.getObjCInterfaceType(Class)));
1344 }
1345 }
1346
1347 // - if the receiver is the name of a class U, T is a pointer to U
1348 if (ReceiverType->getAsObjCInterfaceType())
1349 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1350 // - if the receiver is of type Class or qualified Class type,
1351 // T is the declared return type of the method.
1352 if (ReceiverType->isObjCClassType() ||
1353 ReceiverType->isObjCQualifiedClassType())
1354 return stripObjCInstanceType(Context,
1355 Method->getSendResultType(ReceiverType));
1356
1357 // - if the receiver is id, qualified id, Class, or qualified Class, T
1358 // is the receiver type, otherwise
1359 // - T is the type of the receiver expression.
1360 return transferNullability(ReceiverType);
1361}
1362
1363QualType Sema::getMessageSendResultType(const Expr *Receiver,
1364 QualType ReceiverType,
1365 ObjCMethodDecl *Method,
1366 bool isClassMessage,
1367 bool isSuperMessage) {
1368 // Produce the result type.
1369 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1370 Method,
1371 isClassMessage,
1372 isSuperMessage);
1373
1374 // If this is a class message, ignore the nullability of the receiver.
1375 if (isClassMessage) {
1376 // In a class method, class messages to 'self' that return instancetype can
1377 // be typed as the current class. We can safely do this in ARC because self
1378 // can't be reassigned, and we do it unsafely outside of ARC because in
1379 // practice people never reassign self in class methods and there's some
1380 // virtue in not being aggressively pedantic.
1381 if (Receiver && Receiver->isObjCSelfExpr()) {
1382 assert(ReceiverType->isObjCClassType() && "expected a Class self")((ReceiverType->isObjCClassType() && "expected a Class self"
) ? static_cast<void> (0) : __assert_fail ("ReceiverType->isObjCClassType() && \"expected a Class self\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 1382, __PRETTY_FUNCTION__))
;
1383 QualType T = Method->getSendResultType(ReceiverType);
1384 AttributedType::stripOuterNullability(T);
1385 if (T == Context.getObjCInstanceType()) {
1386 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1387 cast<ImplicitParamDecl>(
1388 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1389 ->getDeclContext());
1390 assert(MD->isClassMethod() && "expected a class method")((MD->isClassMethod() && "expected a class method"
) ? static_cast<void> (0) : __assert_fail ("MD->isClassMethod() && \"expected a class method\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 1390, __PRETTY_FUNCTION__))
;
1391 QualType NewResultType = Context.getObjCObjectPointerType(
1392 Context.getObjCInterfaceType(MD->getClassInterface()));
1393 if (auto Nullability = resultType->getNullability(Context))
1394 NewResultType = Context.getAttributedType(
1395 AttributedType::getNullabilityAttrKind(*Nullability),
1396 NewResultType, NewResultType);
1397 return NewResultType;
1398 }
1399 }
1400 return resultType;
1401 }
1402
1403 // There is nothing left to do if the result type cannot have a nullability
1404 // specifier.
1405 if (!resultType->canHaveNullability())
1406 return resultType;
1407
1408 // Map the nullability of the result into a table index.
1409 unsigned receiverNullabilityIdx = 0;
1410 if (auto nullability = ReceiverType->getNullability(Context))
1411 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1412
1413 unsigned resultNullabilityIdx = 0;
1414 if (auto nullability = resultType->getNullability(Context))
1415 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1416
1417 // The table of nullability mappings, indexed by the receiver's nullability
1418 // and then the result type's nullability.
1419 static const uint8_t None = 0;
1420 static const uint8_t NonNull = 1;
1421 static const uint8_t Nullable = 2;
1422 static const uint8_t Unspecified = 3;
1423 static const uint8_t nullabilityMap[4][4] = {
1424 // None NonNull Nullable Unspecified
1425 /* None */ { None, None, Nullable, None },
1426 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1427 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1428 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1429 };
1430
1431 unsigned newResultNullabilityIdx
1432 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1433 if (newResultNullabilityIdx == resultNullabilityIdx)
1434 return resultType;
1435
1436 // Strip off the existing nullability. This removes as little type sugar as
1437 // possible.
1438 do {
1439 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1440 resultType = attributed->getModifiedType();
1441 } else {
1442 resultType = resultType.getDesugaredType(Context);
1443 }
1444 } while (resultType->getNullability(Context));
1445
1446 // Add nullability back if needed.
1447 if (newResultNullabilityIdx > 0) {
1448 auto newNullability
1449 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1450 return Context.getAttributedType(
1451 AttributedType::getNullabilityAttrKind(newNullability),
1452 resultType, resultType);
1453 }
1454
1455 return resultType;
1456}
1457
1458/// Look for an ObjC method whose result type exactly matches the given type.
1459static const ObjCMethodDecl *
1460findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1461 QualType instancetype) {
1462 if (MD->getReturnType() == instancetype)
1463 return MD;
1464
1465 // For these purposes, a method in an @implementation overrides a
1466 // declaration in the @interface.
1467 if (const ObjCImplDecl *impl =
1468 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1469 const ObjCContainerDecl *iface;
1470 if (const ObjCCategoryImplDecl *catImpl =
1471 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1472 iface = catImpl->getCategoryDecl();
1473 } else {
1474 iface = impl->getClassInterface();
1475 }
1476
1477 const ObjCMethodDecl *ifaceMD =
1478 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1479 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1480 }
1481
1482 SmallVector<const ObjCMethodDecl *, 4> overrides;
1483 MD->getOverriddenMethods(overrides);
1484 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1485 if (const ObjCMethodDecl *result =
1486 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1487 return result;
1488 }
1489
1490 return nullptr;
1491}
1492
1493void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1494 // Only complain if we're in an ObjC method and the required return
1495 // type doesn't match the method's declared return type.
1496 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1497 if (!MD || !MD->hasRelatedResultType() ||
1498 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1499 return;
1500
1501 // Look for a method overridden by this method which explicitly uses
1502 // 'instancetype'.
1503 if (const ObjCMethodDecl *overridden =
1504 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1505 SourceRange range = overridden->getReturnTypeSourceRange();
1506 SourceLocation loc = range.getBegin();
1507 if (loc.isInvalid())
1508 loc = overridden->getLocation();
1509 Diag(loc, diag::note_related_result_type_explicit)
1510 << /*current method*/ 1 << range;
1511 return;
1512 }
1513
1514 // Otherwise, if we have an interesting method family, note that.
1515 // This should always trigger if the above didn't.
1516 if (ObjCMethodFamily family = MD->getMethodFamily())
1517 Diag(MD->getLocation(), diag::note_related_result_type_family)
1518 << /*current method*/ 1
1519 << family;
1520}
1521
1522void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1523 E = E->IgnoreParenImpCasts();
1524 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1525 if (!MsgSend)
1526 return;
1527
1528 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1529 if (!Method)
1530 return;
1531
1532 if (!Method->hasRelatedResultType())
1533 return;
1534
1535 if (Context.hasSameUnqualifiedType(
1536 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1537 return;
1538
1539 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1540 Context.getObjCInstanceType()))
1541 return;
1542
1543 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1544 << Method->isInstanceMethod() << Method->getSelector()
1545 << MsgSend->getType();
1546}
1547
1548bool Sema::CheckMessageArgumentTypes(
1549 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1550 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1551 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1552 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1553 ExprValueKind &VK) {
1554 SourceLocation SelLoc;
1555 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
29
Assuming the condition is false
1556 SelLoc = SelectorLocs.front();
1557 else
1558 SelLoc = lbrac;
1559
1560 if (!Method
29.1
'Method' is null
29.1
'Method' is null
) {
30
Taking true branch
1561 // Apply default argument promotion as for (C99 6.5.2.2p6).
1562 for (unsigned i = 0, e = Args.size(); i != e; i++) {
31
Assuming 'i' is equal to 'e'
32
Loop condition is false. Execution continues on line 1578
1563 if (Args[i]->isTypeDependent())
1564 continue;
1565
1566 ExprResult result;
1567 if (getLangOpts().DebuggerSupport) {
1568 QualType paramTy; // ignored
1569 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1570 } else {
1571 result = DefaultArgumentPromotion(Args[i]);
1572 }
1573 if (result.isInvalid())
1574 return true;
1575 Args[i] = result.get();
1576 }
1577
1578 unsigned DiagID;
1579 if (getLangOpts().ObjCAutoRefCount)
33
Assuming field 'ObjCAutoRefCount' is not equal to 0
34
Taking true branch
1580 DiagID = diag::err_arc_method_not_found;
1581 else
1582 DiagID = isClassMessage ? diag::warn_class_method_not_found
1583 : diag::warn_inst_method_not_found;
1584 if (!getLangOpts().DebuggerSupport) {
35
Assuming field 'DebuggerSupport' is 0
36
Taking true branch
1585 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1586 if (OMD && !OMD->isInvalidDecl()) {
37
Assuming 'OMD' is null
1587 if (getLangOpts().ObjCAutoRefCount)
1588 DiagID = diag::err_method_not_found_with_typo;
1589 else
1590 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1591 : diag::warn_instance_method_not_found_with_typo;
1592 Selector MatchedSel = OMD->getSelector();
1593 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1594 if (MatchedSel.isUnarySelector())
1595 Diag(SelLoc, DiagID)
1596 << Sel<< isClassMessage << MatchedSel
1597 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1598 else
1599 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1600 }
1601 else
1602 Diag(SelLoc, DiagID)
1603 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1604 SelectorLocs.back());
1605 // Find the class to which we are sending this message.
1606 if (ReceiverType->isObjCObjectPointerType()) {
38
Calling 'Type::isObjCObjectPointerType'
41
Returning from 'Type::isObjCObjectPointerType'
42
Taking true branch
1607 if (ObjCInterfaceDecl *ThisClass =
1608 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
43
Assuming the object is not a 'ObjCObjectPointerType'
44
Called C++ object pointer is null
1609 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1610 if (!RecRange.isInvalid())
1611 if (ThisClass->lookupClassMethod(Sel))
1612 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1613 << FixItHint::CreateReplacement(RecRange,
1614 ThisClass->getNameAsString());
1615 }
1616 }
1617 }
1618
1619 // In debuggers, we want to use __unknown_anytype for these
1620 // results so that clients can cast them.
1621 if (getLangOpts().DebuggerSupport) {
1622 ReturnType = Context.UnknownAnyTy;
1623 } else {
1624 ReturnType = Context.getObjCIdType();
1625 }
1626 VK = VK_RValue;
1627 return false;
1628 }
1629
1630 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1631 isClassMessage, isSuperMessage);
1632 VK = Expr::getValueKindForType(Method->getReturnType());
1633
1634 unsigned NumNamedArgs = Sel.getNumArgs();
1635 // Method might have more arguments than selector indicates. This is due
1636 // to addition of c-style arguments in method.
1637 if (Method->param_size() > Sel.getNumArgs())
1638 NumNamedArgs = Method->param_size();
1639 // FIXME. This need be cleaned up.
1640 if (Args.size() < NumNamedArgs) {
1641 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1642 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1643 return false;
1644 }
1645
1646 // Compute the set of type arguments to be substituted into each parameter
1647 // type.
1648 Optional<ArrayRef<QualType>> typeArgs
1649 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1650 bool IsError = false;
1651 for (unsigned i = 0; i < NumNamedArgs; i++) {
1652 // We can't do any type-checking on a type-dependent argument.
1653 if (Args[i]->isTypeDependent())
1654 continue;
1655
1656 Expr *argExpr = Args[i];
1657
1658 ParmVarDecl *param = Method->parameters()[i];
1659 assert(argExpr && "CheckMessageArgumentTypes(): missing expression")((argExpr && "CheckMessageArgumentTypes(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("argExpr && \"CheckMessageArgumentTypes(): missing expression\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 1659, __PRETTY_FUNCTION__))
;
1660
1661 if (param->hasAttr<NoEscapeAttr>())
1662 if (auto *BE = dyn_cast<BlockExpr>(
1663 argExpr->IgnoreParenNoopCasts(Context)))
1664 BE->getBlockDecl()->setDoesNotEscape();
1665
1666 // Strip the unbridged-cast placeholder expression off unless it's
1667 // a consumed argument.
1668 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1669 !param->hasAttr<CFConsumedAttr>())
1670 argExpr = stripARCUnbridgedCast(argExpr);
1671
1672 // If the parameter is __unknown_anytype, infer its type
1673 // from the argument.
1674 if (param->getType() == Context.UnknownAnyTy) {
1675 QualType paramType;
1676 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1677 if (argE.isInvalid()) {
1678 IsError = true;
1679 } else {
1680 Args[i] = argE.get();
1681
1682 // Update the parameter type in-place.
1683 param->setType(paramType);
1684 }
1685 continue;
1686 }
1687
1688 QualType origParamType = param->getType();
1689 QualType paramType = param->getType();
1690 if (typeArgs)
1691 paramType = paramType.substObjCTypeArgs(
1692 Context,
1693 *typeArgs,
1694 ObjCSubstitutionContext::Parameter);
1695
1696 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1697 paramType,
1698 diag::err_call_incomplete_argument, argExpr))
1699 return true;
1700
1701 InitializedEntity Entity
1702 = InitializedEntity::InitializeParameter(Context, param, paramType);
1703 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1704 if (ArgE.isInvalid())
1705 IsError = true;
1706 else {
1707 Args[i] = ArgE.getAs<Expr>();
1708
1709 // If we are type-erasing a block to a block-compatible
1710 // Objective-C pointer type, we may need to extend the lifetime
1711 // of the block object.
1712 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1713 Args[i]->getType()->isBlockPointerType() &&
1714 origParamType->isObjCObjectPointerType()) {
1715 ExprResult arg = Args[i];
1716 maybeExtendBlockObject(arg);
1717 Args[i] = arg.get();
1718 }
1719 }
1720 }
1721
1722 // Promote additional arguments to variadic methods.
1723 if (Method->isVariadic()) {
1724 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1725 if (Args[i]->isTypeDependent())
1726 continue;
1727
1728 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1729 nullptr);
1730 IsError |= Arg.isInvalid();
1731 Args[i] = Arg.get();
1732 }
1733 } else {
1734 // Check for extra arguments to non-variadic methods.
1735 if (Args.size() != NumNamedArgs) {
1736 Diag(Args[NumNamedArgs]->getBeginLoc(),
1737 diag::err_typecheck_call_too_many_args)
1738 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1739 << Method->getSourceRange()
1740 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1741 Args.back()->getEndLoc());
1742 }
1743 }
1744
1745 DiagnoseSentinelCalls(Method, SelLoc, Args);
1746
1747 // Do additional checkings on method.
1748 IsError |= CheckObjCMethodCall(
1749 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1750
1751 return IsError;
1752}
1753
1754bool Sema::isSelfExpr(Expr *RExpr) {
1755 // 'self' is objc 'self' in an objc method only.
1756 ObjCMethodDecl *Method =
1757 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1758 return isSelfExpr(RExpr, Method);
1759}
1760
1761bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1762 if (!method) return false;
1763
1764 receiver = receiver->IgnoreParenLValueCasts();
1765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1766 if (DRE->getDecl() == method->getSelfDecl())
1767 return true;
1768 return false;
1769}
1770
1771/// LookupMethodInType - Look up a method in an ObjCObjectType.
1772ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1773 bool isInstance) {
1774 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1775 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1776 // Look it up in the main interface (and categories, etc.)
1777 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1778 return method;
1779
1780 // Okay, look for "private" methods declared in any
1781 // @implementations we've seen.
1782 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1783 return method;
1784 }
1785
1786 // Check qualifiers.
1787 for (const auto *I : objType->quals())
1788 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1789 return method;
1790
1791 return nullptr;
1792}
1793
1794/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1795/// list of a qualified objective pointer type.
1796ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1797 const ObjCObjectPointerType *OPT,
1798 bool Instance)
1799{
1800 ObjCMethodDecl *MD = nullptr;
1801 for (const auto *PROTO : OPT->quals()) {
1802 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1803 return MD;
1804 }
1805 }
1806 return nullptr;
1807}
1808
1809/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1810/// objective C interface. This is a property reference expression.
1811ExprResult Sema::
1812HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1813 Expr *BaseExpr, SourceLocation OpLoc,
1814 DeclarationName MemberName,
1815 SourceLocation MemberLoc,
1816 SourceLocation SuperLoc, QualType SuperType,
1817 bool Super) {
1818 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1819 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1820
1821 if (!MemberName.isIdentifier()) {
1822 Diag(MemberLoc, diag::err_invalid_property_name)
1823 << MemberName << QualType(OPT, 0);
1824 return ExprError();
1825 }
1826
1827 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1828
1829 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1830 : BaseExpr->getSourceRange();
1831 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1832 diag::err_property_not_found_forward_class,
1833 MemberName, BaseRange))
1834 return ExprError();
1835
1836 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1837 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1838 // Check whether we can reference this property.
1839 if (DiagnoseUseOfDecl(PD, MemberLoc))
1840 return ExprError();
1841 if (Super)
1842 return new (Context)
1843 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1844 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1845 else
1846 return new (Context)
1847 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1848 OK_ObjCProperty, MemberLoc, BaseExpr);
1849 }
1850 // Check protocols on qualified interfaces.
1851 for (const auto *I : OPT->quals())
1852 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1853 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1854 // Check whether we can reference this property.
1855 if (DiagnoseUseOfDecl(PD, MemberLoc))
1856 return ExprError();
1857
1858 if (Super)
1859 return new (Context) ObjCPropertyRefExpr(
1860 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1861 SuperLoc, SuperType);
1862 else
1863 return new (Context)
1864 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1865 OK_ObjCProperty, MemberLoc, BaseExpr);
1866 }
1867 // If that failed, look for an "implicit" property by seeing if the nullary
1868 // selector is implemented.
1869
1870 // FIXME: The logic for looking up nullary and unary selectors should be
1871 // shared with the code in ActOnInstanceMessage.
1872
1873 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1874 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1875
1876 // May be found in property's qualified list.
1877 if (!Getter)
1878 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1879
1880 // If this reference is in an @implementation, check for 'private' methods.
1881 if (!Getter)
1882 Getter = IFace->lookupPrivateMethod(Sel);
1883
1884 if (Getter) {
1885 // Check if we can reference this property.
1886 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1887 return ExprError();
1888 }
1889 // If we found a getter then this may be a valid dot-reference, we
1890 // will look for the matching setter, in case it is needed.
1891 Selector SetterSel =
1892 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1893 PP.getSelectorTable(), Member);
1894 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1895
1896 // May be found in property's qualified list.
1897 if (!Setter)
1898 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1899
1900 if (!Setter) {
1901 // If this reference is in an @implementation, also check for 'private'
1902 // methods.
1903 Setter = IFace->lookupPrivateMethod(SetterSel);
1904 }
1905
1906 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1907 return ExprError();
1908
1909 // Special warning if member name used in a property-dot for a setter accessor
1910 // does not use a property with same name; e.g. obj.X = ... for a property with
1911 // name 'x'.
1912 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1913 !IFace->FindPropertyDeclaration(
1914 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1915 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1916 // Do not warn if user is using property-dot syntax to make call to
1917 // user named setter.
1918 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1919 Diag(MemberLoc,
1920 diag::warn_property_access_suggest)
1921 << MemberName << QualType(OPT, 0) << PDecl->getName()
1922 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1923 }
1924 }
1925
1926 if (Getter || Setter) {
1927 if (Super)
1928 return new (Context)
1929 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1930 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1931 else
1932 return new (Context)
1933 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1934 OK_ObjCProperty, MemberLoc, BaseExpr);
1935
1936 }
1937
1938 // Attempt to correct for typos in property names.
1939 DeclFilterCCC<ObjCPropertyDecl> CCC{};
1940 if (TypoCorrection Corrected = CorrectTypo(
1941 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1942 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
1943 DeclarationName TypoResult = Corrected.getCorrection();
1944 if (TypoResult.isIdentifier() &&
1945 TypoResult.getAsIdentifierInfo() == Member) {
1946 // There is no need to try the correction if it is the same.
1947 NamedDecl *ChosenDecl =
1948 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1949 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1950 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1951 // This is a class property, we should not use the instance to
1952 // access it.
1953 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1954 << OPT->getInterfaceDecl()->getName()
1955 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1956 OPT->getInterfaceDecl()->getName());
1957 return ExprError();
1958 }
1959 } else {
1960 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1961 << MemberName << QualType(OPT, 0));
1962 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1963 TypoResult, MemberLoc,
1964 SuperLoc, SuperType, Super);
1965 }
1966 }
1967 ObjCInterfaceDecl *ClassDeclared;
1968 if (ObjCIvarDecl *Ivar =
1969 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1970 QualType T = Ivar->getType();
1971 if (const ObjCObjectPointerType * OBJPT =
1972 T->getAsObjCInterfacePointerType()) {
1973 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1974 diag::err_property_not_as_forward_class,
1975 MemberName, BaseExpr))
1976 return ExprError();
1977 }
1978 Diag(MemberLoc,
1979 diag::err_ivar_access_using_property_syntax_suggest)
1980 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1981 << FixItHint::CreateReplacement(OpLoc, "->");
1982 return ExprError();
1983 }
1984
1985 Diag(MemberLoc, diag::err_property_not_found)
1986 << MemberName << QualType(OPT, 0);
1987 if (Setter)
1988 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1989 << MemberName << BaseExpr->getSourceRange();
1990 return ExprError();
1991}
1992
1993ExprResult Sema::
1994ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1995 IdentifierInfo &propertyName,
1996 SourceLocation receiverNameLoc,
1997 SourceLocation propertyNameLoc) {
1998
1999 IdentifierInfo *receiverNamePtr = &receiverName;
2000 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2001 receiverNameLoc);
2002
2003 QualType SuperType;
2004 if (!IFace) {
2005 // If the "receiver" is 'super' in a method, handle it as an expression-like
2006 // property reference.
2007 if (receiverNamePtr->isStr("super")) {
2008 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2009 if (auto classDecl = CurMethod->getClassInterface()) {
2010 SuperType = QualType(classDecl->getSuperClassType(), 0);
2011 if (CurMethod->isInstanceMethod()) {
2012 if (SuperType.isNull()) {
2013 // The current class does not have a superclass.
2014 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2015 << CurMethod->getClassInterface()->getIdentifier();
2016 return ExprError();
2017 }
2018 QualType T = Context.getObjCObjectPointerType(SuperType);
2019
2020 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2021 /*BaseExpr*/nullptr,
2022 SourceLocation()/*OpLoc*/,
2023 &propertyName,
2024 propertyNameLoc,
2025 receiverNameLoc, T, true);
2026 }
2027
2028 // Otherwise, if this is a class method, try dispatching to our
2029 // superclass.
2030 IFace = CurMethod->getClassInterface()->getSuperClass();
2031 }
2032 }
2033 }
2034
2035 if (!IFace) {
2036 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2037 << tok::l_paren;
2038 return ExprError();
2039 }
2040 }
2041
2042 Selector GetterSel;
2043 Selector SetterSel;
2044 if (auto PD = IFace->FindPropertyDeclaration(
2045 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2046 GetterSel = PD->getGetterName();
2047 SetterSel = PD->getSetterName();
2048 } else {
2049 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2050 SetterSel = SelectorTable::constructSetterSelector(
2051 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2052 }
2053
2054 // Search for a declared property first.
2055 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2056
2057 // If this reference is in an @implementation, check for 'private' methods.
2058 if (!Getter)
2059 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2060
2061 if (Getter) {
2062 // FIXME: refactor/share with ActOnMemberReference().
2063 // Check if we can reference this property.
2064 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2065 return ExprError();
2066 }
2067
2068 // Look for the matching setter, in case it is needed.
2069 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2070 if (!Setter) {
2071 // If this reference is in an @implementation, also check for 'private'
2072 // methods.
2073 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2074 }
2075 // Look through local category implementations associated with the class.
2076 if (!Setter)
2077 Setter = IFace->getCategoryClassMethod(SetterSel);
2078
2079 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2080 return ExprError();
2081
2082 if (Getter || Setter) {
2083 if (!SuperType.isNull())
2084 return new (Context)
2085 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2086 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2087 SuperType);
2088
2089 return new (Context) ObjCPropertyRefExpr(
2090 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2091 propertyNameLoc, receiverNameLoc, IFace);
2092 }
2093 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2094 << &propertyName << Context.getObjCInterfaceType(IFace));
2095}
2096
2097namespace {
2098
2099class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2100 public:
2101 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2102 // Determine whether "super" is acceptable in the current context.
2103 if (Method && Method->getClassInterface())
2104 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2105 }
2106
2107 bool ValidateCandidate(const TypoCorrection &candidate) override {
2108 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2109 candidate.isKeyword("super");
2110 }
2111
2112 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2113 return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2114 }
2115};
2116
2117} // end anonymous namespace
2118
2119Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2120 IdentifierInfo *Name,
2121 SourceLocation NameLoc,
2122 bool IsSuper,
2123 bool HasTrailingDot,
2124 ParsedType &ReceiverType) {
2125 ReceiverType = nullptr;
2126
2127 // If the identifier is "super" and there is no trailing dot, we're
2128 // messaging super. If the identifier is "super" and there is a
2129 // trailing dot, it's an instance message.
2130 if (IsSuper && S->isInObjcMethodScope())
2131 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2132
2133 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2134 LookupName(Result, S);
2135
2136 switch (Result.getResultKind()) {
2137 case LookupResult::NotFound:
2138 // Normal name lookup didn't find anything. If we're in an
2139 // Objective-C method, look for ivars. If we find one, we're done!
2140 // FIXME: This is a hack. Ivar lookup should be part of normal
2141 // lookup.
2142 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2143 if (!Method->getClassInterface()) {
2144 // Fall back: let the parser try to parse it as an instance message.
2145 return ObjCInstanceMessage;
2146 }
2147
2148 ObjCInterfaceDecl *ClassDeclared;
2149 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2150 ClassDeclared))
2151 return ObjCInstanceMessage;
2152 }
2153
2154 // Break out; we'll perform typo correction below.
2155 break;
2156
2157 case LookupResult::NotFoundInCurrentInstantiation:
2158 case LookupResult::FoundOverloaded:
2159 case LookupResult::FoundUnresolvedValue:
2160 case LookupResult::Ambiguous:
2161 Result.suppressDiagnostics();
2162 return ObjCInstanceMessage;
2163
2164 case LookupResult::Found: {
2165 // If the identifier is a class or not, and there is a trailing dot,
2166 // it's an instance message.
2167 if (HasTrailingDot)
2168 return ObjCInstanceMessage;
2169 // We found something. If it's a type, then we have a class
2170 // message. Otherwise, it's an instance message.
2171 NamedDecl *ND = Result.getFoundDecl();
2172 QualType T;
2173 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2174 T = Context.getObjCInterfaceType(Class);
2175 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2176 T = Context.getTypeDeclType(Type);
2177 DiagnoseUseOfDecl(Type, NameLoc);
2178 }
2179 else
2180 return ObjCInstanceMessage;
2181
2182 // We have a class message, and T is the type we're
2183 // messaging. Build source-location information for it.
2184 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2185 ReceiverType = CreateParsedType(T, TSInfo);
2186 return ObjCClassMessage;
2187 }
2188 }
2189
2190 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2191 if (TypoCorrection Corrected = CorrectTypo(
2192 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2193 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2194 if (Corrected.isKeyword()) {
2195 // If we've found the keyword "super" (the only keyword that would be
2196 // returned by CorrectTypo), this is a send to super.
2197 diagnoseTypo(Corrected,
2198 PDiag(diag::err_unknown_receiver_suggest) << Name);
2199 return ObjCSuperMessage;
2200 } else if (ObjCInterfaceDecl *Class =
2201 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2202 // If we found a declaration, correct when it refers to an Objective-C
2203 // class.
2204 diagnoseTypo(Corrected,
2205 PDiag(diag::err_unknown_receiver_suggest) << Name);
2206 QualType T = Context.getObjCInterfaceType(Class);
2207 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2208 ReceiverType = CreateParsedType(T, TSInfo);
2209 return ObjCClassMessage;
2210 }
2211 }
2212
2213 // Fall back: let the parser try to parse it as an instance message.
2214 return ObjCInstanceMessage;
2215}
2216
2217ExprResult Sema::ActOnSuperMessage(Scope *S,
2218 SourceLocation SuperLoc,
2219 Selector Sel,
2220 SourceLocation LBracLoc,
2221 ArrayRef<SourceLocation> SelectorLocs,
2222 SourceLocation RBracLoc,
2223 MultiExprArg Args) {
2224 // Determine whether we are inside a method or not.
2225 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2226 if (!Method) {
2227 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2228 return ExprError();
2229 }
2230
2231 ObjCInterfaceDecl *Class = Method->getClassInterface();
2232 if (!Class) {
2233 Diag(SuperLoc, diag::err_no_super_class_message)
2234 << Method->getDeclName();
2235 return ExprError();
2236 }
2237
2238 QualType SuperTy(Class->getSuperClassType(), 0);
2239 if (SuperTy.isNull()) {
2240 // The current class does not have a superclass.
2241 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2242 << Class->getIdentifier();
2243 return ExprError();
2244 }
2245
2246 // We are in a method whose class has a superclass, so 'super'
2247 // is acting as a keyword.
2248 if (Method->getSelector() == Sel)
2249 getCurFunction()->ObjCShouldCallSuper = false;
2250
2251 if (Method->isInstanceMethod()) {
2252 // Since we are in an instance method, this is an instance
2253 // message to the superclass instance.
2254 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2255 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2256 Sel, /*Method=*/nullptr,
2257 LBracLoc, SelectorLocs, RBracLoc, Args);
2258 }
2259
2260 // Since we are in a class method, this is a class message to
2261 // the superclass.
2262 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2263 SuperTy,
2264 SuperLoc, Sel, /*Method=*/nullptr,
2265 LBracLoc, SelectorLocs, RBracLoc, Args);
2266}
2267
2268ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2269 bool isSuperReceiver,
2270 SourceLocation Loc,
2271 Selector Sel,
2272 ObjCMethodDecl *Method,
2273 MultiExprArg Args) {
2274 TypeSourceInfo *receiverTypeInfo = nullptr;
2275 if (!ReceiverType.isNull())
2276 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2277
2278 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2279 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2280 Sel, Method, Loc, Loc, Loc, Args,
2281 /*isImplicit=*/true);
2282}
2283
2284static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2285 unsigned DiagID,
2286 bool (*refactor)(const ObjCMessageExpr *,
2287 const NSAPI &, edit::Commit &)) {
2288 SourceLocation MsgLoc = Msg->getExprLoc();
2289 if (S.Diags.isIgnored(DiagID, MsgLoc))
2290 return;
2291
2292 SourceManager &SM = S.SourceMgr;
2293 edit::Commit ECommit(SM, S.LangOpts);
2294 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2295 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2296 << Msg->getSelector() << Msg->getSourceRange();
2297 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2298 if (!ECommit.isCommitable())
2299 return;
2300 for (edit::Commit::edit_iterator
2301 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2302 const edit::Commit::Edit &Edit = *I;
2303 switch (Edit.Kind) {
2304 case edit::Commit::Act_Insert:
2305 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2306 Edit.Text,
2307 Edit.BeforePrev));
2308 break;
2309 case edit::Commit::Act_InsertFromRange:
2310 Builder.AddFixItHint(
2311 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2312 Edit.getInsertFromRange(SM),
2313 Edit.BeforePrev));
2314 break;
2315 case edit::Commit::Act_Remove:
2316 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2317 break;
2318 }
2319 }
2320 }
2321}
2322
2323static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2324 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2325 edit::rewriteObjCRedundantCallWithLiteral);
2326}
2327
2328static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2329 const ObjCMethodDecl *Method,
2330 ArrayRef<Expr *> Args, QualType ReceiverType,
2331 bool IsClassObjectCall) {
2332 // Check if this is a performSelector method that uses a selector that returns
2333 // a record or a vector type.
2334 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2335 Args.empty())
2336 return;
2337 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2338 if (!SE)
2339 return;
2340 ObjCMethodDecl *ImpliedMethod;
2341 if (!IsClassObjectCall) {
2342 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2343 if (!OPT || !OPT->getInterfaceDecl())
2344 return;
2345 ImpliedMethod =
2346 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2347 if (!ImpliedMethod)
2348 ImpliedMethod =
2349 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2350 } else {
2351 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2352 if (!IT)
2353 return;
2354 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2355 if (!ImpliedMethod)
2356 ImpliedMethod =
2357 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2358 }
2359 if (!ImpliedMethod)
2360 return;
2361 QualType Ret = ImpliedMethod->getReturnType();
2362 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2363 QualType Ret = ImpliedMethod->getReturnType();
2364 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2365 << Method->getSelector()
2366 << (!Ret->isRecordType()
2367 ? /*Vector*/ 2
2368 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2369 S.Diag(ImpliedMethod->getBeginLoc(),
2370 diag::note_objc_unsafe_perform_selector_method_declared_here)
2371 << ImpliedMethod->getSelector() << Ret;
2372 }
2373}
2374
2375/// Diagnose use of %s directive in an NSString which is being passed
2376/// as formatting string to formatting method.
2377static void
2378DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2379 ObjCMethodDecl *Method,
2380 Selector Sel,
2381 Expr **Args, unsigned NumArgs) {
2382 unsigned Idx = 0;
2383 bool Format = false;
2384 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2385 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2386 Idx = 0;
2387 Format = true;
2388 }
2389 else if (Method) {
2390 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2391 if (S.GetFormatNSStringIdx(I, Idx)) {
2392 Format = true;
2393 break;
2394 }
2395 }
2396 }
2397 if (!Format || NumArgs <= Idx)
2398 return;
2399
2400 Expr *FormatExpr = Args[Idx];
2401 if (ObjCStringLiteral *OSL =
2402 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2403 StringLiteral *FormatString = OSL->getString();
2404 if (S.FormatStringHasSArg(FormatString)) {
2405 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2406 << "%s" << 0 << 0;
2407 if (Method)
2408 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2409 << Method->getDeclName();
2410 }
2411 }
2412}
2413
2414/// Build an Objective-C class message expression.
2415///
2416/// This routine takes care of both normal class messages and
2417/// class messages to the superclass.
2418///
2419/// \param ReceiverTypeInfo Type source information that describes the
2420/// receiver of this message. This may be NULL, in which case we are
2421/// sending to the superclass and \p SuperLoc must be a valid source
2422/// location.
2423
2424/// \param ReceiverType The type of the object receiving the
2425/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2426/// type as that refers to. For a superclass send, this is the type of
2427/// the superclass.
2428///
2429/// \param SuperLoc The location of the "super" keyword in a
2430/// superclass message.
2431///
2432/// \param Sel The selector to which the message is being sent.
2433///
2434/// \param Method The method that this class message is invoking, if
2435/// already known.
2436///
2437/// \param LBracLoc The location of the opening square bracket ']'.
2438///
2439/// \param RBracLoc The location of the closing square bracket ']'.
2440///
2441/// \param ArgsIn The message arguments.
2442ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2443 QualType ReceiverType,
2444 SourceLocation SuperLoc,
2445 Selector Sel,
2446 ObjCMethodDecl *Method,
2447 SourceLocation LBracLoc,
2448 ArrayRef<SourceLocation> SelectorLocs,
2449 SourceLocation RBracLoc,
2450 MultiExprArg ArgsIn,
2451 bool isImplicit) {
2452 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
5
'?' condition is false
2453 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2454 if (LBracLoc.isInvalid()) {
6
Taking false branch
2455 Diag(Loc, diag::err_missing_open_square_message_send)
2456 << FixItHint::CreateInsertion(Loc, "[");
2457 LBracLoc = Loc;
2458 }
2459 ArrayRef<SourceLocation> SelectorSlotLocs;
2460 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
7
Assuming the condition is false
2461 SelectorSlotLocs = SelectorLocs;
2462 else
2463 SelectorSlotLocs = Loc;
2464 SourceLocation SelLoc = SelectorSlotLocs.front();
2465
2466 if (ReceiverType->isDependentType()) {
8
Assuming the condition is false
9
Taking false branch
2467 // If the receiver type is dependent, we can't type-check anything
2468 // at this point. Build a dependent expression.
2469 unsigned NumArgs = ArgsIn.size();
2470 Expr **Args = ArgsIn.data();
2471 assert(SuperLoc.isInvalid() && "Message to super with dependent type")((SuperLoc.isInvalid() && "Message to super with dependent type"
) ? static_cast<void> (0) : __assert_fail ("SuperLoc.isInvalid() && \"Message to super with dependent type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2471, __PRETTY_FUNCTION__))
;
2472 return ObjCMessageExpr::Create(
2473 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2474 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2475 isImplicit);
2476 }
2477
2478 // Find the class to which we are sending this message.
2479 ObjCInterfaceDecl *Class = nullptr;
2480 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
10
Assuming the object is a 'ObjCObjectType'
2481 if (!ClassType || !(Class = ClassType->getInterface())) {
11
Assuming 'ClassType' is non-null
12
Assuming pointer value is null
13
Assuming 'Class' is non-null
14
Taking false branch
2482 Diag(Loc, diag::err_invalid_receiver_class_message)
2483 << ReceiverType;
2484 return ExprError();
2485 }
2486 assert
14.1
'Class' is non-null
14.1
'Class' is non-null
(Class && "We don't know which class we're messaging?")((Class && "We don't know which class we're messaging?"
) ? static_cast<void> (0) : __assert_fail ("Class && \"We don't know which class we're messaging?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2486, __PRETTY_FUNCTION__))
;
15
'?' condition is true
2487 // objc++ diagnoses during typename annotation.
2488 if (!getLangOpts().CPlusPlus)
16
Assuming field 'CPlusPlus' is not equal to 0
17
Taking false branch
2489 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2490 // Find the method we are messaging.
2491 if (!Method
17.1
'Method' is null
17.1
'Method' is null
) {
18
Taking true branch
2492 SourceRange TypeRange
2493 = SuperLoc.isValid()? SourceRange(SuperLoc)
19
'?' condition is false
2494 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2495 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
22
Assuming the condition is false
23
Taking false branch
2496 (getLangOpts().ObjCAutoRefCount
20
Assuming field 'ObjCAutoRefCount' is 0
21
'?' condition is false
2497 ? diag::err_arc_receiver_forward_class
2498 : diag::warn_receiver_forward_class),
2499 TypeRange)) {
2500 // A forward class used in messaging is treated as a 'Class'
2501 Method = LookupFactoryMethodInGlobalPool(Sel,
2502 SourceRange(LBracLoc, RBracLoc));
2503 if (Method && !getLangOpts().ObjCAutoRefCount)
2504 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2505 << Method->getDeclName();
2506 }
2507 if (!Method
23.1
'Method' is null
23.1
'Method' is null
)
24
Taking true branch
2508 Method = Class->lookupClassMethod(Sel);
2509
2510 // If we have an implementation in scope, check "private" methods.
2511 if (!Method)
25
Assuming 'Method' is null
26
Taking true branch
2512 Method = Class->lookupPrivateClassMethod(Sel);
2513
2514 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
27
Assuming 'Method' is null
2515 nullptr, false, false, Class))
2516 return ExprError();
2517 }
2518
2519 // Check the argument types and determine the result type.
2520 QualType ReturnType;
2521 ExprValueKind VK = VK_RValue;
2522
2523 unsigned NumArgs = ArgsIn.size();
2524 Expr **Args = ArgsIn.data();
2525 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
28
Calling 'Sema::CheckMessageArgumentTypes'
2526 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2527 Method, true, SuperLoc.isValid(), LBracLoc,
2528 RBracLoc, SourceRange(), ReturnType, VK))
2529 return ExprError();
2530
2531 if (Method && !Method->getReturnType()->isVoidType() &&
2532 RequireCompleteType(LBracLoc, Method->getReturnType(),
2533 diag::err_illegal_message_expr_incomplete_type))
2534 return ExprError();
2535
2536 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2537 if (Method && Method->getMethodFamily() == OMF_initialize) {
2538 if (!SuperLoc.isValid()) {
2539 const ObjCInterfaceDecl *ID =
2540 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2541 if (ID == Class) {
2542 Diag(Loc, diag::warn_direct_initialize_call);
2543 Diag(Method->getLocation(), diag::note_method_declared_at)
2544 << Method->getDeclName();
2545 }
2546 }
2547 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2548 // [super initialize] is allowed only within an +initialize implementation
2549 if (CurMeth->getMethodFamily() != OMF_initialize) {
2550 Diag(Loc, diag::warn_direct_super_initialize_call);
2551 Diag(Method->getLocation(), diag::note_method_declared_at)
2552 << Method->getDeclName();
2553 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2554 << CurMeth->getDeclName();
2555 }
2556 }
2557 }
2558
2559 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2560
2561 // Construct the appropriate ObjCMessageExpr.
2562 ObjCMessageExpr *Result;
2563 if (SuperLoc.isValid())
2564 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2565 SuperLoc, /*IsInstanceSuper=*/false,
2566 ReceiverType, Sel, SelectorLocs,
2567 Method, makeArrayRef(Args, NumArgs),
2568 RBracLoc, isImplicit);
2569 else {
2570 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2571 ReceiverTypeInfo, Sel, SelectorLocs,
2572 Method, makeArrayRef(Args, NumArgs),
2573 RBracLoc, isImplicit);
2574 if (!isImplicit)
2575 checkCocoaAPI(*this, Result);
2576 }
2577 if (Method)
2578 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2579 ReceiverType, /*IsClassObjectCall=*/true);
2580 return MaybeBindToTemporary(Result);
2581}
2582
2583// ActOnClassMessage - used for both unary and keyword messages.
2584// ArgExprs is optional - if it is present, the number of expressions
2585// is obtained from Sel.getNumArgs().
2586ExprResult Sema::ActOnClassMessage(Scope *S,
2587 ParsedType Receiver,
2588 Selector Sel,
2589 SourceLocation LBracLoc,
2590 ArrayRef<SourceLocation> SelectorLocs,
2591 SourceLocation RBracLoc,
2592 MultiExprArg Args) {
2593 TypeSourceInfo *ReceiverTypeInfo;
2594 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2595 if (ReceiverType.isNull())
1
Taking false branch
2596 return ExprError();
2597
2598 if (!ReceiverTypeInfo)
2
Assuming 'ReceiverTypeInfo' is non-null
3
Taking false branch
2599 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2600
2601 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
4
Calling 'Sema::BuildClassMessage'
2602 /*SuperLoc=*/SourceLocation(), Sel,
2603 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2604 Args);
2605}
2606
2607ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2608 QualType ReceiverType,
2609 SourceLocation Loc,
2610 Selector Sel,
2611 ObjCMethodDecl *Method,
2612 MultiExprArg Args) {
2613 return BuildInstanceMessage(Receiver, ReceiverType,
2614 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2615 Sel, Method, Loc, Loc, Loc, Args,
2616 /*isImplicit=*/true);
2617}
2618
2619static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2620 if (!S.NSAPIObj)
2621 return false;
2622 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2623 if (!Protocol)
2624 return false;
2625 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2626 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2627 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2628 Sema::LookupOrdinaryName))) {
2629 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2630 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2631 return true;
2632 }
2633 }
2634 return false;
2635}
2636
2637/// Build an Objective-C instance message expression.
2638///
2639/// This routine takes care of both normal instance messages and
2640/// instance messages to the superclass instance.
2641///
2642/// \param Receiver The expression that computes the object that will
2643/// receive this message. This may be empty, in which case we are
2644/// sending to the superclass instance and \p SuperLoc must be a valid
2645/// source location.
2646///
2647/// \param ReceiverType The (static) type of the object receiving the
2648/// message. When a \p Receiver expression is provided, this is the
2649/// same type as that expression. For a superclass instance send, this
2650/// is a pointer to the type of the superclass.
2651///
2652/// \param SuperLoc The location of the "super" keyword in a
2653/// superclass instance message.
2654///
2655/// \param Sel The selector to which the message is being sent.
2656///
2657/// \param Method The method that this instance message is invoking, if
2658/// already known.
2659///
2660/// \param LBracLoc The location of the opening square bracket ']'.
2661///
2662/// \param RBracLoc The location of the closing square bracket ']'.
2663///
2664/// \param ArgsIn The message arguments.
2665ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2666 QualType ReceiverType,
2667 SourceLocation SuperLoc,
2668 Selector Sel,
2669 ObjCMethodDecl *Method,
2670 SourceLocation LBracLoc,
2671 ArrayRef<SourceLocation> SelectorLocs,
2672 SourceLocation RBracLoc,
2673 MultiExprArg ArgsIn,
2674 bool isImplicit) {
2675 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "(((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
"SuperLoc must be valid so we can " "use it instead.") ? static_cast
<void> (0) : __assert_fail ("(Receiver || SuperLoc.isValid()) && \"If the Receiver is null, the \" \"SuperLoc must be valid so we can \" \"use it instead.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2677, __PRETTY_FUNCTION__))
2676 "SuperLoc must be valid so we can "(((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
"SuperLoc must be valid so we can " "use it instead.") ? static_cast
<void> (0) : __assert_fail ("(Receiver || SuperLoc.isValid()) && \"If the Receiver is null, the \" \"SuperLoc must be valid so we can \" \"use it instead.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2677, __PRETTY_FUNCTION__))
2677 "use it instead.")(((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
"SuperLoc must be valid so we can " "use it instead.") ? static_cast
<void> (0) : __assert_fail ("(Receiver || SuperLoc.isValid()) && \"If the Receiver is null, the \" \"SuperLoc must be valid so we can \" \"use it instead.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2677, __PRETTY_FUNCTION__))
;
2678
2679 // The location of the receiver.
2680 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
2681 SourceRange RecRange =
2682 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2683 ArrayRef<SourceLocation> SelectorSlotLocs;
2684 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2685 SelectorSlotLocs = SelectorLocs;
2686 else
2687 SelectorSlotLocs = Loc;
2688 SourceLocation SelLoc = SelectorSlotLocs.front();
2689
2690 if (LBracLoc.isInvalid()) {
2691 Diag(Loc, diag::err_missing_open_square_message_send)
2692 << FixItHint::CreateInsertion(Loc, "[");
2693 LBracLoc = Loc;
2694 }
2695
2696 // If we have a receiver expression, perform appropriate promotions
2697 // and determine receiver type.
2698 if (Receiver) {
2699 if (Receiver->hasPlaceholderType()) {
2700 ExprResult Result;
2701 if (Receiver->getType() == Context.UnknownAnyTy)
2702 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2703 else
2704 Result = CheckPlaceholderExpr(Receiver);
2705 if (Result.isInvalid()) return ExprError();
2706 Receiver = Result.get();
2707 }
2708
2709 if (Receiver->isTypeDependent()) {
2710 // If the receiver is type-dependent, we can't type-check anything
2711 // at this point. Build a dependent expression.
2712 unsigned NumArgs = ArgsIn.size();
2713 Expr **Args = ArgsIn.data();
2714 assert(SuperLoc.isInvalid() && "Message to super with dependent type")((SuperLoc.isInvalid() && "Message to super with dependent type"
) ? static_cast<void> (0) : __assert_fail ("SuperLoc.isInvalid() && \"Message to super with dependent type\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2714, __PRETTY_FUNCTION__))
;
2715 return ObjCMessageExpr::Create(
2716 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2717 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2718 RBracLoc, isImplicit);
2719 }
2720
2721 // If necessary, apply function/array conversion to the receiver.
2722 // C99 6.7.5.3p[7,8].
2723 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2724 if (Result.isInvalid())
2725 return ExprError();
2726 Receiver = Result.get();
2727 ReceiverType = Receiver->getType();
2728
2729 // If the receiver is an ObjC pointer, a block pointer, or an
2730 // __attribute__((NSObject)) pointer, we don't need to do any
2731 // special conversion in order to look up a receiver.
2732 if (ReceiverType->isObjCRetainableType()) {
2733 // do nothing
2734 } else if (!getLangOpts().ObjCAutoRefCount &&
2735 !Context.getObjCIdType().isNull() &&
2736 (ReceiverType->isPointerType() ||
2737 ReceiverType->isIntegerType())) {
2738 // Implicitly convert integers and pointers to 'id' but emit a warning.
2739 // But not in ARC.
2740 Diag(Loc, diag::warn_bad_receiver_type)
2741 << ReceiverType
2742 << Receiver->getSourceRange();
2743 if (ReceiverType->isPointerType()) {
2744 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2745 CK_CPointerToObjCPointerCast).get();
2746 } else {
2747 // TODO: specialized warning on null receivers?
2748 bool IsNull = Receiver->isNullPointerConstant(Context,
2749 Expr::NPC_ValueDependentIsNull);
2750 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2751 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2752 Kind).get();
2753 }
2754 ReceiverType = Receiver->getType();
2755 } else if (getLangOpts().CPlusPlus) {
2756 // The receiver must be a complete type.
2757 if (RequireCompleteType(Loc, Receiver->getType(),
2758 diag::err_incomplete_receiver_type))
2759 return ExprError();
2760
2761 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2762 if (result.isUsable()) {
2763 Receiver = result.get();
2764 ReceiverType = Receiver->getType();
2765 }
2766 }
2767 }
2768
2769 if (ReceiverType->isObjCIdType() && !isImplicit)
2770 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2771
2772 // There's a somewhat weird interaction here where we assume that we
2773 // won't actually have a method unless we also don't need to do some
2774 // of the more detailed type-checking on the receiver.
2775
2776 if (!Method) {
2777 // Handle messages to id and __kindof types (where we use the
2778 // global method pool).
2779 const ObjCObjectType *typeBound = nullptr;
2780 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2781 typeBound);
2782 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2783 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2784 SmallVector<ObjCMethodDecl*, 4> Methods;
2785 // If we have a type bound, further filter the methods.
2786 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2787 true/*CheckTheOther*/, typeBound);
2788 if (!Methods.empty()) {
2789 // We choose the first method as the initial candidate, then try to
2790 // select a better one.
2791 Method = Methods[0];
2792
2793 if (ObjCMethodDecl *BestMethod =
2794 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2795 Method = BestMethod;
2796
2797 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2798 SourceRange(LBracLoc, RBracLoc),
2799 receiverIsIdLike, Methods))
2800 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2801 }
2802 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2803 ReceiverType->isObjCQualifiedClassType()) {
2804 // Handle messages to Class.
2805 // We allow sending a message to a qualified Class ("Class<foo>"), which
2806 // is ok as long as one of the protocols implements the selector (if not,
2807 // warn).
2808 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2809 const ObjCObjectPointerType *QClassTy
2810 = ReceiverType->getAsObjCQualifiedClassType();
2811 // Search protocols for class methods.
2812 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2813 if (!Method) {
2814 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2815 // warn if instance method found for a Class message.
2816 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2817 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2818 << Method->getSelector() << Sel;
2819 Diag(Method->getLocation(), diag::note_method_declared_at)
2820 << Method->getDeclName();
2821 }
2822 }
2823 } else {
2824 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2825 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2826 // As a guess, try looking for the method in the current interface.
2827 // This very well may not produce the "right" method.
2828
2829 // First check the public methods in the class interface.
2830 Method = ClassDecl->lookupClassMethod(Sel);
2831
2832 if (!Method)
2833 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2834
2835 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2836 return ExprError();
2837 }
2838 }
2839 if (!Method) {
2840 // If not messaging 'self', look for any factory method named 'Sel'.
2841 if (!Receiver || !isSelfExpr(Receiver)) {
2842 // If no class (factory) method was found, check if an _instance_
2843 // method of the same name exists in the root class only.
2844 SmallVector<ObjCMethodDecl*, 4> Methods;
2845 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2846 false/*InstanceFirst*/,
2847 true/*CheckTheOther*/);
2848 if (!Methods.empty()) {
2849 // We choose the first method as the initial candidate, then try
2850 // to select a better one.
2851 Method = Methods[0];
2852
2853 // If we find an instance method, emit warning.
2854 if (Method->isInstanceMethod()) {
2855 if (const ObjCInterfaceDecl *ID =
2856 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2857 if (ID->getSuperClass())
2858 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2859 << Sel << SourceRange(LBracLoc, RBracLoc);
2860 }
2861 }
2862
2863 if (ObjCMethodDecl *BestMethod =
2864 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2865 Methods))
2866 Method = BestMethod;
2867 }
2868 }
2869 }
2870 }
2871 } else {
2872 ObjCInterfaceDecl *ClassDecl = nullptr;
2873
2874 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2875 // long as one of the protocols implements the selector (if not, warn).
2876 // And as long as message is not deprecated/unavailable (warn if it is).
2877 if (const ObjCObjectPointerType *QIdTy
2878 = ReceiverType->getAsObjCQualifiedIdType()) {
2879 // Search protocols for instance methods.
2880 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2881 if (!Method)
2882 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2883 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2884 return ExprError();
2885 } else if (const ObjCObjectPointerType *OCIType
2886 = ReceiverType->getAsObjCInterfacePointerType()) {
2887 // We allow sending a message to a pointer to an interface (an object).
2888 ClassDecl = OCIType->getInterfaceDecl();
2889
2890 // Try to complete the type. Under ARC, this is a hard error from which
2891 // we don't try to recover.
2892 // FIXME: In the non-ARC case, this will still be a hard error if the
2893 // definition is found in a module that's not visible.
2894 const ObjCInterfaceDecl *forwardClass = nullptr;
2895 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2896 getLangOpts().ObjCAutoRefCount
2897 ? diag::err_arc_receiver_forward_instance
2898 : diag::warn_receiver_forward_instance,
2899 Receiver? Receiver->getSourceRange()
2900 : SourceRange(SuperLoc))) {
2901 if (getLangOpts().ObjCAutoRefCount)
2902 return ExprError();
2903
2904 forwardClass = OCIType->getInterfaceDecl();
2905 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2906 diag::note_receiver_is_id);
2907 Method = nullptr;
2908 } else {
2909 Method = ClassDecl->lookupInstanceMethod(Sel);
2910 }
2911
2912 if (!Method)
2913 // Search protocol qualifiers.
2914 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2915
2916 if (!Method) {
2917 // If we have implementations in scope, check "private" methods.
2918 Method = ClassDecl->lookupPrivateMethod(Sel);
2919
2920 if (!Method && getLangOpts().ObjCAutoRefCount) {
2921 Diag(SelLoc, diag::err_arc_may_not_respond)
2922 << OCIType->getPointeeType() << Sel << RecRange
2923 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2924 return ExprError();
2925 }
2926
2927 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2928 // If we still haven't found a method, look in the global pool. This
2929 // behavior isn't very desirable, however we need it for GCC
2930 // compatibility. FIXME: should we deviate??
2931 if (OCIType->qual_empty()) {
2932 SmallVector<ObjCMethodDecl*, 4> Methods;
2933 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2934 true/*InstanceFirst*/,
2935 false/*CheckTheOther*/);
2936 if (!Methods.empty()) {
2937 // We choose the first method as the initial candidate, then try
2938 // to select a better one.
2939 Method = Methods[0];
2940
2941 if (ObjCMethodDecl *BestMethod =
2942 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2943 Methods))
2944 Method = BestMethod;
2945
2946 AreMultipleMethodsInGlobalPool(Sel, Method,
2947 SourceRange(LBracLoc, RBracLoc),
2948 true/*receiverIdOrClass*/,
2949 Methods);
2950 }
2951 if (Method && !forwardClass)
2952 Diag(SelLoc, diag::warn_maynot_respond)
2953 << OCIType->getInterfaceDecl()->getIdentifier()
2954 << Sel << RecRange;
2955 }
2956 }
2957 }
2958 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
2959 return ExprError();
2960 } else {
2961 // Reject other random receiver types (e.g. structs).
2962 Diag(Loc, diag::err_bad_receiver_type)
2963 << ReceiverType << Receiver->getSourceRange();
2964 return ExprError();
2965 }
2966 }
2967 }
2968
2969 FunctionScopeInfo *DIFunctionScopeInfo =
2970 (Method && Method->getMethodFamily() == OMF_init)
2971 ? getEnclosingFunction() : nullptr;
2972
2973 if (DIFunctionScopeInfo &&
2974 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2975 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2976 bool isDesignatedInitChain = false;
2977 if (SuperLoc.isValid()) {
2978 if (const ObjCObjectPointerType *
2979 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2980 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2981 // Either we know this is a designated initializer or we
2982 // conservatively assume it because we don't know for sure.
2983 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2984 ID->isDesignatedInitializer(Sel)) {
2985 isDesignatedInitChain = true;
2986 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2987 }
2988 }
2989 }
2990 }
2991 if (!isDesignatedInitChain) {
2992 const ObjCMethodDecl *InitMethod = nullptr;
2993 bool isDesignated =
2994 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2995 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 2995, __PRETTY_FUNCTION__))
;
2996 (void)isDesignated;
2997 Diag(SelLoc, SuperLoc.isValid() ?
2998 diag::warn_objc_designated_init_non_designated_init_call :
2999 diag::warn_objc_designated_init_non_super_designated_init_call);
3000 Diag(InitMethod->getLocation(),
3001 diag::note_objc_designated_init_marked_here);
3002 }
3003 }
3004
3005 if (DIFunctionScopeInfo &&
3006 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
3007 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3008 if (SuperLoc.isValid()) {
3009 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3010 } else {
3011 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3012 }
3013 }
3014
3015 // Check the message arguments.
3016 unsigned NumArgs = ArgsIn.size();
3017 Expr **Args = ArgsIn.data();
3018 QualType ReturnType;
3019 ExprValueKind VK = VK_RValue;
3020 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3021 ReceiverType->isObjCQualifiedClassType());
3022 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3023 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3024 Method, ClassMessage, SuperLoc.isValid(),
3025 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3026 return ExprError();
3027
3028 if (Method && !Method->getReturnType()->isVoidType() &&
3029 RequireCompleteType(LBracLoc, Method->getReturnType(),
3030 diag::err_illegal_message_expr_incomplete_type))
3031 return ExprError();
3032
3033 // In ARC, forbid the user from sending messages to
3034 // retain/release/autorelease/dealloc/retainCount explicitly.
3035 if (getLangOpts().ObjCAutoRefCount) {
3036 ObjCMethodFamily family =
3037 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3038 switch (family) {
3039 case OMF_init:
3040 if (Method)
3041 checkInitMethod(Method, ReceiverType);
3042 break;
3043
3044 case OMF_None:
3045 case OMF_alloc:
3046 case OMF_copy:
3047 case OMF_finalize:
3048 case OMF_mutableCopy:
3049 case OMF_new:
3050 case OMF_self:
3051 case OMF_initialize:
3052 break;
3053
3054 case OMF_dealloc:
3055 case OMF_retain:
3056 case OMF_release:
3057 case OMF_autorelease:
3058 case OMF_retainCount:
3059 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3060 << Sel << RecRange;
3061 break;
3062
3063 case OMF_performSelector:
3064 if (Method && NumArgs >= 1) {
3065 if (const auto *SelExp =
3066 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3067 Selector ArgSel = SelExp->getSelector();
3068 ObjCMethodDecl *SelMethod =
3069 LookupInstanceMethodInGlobalPool(ArgSel,
3070 SelExp->getSourceRange());
3071 if (!SelMethod)
3072 SelMethod =
3073 LookupFactoryMethodInGlobalPool(ArgSel,
3074 SelExp->getSourceRange());
3075 if (SelMethod) {
3076 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3077 switch (SelFamily) {
3078 case OMF_alloc:
3079 case OMF_copy:
3080 case OMF_mutableCopy:
3081 case OMF_new:
3082 case OMF_init:
3083 // Issue error, unless ns_returns_not_retained.
3084 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3085 // selector names a +1 method
3086 Diag(SelLoc,
3087 diag::err_arc_perform_selector_retains);
3088 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3089 << SelMethod->getDeclName();
3090 }
3091 break;
3092 default:
3093 // +0 call. OK. unless ns_returns_retained.
3094 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3095 // selector names a +1 method
3096 Diag(SelLoc,
3097 diag::err_arc_perform_selector_retains);
3098 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3099 << SelMethod->getDeclName();
3100 }
3101 break;
3102 }
3103 }
3104 } else {
3105 // error (may leak).
3106 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3107 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3108 }
3109 }
3110 break;
3111 }
3112 }
3113
3114 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3115
3116 // Construct the appropriate ObjCMessageExpr instance.
3117 ObjCMessageExpr *Result;
3118 if (SuperLoc.isValid())
3119 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3120 SuperLoc, /*IsInstanceSuper=*/true,
3121 ReceiverType, Sel, SelectorLocs, Method,
3122 makeArrayRef(Args, NumArgs), RBracLoc,
3123 isImplicit);
3124 else {
3125 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3126 Receiver, Sel, SelectorLocs, Method,
3127 makeArrayRef(Args, NumArgs), RBracLoc,
3128 isImplicit);
3129 if (!isImplicit)
3130 checkCocoaAPI(*this, Result);
3131 }
3132 if (Method) {
3133 bool IsClassObjectCall = ClassMessage;
3134 // 'self' message receivers in class methods should be treated as message
3135 // sends to the class object in order for the semantic checks to be
3136 // performed correctly. Messages to 'super' already count as class messages,
3137 // so they don't need to be handled here.
3138 if (Receiver && isSelfExpr(Receiver)) {
3139 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3140 if (OPT->getObjectType()->isObjCClass()) {
3141 if (const auto *CurMeth = getCurMethodDecl()) {
3142 IsClassObjectCall = true;
3143 ReceiverType =
3144 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3145 }
3146 }
3147 }
3148 }
3149 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3150 ReceiverType, IsClassObjectCall);
3151 }
3152
3153 if (getLangOpts().ObjCAutoRefCount) {
3154 // In ARC, annotate delegate init calls.
3155 if (Result->getMethodFamily() == OMF_init &&
3156 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3157 // Only consider init calls *directly* in init implementations,
3158 // not within blocks.
3159 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3160 if (method && method->getMethodFamily() == OMF_init) {
3161 // The implicit assignment to self means we also don't want to
3162 // consume the result.
3163 Result->setDelegateInitCall(true);
3164 return Result;
3165 }
3166 }
3167
3168 // In ARC, check for message sends which are likely to introduce
3169 // retain cycles.
3170 checkRetainCycles(Result);
3171 }
3172
3173 if (getLangOpts().ObjCWeak) {
3174 if (!isImplicit && Method) {
3175 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3176 bool IsWeak =
3177 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3178 if (!IsWeak && Sel.isUnarySelector())
3179 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3180 if (IsWeak && !isUnevaluatedContext() &&
3181 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3182 getCurFunction()->recordUseOfWeak(Result, Prop);
3183 }
3184 }
3185 }
3186
3187 CheckObjCCircularContainer(Result);
3188
3189 return MaybeBindToTemporary(Result);
3190}
3191
3192static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3193 if (ObjCSelectorExpr *OSE =
3194 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3195 Selector Sel = OSE->getSelector();
3196 SourceLocation Loc = OSE->getAtLoc();
3197 auto Pos = S.ReferencedSelectors.find(Sel);
3198 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3199 S.ReferencedSelectors.erase(Pos);
3200 }
3201}
3202
3203// ActOnInstanceMessage - used for both unary and keyword messages.
3204// ArgExprs is optional - if it is present, the number of expressions
3205// is obtained from Sel.getNumArgs().
3206ExprResult Sema::ActOnInstanceMessage(Scope *S,
3207 Expr *Receiver,
3208 Selector Sel,
3209 SourceLocation LBracLoc,
3210 ArrayRef<SourceLocation> SelectorLocs,
3211 SourceLocation RBracLoc,
3212 MultiExprArg Args) {
3213 if (!Receiver)
3214 return ExprError();
3215
3216 // A ParenListExpr can show up while doing error recovery with invalid code.
3217 if (isa<ParenListExpr>(Receiver)) {
3218 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3219 if (Result.isInvalid()) return ExprError();
3220 Receiver = Result.get();
3221 }
3222
3223 if (RespondsToSelectorSel.isNull()) {
3224 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3225 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3226 }
3227 if (Sel == RespondsToSelectorSel)
3228 RemoveSelectorFromWarningCache(*this, Args[0]);
3229
3230 return BuildInstanceMessage(Receiver, Receiver->getType(),
3231 /*SuperLoc=*/SourceLocation(), Sel,
3232 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3233 RBracLoc, Args);
3234}
3235
3236enum ARCConversionTypeClass {
3237 /// int, void, struct A
3238 ACTC_none,
3239
3240 /// id, void (^)()
3241 ACTC_retainable,
3242
3243 /// id*, id***, void (^*)(),
3244 ACTC_indirectRetainable,
3245
3246 /// void* might be a normal C type, or it might a CF type.
3247 ACTC_voidPtr,
3248
3249 /// struct A*
3250 ACTC_coreFoundation
3251};
3252
3253static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3254 return (ACTC == ACTC_retainable ||
3255 ACTC == ACTC_coreFoundation ||
3256 ACTC == ACTC_voidPtr);
3257}
3258
3259static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3260 return ACTC == ACTC_none ||
3261 ACTC == ACTC_voidPtr ||
3262 ACTC == ACTC_coreFoundation;
3263}
3264
3265static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3266 bool isIndirect = false;
3267
3268 // Ignore an outermost reference type.
3269 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3270 type = ref->getPointeeType();
3271 isIndirect = true;
3272 }
3273
3274 // Drill through pointers and arrays recursively.
3275 while (true) {
3276 if (const PointerType *ptr = type->getAs<PointerType>()) {
3277 type = ptr->getPointeeType();
3278
3279 // The first level of pointer may be the innermost pointer on a CF type.
3280 if (!isIndirect) {
3281 if (type->isVoidType()) return ACTC_voidPtr;
3282 if (type->isRecordType()) return ACTC_coreFoundation;
3283 }
3284 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3285 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3286 } else {
3287 break;
3288 }
3289 isIndirect = true;
3290 }
3291
3292 if (isIndirect) {
3293 if (type->isObjCARCBridgableType())
3294 return ACTC_indirectRetainable;
3295 return ACTC_none;
3296 }
3297
3298 if (type->isObjCARCBridgableType())
3299 return ACTC_retainable;
3300
3301 return ACTC_none;
3302}
3303
3304namespace {
3305 /// A result from the cast checker.
3306 enum ACCResult {
3307 /// Cannot be casted.
3308 ACC_invalid,
3309
3310 /// Can be safely retained or not retained.
3311 ACC_bottom,
3312
3313 /// Can be casted at +0.
3314 ACC_plusZero,
3315
3316 /// Can be casted at +1.
3317 ACC_plusOne
3318 };
3319 ACCResult merge(ACCResult left, ACCResult right) {
3320 if (left == right) return left;
3321 if (left == ACC_bottom) return right;
3322 if (right == ACC_bottom) return left;
3323 return ACC_invalid;
3324 }
3325
3326 /// A checker which white-lists certain expressions whose conversion
3327 /// to or from retainable type would otherwise be forbidden in ARC.
3328 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3329 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3330
3331 ASTContext &Context;
3332 ARCConversionTypeClass SourceClass;
3333 ARCConversionTypeClass TargetClass;
3334 bool Diagnose;
3335
3336 static bool isCFType(QualType type) {
3337 // Someday this can use ns_bridged. For now, it has to do this.
3338 return type->isCARCBridgableType();
3339 }
3340
3341 public:
3342 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3343 ARCConversionTypeClass target, bool diagnose)
3344 : Context(Context), SourceClass(source), TargetClass(target),
3345 Diagnose(diagnose) {}
3346
3347 using super::Visit;
3348 ACCResult Visit(Expr *e) {
3349 return super::Visit(e->IgnoreParens());
3350 }
3351
3352 ACCResult VisitStmt(Stmt *s) {
3353 return ACC_invalid;
3354 }
3355
3356 /// Null pointer constants can be casted however you please.
3357 ACCResult VisitExpr(Expr *e) {
3358 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3359 return ACC_bottom;
3360 return ACC_invalid;
3361 }
3362
3363 /// Objective-C string literals can be safely casted.
3364 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3365 // If we're casting to any retainable type, go ahead. Global
3366 // strings are immune to retains, so this is bottom.
3367 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3368
3369 return ACC_invalid;
3370 }
3371
3372 /// Look through certain implicit and explicit casts.
3373 ACCResult VisitCastExpr(CastExpr *e) {
3374 switch (e->getCastKind()) {
3375 case CK_NullToPointer:
3376 return ACC_bottom;
3377
3378 case CK_NoOp:
3379 case CK_LValueToRValue:
3380 case CK_BitCast:
3381 case CK_CPointerToObjCPointerCast:
3382 case CK_BlockPointerToObjCPointerCast:
3383 case CK_AnyPointerToBlockPointerCast:
3384 return Visit(e->getSubExpr());
3385
3386 default:
3387 return ACC_invalid;
3388 }
3389 }
3390
3391 /// Look through unary extension.
3392 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3393 return Visit(e->getSubExpr());
3394 }
3395
3396 /// Ignore the LHS of a comma operator.
3397 ACCResult VisitBinComma(BinaryOperator *e) {
3398 return Visit(e->getRHS());
3399 }
3400
3401 /// Conditional operators are okay if both sides are okay.
3402 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3403 ACCResult left = Visit(e->getTrueExpr());
3404 if (left == ACC_invalid) return ACC_invalid;
3405 return merge(left, Visit(e->getFalseExpr()));
3406 }
3407
3408 /// Look through pseudo-objects.
3409 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3410 // If we're getting here, we should always have a result.
3411 return Visit(e->getResultExpr());
3412 }
3413
3414 /// Statement expressions are okay if their result expression is okay.
3415 ACCResult VisitStmtExpr(StmtExpr *e) {
3416 return Visit(e->getSubStmt()->body_back());
3417 }
3418
3419 /// Some declaration references are okay.
3420 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3421 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3422 // References to global constants are okay.
3423 if (isAnyRetainable(TargetClass) &&
3424 isAnyRetainable(SourceClass) &&
3425 var &&
3426 !var->hasDefinition(Context) &&
3427 var->getType().isConstQualified()) {
3428
3429 // In system headers, they can also be assumed to be immune to retains.
3430 // These are things like 'kCFStringTransformToLatin'.
3431 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3432 return ACC_bottom;
3433
3434 return ACC_plusZero;
3435 }
3436
3437 // Nothing else.
3438 return ACC_invalid;
3439 }
3440
3441 /// Some calls are okay.
3442 ACCResult VisitCallExpr(CallExpr *e) {
3443 if (FunctionDecl *fn = e->getDirectCallee())
3444 if (ACCResult result = checkCallToFunction(fn))
3445 return result;
3446
3447 return super::VisitCallExpr(e);
3448 }
3449
3450 ACCResult checkCallToFunction(FunctionDecl *fn) {
3451 // Require a CF*Ref return type.
3452 if (!isCFType(fn->getReturnType()))
3453 return ACC_invalid;
3454
3455 if (!isAnyRetainable(TargetClass))
3456 return ACC_invalid;
3457
3458 // Honor an explicit 'not retained' attribute.
3459 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3460 return ACC_plusZero;
3461
3462 // Honor an explicit 'retained' attribute, except that for
3463 // now we're not going to permit implicit handling of +1 results,
3464 // because it's a bit frightening.
3465 if (fn->hasAttr<CFReturnsRetainedAttr>())
3466 return Diagnose ? ACC_plusOne
3467 : ACC_invalid; // ACC_plusOne if we start accepting this
3468
3469 // Recognize this specific builtin function, which is used by CFSTR.
3470 unsigned builtinID = fn->getBuiltinID();
3471 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3472 return ACC_bottom;
3473
3474 // Otherwise, don't do anything implicit with an unaudited function.
3475 if (!fn->hasAttr<CFAuditedTransferAttr>())
3476 return ACC_invalid;
3477
3478 // Otherwise, it's +0 unless it follows the create convention.
3479 if (ento::coreFoundation::followsCreateRule(fn))
3480 return Diagnose ? ACC_plusOne
3481 : ACC_invalid; // ACC_plusOne if we start accepting this
3482
3483 return ACC_plusZero;
3484 }
3485
3486 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3487 return checkCallToMethod(e->getMethodDecl());
3488 }
3489
3490 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3491 ObjCMethodDecl *method;
3492 if (e->isExplicitProperty())
3493 method = e->getExplicitProperty()->getGetterMethodDecl();
3494 else
3495 method = e->getImplicitPropertyGetter();
3496 return checkCallToMethod(method);
3497 }
3498
3499 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3500 if (!method) return ACC_invalid;
3501
3502 // Check for message sends to functions returning CF types. We
3503 // just obey the Cocoa conventions with these, even though the
3504 // return type is CF.
3505 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3506 return ACC_invalid;
3507
3508 // If the method is explicitly marked not-retained, it's +0.
3509 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3510 return ACC_plusZero;
3511
3512 // If the method is explicitly marked as returning retained, or its
3513 // selector follows a +1 Cocoa convention, treat it as +1.
3514 if (method->hasAttr<CFReturnsRetainedAttr>())
3515 return ACC_plusOne;
3516
3517 switch (method->getSelector().getMethodFamily()) {
3518 case OMF_alloc:
3519 case OMF_copy:
3520 case OMF_mutableCopy:
3521 case OMF_new:
3522 return ACC_plusOne;
3523
3524 default:
3525 // Otherwise, treat it as +0.
3526 return ACC_plusZero;
3527 }
3528 }
3529 };
3530} // end anonymous namespace
3531
3532bool Sema::isKnownName(StringRef name) {
3533 if (name.empty())
3534 return false;
3535 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3536 Sema::LookupOrdinaryName);
3537 return LookupName(R, TUScope, false);
3538}
3539
3540static void addFixitForObjCARCConversion(Sema &S,
3541 DiagnosticBuilder &DiagB,
3542 Sema::CheckedConversionKind CCK,
3543 SourceLocation afterLParen,
3544 QualType castType,
3545 Expr *castExpr,
3546 Expr *realCast,
3547 const char *bridgeKeyword,
3548 const char *CFBridgeName) {
3549 // We handle C-style and implicit casts here.
3550 switch (CCK) {
3551 case Sema::CCK_ImplicitConversion:
3552 case Sema::CCK_ForBuiltinOverloadedOp:
3553 case Sema::CCK_CStyleCast:
3554 case Sema::CCK_OtherCast:
3555 break;
3556 case Sema::CCK_FunctionalCast:
3557 return;
3558 }
3559
3560 if (CFBridgeName) {
3561 if (CCK == Sema::CCK_OtherCast) {
3562 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3563 SourceRange range(NCE->getOperatorLoc(),
3564 NCE->getAngleBrackets().getEnd());
3565 SmallString<32> BridgeCall;
3566
3567 SourceManager &SM = S.getSourceManager();
3568 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3569 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3570 BridgeCall += ' ';
3571
3572 BridgeCall += CFBridgeName;
3573 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3574 }
3575 return;
3576 }
3577 Expr *castedE = castExpr;
3578 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3579 castedE = CCE->getSubExpr();
3580 castedE = castedE->IgnoreImpCasts();
3581 SourceRange range = castedE->getSourceRange();
3582
3583 SmallString<32> BridgeCall;
3584
3585 SourceManager &SM = S.getSourceManager();
3586 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3587 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3588 BridgeCall += ' ';
3589
3590 BridgeCall += CFBridgeName;
3591
3592 if (isa<ParenExpr>(castedE)) {
3593 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3594 BridgeCall));
3595 } else {
3596 BridgeCall += '(';
3597 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3598 BridgeCall));
3599 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3600 S.getLocForEndOfToken(range.getEnd()),
3601 ")"));
3602 }
3603 return;
3604 }
3605
3606 if (CCK == Sema::CCK_CStyleCast) {
3607 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3608 } else if (CCK == Sema::CCK_OtherCast) {
3609 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3610 std::string castCode = "(";
3611 castCode += bridgeKeyword;
3612 castCode += castType.getAsString();
3613 castCode += ")";
3614 SourceRange Range(NCE->getOperatorLoc(),
3615 NCE->getAngleBrackets().getEnd());
3616 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3617 }
3618 } else {
3619 std::string castCode = "(";
3620 castCode += bridgeKeyword;
3621 castCode += castType.getAsString();
3622 castCode += ")";
3623 Expr *castedE = castExpr->IgnoreImpCasts();
3624 SourceRange range = castedE->getSourceRange();
3625 if (isa<ParenExpr>(castedE)) {
3626 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3627 castCode));
3628 } else {
3629 castCode += "(";
3630 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3631 castCode));
3632 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3633 S.getLocForEndOfToken(range.getEnd()),
3634 ")"));
3635 }
3636 }
3637}
3638
3639template <typename T>
3640static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3641 TypedefNameDecl *TDNDecl = TD->getDecl();
3642 QualType QT = TDNDecl->getUnderlyingType();
3643 if (QT->isPointerType()) {
3644 QT = QT->getPointeeType();
3645 if (const RecordType *RT = QT->getAs<RecordType>())
3646 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3647 return RD->getAttr<T>();
3648 }
3649 return nullptr;
3650}
3651
3652static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3653 TypedefNameDecl *&TDNDecl) {
3654 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3655 TDNDecl = TD->getDecl();
3656 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3657 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3658 return ObjCBAttr;
3659 T = TDNDecl->getUnderlyingType();
3660 }
3661 return nullptr;
3662}
3663
3664static void
3665diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3666 QualType castType, ARCConversionTypeClass castACTC,
3667 Expr *castExpr, Expr *realCast,
3668 ARCConversionTypeClass exprACTC,
3669 Sema::CheckedConversionKind CCK) {
3670 SourceLocation loc =
3671 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3672
3673 if (S.makeUnavailableInSystemHeader(loc,
3674 UnavailableAttr::IR_ARCForbiddenConversion))
3675 return;
3676
3677 QualType castExprType = castExpr->getType();
3678 // Defer emitting a diagnostic for bridge-related casts; that will be
3679 // handled by CheckObjCBridgeRelatedConversions.
3680 TypedefNameDecl *TDNDecl = nullptr;
3681 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3682 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3683 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3684 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3685 return;
3686
3687 unsigned srcKind = 0;
3688 switch (exprACTC) {
3689 case ACTC_none:
3690 case ACTC_coreFoundation:
3691 case ACTC_voidPtr:
3692 srcKind = (castExprType->isPointerType() ? 1 : 0);
3693 break;
3694 case ACTC_retainable:
3695 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3696 break;
3697 case ACTC_indirectRetainable:
3698 srcKind = 4;
3699 break;
3700 }
3701
3702 // Check whether this could be fixed with a bridge cast.
3703 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3704 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3705
3706 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3707
3708 // Bridge from an ARC type to a CF type.
3709 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3710
3711 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3712 << convKindForDiag
3713 << 2 // of C pointer type
3714 << castExprType
3715 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3716 << castType
3717 << castRange
3718 << castExpr->getSourceRange();
3719 bool br = S.isKnownName("CFBridgingRelease");
3720 ACCResult CreateRule =
3721 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3722 assert(CreateRule != ACC_bottom && "This cast should already be accepted.")((CreateRule != ACC_bottom && "This cast should already be accepted."
) ? static_cast<void> (0) : __assert_fail ("CreateRule != ACC_bottom && \"This cast should already be accepted.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 3722, __PRETTY_FUNCTION__))
;
3723 if (CreateRule != ACC_plusOne)
3724 {
3725 DiagnosticBuilder DiagB =
3726 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3727 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3728
3729 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3730 castType, castExpr, realCast, "__bridge ",
3731 nullptr);
3732 }
3733 if (CreateRule != ACC_plusZero)
3734 {
3735 DiagnosticBuilder DiagB =
3736 (CCK == Sema::CCK_OtherCast && !br) ?
3737 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3738 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3739 diag::note_arc_bridge_transfer)
3740 << castExprType << br;
3741
3742 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3743 castType, castExpr, realCast, "__bridge_transfer ",
3744 br ? "CFBridgingRelease" : nullptr);
3745 }
3746
3747 return;
3748 }
3749
3750 // Bridge from a CF type to an ARC type.
3751 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3752 bool br = S.isKnownName("CFBridgingRetain");
3753 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3754 << convKindForDiag
3755 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3756 << castExprType
3757 << 2 // to C pointer type
3758 << castType
3759 << castRange
3760 << castExpr->getSourceRange();
3761 ACCResult CreateRule =
3762 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3763 assert(CreateRule != ACC_bottom && "This cast should already be accepted.")((CreateRule != ACC_bottom && "This cast should already be accepted."
) ? static_cast<void> (0) : __assert_fail ("CreateRule != ACC_bottom && \"This cast should already be accepted.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 3763, __PRETTY_FUNCTION__))
;
3764 if (CreateRule != ACC_plusOne)
3765 {
3766 DiagnosticBuilder DiagB =
3767 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3768 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3769 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3770 castType, castExpr, realCast, "__bridge ",
3771 nullptr);
3772 }
3773 if (CreateRule != ACC_plusZero)
3774 {
3775 DiagnosticBuilder DiagB =
3776 (CCK == Sema::CCK_OtherCast && !br) ?
3777 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3778 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3779 diag::note_arc_bridge_retained)
3780 << castType << br;
3781
3782 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3783 castType, castExpr, realCast, "__bridge_retained ",
3784 br ? "CFBridgingRetain" : nullptr);
3785 }
3786
3787 return;
3788 }
3789
3790 S.Diag(loc, diag::err_arc_mismatched_cast)
3791 << !convKindForDiag
3792 << srcKind << castExprType << castType
3793 << castRange << castExpr->getSourceRange();
3794}
3795
3796template <typename TB>
3797static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3798 bool &HadTheAttribute, bool warn) {
3799 QualType T = castExpr->getType();
3800 HadTheAttribute = false;
3801 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3802 TypedefNameDecl *TDNDecl = TD->getDecl();
3803 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3804 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3805 HadTheAttribute = true;
3806 if (Parm->isStr("id"))
3807 return true;
3808
3809 NamedDecl *Target = nullptr;
3810 // Check for an existing type with this name.
3811 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3812 Sema::LookupOrdinaryName);
3813 if (S.LookupName(R, S.TUScope)) {
3814 Target = R.getFoundDecl();
3815 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3816 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3817 if (const ObjCObjectPointerType *InterfacePointerType =
3818 castType->getAsObjCInterfacePointerType()) {
3819 ObjCInterfaceDecl *CastClass
3820 = InterfacePointerType->getObjectType()->getInterface();
3821 if ((CastClass == ExprClass) ||
3822 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3823 return true;
3824 if (warn)
3825 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3826 << T << Target->getName() << castType->getPointeeType();
3827 return false;
3828 } else if (castType->isObjCIdType() ||
3829 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3830 castType, ExprClass)))
3831 // ok to cast to 'id'.
3832 // casting to id<p-list> is ok if bridge type adopts all of
3833 // p-list protocols.
3834 return true;
3835 else {
3836 if (warn) {
3837 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3838 << T << Target->getName() << castType;
3839 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3840 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3841 }
3842 return false;
3843 }
3844 }
3845 } else if (!castType->isObjCIdType()) {
3846 S.Diag(castExpr->getBeginLoc(),
3847 diag::err_objc_cf_bridged_not_interface)
3848 << castExpr->getType() << Parm;
3849 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3850 if (Target)
3851 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3852 }
3853 return true;
3854 }
3855 return false;
3856 }
3857 T = TDNDecl->getUnderlyingType();
3858 }
3859 return true;
3860}
3861
3862template <typename TB>
3863static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3864 bool &HadTheAttribute, bool warn) {
3865 QualType T = castType;
3866 HadTheAttribute = false;
3867 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3868 TypedefNameDecl *TDNDecl = TD->getDecl();
3869 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3870 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3871 HadTheAttribute = true;
3872 if (Parm->isStr("id"))
3873 return true;
3874
3875 NamedDecl *Target = nullptr;
3876 // Check for an existing type with this name.
3877 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3878 Sema::LookupOrdinaryName);
3879 if (S.LookupName(R, S.TUScope)) {
3880 Target = R.getFoundDecl();
3881 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3882 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3883 if (const ObjCObjectPointerType *InterfacePointerType =
3884 castExpr->getType()->getAsObjCInterfacePointerType()) {
3885 ObjCInterfaceDecl *ExprClass
3886 = InterfacePointerType->getObjectType()->getInterface();
3887 if ((CastClass == ExprClass) ||
3888 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3889 return true;
3890 if (warn) {
3891 S.Diag(castExpr->getBeginLoc(),
3892 diag::warn_objc_invalid_bridge_to_cf)
3893 << castExpr->getType()->getPointeeType() << T;
3894 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3895 }
3896 return false;
3897 } else if (castExpr->getType()->isObjCIdType() ||
3898 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3899 castExpr->getType(), CastClass)))
3900 // ok to cast an 'id' expression to a CFtype.
3901 // ok to cast an 'id<plist>' expression to CFtype provided plist
3902 // adopts all of CFtype's ObjetiveC's class plist.
3903 return true;
3904 else {
3905 if (warn) {
3906 S.Diag(castExpr->getBeginLoc(),
3907 diag::warn_objc_invalid_bridge_to_cf)
3908 << castExpr->getType() << castType;
3909 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3910 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3911 }
3912 return false;
3913 }
3914 }
3915 }
3916 S.Diag(castExpr->getBeginLoc(),
3917 diag::err_objc_ns_bridged_invalid_cfobject)
3918 << castExpr->getType() << castType;
3919 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3920 if (Target)
3921 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3922 return true;
3923 }
3924 return false;
3925 }
3926 T = TDNDecl->getUnderlyingType();
3927 }
3928 return true;
3929}
3930
3931void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3932 if (!getLangOpts().ObjC)
3933 return;
3934 // warn in presence of __bridge casting to or from a toll free bridge cast.
3935 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3936 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3937 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3938 bool HasObjCBridgeAttr;
3939 bool ObjCBridgeAttrWillNotWarn =
3940 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3941 false);
3942 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3943 return;
3944 bool HasObjCBridgeMutableAttr;
3945 bool ObjCBridgeMutableAttrWillNotWarn =
3946 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3947 HasObjCBridgeMutableAttr, false);
3948 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3949 return;
3950
3951 if (HasObjCBridgeAttr)
3952 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3953 true);
3954 else if (HasObjCBridgeMutableAttr)
3955 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3956 HasObjCBridgeMutableAttr, true);
3957 }
3958 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3959 bool HasObjCBridgeAttr;
3960 bool ObjCBridgeAttrWillNotWarn =
3961 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3962 false);
3963 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3964 return;
3965 bool HasObjCBridgeMutableAttr;
3966 bool ObjCBridgeMutableAttrWillNotWarn =
3967 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3968 HasObjCBridgeMutableAttr, false);
3969 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3970 return;
3971
3972 if (HasObjCBridgeAttr)
3973 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3974 true);
3975 else if (HasObjCBridgeMutableAttr)
3976 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3977 HasObjCBridgeMutableAttr, true);
3978 }
3979}
3980
3981void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3982 QualType SrcType = castExpr->getType();
3983 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3984 if (PRE->isExplicitProperty()) {
3985 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3986 SrcType = PDecl->getType();
3987 }
3988 else if (PRE->isImplicitProperty()) {
3989 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3990 SrcType = Getter->getReturnType();
3991 }
3992 }
3993
3994 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3995 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3996 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3997 return;
3998 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
3999 castExpr);
4000}
4001
4002bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4003 CastKind &Kind) {
4004 if (!getLangOpts().ObjC)
4005 return false;
4006 ARCConversionTypeClass exprACTC =
4007 classifyTypeForARCConversion(castExpr->getType());
4008 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4009 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
4010 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
4011 CheckTollFreeBridgeCast(castType, castExpr);
4012 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4013 : CK_CPointerToObjCPointerCast;
4014 return true;
4015 }
4016 return false;
4017}
4018
4019bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4020 QualType DestType, QualType SrcType,
4021 ObjCInterfaceDecl *&RelatedClass,
4022 ObjCMethodDecl *&ClassMethod,
4023 ObjCMethodDecl *&InstanceMethod,
4024 TypedefNameDecl *&TDNDecl,
4025 bool CfToNs, bool Diagnose) {
4026 QualType T = CfToNs ? SrcType : DestType;
4027 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4028 if (!ObjCBAttr)
4029 return false;
4030
4031 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4032 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4033 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4034 if (!RCId)
4035 return false;
4036 NamedDecl *Target = nullptr;
4037 // Check for an existing type with this name.
4038 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4039 Sema::LookupOrdinaryName);
4040 if (!LookupName(R, TUScope)) {
4041 if (Diagnose) {
4042 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4043 << SrcType << DestType;
4044 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4045 }
4046 return false;
4047 }
4048 Target = R.getFoundDecl();
4049 if (Target && isa<ObjCInterfaceDecl>(Target))
4050 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4051 else {
4052 if (Diagnose) {
4053 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4054 << SrcType << DestType;
4055 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4056 if (Target)
4057 Diag(Target->getBeginLoc(), diag::note_declared_at);
4058 }
4059 return false;
4060 }
4061
4062 // Check for an existing class method with the given selector name.
4063 if (CfToNs && CMId) {
4064 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4065 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4066 if (!ClassMethod) {
4067 if (Diagnose) {
4068 Diag(Loc, diag::err_objc_bridged_related_known_method)
4069 << SrcType << DestType << Sel << false;
4070 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4071 }
4072 return false;
4073 }
4074 }
4075
4076 // Check for an existing instance method with the given selector name.
4077 if (!CfToNs && IMId) {
4078 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4079 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4080 if (!InstanceMethod) {
4081 if (Diagnose) {
4082 Diag(Loc, diag::err_objc_bridged_related_known_method)
4083 << SrcType << DestType << Sel << true;
4084 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4085 }
4086 return false;
4087 }
4088 }
4089 return true;
4090}
4091
4092bool
4093Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4094 QualType DestType, QualType SrcType,
4095 Expr *&SrcExpr, bool Diagnose) {
4096 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4097 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4098 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4099 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4100 if (!CfToNs && !NsToCf)
4101 return false;
4102
4103 ObjCInterfaceDecl *RelatedClass;
4104 ObjCMethodDecl *ClassMethod = nullptr;
4105 ObjCMethodDecl *InstanceMethod = nullptr;
4106 TypedefNameDecl *TDNDecl = nullptr;
4107 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4108 ClassMethod, InstanceMethod, TDNDecl,
4109 CfToNs, Diagnose))
4110 return false;
4111
4112 if (CfToNs) {
4113 // Implicit conversion from CF to ObjC object is needed.
4114 if (ClassMethod) {
4115 if (Diagnose) {
4116 std::string ExpressionString = "[";
4117 ExpressionString += RelatedClass->getNameAsString();
4118 ExpressionString += " ";
4119 ExpressionString += ClassMethod->getSelector().getAsString();
4120 SourceLocation SrcExprEndLoc =
4121 getLocForEndOfToken(SrcExpr->getEndLoc());
4122 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4123 Diag(Loc, diag::err_objc_bridged_related_known_method)
4124 << SrcType << DestType << ClassMethod->getSelector() << false
4125 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4126 ExpressionString)
4127 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4128 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4129 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4130
4131 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4132 // Argument.
4133 Expr *args[] = { SrcExpr };
4134 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4135 ClassMethod->getLocation(),
4136 ClassMethod->getSelector(), ClassMethod,
4137 MultiExprArg(args, 1));
4138 SrcExpr = msg.get();
4139 }
4140 return true;
4141 }
4142 }
4143 else {
4144 // Implicit conversion from ObjC type to CF object is needed.
4145 if (InstanceMethod) {
4146 if (Diagnose) {
4147 std::string ExpressionString;
4148 SourceLocation SrcExprEndLoc =
4149 getLocForEndOfToken(SrcExpr->getEndLoc());
4150 if (InstanceMethod->isPropertyAccessor())
4151 if (const ObjCPropertyDecl *PDecl =
4152 InstanceMethod->findPropertyDecl()) {
4153 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4154 ExpressionString = ".";
4155 ExpressionString += PDecl->getNameAsString();
4156 Diag(Loc, diag::err_objc_bridged_related_known_method)
4157 << SrcType << DestType << InstanceMethod->getSelector() << true
4158 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4159 }
4160 if (ExpressionString.empty()) {
4161 // Provide a fixit: [ObjectExpr InstanceMethod]
4162 ExpressionString = " ";
4163 ExpressionString += InstanceMethod->getSelector().getAsString();
4164 ExpressionString += "]";
4165
4166 Diag(Loc, diag::err_objc_bridged_related_known_method)
4167 << SrcType << DestType << InstanceMethod->getSelector() << true
4168 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4169 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4170 }
4171 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4172 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4173
4174 ExprResult msg =
4175 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4176 InstanceMethod->getLocation(),
4177 InstanceMethod->getSelector(),
4178 InstanceMethod, None);
4179 SrcExpr = msg.get();
4180 }
4181 return true;
4182 }
4183 }
4184 return false;
4185}
4186
4187Sema::ARCConversionResult
4188Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4189 Expr *&castExpr, CheckedConversionKind CCK,
4190 bool Diagnose, bool DiagnoseCFAudited,
4191 BinaryOperatorKind Opc) {
4192 QualType castExprType = castExpr->getType();
4193
4194 // For the purposes of the classification, we assume reference types
4195 // will bind to temporaries.
4196 QualType effCastType = castType;
4197 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4198 effCastType = ref->getPointeeType();
4199
4200 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4201 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4202 if (exprACTC == castACTC) {
4203 // Check for viability and report error if casting an rvalue to a
4204 // life-time qualifier.
4205 if (castACTC == ACTC_retainable &&
4206 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4207 castType != castExprType) {
4208 const Type *DT = castType.getTypePtr();
4209 QualType QDT = castType;
4210 // We desugar some types but not others. We ignore those
4211 // that cannot happen in a cast; i.e. auto, and those which
4212 // should not be de-sugared; i.e typedef.
4213 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4214 QDT = PT->desugar();
4215 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4216 QDT = TP->desugar();
4217 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4218 QDT = AT->desugar();
4219 if (QDT != castType &&
4220 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4221 if (Diagnose) {
4222 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4223 : castExpr->getExprLoc());
4224 Diag(loc, diag::err_arc_nolifetime_behavior);
4225 }
4226 return ACR_error;
4227 }
4228 }
4229 return ACR_okay;
4230 }
4231
4232 // The life-time qualifier cast check above is all we need for ObjCWeak.
4233 // ObjCAutoRefCount has more restrictions on what is legal.
4234 if (!getLangOpts().ObjCAutoRefCount)
4235 return ACR_okay;
4236
4237 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4238
4239 // Allow all of these types to be cast to integer types (but not
4240 // vice-versa).
4241 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4242 return ACR_okay;
4243
4244 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4245 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4246 // must be explicit.
4247 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4248 return ACR_okay;
4249 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4250 isCast(CCK))
4251 return ACR_okay;
4252
4253 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4254 // For invalid casts, fall through.
4255 case ACC_invalid:
4256 break;
4257
4258 // Do nothing for both bottom and +0.
4259 case ACC_bottom:
4260 case ACC_plusZero:
4261 return ACR_okay;
4262
4263 // If the result is +1, consume it here.
4264 case ACC_plusOne:
4265 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4266 CK_ARCConsumeObject, castExpr,
4267 nullptr, VK_RValue);
4268 Cleanup.setExprNeedsCleanups(true);
4269 return ACR_okay;
4270 }
4271
4272 // If this is a non-implicit cast from id or block type to a
4273 // CoreFoundation type, delay complaining in case the cast is used
4274 // in an acceptable context.
4275 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
4276 return ACR_unbridged;
4277
4278 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4279 // to 'NSString *', instead of falling through to report a "bridge cast"
4280 // diagnostic.
4281 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4282 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4283 return ACR_error;
4284
4285 // Do not issue "bridge cast" diagnostic when implicit casting
4286 // a retainable object to a CF type parameter belonging to an audited
4287 // CF API function. Let caller issue a normal type mismatched diagnostic
4288 // instead.
4289 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4290 castACTC != ACTC_coreFoundation) &&
4291 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4292 (Opc == BO_NE || Opc == BO_EQ))) {
4293 if (Diagnose)
4294 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4295 castExpr, exprACTC, CCK);
4296 return ACR_error;
4297 }
4298 return ACR_okay;
4299}
4300
4301/// Given that we saw an expression with the ARCUnbridgedCastTy
4302/// placeholder type, complain bitterly.
4303void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4304 // We expect the spurious ImplicitCastExpr to already have been stripped.
4305 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ?
static_cast<void> (0) : __assert_fail ("!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4305, __PRETTY_FUNCTION__))
;
4306 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4307
4308 SourceRange castRange;
4309 QualType castType;
4310 CheckedConversionKind CCK;
4311
4312 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4313 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4314 castType = cast->getTypeAsWritten();
4315 CCK = CCK_CStyleCast;
4316 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4317 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4318 castType = cast->getTypeAsWritten();
4319 CCK = CCK_OtherCast;
4320 } else {
4321 llvm_unreachable("Unexpected ImplicitCastExpr")::llvm::llvm_unreachable_internal("Unexpected ImplicitCastExpr"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4321)
;
4322 }
4323
4324 ARCConversionTypeClass castACTC =
4325 classifyTypeForARCConversion(castType.getNonReferenceType());
4326
4327 Expr *castExpr = realCast->getSubExpr();
4328 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable)((classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable
) ? static_cast<void> (0) : __assert_fail ("classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4328, __PRETTY_FUNCTION__))
;
4329
4330 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4331 castExpr, realCast, ACTC_retainable, CCK);
4332}
4333
4334/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4335/// type, remove the placeholder cast.
4336Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4337 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast))((e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)) ? static_cast
<void> (0) : __assert_fail ("e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4337, __PRETTY_FUNCTION__))
;
4338
4339 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4340 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4341 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4342 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4343 assert(uo->getOpcode() == UO_Extension)((uo->getOpcode() == UO_Extension) ? static_cast<void>
(0) : __assert_fail ("uo->getOpcode() == UO_Extension", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4343, __PRETTY_FUNCTION__))
;
4344 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4345 return new (Context)
4346 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4347 sub->getObjectKind(), uo->getOperatorLoc(), false);
4348 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4349 assert(!gse->isResultDependent())((!gse->isResultDependent()) ? static_cast<void> (0)
: __assert_fail ("!gse->isResultDependent()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4349, __PRETTY_FUNCTION__))
;
4350
4351 unsigned n = gse->getNumAssocs();
4352 SmallVector<Expr *, 4> subExprs;
4353 SmallVector<TypeSourceInfo *, 4> subTypes;
4354 subExprs.reserve(n);
4355 subTypes.reserve(n);
4356 for (const GenericSelectionExpr::Association &assoc : gse->associations()) {
4357 subTypes.push_back(assoc.getTypeSourceInfo());
4358 Expr *sub = assoc.getAssociationExpr();
4359 if (assoc.isSelected())
4360 sub = stripARCUnbridgedCast(sub);
4361 subExprs.push_back(sub);
4362 }
4363
4364 return GenericSelectionExpr::Create(
4365 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4366 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4367 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4368 } else {
4369 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!")((isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"
) ? static_cast<void> (0) : __assert_fail ("isa<ImplicitCastExpr>(e) && \"bad form of unbridged cast!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaExprObjC.cpp"
, 4369, __PRETTY_FUNCTION__))
;
4370 return cast<ImplicitCastExpr>(e)->getSubExpr();
4371 }
4372}
4373
4374bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4375 QualType exprType) {
4376 QualType canCastType =
4377 Context.getCanonicalType(castType).getUnqualifiedType();
4378 QualType canExprType =
4379 Context.getCanonicalType(exprType).getUnqualifiedType();
4380 if (isa<ObjCObjectPointerType>(canCastType) &&
4381 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4382 canExprType->isObjCObjectPointerType()) {
4383 if (const ObjCObjectPointerType *ObjT =
4384 canExprType->getAs<ObjCObjectPointerType>())
4385 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4386 return !ObjI->isArcWeakrefUnavailable();
4387 }
4388 return true;
4389}
4390
4391/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4392static Expr *maybeUndoReclaimObject(Expr *e) {
4393 Expr *curExpr = e, *prevExpr = nullptr;
4394
4395 // Walk down the expression until we hit an implicit cast of kind
4396 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4397 while (true) {
4398 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4399 prevExpr = curExpr;
4400 curExpr = pe->getSubExpr();
4401 continue;
4402 }
4403
4404 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4405 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4406 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4407 if (!prevExpr)
4408 return ice->getSubExpr();
4409 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4410 pe->setSubExpr(ice->getSubExpr());
4411 else
4412 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4413 return e;
4414 }
4415
4416 prevExpr = curExpr;
4417 curExpr = ce->getSubExpr();
4418 continue;
4419 }
4420
4421 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4422 break;
4423 }
4424
4425 return e;
4426}
4427
4428ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4429 ObjCBridgeCastKind Kind,
4430 SourceLocation BridgeKeywordLoc,
4431 TypeSourceInfo *TSInfo,
4432 Expr *SubExpr) {
4433 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4434 if (SubResult.isInvalid()) return ExprError();
4435 SubExpr = SubResult.get();
4436
4437 QualType T = TSInfo->getType();
4438 QualType FromType = SubExpr->getType();
4439
4440 CastKind CK;
4441
4442 bool MustConsume = false;
4443 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4444 // Okay: we'll build a dependent expression type.
4445 CK = CK_Dependent;
4446 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4447 // Casting CF -> id
4448 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4449 : CK_CPointerToObjCPointerCast);
4450 switch (Kind) {
4451 case OBC_Bridge:
4452 break;
4453
4454 case OBC_BridgeRetained: {
4455 bool br = isKnownName("CFBridgingRelease");
4456 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4457 << 2
4458 << FromType
4459 << (T->isBlockPointerType()? 1 : 0)
4460 << T
4461 << SubExpr->getSourceRange()
4462 << Kind;
4463 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4464 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4465 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4466 << FromType << br
4467 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4468 br ? "CFBridgingRelease "
4469 : "__bridge_transfer ");
4470
4471 Kind = OBC_Bridge;
4472 break;
4473 }
4474
4475 case OBC_BridgeTransfer:
4476 // We must consume the Objective-C object produced by the cast.
4477 MustConsume = true;
4478 break;
4479 }
4480 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4481 // Okay: id -> CF
4482 CK = CK_BitCast;
4483 switch (Kind) {
4484 case OBC_Bridge:
4485 // Reclaiming a value that's going to be __bridge-casted to CF
4486 // is very dangerous, so we don't do it.
4487 SubExpr = maybeUndoReclaimObject(SubExpr);
4488 break;
4489
4490 case OBC_BridgeRetained:
4491 // Produce the object before casting it.
4492 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4493 CK_ARCProduceObject,
4494 SubExpr, nullptr, VK_RValue);
4495 break;
4496
4497 case OBC_BridgeTransfer: {
4498 bool br = isKnownName("CFBridgingRetain");
4499 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4500 << (FromType->isBlockPointerType()? 1 : 0)
4501 << FromType
4502 << 2
4503 << T
4504 << SubExpr->getSourceRange()
4505 << Kind;
4506
4507 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4508 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4509 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4510 << T << br
4511 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4512 br ? "CFBridgingRetain " : "__bridge_retained");
4513
4514 Kind = OBC_Bridge;
4515 break;
4516 }
4517 }
4518 } else {
4519 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4520 << FromType << T << Kind
4521 << SubExpr->getSourceRange()
4522 << TSInfo->getTypeLoc().getSourceRange();
4523 return ExprError();
4524 }
4525
4526 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4527 BridgeKeywordLoc,
4528 TSInfo, SubExpr);
4529
4530 if (MustConsume) {
4531 Cleanup.setExprNeedsCleanups(true);
4532 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4533 nullptr, VK_RValue);
4534 }
4535
4536 return Result;
4537}
4538
4539ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4540 SourceLocation LParenLoc,
4541 ObjCBridgeCastKind Kind,
4542 SourceLocation BridgeKeywordLoc,
4543 ParsedType Type,
4544 SourceLocation RParenLoc,
4545 Expr *SubExpr) {
4546 TypeSourceInfo *TSInfo = nullptr;
4547 QualType T = GetTypeFromParser(Type, &TSInfo);
4548 if (Kind == OBC_Bridge)
4549 CheckTollFreeBridgeCast(T, SubExpr);
4550 if (!TSInfo)
4551 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4552 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4553 SubExpr);
4554}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.