Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaType.cpp
Warning:line 6055, column 45
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaType.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 -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaType.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaType.cpp

1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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 type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTStructuralEquivalence.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeLocVisitor.h"
24#include "clang/Basic/PartialDiagnostic.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/DelayedDiagnostic.h"
29#include "clang/Sema/Lookup.h"
30#include "clang/Sema/ParsedTemplate.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/Template.h"
34#include "clang/Sema/TemplateInstCallback.h"
35#include "llvm/ADT/SmallPtrSet.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/StringSwitch.h"
38#include "llvm/IR/DerivedTypes.h"
39#include "llvm/Support/ErrorHandling.h"
40#include <bitset>
41
42using namespace clang;
43
44enum TypeDiagSelector {
45 TDS_Function,
46 TDS_Pointer,
47 TDS_ObjCObjOrBlock
48};
49
50/// isOmittedBlockReturnType - Return true if this declarator is missing a
51/// return type because this is a omitted return type on a block literal.
52static bool isOmittedBlockReturnType(const Declarator &D) {
53 if (D.getContext() != DeclaratorContext::BlockLiteral ||
54 D.getDeclSpec().hasTypeSpecifier())
55 return false;
56
57 if (D.getNumTypeObjects() == 0)
58 return true; // ^{ ... }
59
60 if (D.getNumTypeObjects() == 1 &&
61 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
62 return true; // ^(int X, float Y) { ... }
63
64 return false;
65}
66
67/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
68/// doesn't apply to the given type.
69static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
70 QualType type) {
71 TypeDiagSelector WhichType;
72 bool useExpansionLoc = true;
73 switch (attr.getKind()) {
74 case ParsedAttr::AT_ObjCGC:
75 WhichType = TDS_Pointer;
76 break;
77 case ParsedAttr::AT_ObjCOwnership:
78 WhichType = TDS_ObjCObjOrBlock;
79 break;
80 default:
81 // Assume everything else was a function attribute.
82 WhichType = TDS_Function;
83 useExpansionLoc = false;
84 break;
85 }
86
87 SourceLocation loc = attr.getLoc();
88 StringRef name = attr.getAttrName()->getName();
89
90 // The GC attributes are usually written with macros; special-case them.
91 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
92 : nullptr;
93 if (useExpansionLoc && loc.isMacroID() && II) {
94 if (II->isStr("strong")) {
95 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
96 } else if (II->isStr("weak")) {
97 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
98 }
99 }
100
101 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
102 << type;
103}
104
105// objc_gc applies to Objective-C pointers or, otherwise, to the
106// smallest available pointer type (i.e. 'void*' in 'void**').
107#define OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership \
108 case ParsedAttr::AT_ObjCGC: \
109 case ParsedAttr::AT_ObjCOwnership
110
111// Calling convention attributes.
112#define CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case
ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr
::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall
: case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall
: case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI
: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr
::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr
::AT_PreserveAll
\
113 case ParsedAttr::AT_CDecl: \
114 case ParsedAttr::AT_FastCall: \
115 case ParsedAttr::AT_StdCall: \
116 case ParsedAttr::AT_ThisCall: \
117 case ParsedAttr::AT_RegCall: \
118 case ParsedAttr::AT_Pascal: \
119 case ParsedAttr::AT_SwiftCall: \
120 case ParsedAttr::AT_SwiftAsyncCall: \
121 case ParsedAttr::AT_VectorCall: \
122 case ParsedAttr::AT_AArch64VectorPcs: \
123 case ParsedAttr::AT_MSABI: \
124 case ParsedAttr::AT_SysVABI: \
125 case ParsedAttr::AT_Pcs: \
126 case ParsedAttr::AT_IntelOclBicc: \
127 case ParsedAttr::AT_PreserveMost: \
128 case ParsedAttr::AT_PreserveAll
129
130// Function type attributes.
131#define FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn
: case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall
: case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr
::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr
::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::
AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal
: case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall
: case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs
: case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case
ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr
::AT_PreserveMost: case ParsedAttr::AT_PreserveAll
\
132 case ParsedAttr::AT_NSReturnsRetained: \
133 case ParsedAttr::AT_NoReturn: \
134 case ParsedAttr::AT_Regparm: \
135 case ParsedAttr::AT_CmseNSCall: \
136 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
137 case ParsedAttr::AT_AnyX86NoCfCheck: \
138 CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case
ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr
::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall
: case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall
: case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI
: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr
::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr
::AT_PreserveAll
139
140// Microsoft-specific type qualifiers.
141#define MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr
::AT_SPtr: case ParsedAttr::AT_UPtr
\
142 case ParsedAttr::AT_Ptr32: \
143 case ParsedAttr::AT_Ptr64: \
144 case ParsedAttr::AT_SPtr: \
145 case ParsedAttr::AT_UPtr
146
147// Nullability qualifiers.
148#define NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable
: case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified
\
149 case ParsedAttr::AT_TypeNonNull: \
150 case ParsedAttr::AT_TypeNullable: \
151 case ParsedAttr::AT_TypeNullableResult: \
152 case ParsedAttr::AT_TypeNullUnspecified
153
154namespace {
155 /// An object which stores processing state for the entire
156 /// GetTypeForDeclarator process.
157 class TypeProcessingState {
158 Sema &sema;
159
160 /// The declarator being processed.
161 Declarator &declarator;
162
163 /// The index of the declarator chunk we're currently processing.
164 /// May be the total number of valid chunks, indicating the
165 /// DeclSpec.
166 unsigned chunkIndex;
167
168 /// Whether there are non-trivial modifications to the decl spec.
169 bool trivial;
170
171 /// Whether we saved the attributes in the decl spec.
172 bool hasSavedAttrs;
173
174 /// The original set of attributes on the DeclSpec.
175 SmallVector<ParsedAttr *, 2> savedAttrs;
176
177 /// A list of attributes to diagnose the uselessness of when the
178 /// processing is complete.
179 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
180
181 /// Attributes corresponding to AttributedTypeLocs that we have not yet
182 /// populated.
183 // FIXME: The two-phase mechanism by which we construct Types and fill
184 // their TypeLocs makes it hard to correctly assign these. We keep the
185 // attributes in creation order as an attempt to make them line up
186 // properly.
187 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
188 SmallVector<TypeAttrPair, 8> AttrsForTypes;
189 bool AttrsForTypesSorted = true;
190
191 /// MacroQualifiedTypes mapping to macro expansion locations that will be
192 /// stored in a MacroQualifiedTypeLoc.
193 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
194
195 /// Flag to indicate we parsed a noderef attribute. This is used for
196 /// validating that noderef was used on a pointer or array.
197 bool parsedNoDeref;
198
199 public:
200 TypeProcessingState(Sema &sema, Declarator &declarator)
201 : sema(sema), declarator(declarator),
202 chunkIndex(declarator.getNumTypeObjects()), trivial(true),
203 hasSavedAttrs(false), parsedNoDeref(false) {}
204
205 Sema &getSema() const {
206 return sema;
207 }
208
209 Declarator &getDeclarator() const {
210 return declarator;
211 }
212
213 bool isProcessingDeclSpec() const {
214 return chunkIndex == declarator.getNumTypeObjects();
215 }
216
217 unsigned getCurrentChunkIndex() const {
218 return chunkIndex;
219 }
220
221 void setCurrentChunkIndex(unsigned idx) {
222 assert(idx <= declarator.getNumTypeObjects())((void)0);
223 chunkIndex = idx;
224 }
225
226 ParsedAttributesView &getCurrentAttributes() const {
227 if (isProcessingDeclSpec())
228 return getMutableDeclSpec().getAttributes();
229 return declarator.getTypeObject(chunkIndex).getAttrs();
230 }
231
232 /// Save the current set of attributes on the DeclSpec.
233 void saveDeclSpecAttrs() {
234 // Don't try to save them multiple times.
235 if (hasSavedAttrs) return;
236
237 DeclSpec &spec = getMutableDeclSpec();
238 for (ParsedAttr &AL : spec.getAttributes())
239 savedAttrs.push_back(&AL);
240 trivial &= savedAttrs.empty();
241 hasSavedAttrs = true;
242 }
243
244 /// Record that we had nowhere to put the given type attribute.
245 /// We will diagnose such attributes later.
246 void addIgnoredTypeAttr(ParsedAttr &attr) {
247 ignoredTypeAttrs.push_back(&attr);
248 }
249
250 /// Diagnose all the ignored type attributes, given that the
251 /// declarator worked out to the given type.
252 void diagnoseIgnoredTypeAttrs(QualType type) const {
253 for (auto *Attr : ignoredTypeAttrs)
254 diagnoseBadTypeAttribute(getSema(), *Attr, type);
255 }
256
257 /// Get an attributed type for the given attribute, and remember the Attr
258 /// object so that we can attach it to the AttributedTypeLoc.
259 QualType getAttributedType(Attr *A, QualType ModifiedType,
260 QualType EquivType) {
261 QualType T =
262 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
263 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
264 AttrsForTypesSorted = false;
265 return T;
266 }
267
268 /// Completely replace the \c auto in \p TypeWithAuto by
269 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
270 /// necessary.
271 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
272 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
273 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
274 // Attributed type still should be an attributed type after replacement.
275 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
276 for (TypeAttrPair &A : AttrsForTypes) {
277 if (A.first == AttrTy)
278 A.first = NewAttrTy;
279 }
280 AttrsForTypesSorted = false;
281 }
282 return T;
283 }
284
285 /// Extract and remove the Attr* for a given attributed type.
286 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
287 if (!AttrsForTypesSorted) {
288 llvm::stable_sort(AttrsForTypes, llvm::less_first());
289 AttrsForTypesSorted = true;
290 }
291
292 // FIXME: This is quadratic if we have lots of reuses of the same
293 // attributed type.
294 for (auto It = std::partition_point(
295 AttrsForTypes.begin(), AttrsForTypes.end(),
296 [=](const TypeAttrPair &A) { return A.first < AT; });
297 It != AttrsForTypes.end() && It->first == AT; ++It) {
298 if (It->second) {
299 const Attr *Result = It->second;
300 It->second = nullptr;
301 return Result;
302 }
303 }
304
305 llvm_unreachable("no Attr* for AttributedType*")__builtin_unreachable();
306 }
307
308 SourceLocation
309 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
310 auto FoundLoc = LocsForMacros.find(MQT);
311 assert(FoundLoc != LocsForMacros.end() &&((void)0)
312 "Unable to find macro expansion location for MacroQualifedType")((void)0);
313 return FoundLoc->second;
314 }
315
316 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
317 SourceLocation Loc) {
318 LocsForMacros[MQT] = Loc;
319 }
320
321 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
322
323 bool didParseNoDeref() const { return parsedNoDeref; }
324
325 ~TypeProcessingState() {
326 if (trivial) return;
327
328 restoreDeclSpecAttrs();
329 }
330
331 private:
332 DeclSpec &getMutableDeclSpec() const {
333 return const_cast<DeclSpec&>(declarator.getDeclSpec());
334 }
335
336 void restoreDeclSpecAttrs() {
337 assert(hasSavedAttrs)((void)0);
338
339 getMutableDeclSpec().getAttributes().clearListOnly();
340 for (ParsedAttr *AL : savedAttrs)
341 getMutableDeclSpec().getAttributes().addAtEnd(AL);
342 }
343 };
344} // end anonymous namespace
345
346static void moveAttrFromListToList(ParsedAttr &attr,
347 ParsedAttributesView &fromList,
348 ParsedAttributesView &toList) {
349 fromList.remove(&attr);
350 toList.addAtEnd(&attr);
351}
352
353/// The location of a type attribute.
354enum TypeAttrLocation {
355 /// The attribute is in the decl-specifier-seq.
356 TAL_DeclSpec,
357 /// The attribute is part of a DeclaratorChunk.
358 TAL_DeclChunk,
359 /// The attribute is immediately after the declaration's name.
360 TAL_DeclName
361};
362
363static void processTypeAttrs(TypeProcessingState &state, QualType &type,
364 TypeAttrLocation TAL, ParsedAttributesView &attrs);
365
366static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
367 QualType &type);
368
369static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
370 ParsedAttr &attr, QualType &type);
371
372static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
373 QualType &type);
374
375static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
376 ParsedAttr &attr, QualType &type);
377
378static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
379 ParsedAttr &attr, QualType &type) {
380 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
381 return handleObjCGCTypeAttr(state, attr, type);
382 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership)((void)0);
383 return handleObjCOwnershipTypeAttr(state, attr, type);
384}
385
386/// Given the index of a declarator chunk, check whether that chunk
387/// directly specifies the return type of a function and, if so, find
388/// an appropriate place for it.
389///
390/// \param i - a notional index which the search will start
391/// immediately inside
392///
393/// \param onlyBlockPointers Whether we should only look into block
394/// pointer types (vs. all pointer types).
395static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
396 unsigned i,
397 bool onlyBlockPointers) {
398 assert(i <= declarator.getNumTypeObjects())((void)0);
399
400 DeclaratorChunk *result = nullptr;
401
402 // First, look inwards past parens for a function declarator.
403 for (; i != 0; --i) {
404 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
405 switch (fnChunk.Kind) {
406 case DeclaratorChunk::Paren:
407 continue;
408
409 // If we find anything except a function, bail out.
410 case DeclaratorChunk::Pointer:
411 case DeclaratorChunk::BlockPointer:
412 case DeclaratorChunk::Array:
413 case DeclaratorChunk::Reference:
414 case DeclaratorChunk::MemberPointer:
415 case DeclaratorChunk::Pipe:
416 return result;
417
418 // If we do find a function declarator, scan inwards from that,
419 // looking for a (block-)pointer declarator.
420 case DeclaratorChunk::Function:
421 for (--i; i != 0; --i) {
422 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
423 switch (ptrChunk.Kind) {
424 case DeclaratorChunk::Paren:
425 case DeclaratorChunk::Array:
426 case DeclaratorChunk::Function:
427 case DeclaratorChunk::Reference:
428 case DeclaratorChunk::Pipe:
429 continue;
430
431 case DeclaratorChunk::MemberPointer:
432 case DeclaratorChunk::Pointer:
433 if (onlyBlockPointers)
434 continue;
435
436 LLVM_FALLTHROUGH[[gnu::fallthrough]];
437
438 case DeclaratorChunk::BlockPointer:
439 result = &ptrChunk;
440 goto continue_outer;
441 }
442 llvm_unreachable("bad declarator chunk kind")__builtin_unreachable();
443 }
444
445 // If we run out of declarators doing that, we're done.
446 return result;
447 }
448 llvm_unreachable("bad declarator chunk kind")__builtin_unreachable();
449
450 // Okay, reconsider from our new point.
451 continue_outer: ;
452 }
453
454 // Ran out of chunks, bail out.
455 return result;
456}
457
458/// Given that an objc_gc attribute was written somewhere on a
459/// declaration *other* than on the declarator itself (for which, use
460/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
461/// didn't apply in whatever position it was written in, try to move
462/// it to a more appropriate position.
463static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
464 ParsedAttr &attr, QualType type) {
465 Declarator &declarator = state.getDeclarator();
466
467 // Move it to the outermost normal or block pointer declarator.
468 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
469 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
470 switch (chunk.Kind) {
471 case DeclaratorChunk::Pointer:
472 case DeclaratorChunk::BlockPointer: {
473 // But don't move an ARC ownership attribute to the return type
474 // of a block.
475 DeclaratorChunk *destChunk = nullptr;
476 if (state.isProcessingDeclSpec() &&
477 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
478 destChunk = maybeMovePastReturnType(declarator, i - 1,
479 /*onlyBlockPointers=*/true);
480 if (!destChunk) destChunk = &chunk;
481
482 moveAttrFromListToList(attr, state.getCurrentAttributes(),
483 destChunk->getAttrs());
484 return;
485 }
486
487 case DeclaratorChunk::Paren:
488 case DeclaratorChunk::Array:
489 continue;
490
491 // We may be starting at the return type of a block.
492 case DeclaratorChunk::Function:
493 if (state.isProcessingDeclSpec() &&
494 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
495 if (DeclaratorChunk *dest = maybeMovePastReturnType(
496 declarator, i,
497 /*onlyBlockPointers=*/true)) {
498 moveAttrFromListToList(attr, state.getCurrentAttributes(),
499 dest->getAttrs());
500 return;
501 }
502 }
503 goto error;
504
505 // Don't walk through these.
506 case DeclaratorChunk::Reference:
507 case DeclaratorChunk::MemberPointer:
508 case DeclaratorChunk::Pipe:
509 goto error;
510 }
511 }
512 error:
513
514 diagnoseBadTypeAttribute(state.getSema(), attr, type);
515}
516
517/// Distribute an objc_gc type attribute that was written on the
518/// declarator.
519static void distributeObjCPointerTypeAttrFromDeclarator(
520 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
521 Declarator &declarator = state.getDeclarator();
522
523 // objc_gc goes on the innermost pointer to something that's not a
524 // pointer.
525 unsigned innermost = -1U;
526 bool considerDeclSpec = true;
527 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
528 DeclaratorChunk &chunk = declarator.getTypeObject(i);
529 switch (chunk.Kind) {
530 case DeclaratorChunk::Pointer:
531 case DeclaratorChunk::BlockPointer:
532 innermost = i;
533 continue;
534
535 case DeclaratorChunk::Reference:
536 case DeclaratorChunk::MemberPointer:
537 case DeclaratorChunk::Paren:
538 case DeclaratorChunk::Array:
539 case DeclaratorChunk::Pipe:
540 continue;
541
542 case DeclaratorChunk::Function:
543 considerDeclSpec = false;
544 goto done;
545 }
546 }
547 done:
548
549 // That might actually be the decl spec if we weren't blocked by
550 // anything in the declarator.
551 if (considerDeclSpec) {
552 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
553 // Splice the attribute into the decl spec. Prevents the
554 // attribute from being applied multiple times and gives
555 // the source-location-filler something to work with.
556 state.saveDeclSpecAttrs();
557 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
558 declarator.getAttributes(), &attr);
559 return;
560 }
561 }
562
563 // Otherwise, if we found an appropriate chunk, splice the attribute
564 // into it.
565 if (innermost != -1U) {
566 moveAttrFromListToList(attr, declarator.getAttributes(),
567 declarator.getTypeObject(innermost).getAttrs());
568 return;
569 }
570
571 // Otherwise, diagnose when we're done building the type.
572 declarator.getAttributes().remove(&attr);
573 state.addIgnoredTypeAttr(attr);
574}
575
576/// A function type attribute was written somewhere in a declaration
577/// *other* than on the declarator itself or in the decl spec. Given
578/// that it didn't apply in whatever position it was written in, try
579/// to move it to a more appropriate position.
580static void distributeFunctionTypeAttr(TypeProcessingState &state,
581 ParsedAttr &attr, QualType type) {
582 Declarator &declarator = state.getDeclarator();
583
584 // Try to push the attribute from the return type of a function to
585 // the function itself.
586 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
587 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
588 switch (chunk.Kind) {
589 case DeclaratorChunk::Function:
590 moveAttrFromListToList(attr, state.getCurrentAttributes(),
591 chunk.getAttrs());
592 return;
593
594 case DeclaratorChunk::Paren:
595 case DeclaratorChunk::Pointer:
596 case DeclaratorChunk::BlockPointer:
597 case DeclaratorChunk::Array:
598 case DeclaratorChunk::Reference:
599 case DeclaratorChunk::MemberPointer:
600 case DeclaratorChunk::Pipe:
601 continue;
602 }
603 }
604
605 diagnoseBadTypeAttribute(state.getSema(), attr, type);
606}
607
608/// Try to distribute a function type attribute to the innermost
609/// function chunk or type. Returns true if the attribute was
610/// distributed, false if no location was found.
611static bool distributeFunctionTypeAttrToInnermost(
612 TypeProcessingState &state, ParsedAttr &attr,
613 ParsedAttributesView &attrList, QualType &declSpecType) {
614 Declarator &declarator = state.getDeclarator();
615
616 // Put it on the innermost function chunk, if there is one.
617 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
618 DeclaratorChunk &chunk = declarator.getTypeObject(i);
619 if (chunk.Kind != DeclaratorChunk::Function) continue;
620
621 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
622 return true;
623 }
624
625 return handleFunctionTypeAttr(state, attr, declSpecType);
626}
627
628/// A function type attribute was written in the decl spec. Try to
629/// apply it somewhere.
630static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
631 ParsedAttr &attr,
632 QualType &declSpecType) {
633 state.saveDeclSpecAttrs();
634
635 // C++11 attributes before the decl specifiers actually appertain to
636 // the declarators. Move them straight there. We don't support the
637 // 'put them wherever you like' semantics we allow for GNU attributes.
638 if (attr.isStandardAttributeSyntax()) {
639 moveAttrFromListToList(attr, state.getCurrentAttributes(),
640 state.getDeclarator().getAttributes());
641 return;
642 }
643
644 // Try to distribute to the innermost.
645 if (distributeFunctionTypeAttrToInnermost(
646 state, attr, state.getCurrentAttributes(), declSpecType))
647 return;
648
649 // If that failed, diagnose the bad attribute when the declarator is
650 // fully built.
651 state.addIgnoredTypeAttr(attr);
652}
653
654/// A function type attribute was written on the declarator. Try to
655/// apply it somewhere.
656static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
657 ParsedAttr &attr,
658 QualType &declSpecType) {
659 Declarator &declarator = state.getDeclarator();
660
661 // Try to distribute to the innermost.
662 if (distributeFunctionTypeAttrToInnermost(
663 state, attr, declarator.getAttributes(), declSpecType))
664 return;
665
666 // If that failed, diagnose the bad attribute when the declarator is
667 // fully built.
668 declarator.getAttributes().remove(&attr);
669 state.addIgnoredTypeAttr(attr);
670}
671
672/// Given that there are attributes written on the declarator
673/// itself, try to distribute any type attributes to the appropriate
674/// declarator chunk.
675///
676/// These are attributes like the following:
677/// int f ATTR;
678/// int (f ATTR)();
679/// but not necessarily this:
680/// int f() ATTR;
681static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
682 QualType &declSpecType) {
683 // Collect all the type attributes from the declarator itself.
684 assert(!state.getDeclarator().getAttributes().empty() &&((void)0)
685 "declarator has no attrs!")((void)0);
686 // The called functions in this loop actually remove things from the current
687 // list, so iterating over the existing list isn't possible. Instead, make a
688 // non-owning copy and iterate over that.
689 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
690 for (ParsedAttr &attr : AttrsCopy) {
691 // Do not distribute [[]] attributes. They have strict rules for what
692 // they appertain to.
693 if (attr.isStandardAttributeSyntax())
694 continue;
695
696 switch (attr.getKind()) {
697 OBJC_POINTER_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_ObjCGC: case ParsedAttr::AT_ObjCOwnership:
698 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
699 break;
700
701 FUNCTION_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_NSReturnsRetained: case ParsedAttr::AT_NoReturn
: case ParsedAttr::AT_Regparm: case ParsedAttr::AT_CmseNSCall
: case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: case ParsedAttr
::AT_AnyX86NoCfCheck: case ParsedAttr::AT_CDecl: case ParsedAttr
::AT_FastCall: case ParsedAttr::AT_StdCall: case ParsedAttr::
AT_ThisCall: case ParsedAttr::AT_RegCall: case ParsedAttr::AT_Pascal
: case ParsedAttr::AT_SwiftCall: case ParsedAttr::AT_SwiftAsyncCall
: case ParsedAttr::AT_VectorCall: case ParsedAttr::AT_AArch64VectorPcs
: case ParsedAttr::AT_MSABI: case ParsedAttr::AT_SysVABI: case
ParsedAttr::AT_Pcs: case ParsedAttr::AT_IntelOclBicc: case ParsedAttr
::AT_PreserveMost: case ParsedAttr::AT_PreserveAll
:
702 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
703 break;
704
705 MS_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_Ptr32: case ParsedAttr::AT_Ptr64: case ParsedAttr
::AT_SPtr: case ParsedAttr::AT_UPtr
:
706 // Microsoft type attributes cannot go after the declarator-id.
707 continue;
708
709 NULLABILITY_TYPE_ATTRS_CASELISTcase ParsedAttr::AT_TypeNonNull: case ParsedAttr::AT_TypeNullable
: case ParsedAttr::AT_TypeNullableResult: case ParsedAttr::AT_TypeNullUnspecified
:
710 // Nullability specifiers cannot go after the declarator-id.
711
712 // Objective-C __kindof does not get distributed.
713 case ParsedAttr::AT_ObjCKindOf:
714 continue;
715
716 default:
717 break;
718 }
719 }
720}
721
722/// Add a synthetic '()' to a block-literal declarator if it is
723/// required, given the return type.
724static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
725 QualType declSpecType) {
726 Declarator &declarator = state.getDeclarator();
727
728 // First, check whether the declarator would produce a function,
729 // i.e. whether the innermost semantic chunk is a function.
730 if (declarator.isFunctionDeclarator()) {
731 // If so, make that declarator a prototyped declarator.
732 declarator.getFunctionTypeInfo().hasPrototype = true;
733 return;
734 }
735
736 // If there are any type objects, the type as written won't name a
737 // function, regardless of the decl spec type. This is because a
738 // block signature declarator is always an abstract-declarator, and
739 // abstract-declarators can't just be parentheses chunks. Therefore
740 // we need to build a function chunk unless there are no type
741 // objects and the decl spec type is a function.
742 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
743 return;
744
745 // Note that there *are* cases with invalid declarators where
746 // declarators consist solely of parentheses. In general, these
747 // occur only in failed efforts to make function declarators, so
748 // faking up the function chunk is still the right thing to do.
749
750 // Otherwise, we need to fake up a function declarator.
751 SourceLocation loc = declarator.getBeginLoc();
752
753 // ...and *prepend* it to the declarator.
754 SourceLocation NoLoc;
755 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
756 /*HasProto=*/true,
757 /*IsAmbiguous=*/false,
758 /*LParenLoc=*/NoLoc,
759 /*ArgInfo=*/nullptr,
760 /*NumParams=*/0,
761 /*EllipsisLoc=*/NoLoc,
762 /*RParenLoc=*/NoLoc,
763 /*RefQualifierIsLvalueRef=*/true,
764 /*RefQualifierLoc=*/NoLoc,
765 /*MutableLoc=*/NoLoc, EST_None,
766 /*ESpecRange=*/SourceRange(),
767 /*Exceptions=*/nullptr,
768 /*ExceptionRanges=*/nullptr,
769 /*NumExceptions=*/0,
770 /*NoexceptExpr=*/nullptr,
771 /*ExceptionSpecTokens=*/nullptr,
772 /*DeclsInPrototype=*/None, loc, loc, declarator));
773
774 // For consistency, make sure the state still has us as processing
775 // the decl spec.
776 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)((void)0);
777 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
778}
779
780static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
781 unsigned &TypeQuals,
782 QualType TypeSoFar,
783 unsigned RemoveTQs,
784 unsigned DiagID) {
785 // If this occurs outside a template instantiation, warn the user about
786 // it; they probably didn't mean to specify a redundant qualifier.
787 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
788 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
789 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
790 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
791 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
792 if (!(RemoveTQs & Qual.first))
793 continue;
794
795 if (!S.inTemplateInstantiation()) {
796 if (TypeQuals & Qual.first)
797 S.Diag(Qual.second, DiagID)
798 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
799 << FixItHint::CreateRemoval(Qual.second);
800 }
801
802 TypeQuals &= ~Qual.first;
803 }
804}
805
806/// Return true if this is omitted block return type. Also check type
807/// attributes and type qualifiers when returning true.
808static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
809 QualType Result) {
810 if (!isOmittedBlockReturnType(declarator))
811 return false;
812
813 // Warn if we see type attributes for omitted return type on a block literal.
814 SmallVector<ParsedAttr *, 2> ToBeRemoved;
815 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
816 if (AL.isInvalid() || !AL.isTypeAttr())
817 continue;
818 S.Diag(AL.getLoc(),
819 diag::warn_block_literal_attributes_on_omitted_return_type)
820 << AL;
821 ToBeRemoved.push_back(&AL);
822 }
823 // Remove bad attributes from the list.
824 for (ParsedAttr *AL : ToBeRemoved)
825 declarator.getMutableDeclSpec().getAttributes().remove(AL);
826
827 // Warn if we see type qualifiers for omitted return type on a block literal.
828 const DeclSpec &DS = declarator.getDeclSpec();
829 unsigned TypeQuals = DS.getTypeQualifiers();
830 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
831 diag::warn_block_literal_qualifiers_on_omitted_return_type);
832 declarator.getMutableDeclSpec().ClearTypeQualifiers();
833
834 return true;
835}
836
837/// Apply Objective-C type arguments to the given type.
838static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
839 ArrayRef<TypeSourceInfo *> typeArgs,
840 SourceRange typeArgsRange,
841 bool failOnError = false) {
842 // We can only apply type arguments to an Objective-C class type.
843 const auto *objcObjectType = type->getAs<ObjCObjectType>();
844 if (!objcObjectType || !objcObjectType->getInterface()) {
845 S.Diag(loc, diag::err_objc_type_args_non_class)
846 << type
847 << typeArgsRange;
848
849 if (failOnError)
850 return QualType();
851 return type;
852 }
853
854 // The class type must be parameterized.
855 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
856 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
857 if (!typeParams) {
858 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
859 << objcClass->getDeclName()
860 << FixItHint::CreateRemoval(typeArgsRange);
861
862 if (failOnError)
863 return QualType();
864
865 return type;
866 }
867
868 // The type must not already be specialized.
869 if (objcObjectType->isSpecialized()) {
870 S.Diag(loc, diag::err_objc_type_args_specialized_class)
871 << type
872 << FixItHint::CreateRemoval(typeArgsRange);
873
874 if (failOnError)
875 return QualType();
876
877 return type;
878 }
879
880 // Check the type arguments.
881 SmallVector<QualType, 4> finalTypeArgs;
882 unsigned numTypeParams = typeParams->size();
883 bool anyPackExpansions = false;
884 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
885 TypeSourceInfo *typeArgInfo = typeArgs[i];
886 QualType typeArg = typeArgInfo->getType();
887
888 // Type arguments cannot have explicit qualifiers or nullability.
889 // We ignore indirect sources of these, e.g. behind typedefs or
890 // template arguments.
891 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
892 bool diagnosed = false;
893 SourceRange rangeToRemove;
894 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
895 rangeToRemove = attr.getLocalSourceRange();
896 if (attr.getTypePtr()->getImmediateNullability()) {
897 typeArg = attr.getTypePtr()->getModifiedType();
898 S.Diag(attr.getBeginLoc(),
899 diag::err_objc_type_arg_explicit_nullability)
900 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
901 diagnosed = true;
902 }
903 }
904
905 if (!diagnosed) {
906 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
907 << typeArg << typeArg.getQualifiers().getAsString()
908 << FixItHint::CreateRemoval(rangeToRemove);
909 }
910 }
911
912 // Remove qualifiers even if they're non-local.
913 typeArg = typeArg.getUnqualifiedType();
914
915 finalTypeArgs.push_back(typeArg);
916
917 if (typeArg->getAs<PackExpansionType>())
918 anyPackExpansions = true;
919
920 // Find the corresponding type parameter, if there is one.
921 ObjCTypeParamDecl *typeParam = nullptr;
922 if (!anyPackExpansions) {
923 if (i < numTypeParams) {
924 typeParam = typeParams->begin()[i];
925 } else {
926 // Too many arguments.
927 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
928 << false
929 << objcClass->getDeclName()
930 << (unsigned)typeArgs.size()
931 << numTypeParams;
932 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
933 << objcClass;
934
935 if (failOnError)
936 return QualType();
937
938 return type;
939 }
940 }
941
942 // Objective-C object pointer types must be substitutable for the bounds.
943 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
944 // If we don't have a type parameter to match against, assume
945 // everything is fine. There was a prior pack expansion that
946 // means we won't be able to match anything.
947 if (!typeParam) {
948 assert(anyPackExpansions && "Too many arguments?")((void)0);
949 continue;
950 }
951
952 // Retrieve the bound.
953 QualType bound = typeParam->getUnderlyingType();
954 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
955
956 // Determine whether the type argument is substitutable for the bound.
957 if (typeArgObjC->isObjCIdType()) {
958 // When the type argument is 'id', the only acceptable type
959 // parameter bound is 'id'.
960 if (boundObjC->isObjCIdType())
961 continue;
962 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
963 // Otherwise, we follow the assignability rules.
964 continue;
965 }
966
967 // Diagnose the mismatch.
968 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
969 diag::err_objc_type_arg_does_not_match_bound)
970 << typeArg << bound << typeParam->getDeclName();
971 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
972 << typeParam->getDeclName();
973
974 if (failOnError)
975 return QualType();
976
977 return type;
978 }
979
980 // Block pointer types are permitted for unqualified 'id' bounds.
981 if (typeArg->isBlockPointerType()) {
982 // If we don't have a type parameter to match against, assume
983 // everything is fine. There was a prior pack expansion that
984 // means we won't be able to match anything.
985 if (!typeParam) {
986 assert(anyPackExpansions && "Too many arguments?")((void)0);
987 continue;
988 }
989
990 // Retrieve the bound.
991 QualType bound = typeParam->getUnderlyingType();
992 if (bound->isBlockCompatibleObjCPointerType(S.Context))
993 continue;
994
995 // Diagnose the mismatch.
996 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
997 diag::err_objc_type_arg_does_not_match_bound)
998 << typeArg << bound << typeParam->getDeclName();
999 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1000 << typeParam->getDeclName();
1001
1002 if (failOnError)
1003 return QualType();
1004
1005 return type;
1006 }
1007
1008 // Dependent types will be checked at instantiation time.
1009 if (typeArg->isDependentType()) {
1010 continue;
1011 }
1012
1013 // Diagnose non-id-compatible type arguments.
1014 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1015 diag::err_objc_type_arg_not_id_compatible)
1016 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1017
1018 if (failOnError)
1019 return QualType();
1020
1021 return type;
1022 }
1023
1024 // Make sure we didn't have the wrong number of arguments.
1025 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1026 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1027 << (typeArgs.size() < typeParams->size())
1028 << objcClass->getDeclName()
1029 << (unsigned)finalTypeArgs.size()
1030 << (unsigned)numTypeParams;
1031 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1032 << objcClass;
1033
1034 if (failOnError)
1035 return QualType();
1036
1037 return type;
1038 }
1039
1040 // Success. Form the specialized type.
1041 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1042}
1043
1044QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1045 SourceLocation ProtocolLAngleLoc,
1046 ArrayRef<ObjCProtocolDecl *> Protocols,
1047 ArrayRef<SourceLocation> ProtocolLocs,
1048 SourceLocation ProtocolRAngleLoc,
1049 bool FailOnError) {
1050 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1051 if (!Protocols.empty()) {
1052 bool HasError;
1053 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1054 HasError);
1055 if (HasError) {
1056 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1057 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1058 if (FailOnError) Result = QualType();
1059 }
1060 if (FailOnError && Result.isNull())
1061 return QualType();
1062 }
1063
1064 return Result;
1065}
1066
1067QualType Sema::BuildObjCObjectType(QualType BaseType,
1068 SourceLocation Loc,
1069 SourceLocation TypeArgsLAngleLoc,
1070 ArrayRef<TypeSourceInfo *> TypeArgs,
1071 SourceLocation TypeArgsRAngleLoc,
1072 SourceLocation ProtocolLAngleLoc,
1073 ArrayRef<ObjCProtocolDecl *> Protocols,
1074 ArrayRef<SourceLocation> ProtocolLocs,
1075 SourceLocation ProtocolRAngleLoc,
1076 bool FailOnError) {
1077 QualType Result = BaseType;
1078 if (!TypeArgs.empty()) {
1079 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1080 SourceRange(TypeArgsLAngleLoc,
1081 TypeArgsRAngleLoc),
1082 FailOnError);
1083 if (FailOnError && Result.isNull())
1084 return QualType();
1085 }
1086
1087 if (!Protocols.empty()) {
1088 bool HasError;
1089 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1090 HasError);
1091 if (HasError) {
1092 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1093 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1094 if (FailOnError) Result = QualType();
1095 }
1096 if (FailOnError && Result.isNull())
1097 return QualType();
1098 }
1099
1100 return Result;
1101}
1102
1103TypeResult Sema::actOnObjCProtocolQualifierType(
1104 SourceLocation lAngleLoc,
1105 ArrayRef<Decl *> protocols,
1106 ArrayRef<SourceLocation> protocolLocs,
1107 SourceLocation rAngleLoc) {
1108 // Form id<protocol-list>.
1109 QualType Result = Context.getObjCObjectType(
1110 Context.ObjCBuiltinIdTy, { },
1111 llvm::makeArrayRef(
1112 (ObjCProtocolDecl * const *)protocols.data(),
1113 protocols.size()),
1114 false);
1115 Result = Context.getObjCObjectPointerType(Result);
1116
1117 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1118 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1119
1120 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1121 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1122
1123 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1124 .castAs<ObjCObjectTypeLoc>();
1125 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1126 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1127
1128 // No type arguments.
1129 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1130 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1131
1132 // Fill in protocol qualifiers.
1133 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1134 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1135 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1136 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1137
1138 // We're done. Return the completed type to the parser.
1139 return CreateParsedType(Result, ResultTInfo);
1140}
1141
1142TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1143 Scope *S,
1144 SourceLocation Loc,
1145 ParsedType BaseType,
1146 SourceLocation TypeArgsLAngleLoc,
1147 ArrayRef<ParsedType> TypeArgs,
1148 SourceLocation TypeArgsRAngleLoc,
1149 SourceLocation ProtocolLAngleLoc,
1150 ArrayRef<Decl *> Protocols,
1151 ArrayRef<SourceLocation> ProtocolLocs,
1152 SourceLocation ProtocolRAngleLoc) {
1153 TypeSourceInfo *BaseTypeInfo = nullptr;
1154 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1155 if (T.isNull())
1156 return true;
1157
1158 // Handle missing type-source info.
1159 if (!BaseTypeInfo)
1160 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1161
1162 // Extract type arguments.
1163 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1164 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1165 TypeSourceInfo *TypeArgInfo = nullptr;
1166 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1167 if (TypeArg.isNull()) {
1168 ActualTypeArgInfos.clear();
1169 break;
1170 }
1171
1172 assert(TypeArgInfo && "No type source info?")((void)0);
1173 ActualTypeArgInfos.push_back(TypeArgInfo);
1174 }
1175
1176 // Build the object type.
1177 QualType Result = BuildObjCObjectType(
1178 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1179 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1180 ProtocolLAngleLoc,
1181 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1182 Protocols.size()),
1183 ProtocolLocs, ProtocolRAngleLoc,
1184 /*FailOnError=*/false);
1185
1186 if (Result == T)
1187 return BaseType;
1188
1189 // Create source information for this type.
1190 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1191 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1192
1193 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1194 // object pointer type. Fill in source information for it.
1195 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1196 // The '*' is implicit.
1197 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1198 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1199 }
1200
1201 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1202 // Protocol qualifier information.
1203 if (OTPTL.getNumProtocols() > 0) {
1204 assert(OTPTL.getNumProtocols() == Protocols.size())((void)0);
1205 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1206 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1207 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1208 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1209 }
1210
1211 // We're done. Return the completed type to the parser.
1212 return CreateParsedType(Result, ResultTInfo);
1213 }
1214
1215 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1216
1217 // Type argument information.
1218 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1219 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())((void)0);
1220 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1221 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1222 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1223 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1224 } else {
1225 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1226 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1227 }
1228
1229 // Protocol qualifier information.
1230 if (ObjCObjectTL.getNumProtocols() > 0) {
1231 assert(ObjCObjectTL.getNumProtocols() == Protocols.size())((void)0);
1232 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1233 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1234 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1235 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1236 } else {
1237 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1238 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1239 }
1240
1241 // Base type.
1242 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1243 if (ObjCObjectTL.getType() == T)
1244 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1245 else
1246 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1247
1248 // We're done. Return the completed type to the parser.
1249 return CreateParsedType(Result, ResultTInfo);
1250}
1251
1252static OpenCLAccessAttr::Spelling
1253getImageAccess(const ParsedAttributesView &Attrs) {
1254 for (const ParsedAttr &AL : Attrs)
1255 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1256 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1257 return OpenCLAccessAttr::Keyword_read_only;
1258}
1259
1260/// Convert the specified declspec to the appropriate type
1261/// object.
1262/// \param state Specifies the declarator containing the declaration specifier
1263/// to be converted, along with other associated processing state.
1264/// \returns The type described by the declaration specifiers. This function
1265/// never returns null.
1266static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1267 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1268 // checking.
1269
1270 Sema &S = state.getSema();
1271 Declarator &declarator = state.getDeclarator();
1272 DeclSpec &DS = declarator.getMutableDeclSpec();
1273 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1274 if (DeclLoc.isInvalid())
1275 DeclLoc = DS.getBeginLoc();
1276
1277 ASTContext &Context = S.Context;
1278
1279 QualType Result;
1280 switch (DS.getTypeSpecType()) {
1281 case DeclSpec::TST_void:
1282 Result = Context.VoidTy;
1283 break;
1284 case DeclSpec::TST_char:
1285 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1286 Result = Context.CharTy;
1287 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1288 Result = Context.SignedCharTy;
1289 else {
1290 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&((void)0)
1291 "Unknown TSS value")((void)0);
1292 Result = Context.UnsignedCharTy;
1293 }
1294 break;
1295 case DeclSpec::TST_wchar:
1296 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1297 Result = Context.WCharTy;
1298 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1299 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1300 << DS.getSpecifierName(DS.getTypeSpecType(),
1301 Context.getPrintingPolicy());
1302 Result = Context.getSignedWCharType();
1303 } else {
1304 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&((void)0)
1305 "Unknown TSS value")((void)0);
1306 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1307 << DS.getSpecifierName(DS.getTypeSpecType(),
1308 Context.getPrintingPolicy());
1309 Result = Context.getUnsignedWCharType();
1310 }
1311 break;
1312 case DeclSpec::TST_char8:
1313 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((void)0)
1314 "Unknown TSS value")((void)0);
1315 Result = Context.Char8Ty;
1316 break;
1317 case DeclSpec::TST_char16:
1318 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((void)0)
1319 "Unknown TSS value")((void)0);
1320 Result = Context.Char16Ty;
1321 break;
1322 case DeclSpec::TST_char32:
1323 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((void)0)
1324 "Unknown TSS value")((void)0);
1325 Result = Context.Char32Ty;
1326 break;
1327 case DeclSpec::TST_unspecified:
1328 // If this is a missing declspec in a block literal return context, then it
1329 // is inferred from the return statements inside the block.
1330 // The declspec is always missing in a lambda expr context; it is either
1331 // specified with a trailing return type or inferred.
1332 if (S.getLangOpts().CPlusPlus14 &&
1333 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1334 // In C++1y, a lambda's implicit return type is 'auto'.
1335 Result = Context.getAutoDeductType();
1336 break;
1337 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1338 checkOmittedBlockReturnType(S, declarator,
1339 Context.DependentTy)) {
1340 Result = Context.DependentTy;
1341 break;
1342 }
1343
1344 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1345 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1346 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1347 // Note that the one exception to this is function definitions, which are
1348 // allowed to be completely missing a declspec. This is handled in the
1349 // parser already though by it pretending to have seen an 'int' in this
1350 // case.
1351 if (S.getLangOpts().ImplicitInt) {
1352 // In C89 mode, we only warn if there is a completely missing declspec
1353 // when one is not allowed.
1354 if (DS.isEmpty()) {
1355 S.Diag(DeclLoc, diag::ext_missing_declspec)
1356 << DS.getSourceRange()
1357 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1358 }
1359 } else if (!DS.hasTypeSpecifier()) {
1360 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1361 // "At least one type specifier shall be given in the declaration
1362 // specifiers in each declaration, and in the specifier-qualifier list in
1363 // each struct declaration and type name."
1364 if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) {
1365 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1366 << DS.getSourceRange();
1367
1368 // When this occurs in C++ code, often something is very broken with the
1369 // value being declared, poison it as invalid so we don't get chains of
1370 // errors.
1371 declarator.setInvalidType(true);
1372 } else if ((S.getLangOpts().OpenCLVersion >= 200 ||
1373 S.getLangOpts().OpenCLCPlusPlus) &&
1374 DS.isTypeSpecPipe()) {
1375 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1376 << DS.getSourceRange();
1377 declarator.setInvalidType(true);
1378 } else {
1379 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1380 << DS.getSourceRange();
1381 }
1382 }
1383
1384 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1385 case DeclSpec::TST_int: {
1386 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1387 switch (DS.getTypeSpecWidth()) {
1388 case TypeSpecifierWidth::Unspecified:
1389 Result = Context.IntTy;
1390 break;
1391 case TypeSpecifierWidth::Short:
1392 Result = Context.ShortTy;
1393 break;
1394 case TypeSpecifierWidth::Long:
1395 Result = Context.LongTy;
1396 break;
1397 case TypeSpecifierWidth::LongLong:
1398 Result = Context.LongLongTy;
1399
1400 // 'long long' is a C99 or C++11 feature.
1401 if (!S.getLangOpts().C99) {
1402 if (S.getLangOpts().CPlusPlus)
1403 S.Diag(DS.getTypeSpecWidthLoc(),
1404 S.getLangOpts().CPlusPlus11 ?
1405 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1406 else
1407 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1408 }
1409 break;
1410 }
1411 } else {
1412 switch (DS.getTypeSpecWidth()) {
1413 case TypeSpecifierWidth::Unspecified:
1414 Result = Context.UnsignedIntTy;
1415 break;
1416 case TypeSpecifierWidth::Short:
1417 Result = Context.UnsignedShortTy;
1418 break;
1419 case TypeSpecifierWidth::Long:
1420 Result = Context.UnsignedLongTy;
1421 break;
1422 case TypeSpecifierWidth::LongLong:
1423 Result = Context.UnsignedLongLongTy;
1424
1425 // 'long long' is a C99 or C++11 feature.
1426 if (!S.getLangOpts().C99) {
1427 if (S.getLangOpts().CPlusPlus)
1428 S.Diag(DS.getTypeSpecWidthLoc(),
1429 S.getLangOpts().CPlusPlus11 ?
1430 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1431 else
1432 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1433 }
1434 break;
1435 }
1436 }
1437 break;
1438 }
1439 case DeclSpec::TST_extint: {
1440 if (!S.Context.getTargetInfo().hasExtIntType())
1441 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1442 << "_ExtInt";
1443 Result =
1444 S.BuildExtIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1445 DS.getRepAsExpr(), DS.getBeginLoc());
1446 if (Result.isNull()) {
1447 Result = Context.IntTy;
1448 declarator.setInvalidType(true);
1449 }
1450 break;
1451 }
1452 case DeclSpec::TST_accum: {
1453 switch (DS.getTypeSpecWidth()) {
1454 case TypeSpecifierWidth::Short:
1455 Result = Context.ShortAccumTy;
1456 break;
1457 case TypeSpecifierWidth::Unspecified:
1458 Result = Context.AccumTy;
1459 break;
1460 case TypeSpecifierWidth::Long:
1461 Result = Context.LongAccumTy;
1462 break;
1463 case TypeSpecifierWidth::LongLong:
1464 llvm_unreachable("Unable to specify long long as _Accum width")__builtin_unreachable();
1465 }
1466
1467 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1468 Result = Context.getCorrespondingUnsignedType(Result);
1469
1470 if (DS.isTypeSpecSat())
1471 Result = Context.getCorrespondingSaturatedType(Result);
1472
1473 break;
1474 }
1475 case DeclSpec::TST_fract: {
1476 switch (DS.getTypeSpecWidth()) {
1477 case TypeSpecifierWidth::Short:
1478 Result = Context.ShortFractTy;
1479 break;
1480 case TypeSpecifierWidth::Unspecified:
1481 Result = Context.FractTy;
1482 break;
1483 case TypeSpecifierWidth::Long:
1484 Result = Context.LongFractTy;
1485 break;
1486 case TypeSpecifierWidth::LongLong:
1487 llvm_unreachable("Unable to specify long long as _Fract width")__builtin_unreachable();
1488 }
1489
1490 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1491 Result = Context.getCorrespondingUnsignedType(Result);
1492
1493 if (DS.isTypeSpecSat())
1494 Result = Context.getCorrespondingSaturatedType(Result);
1495
1496 break;
1497 }
1498 case DeclSpec::TST_int128:
1499 if (!S.Context.getTargetInfo().hasInt128Type() &&
1500 !S.getLangOpts().SYCLIsDevice &&
1501 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1502 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1503 << "__int128";
1504 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1505 Result = Context.UnsignedInt128Ty;
1506 else
1507 Result = Context.Int128Ty;
1508 break;
1509 case DeclSpec::TST_float16:
1510 // CUDA host and device may have different _Float16 support, therefore
1511 // do not diagnose _Float16 usage to avoid false alarm.
1512 // ToDo: more precise diagnostics for CUDA.
1513 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1514 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1515 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1516 << "_Float16";
1517 Result = Context.Float16Ty;
1518 break;
1519 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1520 case DeclSpec::TST_BFloat16:
1521 if (!S.Context.getTargetInfo().hasBFloat16Type())
1522 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1523 << "__bf16";
1524 Result = Context.BFloat16Ty;
1525 break;
1526 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1527 case DeclSpec::TST_double:
1528 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1529 Result = Context.LongDoubleTy;
1530 else
1531 Result = Context.DoubleTy;
1532 if (S.getLangOpts().OpenCL) {
1533 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1534 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1535 << 0 << Result
1536 << (S.getLangOpts().OpenCLVersion == 300
1537 ? "cl_khr_fp64 and __opencl_c_fp64"
1538 : "cl_khr_fp64");
1539 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1540 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1541 }
1542 break;
1543 case DeclSpec::TST_float128:
1544 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1545 !S.getLangOpts().SYCLIsDevice &&
1546 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1547 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1548 << "__float128";
1549 Result = Context.Float128Ty;
1550 break;
1551 case DeclSpec::TST_bool:
1552 Result = Context.BoolTy; // _Bool or bool
1553 break;
1554 case DeclSpec::TST_decimal32: // _Decimal32
1555 case DeclSpec::TST_decimal64: // _Decimal64
1556 case DeclSpec::TST_decimal128: // _Decimal128
1557 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1558 Result = Context.IntTy;
1559 declarator.setInvalidType(true);
1560 break;
1561 case DeclSpec::TST_class:
1562 case DeclSpec::TST_enum:
1563 case DeclSpec::TST_union:
1564 case DeclSpec::TST_struct:
1565 case DeclSpec::TST_interface: {
1566 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1567 if (!D) {
1568 // This can happen in C++ with ambiguous lookups.
1569 Result = Context.IntTy;
1570 declarator.setInvalidType(true);
1571 break;
1572 }
1573
1574 // If the type is deprecated or unavailable, diagnose it.
1575 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1576
1577 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&((void)0)
1578 DS.getTypeSpecComplex() == 0 &&((void)0)
1579 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((void)0)
1580 "No qualifiers on tag names!")((void)0);
1581
1582 // TypeQuals handled by caller.
1583 Result = Context.getTypeDeclType(D);
1584
1585 // In both C and C++, make an ElaboratedType.
1586 ElaboratedTypeKeyword Keyword
1587 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1588 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1589 DS.isTypeSpecOwned() ? D : nullptr);
1590 break;
1591 }
1592 case DeclSpec::TST_typename: {
1593 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&((void)0)
1594 DS.getTypeSpecComplex() == 0 &&((void)0)
1595 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&((void)0)
1596 "Can't handle qualifiers on typedef names yet!")((void)0);
1597 Result = S.GetTypeFromParser(DS.getRepAsType());
1598 if (Result.isNull()) {
1599 declarator.setInvalidType(true);
1600 }
1601
1602 // TypeQuals handled by caller.
1603 break;
1604 }
1605 case DeclSpec::TST_typeofType:
1606 // FIXME: Preserve type source info.
1607 Result = S.GetTypeFromParser(DS.getRepAsType());
1608 assert(!Result.isNull() && "Didn't get a type for typeof?")((void)0);
1609 if (!Result->isDependentType())
1610 if (const TagType *TT = Result->getAs<TagType>())
1611 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1612 // TypeQuals handled by caller.
1613 Result = Context.getTypeOfType(Result);
1614 break;
1615 case DeclSpec::TST_typeofExpr: {
1616 Expr *E = DS.getRepAsExpr();
1617 assert(E && "Didn't get an expression for typeof?")((void)0);
1618 // TypeQuals handled by caller.
1619 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1620 if (Result.isNull()) {
1621 Result = Context.IntTy;
1622 declarator.setInvalidType(true);
1623 }
1624 break;
1625 }
1626 case DeclSpec::TST_decltype: {
1627 Expr *E = DS.getRepAsExpr();
1628 assert(E && "Didn't get an expression for decltype?")((void)0);
1629 // TypeQuals handled by caller.
1630 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1631 if (Result.isNull()) {
1632 Result = Context.IntTy;
1633 declarator.setInvalidType(true);
1634 }
1635 break;
1636 }
1637 case DeclSpec::TST_underlyingType:
1638 Result = S.GetTypeFromParser(DS.getRepAsType());
1639 assert(!Result.isNull() && "Didn't get a type for __underlying_type?")((void)0);
1640 Result = S.BuildUnaryTransformType(Result,
1641 UnaryTransformType::EnumUnderlyingType,
1642 DS.getTypeSpecTypeLoc());
1643 if (Result.isNull()) {
1644 Result = Context.IntTy;
1645 declarator.setInvalidType(true);
1646 }
1647 break;
1648
1649 case DeclSpec::TST_auto:
1650 case DeclSpec::TST_decltype_auto: {
1651 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1652 ? AutoTypeKeyword::DecltypeAuto
1653 : AutoTypeKeyword::Auto;
1654
1655 ConceptDecl *TypeConstraintConcept = nullptr;
1656 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1657 if (DS.isConstrainedAuto()) {
1658 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1659 TypeConstraintConcept =
1660 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1661 TemplateArgumentListInfo TemplateArgsInfo;
1662 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1663 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1664 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1665 TemplateId->NumArgs);
1666 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1667 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1668 TemplateArgs.push_back(ArgLoc.getArgument());
1669 } else {
1670 declarator.setInvalidType(true);
1671 }
1672 }
1673 Result = S.Context.getAutoType(QualType(), AutoKW,
1674 /*IsDependent*/ false, /*IsPack=*/false,
1675 TypeConstraintConcept, TemplateArgs);
1676 break;
1677 }
1678
1679 case DeclSpec::TST_auto_type:
1680 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1681 break;
1682
1683 case DeclSpec::TST_unknown_anytype:
1684 Result = Context.UnknownAnyTy;
1685 break;
1686
1687 case DeclSpec::TST_atomic:
1688 Result = S.GetTypeFromParser(DS.getRepAsType());
1689 assert(!Result.isNull() && "Didn't get a type for _Atomic?")((void)0);
1690 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1691 if (Result.isNull()) {
1692 Result = Context.IntTy;
1693 declarator.setInvalidType(true);
1694 }
1695 break;
1696
1697#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1698 case DeclSpec::TST_##ImgType##_t: \
1699 switch (getImageAccess(DS.getAttributes())) { \
1700 case OpenCLAccessAttr::Keyword_write_only: \
1701 Result = Context.Id##WOTy; \
1702 break; \
1703 case OpenCLAccessAttr::Keyword_read_write: \
1704 Result = Context.Id##RWTy; \
1705 break; \
1706 case OpenCLAccessAttr::Keyword_read_only: \
1707 Result = Context.Id##ROTy; \
1708 break; \
1709 case OpenCLAccessAttr::SpellingNotCalculated: \
1710 llvm_unreachable("Spelling not yet calculated")__builtin_unreachable(); \
1711 } \
1712 break;
1713#include "clang/Basic/OpenCLImageTypes.def"
1714
1715 case DeclSpec::TST_error:
1716 Result = Context.IntTy;
1717 declarator.setInvalidType(true);
1718 break;
1719 }
1720
1721 // FIXME: we want resulting declarations to be marked invalid, but claiming
1722 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1723 // a null type.
1724 if (Result->containsErrors())
1725 declarator.setInvalidType();
1726
1727 if (S.getLangOpts().OpenCL) {
1728 const auto &OpenCLOptions = S.getOpenCLOptions();
1729 bool IsOpenCLC30 = (S.getLangOpts().OpenCLVersion == 300);
1730 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1731 // support.
1732 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1733 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1734 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1735 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1736 // only when the optional feature is supported
1737 if ((Result->isImageType() || Result->isSamplerT()) &&
1738 (IsOpenCLC30 &&
1739 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1740 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1741 << 0 << Result << "__opencl_c_images";
1742 declarator.setInvalidType();
1743 } else if (Result->isOCLImage3dWOType() &&
1744 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1745 S.getLangOpts())) {
1746 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1747 << 0 << Result
1748 << (IsOpenCLC30
1749 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1750 : "cl_khr_3d_image_writes");
1751 declarator.setInvalidType();
1752 }
1753 }
1754
1755 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1756 DS.getTypeSpecType() == DeclSpec::TST_fract;
1757
1758 // Only fixed point types can be saturated
1759 if (DS.isTypeSpecSat() && !IsFixedPointType)
1760 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1761 << DS.getSpecifierName(DS.getTypeSpecType(),
1762 Context.getPrintingPolicy());
1763
1764 // Handle complex types.
1765 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1766 if (S.getLangOpts().Freestanding)
1767 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1768 Result = Context.getComplexType(Result);
1769 } else if (DS.isTypeAltiVecVector()) {
1770 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1771 assert(typeSize > 0 && "type size for vector must be greater than 0 bits")((void)0);
1772 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1773 if (DS.isTypeAltiVecPixel())
1774 VecKind = VectorType::AltiVecPixel;
1775 else if (DS.isTypeAltiVecBool())
1776 VecKind = VectorType::AltiVecBool;
1777 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1778 }
1779
1780 // FIXME: Imaginary.
1781 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1782 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1783
1784 // Before we process any type attributes, synthesize a block literal
1785 // function declarator if necessary.
1786 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1787 maybeSynthesizeBlockSignature(state, Result);
1788
1789 // Apply any type attributes from the decl spec. This may cause the
1790 // list of type attributes to be temporarily saved while the type
1791 // attributes are pushed around.
1792 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1793 if (!DS.isTypeSpecPipe())
1794 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1795
1796 // Apply const/volatile/restrict qualifiers to T.
1797 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1798 // Warn about CV qualifiers on function types.
1799 // C99 6.7.3p8:
1800 // If the specification of a function type includes any type qualifiers,
1801 // the behavior is undefined.
1802 // C++11 [dcl.fct]p7:
1803 // The effect of a cv-qualifier-seq in a function declarator is not the
1804 // same as adding cv-qualification on top of the function type. In the
1805 // latter case, the cv-qualifiers are ignored.
1806 if (Result->isFunctionType()) {
1807 diagnoseAndRemoveTypeQualifiers(
1808 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1809 S.getLangOpts().CPlusPlus
1810 ? diag::warn_typecheck_function_qualifiers_ignored
1811 : diag::warn_typecheck_function_qualifiers_unspecified);
1812 // No diagnostic for 'restrict' or '_Atomic' applied to a
1813 // function type; we'll diagnose those later, in BuildQualifiedType.
1814 }
1815
1816 // C++11 [dcl.ref]p1:
1817 // Cv-qualified references are ill-formed except when the
1818 // cv-qualifiers are introduced through the use of a typedef-name
1819 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1820 //
1821 // There don't appear to be any other contexts in which a cv-qualified
1822 // reference type could be formed, so the 'ill-formed' clause here appears
1823 // to never happen.
1824 if (TypeQuals && Result->isReferenceType()) {
1825 diagnoseAndRemoveTypeQualifiers(
1826 S, DS, TypeQuals, Result,
1827 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1828 diag::warn_typecheck_reference_qualifiers);
1829 }
1830
1831 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1832 // than once in the same specifier-list or qualifier-list, either directly
1833 // or via one or more typedefs."
1834 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1835 && TypeQuals & Result.getCVRQualifiers()) {
1836 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1837 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1838 << "const";
1839 }
1840
1841 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1842 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1843 << "volatile";
1844 }
1845
1846 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1847 // produce a warning in this case.
1848 }
1849
1850 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1851
1852 // If adding qualifiers fails, just use the unqualified type.
1853 if (Qualified.isNull())
1854 declarator.setInvalidType(true);
1855 else
1856 Result = Qualified;
1857 }
1858
1859 assert(!Result.isNull() && "This function should not return a null type")((void)0);
1860 return Result;
1861}
1862
1863static std::string getPrintableNameForEntity(DeclarationName Entity) {
1864 if (Entity)
1865 return Entity.getAsString();
1866
1867 return "type name";
1868}
1869
1870QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1871 Qualifiers Qs, const DeclSpec *DS) {
1872 if (T.isNull())
1873 return QualType();
1874
1875 // Ignore any attempt to form a cv-qualified reference.
1876 if (T->isReferenceType()) {
1877 Qs.removeConst();
1878 Qs.removeVolatile();
1879 }
1880
1881 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1882 // object or incomplete types shall not be restrict-qualified."
1883 if (Qs.hasRestrict()) {
1884 unsigned DiagID = 0;
1885 QualType ProblemTy;
1886
1887 if (T->isAnyPointerType() || T->isReferenceType() ||
1888 T->isMemberPointerType()) {
1889 QualType EltTy;
1890 if (T->isObjCObjectPointerType())
1891 EltTy = T;
1892 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1893 EltTy = PTy->getPointeeType();
1894 else
1895 EltTy = T->getPointeeType();
1896
1897 // If we have a pointer or reference, the pointee must have an object
1898 // incomplete type.
1899 if (!EltTy->isIncompleteOrObjectType()) {
1900 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1901 ProblemTy = EltTy;
1902 }
1903 } else if (!T->isDependentType()) {
1904 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1905 ProblemTy = T;
1906 }
1907
1908 if (DiagID) {
1909 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1910 Qs.removeRestrict();
1911 }
1912 }
1913
1914 return Context.getQualifiedType(T, Qs);
1915}
1916
1917QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1918 unsigned CVRAU, const DeclSpec *DS) {
1919 if (T.isNull())
1920 return QualType();
1921
1922 // Ignore any attempt to form a cv-qualified reference.
1923 if (T->isReferenceType())
1924 CVRAU &=
1925 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1926
1927 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1928 // TQ_unaligned;
1929 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1930
1931 // C11 6.7.3/5:
1932 // If the same qualifier appears more than once in the same
1933 // specifier-qualifier-list, either directly or via one or more typedefs,
1934 // the behavior is the same as if it appeared only once.
1935 //
1936 // It's not specified what happens when the _Atomic qualifier is applied to
1937 // a type specified with the _Atomic specifier, but we assume that this
1938 // should be treated as if the _Atomic qualifier appeared multiple times.
1939 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1940 // C11 6.7.3/5:
1941 // If other qualifiers appear along with the _Atomic qualifier in a
1942 // specifier-qualifier-list, the resulting type is the so-qualified
1943 // atomic type.
1944 //
1945 // Don't need to worry about array types here, since _Atomic can't be
1946 // applied to such types.
1947 SplitQualType Split = T.getSplitUnqualifiedType();
1948 T = BuildAtomicType(QualType(Split.Ty, 0),
1949 DS ? DS->getAtomicSpecLoc() : Loc);
1950 if (T.isNull())
1951 return T;
1952 Split.Quals.addCVRQualifiers(CVR);
1953 return BuildQualifiedType(T, Loc, Split.Quals);
1954 }
1955
1956 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1957 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1958 return BuildQualifiedType(T, Loc, Q, DS);
1959}
1960
1961/// Build a paren type including \p T.
1962QualType Sema::BuildParenType(QualType T) {
1963 return Context.getParenType(T);
1964}
1965
1966/// Given that we're building a pointer or reference to the given
1967static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1968 SourceLocation loc,
1969 bool isReference) {
1970 // Bail out if retention is unrequired or already specified.
1971 if (!type->isObjCLifetimeType() ||
1972 type.getObjCLifetime() != Qualifiers::OCL_None)
1973 return type;
1974
1975 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1976
1977 // If the object type is const-qualified, we can safely use
1978 // __unsafe_unretained. This is safe (because there are no read
1979 // barriers), and it'll be safe to coerce anything but __weak* to
1980 // the resulting type.
1981 if (type.isConstQualified()) {
1982 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1983
1984 // Otherwise, check whether the static type does not require
1985 // retaining. This currently only triggers for Class (possibly
1986 // protocol-qualifed, and arrays thereof).
1987 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1988 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1989
1990 // If we are in an unevaluated context, like sizeof, skip adding a
1991 // qualification.
1992 } else if (S.isUnevaluatedContext()) {
1993 return type;
1994
1995 // If that failed, give an error and recover using __strong. __strong
1996 // is the option most likely to prevent spurious second-order diagnostics,
1997 // like when binding a reference to a field.
1998 } else {
1999 // These types can show up in private ivars in system headers, so
2000 // we need this to not be an error in those cases. Instead we
2001 // want to delay.
2002 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2003 S.DelayedDiagnostics.add(
2004 sema::DelayedDiagnostic::makeForbiddenType(loc,
2005 diag::err_arc_indirect_no_ownership, type, isReference));
2006 } else {
2007 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2008 }
2009 implicitLifetime = Qualifiers::OCL_Strong;
2010 }
2011 assert(implicitLifetime && "didn't infer any lifetime!")((void)0);
2012
2013 Qualifiers qs;
2014 qs.addObjCLifetime(implicitLifetime);
2015 return S.Context.getQualifiedType(type, qs);
2016}
2017
2018static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2019 std::string Quals = FnTy->getMethodQuals().getAsString();
2020
2021 switch (FnTy->getRefQualifier()) {
2022 case RQ_None:
2023 break;
2024
2025 case RQ_LValue:
2026 if (!Quals.empty())
2027 Quals += ' ';
2028 Quals += '&';
2029 break;
2030
2031 case RQ_RValue:
2032 if (!Quals.empty())
2033 Quals += ' ';
2034 Quals += "&&";
2035 break;
2036 }
2037
2038 return Quals;
2039}
2040
2041namespace {
2042/// Kinds of declarator that cannot contain a qualified function type.
2043///
2044/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2045/// a function type with a cv-qualifier or a ref-qualifier can only appear
2046/// at the topmost level of a type.
2047///
2048/// Parens and member pointers are permitted. We don't diagnose array and
2049/// function declarators, because they don't allow function types at all.
2050///
2051/// The values of this enum are used in diagnostics.
2052enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2053} // end anonymous namespace
2054
2055/// Check whether the type T is a qualified function type, and if it is,
2056/// diagnose that it cannot be contained within the given kind of declarator.
2057static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2058 QualifiedFunctionKind QFK) {
2059 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2060 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2061 if (!FPT ||
2062 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2063 return false;
2064
2065 S.Diag(Loc, diag::err_compound_qualified_function_type)
2066 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2067 << getFunctionQualifiersAsString(FPT);
2068 return true;
2069}
2070
2071bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2072 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2073 if (!FPT ||
2074 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2075 return false;
2076
2077 Diag(Loc, diag::err_qualified_function_typeid)
2078 << T << getFunctionQualifiersAsString(FPT);
2079 return true;
2080}
2081
2082// Helper to deduce addr space of a pointee type in OpenCL mode.
2083static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2084 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2085 !PointeeType->isSamplerT() &&
2086 !PointeeType.hasAddressSpace())
2087 PointeeType = S.getASTContext().getAddrSpaceQualType(
2088 PointeeType, S.getLangOpts().OpenCLGenericAddressSpace
2089 ? LangAS::opencl_generic
2090 : LangAS::opencl_private);
2091 return PointeeType;
2092}
2093
2094/// Build a pointer type.
2095///
2096/// \param T The type to which we'll be building a pointer.
2097///
2098/// \param Loc The location of the entity whose type involves this
2099/// pointer type or, if there is no such entity, the location of the
2100/// type that will have pointer type.
2101///
2102/// \param Entity The name of the entity that involves the pointer
2103/// type, if known.
2104///
2105/// \returns A suitable pointer type, if there are no
2106/// errors. Otherwise, returns a NULL type.
2107QualType Sema::BuildPointerType(QualType T,
2108 SourceLocation Loc, DeclarationName Entity) {
2109 if (T->isReferenceType()) {
2110 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2111 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2112 << getPrintableNameForEntity(Entity) << T;
2113 return QualType();
2114 }
2115
2116 if (T->isFunctionType() && getLangOpts().OpenCL &&
2117 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2118 getLangOpts())) {
2119 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2120 return QualType();
2121 }
2122
2123 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2124 return QualType();
2125
2126 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")((void)0);
2127
2128 // In ARC, it is forbidden to build pointers to unqualified pointers.
2129 if (getLangOpts().ObjCAutoRefCount)
2130 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2131
2132 if (getLangOpts().OpenCL)
2133 T = deduceOpenCLPointeeAddrSpace(*this, T);
2134
2135 // Build the pointer type.
2136 return Context.getPointerType(T);
2137}
2138
2139/// Build a reference type.
2140///
2141/// \param T The type to which we'll be building a reference.
2142///
2143/// \param Loc The location of the entity whose type involves this
2144/// reference type or, if there is no such entity, the location of the
2145/// type that will have reference type.
2146///
2147/// \param Entity The name of the entity that involves the reference
2148/// type, if known.
2149///
2150/// \returns A suitable reference type, if there are no
2151/// errors. Otherwise, returns a NULL type.
2152QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2153 SourceLocation Loc,
2154 DeclarationName Entity) {
2155 assert(Context.getCanonicalType(T) != Context.OverloadTy &&((void)0)
2156 "Unresolved overloaded function type")((void)0);
2157
2158 // C++0x [dcl.ref]p6:
2159 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2160 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2161 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2162 // the type "lvalue reference to T", while an attempt to create the type
2163 // "rvalue reference to cv TR" creates the type TR.
2164 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2165
2166 // C++ [dcl.ref]p4: There shall be no references to references.
2167 //
2168 // According to C++ DR 106, references to references are only
2169 // diagnosed when they are written directly (e.g., "int & &"),
2170 // but not when they happen via a typedef:
2171 //
2172 // typedef int& intref;
2173 // typedef intref& intref2;
2174 //
2175 // Parser::ParseDeclaratorInternal diagnoses the case where
2176 // references are written directly; here, we handle the
2177 // collapsing of references-to-references as described in C++0x.
2178 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2179
2180 // C++ [dcl.ref]p1:
2181 // A declarator that specifies the type "reference to cv void"
2182 // is ill-formed.
2183 if (T->isVoidType()) {
2184 Diag(Loc, diag::err_reference_to_void);
2185 return QualType();
2186 }
2187
2188 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2189 return QualType();
2190
2191 if (T->isFunctionType() && getLangOpts().OpenCL &&
2192 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2193 getLangOpts())) {
2194 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2195 return QualType();
2196 }
2197
2198 // In ARC, it is forbidden to build references to unqualified pointers.
2199 if (getLangOpts().ObjCAutoRefCount)
2200 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2201
2202 if (getLangOpts().OpenCL)
2203 T = deduceOpenCLPointeeAddrSpace(*this, T);
2204
2205 // Handle restrict on references.
2206 if (LValueRef)
2207 return Context.getLValueReferenceType(T, SpelledAsLValue);
2208 return Context.getRValueReferenceType(T);
2209}
2210
2211/// Build a Read-only Pipe type.
2212///
2213/// \param T The type to which we'll be building a Pipe.
2214///
2215/// \param Loc We do not use it for now.
2216///
2217/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2218/// NULL type.
2219QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2220 return Context.getReadPipeType(T);
2221}
2222
2223/// Build a Write-only Pipe type.
2224///
2225/// \param T The type to which we'll be building a Pipe.
2226///
2227/// \param Loc We do not use it for now.
2228///
2229/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2230/// NULL type.
2231QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2232 return Context.getWritePipeType(T);
2233}
2234
2235/// Build a extended int type.
2236///
2237/// \param IsUnsigned Boolean representing the signedness of the type.
2238///
2239/// \param BitWidth Size of this int type in bits, or an expression representing
2240/// that.
2241///
2242/// \param Loc Location of the keyword.
2243QualType Sema::BuildExtIntType(bool IsUnsigned, Expr *BitWidth,
2244 SourceLocation Loc) {
2245 if (BitWidth->isInstantiationDependent())
2246 return Context.getDependentExtIntType(IsUnsigned, BitWidth);
2247
2248 llvm::APSInt Bits(32);
2249 ExprResult ICE =
2250 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2251
2252 if (ICE.isInvalid())
2253 return QualType();
2254
2255 int64_t NumBits = Bits.getSExtValue();
2256 if (!IsUnsigned && NumBits < 2) {
2257 Diag(Loc, diag::err_ext_int_bad_size) << 0;
2258 return QualType();
2259 }
2260
2261 if (IsUnsigned && NumBits < 1) {
2262 Diag(Loc, diag::err_ext_int_bad_size) << 1;
2263 return QualType();
2264 }
2265
2266 if (NumBits > llvm::IntegerType::MAX_INT_BITS) {
2267 Diag(Loc, diag::err_ext_int_max_size) << IsUnsigned
2268 << llvm::IntegerType::MAX_INT_BITS;
2269 return QualType();
2270 }
2271
2272 return Context.getExtIntType(IsUnsigned, NumBits);
2273}
2274
2275/// Check whether the specified array bound can be evaluated using the relevant
2276/// language rules. If so, returns the possibly-converted expression and sets
2277/// SizeVal to the size. If not, but the expression might be a VLA bound,
2278/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2279/// ExprError().
2280static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2281 llvm::APSInt &SizeVal, unsigned VLADiag,
2282 bool VLAIsError) {
2283 if (S.getLangOpts().CPlusPlus14 &&
2284 (VLAIsError ||
2285 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2286 // C++14 [dcl.array]p1:
2287 // The constant-expression shall be a converted constant expression of
2288 // type std::size_t.
2289 //
2290 // Don't apply this rule if we might be forming a VLA: in that case, we
2291 // allow non-constant expressions and constant-folding. We only need to use
2292 // the converted constant expression rules (to properly convert the source)
2293 // when the source expression is of class type.
2294 return S.CheckConvertedConstantExpression(
2295 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2296 }
2297
2298 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2299 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2300 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2301 public:
2302 unsigned VLADiag;
2303 bool VLAIsError;
2304 bool IsVLA = false;
2305
2306 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2307 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2308
2309 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2310 QualType T) override {
2311 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2312 }
2313
2314 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2315 SourceLocation Loc) override {
2316 IsVLA = !VLAIsError;
2317 return S.Diag(Loc, VLADiag);
2318 }
2319
2320 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2321 SourceLocation Loc) override {
2322 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2323 }
2324 } Diagnoser(VLADiag, VLAIsError);
2325
2326 ExprResult R =
2327 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2328 if (Diagnoser.IsVLA)
2329 return ExprResult();
2330 return R;
2331}
2332
2333/// Build an array type.
2334///
2335/// \param T The type of each element in the array.
2336///
2337/// \param ASM C99 array size modifier (e.g., '*', 'static').
2338///
2339/// \param ArraySize Expression describing the size of the array.
2340///
2341/// \param Brackets The range from the opening '[' to the closing ']'.
2342///
2343/// \param Entity The name of the entity that involves the array
2344/// type, if known.
2345///
2346/// \returns A suitable array type, if there are no errors. Otherwise,
2347/// returns a NULL type.
2348QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2349 Expr *ArraySize, unsigned Quals,
2350 SourceRange Brackets, DeclarationName Entity) {
2351
2352 SourceLocation Loc = Brackets.getBegin();
2353 if (getLangOpts().CPlusPlus) {
2354 // C++ [dcl.array]p1:
2355 // T is called the array element type; this type shall not be a reference
2356 // type, the (possibly cv-qualified) type void, a function type or an
2357 // abstract class type.
2358 //
2359 // C++ [dcl.array]p3:
2360 // When several "array of" specifications are adjacent, [...] only the
2361 // first of the constant expressions that specify the bounds of the arrays
2362 // may be omitted.
2363 //
2364 // Note: function types are handled in the common path with C.
2365 if (T->isReferenceType()) {
2366 Diag(Loc, diag::err_illegal_decl_array_of_references)
2367 << getPrintableNameForEntity(Entity) << T;
2368 return QualType();
2369 }
2370
2371 if (T->isVoidType() || T->isIncompleteArrayType()) {
2372 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2373 return QualType();
2374 }
2375
2376 if (RequireNonAbstractType(Brackets.getBegin(), T,
2377 diag::err_array_of_abstract_type))
2378 return QualType();
2379
2380 // Mentioning a member pointer type for an array type causes us to lock in
2381 // an inheritance model, even if it's inside an unused typedef.
2382 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2383 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2384 if (!MPTy->getClass()->isDependentType())
2385 (void)isCompleteType(Loc, T);
2386
2387 } else {
2388 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2389 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2390 if (RequireCompleteSizedType(Loc, T,
2391 diag::err_array_incomplete_or_sizeless_type))
2392 return QualType();
2393 }
2394
2395 if (T->isSizelessType()) {
2396 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2397 return QualType();
2398 }
2399
2400 if (T->isFunctionType()) {
2401 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2402 << getPrintableNameForEntity(Entity) << T;
2403 return QualType();
2404 }
2405
2406 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2407 // If the element type is a struct or union that contains a variadic
2408 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2409 if (EltTy->getDecl()->hasFlexibleArrayMember())
2410 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2411 } else if (T->isObjCObjectType()) {
2412 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2413 return QualType();
2414 }
2415
2416 // Do placeholder conversions on the array size expression.
2417 if (ArraySize && ArraySize->hasPlaceholderType()) {
2418 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2419 if (Result.isInvalid()) return QualType();
2420 ArraySize = Result.get();
2421 }
2422
2423 // Do lvalue-to-rvalue conversions on the array size expression.
2424 if (ArraySize && !ArraySize->isPRValue()) {
2425 ExprResult Result = DefaultLvalueConversion(ArraySize);
2426 if (Result.isInvalid())
2427 return QualType();
2428
2429 ArraySize = Result.get();
2430 }
2431
2432 // C99 6.7.5.2p1: The size expression shall have integer type.
2433 // C++11 allows contextual conversions to such types.
2434 if (!getLangOpts().CPlusPlus11 &&
2435 ArraySize && !ArraySize->isTypeDependent() &&
2436 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2437 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2438 << ArraySize->getType() << ArraySize->getSourceRange();
2439 return QualType();
2440 }
2441
2442 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2443 unsigned VLADiag;
2444 bool VLAIsError;
2445 if (getLangOpts().OpenCL) {
2446 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2447 VLADiag = diag::err_opencl_vla;
2448 VLAIsError = true;
2449 } else if (getLangOpts().C99) {
2450 VLADiag = diag::warn_vla_used;
2451 VLAIsError = false;
2452 } else if (isSFINAEContext()) {
2453 VLADiag = diag::err_vla_in_sfinae;
2454 VLAIsError = true;
2455 } else {
2456 VLADiag = diag::ext_vla;
2457 VLAIsError = false;
2458 }
2459
2460 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2461 if (!ArraySize) {
2462 if (ASM == ArrayType::Star) {
2463 Diag(Loc, VLADiag);
2464 if (VLAIsError)
2465 return QualType();
2466
2467 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2468 } else {
2469 T = Context.getIncompleteArrayType(T, ASM, Quals);
2470 }
2471 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2472 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2473 } else {
2474 ExprResult R =
2475 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2476 if (R.isInvalid())
2477 return QualType();
2478
2479 if (!R.isUsable()) {
2480 // C99: an array with a non-ICE size is a VLA. We accept any expression
2481 // that we can fold to a non-zero positive value as a non-VLA as an
2482 // extension.
2483 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2484 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2485 !T->isConstantSizeType()) {
2486 // C99: an array with an element type that has a non-constant-size is a
2487 // VLA.
2488 // FIXME: Add a note to explain why this isn't a VLA.
2489 Diag(Loc, VLADiag);
2490 if (VLAIsError)
2491 return QualType();
2492 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2493 } else {
2494 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2495 // have a value greater than zero.
2496 // In C++, this follows from narrowing conversions being disallowed.
2497 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2498 if (Entity)
2499 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2500 << getPrintableNameForEntity(Entity)
2501 << ArraySize->getSourceRange();
2502 else
2503 Diag(ArraySize->getBeginLoc(),
2504 diag::err_typecheck_negative_array_size)
2505 << ArraySize->getSourceRange();
2506 return QualType();
2507 }
2508 if (ConstVal == 0) {
2509 // GCC accepts zero sized static arrays. We allow them when
2510 // we're not in a SFINAE context.
2511 Diag(ArraySize->getBeginLoc(),
2512 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2513 : diag::ext_typecheck_zero_array_size)
2514 << ArraySize->getSourceRange();
2515 }
2516
2517 // Is the array too large?
2518 unsigned ActiveSizeBits =
2519 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2520 !T->isIncompleteType() && !T->isUndeducedType())
2521 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2522 : ConstVal.getActiveBits();
2523 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2524 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2525 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2526 return QualType();
2527 }
2528
2529 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2530 }
2531 }
2532
2533 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2534 // CUDA device code and some other targets don't support VLAs.
2535 targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2536 ? diag::err_cuda_vla
2537 : diag::err_vla_unsupported)
2538 << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2539 ? CurrentCUDATarget()
2540 : CFT_InvalidTarget);
2541 }
2542
2543 // If this is not C99, diagnose array size modifiers on non-VLAs.
2544 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2545 (ASM != ArrayType::Normal || Quals != 0)) {
2546 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2547 : diag::ext_c99_array_usage)
2548 << ASM;
2549 }
2550
2551 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2552 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2553 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2554 if (getLangOpts().OpenCL) {
2555 const QualType ArrType = Context.getBaseElementType(T);
2556 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2557 ArrType->isSamplerT() || ArrType->isImageType()) {
2558 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2559 return QualType();
2560 }
2561 }
2562
2563 return T;
2564}
2565
2566QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2567 SourceLocation AttrLoc) {
2568 // The base type must be integer (not Boolean or enumeration) or float, and
2569 // can't already be a vector.
2570 if ((!CurType->isDependentType() &&
2571 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2572 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) ||
2573 CurType->isArrayType()) {
2574 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2575 return QualType();
2576 }
2577
2578 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2579 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2580 VectorType::GenericVector);
2581
2582 Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2583 if (!VecSize) {
2584 Diag(AttrLoc, diag::err_attribute_argument_type)
2585 << "vector_size" << AANT_ArgumentIntegerConstant
2586 << SizeExpr->getSourceRange();
2587 return QualType();
2588 }
2589
2590 if (CurType->isDependentType())
2591 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2592 VectorType::GenericVector);
2593
2594 // vecSize is specified in bytes - convert to bits.
2595 if (!VecSize->isIntN(61)) {
2596 // Bit size will overflow uint64.
2597 Diag(AttrLoc, diag::err_attribute_size_too_large)
2598 << SizeExpr->getSourceRange() << "vector";
2599 return QualType();
2600 }
2601 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2602 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2603
2604 if (VectorSizeBits == 0) {
2605 Diag(AttrLoc, diag::err_attribute_zero_size)
2606 << SizeExpr->getSourceRange() << "vector";
2607 return QualType();
2608 }
2609
2610 if (VectorSizeBits % TypeSize) {
2611 Diag(AttrLoc, diag::err_attribute_invalid_size)
2612 << SizeExpr->getSourceRange();
2613 return QualType();
2614 }
2615
2616 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2617 Diag(AttrLoc, diag::err_attribute_size_too_large)
2618 << SizeExpr->getSourceRange() << "vector";
2619 return QualType();
2620 }
2621
2622 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2623 VectorType::GenericVector);
2624}
2625
2626/// Build an ext-vector type.
2627///
2628/// Run the required checks for the extended vector type.
2629QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2630 SourceLocation AttrLoc) {
2631 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2632 // in conjunction with complex types (pointers, arrays, functions, etc.).
2633 //
2634 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2635 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2636 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2637 // of bool aren't allowed.
2638 if ((!T->isDependentType() && !T->isIntegerType() &&
2639 !T->isRealFloatingType()) ||
2640 T->isBooleanType()) {
2641 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2642 return QualType();
2643 }
2644
2645 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2646 Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2647 if (!vecSize) {
2648 Diag(AttrLoc, diag::err_attribute_argument_type)
2649 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2650 << ArraySize->getSourceRange();
2651 return QualType();
2652 }
2653
2654 if (!vecSize->isIntN(32)) {
2655 Diag(AttrLoc, diag::err_attribute_size_too_large)
2656 << ArraySize->getSourceRange() << "vector";
2657 return QualType();
2658 }
2659 // Unlike gcc's vector_size attribute, the size is specified as the
2660 // number of elements, not the number of bytes.
2661 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2662
2663 if (vectorSize == 0) {
2664 Diag(AttrLoc, diag::err_attribute_zero_size)
2665 << ArraySize->getSourceRange() << "vector";
2666 return QualType();
2667 }
2668
2669 return Context.getExtVectorType(T, vectorSize);
2670 }
2671
2672 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2673}
2674
2675QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2676 SourceLocation AttrLoc) {
2677 assert(Context.getLangOpts().MatrixTypes &&((void)0)
2678 "Should never build a matrix type when it is disabled")((void)0);
2679
2680 // Check element type, if it is not dependent.
2681 if (!ElementTy->isDependentType() &&
2682 !MatrixType::isValidElementType(ElementTy)) {
2683 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2684 return QualType();
2685 }
2686
2687 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2688 NumRows->isValueDependent() || NumCols->isValueDependent())
2689 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2690 AttrLoc);
2691
2692 Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2693 Optional<llvm::APSInt> ValueColumns =
2694 NumCols->getIntegerConstantExpr(Context);
2695
2696 auto const RowRange = NumRows->getSourceRange();
2697 auto const ColRange = NumCols->getSourceRange();
2698
2699 // Both are row and column expressions are invalid.
2700 if (!ValueRows && !ValueColumns) {
2701 Diag(AttrLoc, diag::err_attribute_argument_type)
2702 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2703 << ColRange;
2704 return QualType();
2705 }
2706
2707 // Only the row expression is invalid.
2708 if (!ValueRows) {
2709 Diag(AttrLoc, diag::err_attribute_argument_type)
2710 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2711 return QualType();
2712 }
2713
2714 // Only the column expression is invalid.
2715 if (!ValueColumns) {
2716 Diag(AttrLoc, diag::err_attribute_argument_type)
2717 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2718 return QualType();
2719 }
2720
2721 // Check the matrix dimensions.
2722 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2723 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2724 if (MatrixRows == 0 && MatrixColumns == 0) {
2725 Diag(AttrLoc, diag::err_attribute_zero_size)
2726 << "matrix" << RowRange << ColRange;
2727 return QualType();
2728 }
2729 if (MatrixRows == 0) {
2730 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2731 return QualType();
2732 }
2733 if (MatrixColumns == 0) {
2734 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2735 return QualType();
2736 }
2737 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2738 Diag(AttrLoc, diag::err_attribute_size_too_large)
2739 << RowRange << "matrix row";
2740 return QualType();
2741 }
2742 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2743 Diag(AttrLoc, diag::err_attribute_size_too_large)
2744 << ColRange << "matrix column";
2745 return QualType();
2746 }
2747 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2748}
2749
2750bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2751 if (T->isArrayType() || T->isFunctionType()) {
2752 Diag(Loc, diag::err_func_returning_array_function)
2753 << T->isFunctionType() << T;
2754 return true;
2755 }
2756
2757 // Functions cannot return half FP.
2758 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2759 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2760 FixItHint::CreateInsertion(Loc, "*");
2761 return true;
2762 }
2763
2764 // Methods cannot return interface types. All ObjC objects are
2765 // passed by reference.
2766 if (T->isObjCObjectType()) {
2767 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2768 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2769 return true;
2770 }
2771
2772 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2773 T.hasNonTrivialToPrimitiveCopyCUnion())
2774 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2775 NTCUK_Destruct|NTCUK_Copy);
2776
2777 // C++2a [dcl.fct]p12:
2778 // A volatile-qualified return type is deprecated
2779 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2780 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2781
2782 return false;
2783}
2784
2785/// Check the extended parameter information. Most of the necessary
2786/// checking should occur when applying the parameter attribute; the
2787/// only other checks required are positional restrictions.
2788static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2789 const FunctionProtoType::ExtProtoInfo &EPI,
2790 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2791 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")((void)0);
2792
2793 bool emittedError = false;
2794 auto actualCC = EPI.ExtInfo.getCC();
2795 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2796 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2797 bool isCompatible =
2798 (required == RequiredCC::OnlySwift)
2799 ? (actualCC == CC_Swift)
2800 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2801 if (isCompatible || emittedError)
2802 return;
2803 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2804 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2805 << (required == RequiredCC::OnlySwift);
2806 emittedError = true;
2807 };
2808 for (size_t paramIndex = 0, numParams = paramTypes.size();
2809 paramIndex != numParams; ++paramIndex) {
2810 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2811 // Nothing interesting to check for orindary-ABI parameters.
2812 case ParameterABI::Ordinary:
2813 continue;
2814
2815 // swift_indirect_result parameters must be a prefix of the function
2816 // arguments.
2817 case ParameterABI::SwiftIndirectResult:
2818 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2819 if (paramIndex != 0 &&
2820 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2821 != ParameterABI::SwiftIndirectResult) {
2822 S.Diag(getParamLoc(paramIndex),
2823 diag::err_swift_indirect_result_not_first);
2824 }
2825 continue;
2826
2827 case ParameterABI::SwiftContext:
2828 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2829 continue;
2830
2831 // SwiftAsyncContext is not limited to swiftasynccall functions.
2832 case ParameterABI::SwiftAsyncContext:
2833 continue;
2834
2835 // swift_error parameters must be preceded by a swift_context parameter.
2836 case ParameterABI::SwiftErrorResult:
2837 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2838 if (paramIndex == 0 ||
2839 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2840 ParameterABI::SwiftContext) {
2841 S.Diag(getParamLoc(paramIndex),
2842 diag::err_swift_error_result_not_after_swift_context);
2843 }
2844 continue;
2845 }
2846 llvm_unreachable("bad ABI kind")__builtin_unreachable();
2847 }
2848}
2849
2850QualType Sema::BuildFunctionType(QualType T,
2851 MutableArrayRef<QualType> ParamTypes,
2852 SourceLocation Loc, DeclarationName Entity,
2853 const FunctionProtoType::ExtProtoInfo &EPI) {
2854 bool Invalid = false;
2855
2856 Invalid |= CheckFunctionReturnType(T, Loc);
2857
2858 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2859 // FIXME: Loc is too inprecise here, should use proper locations for args.
2860 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2861 if (ParamType->isVoidType()) {
2862 Diag(Loc, diag::err_param_with_void_type);
2863 Invalid = true;
2864 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2865 // Disallow half FP arguments.
2866 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2867 FixItHint::CreateInsertion(Loc, "*");
2868 Invalid = true;
2869 }
2870
2871 // C++2a [dcl.fct]p4:
2872 // A parameter with volatile-qualified type is deprecated
2873 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2874 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2875
2876 ParamTypes[Idx] = ParamType;
2877 }
2878
2879 if (EPI.ExtParameterInfos) {
2880 checkExtParameterInfos(*this, ParamTypes, EPI,
2881 [=](unsigned i) { return Loc; });
2882 }
2883
2884 if (EPI.ExtInfo.getProducesResult()) {
2885 // This is just a warning, so we can't fail to build if we see it.
2886 checkNSReturnsRetainedReturnType(Loc, T);
2887 }
2888
2889 if (Invalid)
2890 return QualType();
2891
2892 return Context.getFunctionType(T, ParamTypes, EPI);
2893}
2894
2895/// Build a member pointer type \c T Class::*.
2896///
2897/// \param T the type to which the member pointer refers.
2898/// \param Class the class type into which the member pointer points.
2899/// \param Loc the location where this type begins
2900/// \param Entity the name of the entity that will have this member pointer type
2901///
2902/// \returns a member pointer type, if successful, or a NULL type if there was
2903/// an error.
2904QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2905 SourceLocation Loc,
2906 DeclarationName Entity) {
2907 // Verify that we're not building a pointer to pointer to function with
2908 // exception specification.
2909 if (CheckDistantExceptionSpec(T)) {
2910 Diag(Loc, diag::err_distant_exception_spec);
2911 return QualType();
2912 }
2913
2914 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2915 // with reference type, or "cv void."
2916 if (T->isReferenceType()) {
2917 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2918 << getPrintableNameForEntity(Entity) << T;
2919 return QualType();
2920 }
2921
2922 if (T->isVoidType()) {
2923 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2924 << getPrintableNameForEntity(Entity);
2925 return QualType();
2926 }
2927
2928 if (!Class->isDependentType() && !Class->isRecordType()) {
2929 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2930 return QualType();
2931 }
2932
2933 if (T->isFunctionType() && getLangOpts().OpenCL &&
2934 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2935 getLangOpts())) {
2936 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2937 return QualType();
2938 }
2939
2940 // Adjust the default free function calling convention to the default method
2941 // calling convention.
2942 bool IsCtorOrDtor =
2943 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2944 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2945 if (T->isFunctionType())
2946 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2947
2948 return Context.getMemberPointerType(T, Class.getTypePtr());
2949}
2950
2951/// Build a block pointer type.
2952///
2953/// \param T The type to which we'll be building a block pointer.
2954///
2955/// \param Loc The source location, used for diagnostics.
2956///
2957/// \param Entity The name of the entity that involves the block pointer
2958/// type, if known.
2959///
2960/// \returns A suitable block pointer type, if there are no
2961/// errors. Otherwise, returns a NULL type.
2962QualType Sema::BuildBlockPointerType(QualType T,
2963 SourceLocation Loc,
2964 DeclarationName Entity) {
2965 if (!T->isFunctionType()) {
2966 Diag(Loc, diag::err_nonfunction_block_type);
2967 return QualType();
2968 }
2969
2970 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2971 return QualType();
2972
2973 if (getLangOpts().OpenCL)
2974 T = deduceOpenCLPointeeAddrSpace(*this, T);
2975
2976 return Context.getBlockPointerType(T);
2977}
2978
2979QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2980 QualType QT = Ty.get();
2981 if (QT.isNull()) {
35
Calling 'QualType::isNull'
41
Returning from 'QualType::isNull'
42
Taking false branch
2982 if (TInfo) *TInfo = nullptr;
2983 return QualType();
2984 }
2985
2986 TypeSourceInfo *DI = nullptr;
43
'DI' initialized to a null pointer value
2987 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
44
Assuming 'LIT' is null
45
Taking false branch
2988 QT = LIT->getType();
2989 DI = LIT->getTypeSourceInfo();
2990 }
2991
2992 if (TInfo
45.1
'TInfo' is non-null
45.1
'TInfo' is non-null
45.1
'TInfo' is non-null
45.1
'TInfo' is non-null
45.1
'TInfo' is non-null
) *TInfo = DI;
46
Taking true branch
47
Null pointer value stored to 'TInfo'
2993 return QT;
2994}
2995
2996static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2997 Qualifiers::ObjCLifetime ownership,
2998 unsigned chunkIndex);
2999
3000/// Given that this is the declaration of a parameter under ARC,
3001/// attempt to infer attributes and such for pointer-to-whatever
3002/// types.
3003static void inferARCWriteback(TypeProcessingState &state,
3004 QualType &declSpecType) {
3005 Sema &S = state.getSema();
3006 Declarator &declarator = state.getDeclarator();
3007
3008 // TODO: should we care about decl qualifiers?
3009
3010 // Check whether the declarator has the expected form. We walk
3011 // from the inside out in order to make the block logic work.
3012 unsigned outermostPointerIndex = 0;
3013 bool isBlockPointer = false;
3014 unsigned numPointers = 0;
3015 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3016 unsigned chunkIndex = i;
3017 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3018 switch (chunk.Kind) {
3019 case DeclaratorChunk::Paren:
3020 // Ignore parens.
3021 break;
3022
3023 case DeclaratorChunk::Reference:
3024 case DeclaratorChunk::Pointer:
3025 // Count the number of pointers. Treat references
3026 // interchangeably as pointers; if they're mis-ordered, normal
3027 // type building will discover that.
3028 outermostPointerIndex = chunkIndex;
3029 numPointers++;
3030 break;
3031
3032 case DeclaratorChunk::BlockPointer:
3033 // If we have a pointer to block pointer, that's an acceptable
3034 // indirect reference; anything else is not an application of
3035 // the rules.
3036 if (numPointers != 1) return;
3037 numPointers++;
3038 outermostPointerIndex = chunkIndex;
3039 isBlockPointer = true;
3040
3041 // We don't care about pointer structure in return values here.
3042 goto done;
3043
3044 case DeclaratorChunk::Array: // suppress if written (id[])?
3045 case DeclaratorChunk::Function:
3046 case DeclaratorChunk::MemberPointer:
3047 case DeclaratorChunk::Pipe:
3048 return;
3049 }
3050 }
3051 done:
3052
3053 // If we have *one* pointer, then we want to throw the qualifier on
3054 // the declaration-specifiers, which means that it needs to be a
3055 // retainable object type.
3056 if (numPointers == 1) {
3057 // If it's not a retainable object type, the rule doesn't apply.
3058 if (!declSpecType->isObjCRetainableType()) return;
3059
3060 // If it already has lifetime, don't do anything.
3061 if (declSpecType.getObjCLifetime()) return;
3062
3063 // Otherwise, modify the type in-place.
3064 Qualifiers qs;
3065
3066 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3067 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3068 else
3069 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3070 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3071
3072 // If we have *two* pointers, then we want to throw the qualifier on
3073 // the outermost pointer.
3074 } else if (numPointers == 2) {
3075 // If we don't have a block pointer, we need to check whether the
3076 // declaration-specifiers gave us something that will turn into a
3077 // retainable object pointer after we slap the first pointer on it.
3078 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3079 return;
3080
3081 // Look for an explicit lifetime attribute there.
3082 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3083 if (chunk.Kind != DeclaratorChunk::Pointer &&
3084 chunk.Kind != DeclaratorChunk::BlockPointer)
3085 return;
3086 for (const ParsedAttr &AL : chunk.getAttrs())
3087 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3088 return;
3089
3090 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3091 outermostPointerIndex);
3092
3093 // Any other number of pointers/references does not trigger the rule.
3094 } else return;
3095
3096 // TODO: mark whether we did this inference?
3097}
3098
3099void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3100 SourceLocation FallbackLoc,
3101 SourceLocation ConstQualLoc,
3102 SourceLocation VolatileQualLoc,
3103 SourceLocation RestrictQualLoc,
3104 SourceLocation AtomicQualLoc,
3105 SourceLocation UnalignedQualLoc) {
3106 if (!Quals)
3107 return;
3108
3109 struct Qual {
3110 const char *Name;
3111 unsigned Mask;
3112 SourceLocation Loc;
3113 } const QualKinds[5] = {
3114 { "const", DeclSpec::TQ_const, ConstQualLoc },
3115 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3116 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3117 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3118 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3119 };
3120
3121 SmallString<32> QualStr;
3122 unsigned NumQuals = 0;
3123 SourceLocation Loc;
3124 FixItHint FixIts[5];
3125
3126 // Build a string naming the redundant qualifiers.
3127 for (auto &E : QualKinds) {
3128 if (Quals & E.Mask) {
3129 if (!QualStr.empty()) QualStr += ' ';
3130 QualStr += E.Name;
3131
3132 // If we have a location for the qualifier, offer a fixit.
3133 SourceLocation QualLoc = E.Loc;
3134 if (QualLoc.isValid()) {
3135 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3136 if (Loc.isInvalid() ||
3137 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3138 Loc = QualLoc;
3139 }
3140
3141 ++NumQuals;
3142 }
3143 }
3144
3145 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3146 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3147}
3148
3149// Diagnose pointless type qualifiers on the return type of a function.
3150static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3151 Declarator &D,
3152 unsigned FunctionChunkIndex) {
3153 const DeclaratorChunk::FunctionTypeInfo &FTI =
3154 D.getTypeObject(FunctionChunkIndex).Fun;
3155 if (FTI.hasTrailingReturnType()) {
3156 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3157 RetTy.getLocalCVRQualifiers(),
3158 FTI.getTrailingReturnTypeLoc());
3159 return;
3160 }
3161
3162 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3163 End = D.getNumTypeObjects();
3164 OuterChunkIndex != End; ++OuterChunkIndex) {
3165 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3166 switch (OuterChunk.Kind) {
3167 case DeclaratorChunk::Paren:
3168 continue;
3169
3170 case DeclaratorChunk::Pointer: {
3171 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3172 S.diagnoseIgnoredQualifiers(
3173 diag::warn_qual_return_type,
3174 PTI.TypeQuals,
3175 SourceLocation(),
3176 PTI.ConstQualLoc,
3177 PTI.VolatileQualLoc,
3178 PTI.RestrictQualLoc,
3179 PTI.AtomicQualLoc,
3180 PTI.UnalignedQualLoc);
3181 return;
3182 }
3183
3184 case DeclaratorChunk::Function:
3185 case DeclaratorChunk::BlockPointer:
3186 case DeclaratorChunk::Reference:
3187 case DeclaratorChunk::Array:
3188 case DeclaratorChunk::MemberPointer:
3189 case DeclaratorChunk::Pipe:
3190 // FIXME: We can't currently provide an accurate source location and a
3191 // fix-it hint for these.
3192 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3193 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3194 RetTy.getCVRQualifiers() | AtomicQual,
3195 D.getIdentifierLoc());
3196 return;
3197 }
3198
3199 llvm_unreachable("unknown declarator chunk kind")__builtin_unreachable();
3200 }
3201
3202 // If the qualifiers come from a conversion function type, don't diagnose
3203 // them -- they're not necessarily redundant, since such a conversion
3204 // operator can be explicitly called as "x.operator const int()".
3205 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3206 return;
3207
3208 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3209 // which are present there.
3210 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3211 D.getDeclSpec().getTypeQualifiers(),
3212 D.getIdentifierLoc(),
3213 D.getDeclSpec().getConstSpecLoc(),
3214 D.getDeclSpec().getVolatileSpecLoc(),
3215 D.getDeclSpec().getRestrictSpecLoc(),
3216 D.getDeclSpec().getAtomicSpecLoc(),
3217 D.getDeclSpec().getUnalignedSpecLoc());
3218}
3219
3220static std::pair<QualType, TypeSourceInfo *>
3221InventTemplateParameter(TypeProcessingState &state, QualType T,
3222 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3223 InventedTemplateParameterInfo &Info) {
3224 Sema &S = state.getSema();
3225 Declarator &D = state.getDeclarator();
3226
3227 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3228 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3229 const bool IsParameterPack = D.hasEllipsis();
3230
3231 // If auto is mentioned in a lambda parameter or abbreviated function
3232 // template context, convert it to a template parameter type.
3233
3234 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3235 // template parameter type. Template parameters are temporarily added
3236 // to the TU until the associated TemplateDecl is created.
3237 TemplateTypeParmDecl *InventedTemplateParam =
3238 TemplateTypeParmDecl::Create(
3239 S.Context, S.Context.getTranslationUnitDecl(),
3240 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3241 /*NameLoc=*/D.getIdentifierLoc(),
3242 TemplateParameterDepth, AutoParameterPosition,
3243 S.InventAbbreviatedTemplateParameterTypeName(
3244 D.getIdentifier(), AutoParameterPosition), false,
3245 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3246 InventedTemplateParam->setImplicit();
3247 Info.TemplateParams.push_back(InventedTemplateParam);
3248
3249 // Attach type constraints to the new parameter.
3250 if (Auto->isConstrained()) {
3251 if (TrailingTSI) {
3252 // The 'auto' appears in a trailing return type we've already built;
3253 // extract its type constraints to attach to the template parameter.
3254 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3255 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3256 bool Invalid = false;
3257 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3258 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3259 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3260 Sema::UPPC_TypeConstraint))
3261 Invalid = true;
3262 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3263 }
3264
3265 if (!Invalid) {
3266 S.AttachTypeConstraint(
3267 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3268 AutoLoc.getNamedConcept(),
3269 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3270 InventedTemplateParam, D.getEllipsisLoc());
3271 }
3272 } else {
3273 // The 'auto' appears in the decl-specifiers; we've not finished forming
3274 // TypeSourceInfo for it yet.
3275 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3276 TemplateArgumentListInfo TemplateArgsInfo;
3277 bool Invalid = false;
3278 if (TemplateId->LAngleLoc.isValid()) {
3279 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3280 TemplateId->NumArgs);
3281 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3282
3283 if (D.getEllipsisLoc().isInvalid()) {
3284 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3285 if (S.DiagnoseUnexpandedParameterPack(Arg,
3286 Sema::UPPC_TypeConstraint)) {
3287 Invalid = true;
3288 break;
3289 }
3290 }
3291 }
3292 }
3293 if (!Invalid) {
3294 S.AttachTypeConstraint(
3295 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3296 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3297 TemplateId->TemplateNameLoc),
3298 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3299 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3300 InventedTemplateParam, D.getEllipsisLoc());
3301 }
3302 }
3303 }
3304
3305 // Replace the 'auto' in the function parameter with this invented
3306 // template type parameter.
3307 // FIXME: Retain some type sugar to indicate that this was written
3308 // as 'auto'?
3309 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3310 QualType NewT = state.ReplaceAutoType(T, Replacement);
3311 TypeSourceInfo *NewTSI =
3312 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3313 : nullptr;
3314 return {NewT, NewTSI};
3315}
3316
3317static TypeSourceInfo *
3318GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3319 QualType T, TypeSourceInfo *ReturnTypeInfo);
3320
3321static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3322 TypeSourceInfo *&ReturnTypeInfo) {
3323 Sema &SemaRef = state.getSema();
3324 Declarator &D = state.getDeclarator();
3325 QualType T;
3326 ReturnTypeInfo = nullptr;
3327
3328 // The TagDecl owned by the DeclSpec.
3329 TagDecl *OwnedTagDecl = nullptr;
3330
3331 switch (D.getName().getKind()) {
3332 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3333 case UnqualifiedIdKind::IK_OperatorFunctionId:
3334 case UnqualifiedIdKind::IK_Identifier:
3335 case UnqualifiedIdKind::IK_LiteralOperatorId:
3336 case UnqualifiedIdKind::IK_TemplateId:
3337 T = ConvertDeclSpecToType(state);
3338
3339 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3340 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3341 // Owned declaration is embedded in declarator.
3342 OwnedTagDecl->setEmbeddedInDeclarator(true);
3343 }
3344 break;
3345
3346 case UnqualifiedIdKind::IK_ConstructorName:
3347 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3348 case UnqualifiedIdKind::IK_DestructorName:
3349 // Constructors and destructors don't have return types. Use
3350 // "void" instead.
3351 T = SemaRef.Context.VoidTy;
3352 processTypeAttrs(state, T, TAL_DeclSpec,
3353 D.getMutableDeclSpec().getAttributes());
3354 break;
3355
3356 case UnqualifiedIdKind::IK_DeductionGuideName:
3357 // Deduction guides have a trailing return type and no type in their
3358 // decl-specifier sequence. Use a placeholder return type for now.
3359 T = SemaRef.Context.DependentTy;
3360 break;
3361
3362 case UnqualifiedIdKind::IK_ConversionFunctionId:
3363 // The result type of a conversion function is the type that it
3364 // converts to.
3365 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3366 &ReturnTypeInfo);
3367 break;
3368 }
3369
3370 if (!D.getAttributes().empty())
3371 distributeTypeAttrsFromDeclarator(state, T);
3372
3373 // Find the deduced type in this type. Look in the trailing return type if we
3374 // have one, otherwise in the DeclSpec type.
3375 // FIXME: The standard wording doesn't currently describe this.
3376 DeducedType *Deduced = T->getContainedDeducedType();
3377 bool DeducedIsTrailingReturnType = false;
3378 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3379 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3380 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3381 DeducedIsTrailingReturnType = true;
3382 }
3383
3384 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3385 if (Deduced) {
3386 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3387 int Error = -1;
3388
3389 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3390 // class template argument deduction)?
3391 bool IsCXXAutoType =
3392 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3393 bool IsDeducedReturnType = false;
3394
3395 switch (D.getContext()) {
3396 case DeclaratorContext::LambdaExpr:
3397 // Declared return type of a lambda-declarator is implicit and is always
3398 // 'auto'.
3399 break;
3400 case DeclaratorContext::ObjCParameter:
3401 case DeclaratorContext::ObjCResult:
3402 Error = 0;
3403 break;
3404 case DeclaratorContext::RequiresExpr:
3405 Error = 22;
3406 break;
3407 case DeclaratorContext::Prototype:
3408 case DeclaratorContext::LambdaExprParameter: {
3409 InventedTemplateParameterInfo *Info = nullptr;
3410 if (D.getContext() == DeclaratorContext::Prototype) {
3411 // With concepts we allow 'auto' in function parameters.
3412 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3413 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3414 Error = 0;
3415 break;
3416 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3417 Error = 21;
3418 break;
3419 }
3420
3421 Info = &SemaRef.InventedParameterInfos.back();
3422 } else {
3423 // In C++14, generic lambdas allow 'auto' in their parameters.
3424 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3425 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3426 Error = 16;
3427 break;
3428 }
3429 Info = SemaRef.getCurLambda();
3430 assert(Info && "No LambdaScopeInfo on the stack!")((void)0);
3431 }
3432
3433 // We'll deal with inventing template parameters for 'auto' in trailing
3434 // return types when we pick up the trailing return type when processing
3435 // the function chunk.
3436 if (!DeducedIsTrailingReturnType)
3437 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3438 break;
3439 }
3440 case DeclaratorContext::Member: {
3441 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3442 D.isFunctionDeclarator())
3443 break;
3444 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3445 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3446 Error = 6; // Interface member.
3447 } else {
3448 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3449 case TTK_Enum: llvm_unreachable("unhandled tag kind")__builtin_unreachable();
3450 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3451 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3452 case TTK_Class: Error = 5; /* Class member */ break;
3453 case TTK_Interface: Error = 6; /* Interface member */ break;
3454 }
3455 }
3456 if (D.getDeclSpec().isFriendSpecified())
3457 Error = 20; // Friend type
3458 break;
3459 }
3460 case DeclaratorContext::CXXCatch:
3461 case DeclaratorContext::ObjCCatch:
3462 Error = 7; // Exception declaration
3463 break;
3464 case DeclaratorContext::TemplateParam:
3465 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3466 !SemaRef.getLangOpts().CPlusPlus20)
3467 Error = 19; // Template parameter (until C++20)
3468 else if (!SemaRef.getLangOpts().CPlusPlus17)
3469 Error = 8; // Template parameter (until C++17)
3470 break;
3471 case DeclaratorContext::BlockLiteral:
3472 Error = 9; // Block literal
3473 break;
3474 case DeclaratorContext::TemplateArg:
3475 // Within a template argument list, a deduced template specialization
3476 // type will be reinterpreted as a template template argument.
3477 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3478 !D.getNumTypeObjects() &&
3479 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3480 break;
3481 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3482 case DeclaratorContext::TemplateTypeArg:
3483 Error = 10; // Template type argument
3484 break;
3485 case DeclaratorContext::AliasDecl:
3486 case DeclaratorContext::AliasTemplate:
3487 Error = 12; // Type alias
3488 break;
3489 case DeclaratorContext::TrailingReturn:
3490 case DeclaratorContext::TrailingReturnVar:
3491 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3492 Error = 13; // Function return type
3493 IsDeducedReturnType = true;
3494 break;
3495 case DeclaratorContext::ConversionId:
3496 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3497 Error = 14; // conversion-type-id
3498 IsDeducedReturnType = true;
3499 break;
3500 case DeclaratorContext::FunctionalCast:
3501 if (isa<DeducedTemplateSpecializationType>(Deduced))
3502 break;
3503 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3504 case DeclaratorContext::TypeName:
3505 Error = 15; // Generic
3506 break;
3507 case DeclaratorContext::File:
3508 case DeclaratorContext::Block:
3509 case DeclaratorContext::ForInit:
3510 case DeclaratorContext::SelectionInit:
3511 case DeclaratorContext::Condition:
3512 // FIXME: P0091R3 (erroneously) does not permit class template argument
3513 // deduction in conditions, for-init-statements, and other declarations
3514 // that are not simple-declarations.
3515 break;
3516 case DeclaratorContext::CXXNew:
3517 // FIXME: P0091R3 does not permit class template argument deduction here,
3518 // but we follow GCC and allow it anyway.
3519 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3520 Error = 17; // 'new' type
3521 break;
3522 case DeclaratorContext::KNRTypeList:
3523 Error = 18; // K&R function parameter
3524 break;
3525 }
3526
3527 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3528 Error = 11;
3529
3530 // In Objective-C it is an error to use 'auto' on a function declarator
3531 // (and everywhere for '__auto_type').
3532 if (D.isFunctionDeclarator() &&
3533 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3534 Error = 13;
3535
3536 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3537 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3538 AutoRange = D.getName().getSourceRange();
3539
3540 if (Error != -1) {
3541 unsigned Kind;
3542 if (Auto) {
3543 switch (Auto->getKeyword()) {
3544 case AutoTypeKeyword::Auto: Kind = 0; break;
3545 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3546 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3547 }
3548 } else {
3549 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&((void)0)
3550 "unknown auto type")((void)0);
3551 Kind = 3;
3552 }
3553
3554 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3555 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3556
3557 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3558 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3559 << QualType(Deduced, 0) << AutoRange;
3560 if (auto *TD = TN.getAsTemplateDecl())
3561 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3562
3563 T = SemaRef.Context.IntTy;
3564 D.setInvalidType(true);
3565 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3566 // If there was a trailing return type, we already got
3567 // warn_cxx98_compat_trailing_return_type in the parser.
3568 SemaRef.Diag(AutoRange.getBegin(),
3569 D.getContext() == DeclaratorContext::LambdaExprParameter
3570 ? diag::warn_cxx11_compat_generic_lambda
3571 : IsDeducedReturnType
3572 ? diag::warn_cxx11_compat_deduced_return_type
3573 : diag::warn_cxx98_compat_auto_type_specifier)
3574 << AutoRange;
3575 }
3576 }
3577
3578 if (SemaRef.getLangOpts().CPlusPlus &&
3579 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3580 // Check the contexts where C++ forbids the declaration of a new class
3581 // or enumeration in a type-specifier-seq.
3582 unsigned DiagID = 0;
3583 switch (D.getContext()) {
3584 case DeclaratorContext::TrailingReturn:
3585 case DeclaratorContext::TrailingReturnVar:
3586 // Class and enumeration definitions are syntactically not allowed in
3587 // trailing return types.
3588 llvm_unreachable("parser should not have allowed this")__builtin_unreachable();
3589 break;
3590 case DeclaratorContext::File:
3591 case DeclaratorContext::Member:
3592 case DeclaratorContext::Block:
3593 case DeclaratorContext::ForInit:
3594 case DeclaratorContext::SelectionInit:
3595 case DeclaratorContext::BlockLiteral:
3596 case DeclaratorContext::LambdaExpr:
3597 // C++11 [dcl.type]p3:
3598 // A type-specifier-seq shall not define a class or enumeration unless
3599 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3600 // the declaration of a template-declaration.
3601 case DeclaratorContext::AliasDecl:
3602 break;
3603 case DeclaratorContext::AliasTemplate:
3604 DiagID = diag::err_type_defined_in_alias_template;
3605 break;
3606 case DeclaratorContext::TypeName:
3607 case DeclaratorContext::FunctionalCast:
3608 case DeclaratorContext::ConversionId:
3609 case DeclaratorContext::TemplateParam:
3610 case DeclaratorContext::CXXNew:
3611 case DeclaratorContext::CXXCatch:
3612 case DeclaratorContext::ObjCCatch:
3613 case DeclaratorContext::TemplateArg:
3614 case DeclaratorContext::TemplateTypeArg:
3615 DiagID = diag::err_type_defined_in_type_specifier;
3616 break;
3617 case DeclaratorContext::Prototype:
3618 case DeclaratorContext::LambdaExprParameter:
3619 case DeclaratorContext::ObjCParameter:
3620 case DeclaratorContext::ObjCResult:
3621 case DeclaratorContext::KNRTypeList:
3622 case DeclaratorContext::RequiresExpr:
3623 // C++ [dcl.fct]p6:
3624 // Types shall not be defined in return or parameter types.
3625 DiagID = diag::err_type_defined_in_param_type;
3626 break;
3627 case DeclaratorContext::Condition:
3628 // C++ 6.4p2:
3629 // The type-specifier-seq shall not contain typedef and shall not declare
3630 // a new class or enumeration.
3631 DiagID = diag::err_type_defined_in_condition;
3632 break;
3633 }
3634
3635 if (DiagID != 0) {
3636 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3637 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3638 D.setInvalidType(true);
3639 }
3640 }
3641
3642 assert(!T.isNull() && "This function should not return a null type")((void)0);
3643 return T;
3644}
3645
3646/// Produce an appropriate diagnostic for an ambiguity between a function
3647/// declarator and a C++ direct-initializer.
3648static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3649 DeclaratorChunk &DeclType, QualType RT) {
3650 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3651 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")((void)0);
3652
3653 // If the return type is void there is no ambiguity.
3654 if (RT->isVoidType())
3655 return;
3656
3657 // An initializer for a non-class type can have at most one argument.
3658 if (!RT->isRecordType() && FTI.NumParams > 1)
3659 return;
3660
3661 // An initializer for a reference must have exactly one argument.
3662 if (RT->isReferenceType() && FTI.NumParams != 1)
3663 return;
3664
3665 // Only warn if this declarator is declaring a function at block scope, and
3666 // doesn't have a storage class (such as 'extern') specified.
3667 if (!D.isFunctionDeclarator() ||
3668 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3669 !S.CurContext->isFunctionOrMethod() ||
3670 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3671 return;
3672
3673 // Inside a condition, a direct initializer is not permitted. We allow one to
3674 // be parsed in order to give better diagnostics in condition parsing.
3675 if (D.getContext() == DeclaratorContext::Condition)
3676 return;
3677
3678 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3679
3680 S.Diag(DeclType.Loc,
3681 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3682 : diag::warn_empty_parens_are_function_decl)
3683 << ParenRange;
3684
3685 // If the declaration looks like:
3686 // T var1,
3687 // f();
3688 // and name lookup finds a function named 'f', then the ',' was
3689 // probably intended to be a ';'.
3690 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3691 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3692 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3693 if (Comma.getFileID() != Name.getFileID() ||
3694 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3695 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3696 Sema::LookupOrdinaryName);
3697 if (S.LookupName(Result, S.getCurScope()))
3698 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3699 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3700 << D.getIdentifier();
3701 Result.suppressDiagnostics();
3702 }
3703 }
3704
3705 if (FTI.NumParams > 0) {
3706 // For a declaration with parameters, eg. "T var(T());", suggest adding
3707 // parens around the first parameter to turn the declaration into a
3708 // variable declaration.
3709 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3710 SourceLocation B = Range.getBegin();
3711 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3712 // FIXME: Maybe we should suggest adding braces instead of parens
3713 // in C++11 for classes that don't have an initializer_list constructor.
3714 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3715 << FixItHint::CreateInsertion(B, "(")
3716 << FixItHint::CreateInsertion(E, ")");
3717 } else {
3718 // For a declaration without parameters, eg. "T var();", suggest replacing
3719 // the parens with an initializer to turn the declaration into a variable
3720 // declaration.
3721 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3722
3723 // Empty parens mean value-initialization, and no parens mean
3724 // default initialization. These are equivalent if the default
3725 // constructor is user-provided or if zero-initialization is a
3726 // no-op.
3727 if (RD && RD->hasDefinition() &&
3728 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3729 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3730 << FixItHint::CreateRemoval(ParenRange);
3731 else {
3732 std::string Init =
3733 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3734 if (Init.empty() && S.LangOpts.CPlusPlus11)
3735 Init = "{}";
3736 if (!Init.empty())
3737 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3738 << FixItHint::CreateReplacement(ParenRange, Init);
3739 }
3740 }
3741}
3742
3743/// Produce an appropriate diagnostic for a declarator with top-level
3744/// parentheses.
3745static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3746 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3747 assert(Paren.Kind == DeclaratorChunk::Paren &&((void)0)
3748 "do not have redundant top-level parentheses")((void)0);
3749
3750 // This is a syntactic check; we're not interested in cases that arise
3751 // during template instantiation.
3752 if (S.inTemplateInstantiation())
3753 return;
3754
3755 // Check whether this could be intended to be a construction of a temporary
3756 // object in C++ via a function-style cast.
3757 bool CouldBeTemporaryObject =
3758 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3759 !D.isInvalidType() && D.getIdentifier() &&
3760 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3761 (T->isRecordType() || T->isDependentType()) &&
3762 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3763
3764 bool StartsWithDeclaratorId = true;
3765 for (auto &C : D.type_objects()) {
3766 switch (C.Kind) {
3767 case DeclaratorChunk::Paren:
3768 if (&C == &Paren)
3769 continue;
3770 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3771 case DeclaratorChunk::Pointer:
3772 StartsWithDeclaratorId = false;
3773 continue;
3774
3775 case DeclaratorChunk::Array:
3776 if (!C.Arr.NumElts)
3777 CouldBeTemporaryObject = false;
3778 continue;
3779
3780 case DeclaratorChunk::Reference:
3781 // FIXME: Suppress the warning here if there is no initializer; we're
3782 // going to give an error anyway.
3783 // We assume that something like 'T (&x) = y;' is highly likely to not
3784 // be intended to be a temporary object.
3785 CouldBeTemporaryObject = false;
3786 StartsWithDeclaratorId = false;
3787 continue;
3788
3789 case DeclaratorChunk::Function:
3790 // In a new-type-id, function chunks require parentheses.
3791 if (D.getContext() == DeclaratorContext::CXXNew)
3792 return;
3793 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3794 // redundant-parens warning, but we don't know whether the function
3795 // chunk was syntactically valid as an expression here.
3796 CouldBeTemporaryObject = false;
3797 continue;
3798
3799 case DeclaratorChunk::BlockPointer:
3800 case DeclaratorChunk::MemberPointer:
3801 case DeclaratorChunk::Pipe:
3802 // These cannot appear in expressions.
3803 CouldBeTemporaryObject = false;
3804 StartsWithDeclaratorId = false;
3805 continue;
3806 }
3807 }
3808
3809 // FIXME: If there is an initializer, assume that this is not intended to be
3810 // a construction of a temporary object.
3811
3812 // Check whether the name has already been declared; if not, this is not a
3813 // function-style cast.
3814 if (CouldBeTemporaryObject) {
3815 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3816 Sema::LookupOrdinaryName);
3817 if (!S.LookupName(Result, S.getCurScope()))
3818 CouldBeTemporaryObject = false;
3819 Result.suppressDiagnostics();
3820 }
3821
3822 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3823
3824 if (!CouldBeTemporaryObject) {
3825 // If we have A (::B), the parentheses affect the meaning of the program.
3826 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3827 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3828 // formally unambiguous.
3829 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3830 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3831 NNS = NNS->getPrefix()) {
3832 if (NNS->getKind() == NestedNameSpecifier::Global)
3833 return;
3834 }
3835 }
3836
3837 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3838 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3839 << FixItHint::CreateRemoval(Paren.EndLoc);
3840 return;
3841 }
3842
3843 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3844 << ParenRange << D.getIdentifier();
3845 auto *RD = T->getAsCXXRecordDecl();
3846 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3847 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3848 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3849 << D.getIdentifier();
3850 // FIXME: A cast to void is probably a better suggestion in cases where it's
3851 // valid (when there is no initializer and we're not in a condition).
3852 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3853 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3854 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3855 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3856 << FixItHint::CreateRemoval(Paren.Loc)
3857 << FixItHint::CreateRemoval(Paren.EndLoc);
3858}
3859
3860/// Helper for figuring out the default CC for a function declarator type. If
3861/// this is the outermost chunk, then we can determine the CC from the
3862/// declarator context. If not, then this could be either a member function
3863/// type or normal function type.
3864static CallingConv getCCForDeclaratorChunk(
3865 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3866 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3867 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)((void)0);
3868
3869 // Check for an explicit CC attribute.
3870 for (const ParsedAttr &AL : AttrList) {
3871 switch (AL.getKind()) {
3872 CALLING_CONV_ATTRS_CASELISTcase ParsedAttr::AT_CDecl: case ParsedAttr::AT_FastCall: case
ParsedAttr::AT_StdCall: case ParsedAttr::AT_ThisCall: case ParsedAttr
::AT_RegCall: case ParsedAttr::AT_Pascal: case ParsedAttr::AT_SwiftCall
: case ParsedAttr::AT_SwiftAsyncCall: case ParsedAttr::AT_VectorCall
: case ParsedAttr::AT_AArch64VectorPcs: case ParsedAttr::AT_MSABI
: case ParsedAttr::AT_SysVABI: case ParsedAttr::AT_Pcs: case ParsedAttr
::AT_IntelOclBicc: case ParsedAttr::AT_PreserveMost: case ParsedAttr
::AT_PreserveAll
: {
3873 // Ignore attributes that don't validate or can't apply to the
3874 // function type. We'll diagnose the failure to apply them in
3875 // handleFunctionTypeAttr.
3876 CallingConv CC;
3877 if (!S.CheckCallingConvAttr(AL, CC) &&
3878 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3879 return CC;
3880 }
3881 break;
3882 }
3883
3884 default:
3885 break;
3886 }
3887 }
3888
3889 bool IsCXXInstanceMethod = false;
3890
3891 if (S.getLangOpts().CPlusPlus) {
3892 // Look inwards through parentheses to see if this chunk will form a
3893 // member pointer type or if we're the declarator. Any type attributes
3894 // between here and there will override the CC we choose here.
3895 unsigned I = ChunkIndex;
3896 bool FoundNonParen = false;
3897 while (I && !FoundNonParen) {
3898 --I;
3899 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3900 FoundNonParen = true;
3901 }
3902
3903 if (FoundNonParen) {
3904 // If we're not the declarator, we're a regular function type unless we're
3905 // in a member pointer.
3906 IsCXXInstanceMethod =
3907 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3908 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3909 // This can only be a call operator for a lambda, which is an instance
3910 // method.
3911 IsCXXInstanceMethod = true;
3912 } else {
3913 // We're the innermost decl chunk, so must be a function declarator.
3914 assert(D.isFunctionDeclarator())((void)0);
3915
3916 // If we're inside a record, we're declaring a method, but it could be
3917 // explicitly or implicitly static.
3918 IsCXXInstanceMethod =
3919 D.isFirstDeclarationOfMember() &&
3920 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3921 !D.isStaticMember();
3922 }
3923 }
3924
3925 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3926 IsCXXInstanceMethod);
3927
3928 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3929 // and AMDGPU targets, hence it cannot be treated as a calling
3930 // convention attribute. This is the simplest place to infer
3931 // calling convention for OpenCL kernels.
3932 if (S.getLangOpts().OpenCL) {
3933 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3934 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3935 CC = CC_OpenCLKernel;
3936 break;
3937 }
3938 }
3939 }
3940
3941 return CC;
3942}
3943
3944namespace {
3945 /// A simple notion of pointer kinds, which matches up with the various
3946 /// pointer declarators.
3947 enum class SimplePointerKind {
3948 Pointer,
3949 BlockPointer,
3950 MemberPointer,
3951 Array,
3952 };
3953} // end anonymous namespace
3954
3955IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3956 switch (nullability) {
3957 case NullabilityKind::NonNull:
3958 if (!Ident__Nonnull)
3959 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3960 return Ident__Nonnull;
3961
3962 case NullabilityKind::Nullable:
3963 if (!Ident__Nullable)
3964 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3965 return Ident__Nullable;
3966
3967 case NullabilityKind::NullableResult:
3968 if (!Ident__Nullable_result)
3969 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3970 return Ident__Nullable_result;
3971
3972 case NullabilityKind::Unspecified:
3973 if (!Ident__Null_unspecified)
3974 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3975 return Ident__Null_unspecified;
3976 }
3977 llvm_unreachable("Unknown nullability kind.")__builtin_unreachable();
3978}
3979
3980/// Retrieve the identifier "NSError".
3981IdentifierInfo *Sema::getNSErrorIdent() {
3982 if (!Ident_NSError)
3983 Ident_NSError = PP.getIdentifierInfo("NSError");
3984
3985 return Ident_NSError;
3986}
3987
3988/// Check whether there is a nullability attribute of any kind in the given
3989/// attribute list.
3990static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3991 for (const ParsedAttr &AL : attrs) {
3992 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3993 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3994 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3995 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3996 return true;
3997 }
3998
3999 return false;
4000}
4001
4002namespace {
4003 /// Describes the kind of a pointer a declarator describes.
4004 enum class PointerDeclaratorKind {
4005 // Not a pointer.
4006 NonPointer,
4007 // Single-level pointer.
4008 SingleLevelPointer,
4009 // Multi-level pointer (of any pointer kind).
4010 MultiLevelPointer,
4011 // CFFooRef*
4012 MaybePointerToCFRef,
4013 // CFErrorRef*
4014 CFErrorRefPointer,
4015 // NSError**
4016 NSErrorPointerPointer,
4017 };
4018
4019 /// Describes a declarator chunk wrapping a pointer that marks inference as
4020 /// unexpected.
4021 // These values must be kept in sync with diagnostics.
4022 enum class PointerWrappingDeclaratorKind {
4023 /// Pointer is top-level.
4024 None = -1,
4025 /// Pointer is an array element.
4026 Array = 0,
4027 /// Pointer is the referent type of a C++ reference.
4028 Reference = 1
4029 };
4030} // end anonymous namespace
4031
4032/// Classify the given declarator, whose type-specified is \c type, based on
4033/// what kind of pointer it refers to.
4034///
4035/// This is used to determine the default nullability.
4036static PointerDeclaratorKind
4037classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4038 PointerWrappingDeclaratorKind &wrappingKind) {
4039 unsigned numNormalPointers = 0;
4040
4041 // For any dependent type, we consider it a non-pointer.
4042 if (type->isDependentType())
4043 return PointerDeclaratorKind::NonPointer;
4044
4045 // Look through the declarator chunks to identify pointers.
4046 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4047 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4048 switch (chunk.Kind) {
4049 case DeclaratorChunk::Array:
4050 if (numNormalPointers == 0)
4051 wrappingKind = PointerWrappingDeclaratorKind::Array;
4052 break;
4053
4054 case DeclaratorChunk::Function:
4055 case DeclaratorChunk::Pipe:
4056 break;
4057
4058 case DeclaratorChunk::BlockPointer:
4059 case DeclaratorChunk::MemberPointer:
4060 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4061 : PointerDeclaratorKind::SingleLevelPointer;
4062
4063 case DeclaratorChunk::Paren:
4064 break;
4065
4066 case DeclaratorChunk::Reference:
4067 if (numNormalPointers == 0)
4068 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4069 break;
4070
4071 case DeclaratorChunk::Pointer:
4072 ++numNormalPointers;
4073 if (numNormalPointers > 2)
4074 return PointerDeclaratorKind::MultiLevelPointer;
4075 break;
4076 }
4077 }
4078
4079 // Then, dig into the type specifier itself.
4080 unsigned numTypeSpecifierPointers = 0;
4081 do {
4082 // Decompose normal pointers.
4083 if (auto ptrType = type->getAs<PointerType>()) {
4084 ++numNormalPointers;
4085
4086 if (numNormalPointers > 2)
4087 return PointerDeclaratorKind::MultiLevelPointer;
4088
4089 type = ptrType->getPointeeType();
4090 ++numTypeSpecifierPointers;
4091 continue;
4092 }
4093
4094 // Decompose block pointers.
4095 if (type->getAs<BlockPointerType>()) {
4096 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4097 : PointerDeclaratorKind::SingleLevelPointer;
4098 }
4099
4100 // Decompose member pointers.
4101 if (type->getAs<MemberPointerType>()) {
4102 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4103 : PointerDeclaratorKind::SingleLevelPointer;
4104 }
4105
4106 // Look at Objective-C object pointers.
4107 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4108 ++numNormalPointers;
4109 ++numTypeSpecifierPointers;
4110
4111 // If this is NSError**, report that.
4112 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4113 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4114 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4115 return PointerDeclaratorKind::NSErrorPointerPointer;
4116 }
4117 }
4118
4119 break;
4120 }
4121
4122 // Look at Objective-C class types.
4123 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4124 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4125 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4126 return PointerDeclaratorKind::NSErrorPointerPointer;
4127 }
4128
4129 break;
4130 }
4131
4132 // If at this point we haven't seen a pointer, we won't see one.
4133 if (numNormalPointers == 0)
4134 return PointerDeclaratorKind::NonPointer;
4135
4136 if (auto recordType = type->getAs<RecordType>()) {
4137 RecordDecl *recordDecl = recordType->getDecl();
4138
4139 // If this is CFErrorRef*, report it as such.
4140 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4141 S.isCFError(recordDecl)) {
4142 return PointerDeclaratorKind::CFErrorRefPointer;
4143 }
4144 break;
4145 }
4146
4147 break;
4148 } while (true);
4149
4150 switch (numNormalPointers) {
4151 case 0:
4152 return PointerDeclaratorKind::NonPointer;
4153
4154 case 1:
4155 return PointerDeclaratorKind::SingleLevelPointer;
4156
4157 case 2:
4158 return PointerDeclaratorKind::MaybePointerToCFRef;
4159
4160 default:
4161 return PointerDeclaratorKind::MultiLevelPointer;
4162 }
4163}
4164
4165bool Sema::isCFError(RecordDecl *RD) {
4166 // If we already know about CFError, test it directly.
4167 if (CFError)
4168 return CFError == RD;
4169
4170 // Check whether this is CFError, which we identify based on its bridge to
4171 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4172 // declared with "objc_bridge_mutable", so look for either one of the two
4173 // attributes.
4174 if (RD->getTagKind() == TTK_Struct) {
4175 IdentifierInfo *bridgedType = nullptr;
4176 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4177 bridgedType = bridgeAttr->getBridgedType();
4178 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4179 bridgedType = bridgeAttr->getBridgedType();
4180
4181 if (bridgedType == getNSErrorIdent()) {
4182 CFError = RD;
4183 return true;
4184 }
4185 }
4186
4187 return false;
4188}
4189
4190static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4191 SourceLocation loc) {
4192 // If we're anywhere in a function, method, or closure context, don't perform
4193 // completeness checks.
4194 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4195 if (ctx->isFunctionOrMethod())
4196 return FileID();
4197
4198 if (ctx->isFileContext())
4199 break;
4200 }
4201
4202 // We only care about the expansion location.
4203 loc = S.SourceMgr.getExpansionLoc(loc);
4204 FileID file = S.SourceMgr.getFileID(loc);
4205 if (file.isInvalid())
4206 return FileID();
4207
4208 // Retrieve file information.
4209 bool invalid = false;
4210 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4211 if (invalid || !sloc.isFile())
4212 return FileID();
4213
4214 // We don't want to perform completeness checks on the main file or in
4215 // system headers.
4216 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4217 if (fileInfo.getIncludeLoc().isInvalid())
4218 return FileID();
4219 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4220 S.Diags.getSuppressSystemWarnings()) {
4221 return FileID();
4222 }
4223
4224 return file;
4225}
4226
4227/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4228/// taking into account whitespace before and after.
4229template <typename DiagBuilderT>
4230static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4231 SourceLocation PointerLoc,
4232 NullabilityKind Nullability) {
4233 assert(PointerLoc.isValid())((void)0);
4234 if (PointerLoc.isMacroID())
4235 return;
4236
4237 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4238 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4239 return;
4240
4241 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4242 if (!NextChar)
4243 return;
4244
4245 SmallString<32> InsertionTextBuf{" "};
4246 InsertionTextBuf += getNullabilitySpelling(Nullability);
4247 InsertionTextBuf += " ";
4248 StringRef InsertionText = InsertionTextBuf.str();
4249
4250 if (isWhitespace(*NextChar)) {
4251 InsertionText = InsertionText.drop_back();
4252 } else if (NextChar[-1] == '[') {
4253 if (NextChar[0] == ']')
4254 InsertionText = InsertionText.drop_back().drop_front();
4255 else
4256 InsertionText = InsertionText.drop_front();
4257 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
4258 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
4259 InsertionText = InsertionText.drop_back().drop_front();
4260 }
4261
4262 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4263}
4264
4265static void emitNullabilityConsistencyWarning(Sema &S,
4266 SimplePointerKind PointerKind,
4267 SourceLocation PointerLoc,
4268 SourceLocation PointerEndLoc) {
4269 assert(PointerLoc.isValid())((void)0);
4270
4271 if (PointerKind == SimplePointerKind::Array) {
4272 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4273 } else {
4274 S.Diag(PointerLoc, diag::warn_nullability_missing)
4275 << static_cast<unsigned>(PointerKind);
4276 }
4277
4278 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4279 if (FixItLoc.isMacroID())
4280 return;
4281
4282 auto addFixIt = [&](NullabilityKind Nullability) {
4283 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4284 Diag << static_cast<unsigned>(Nullability);
4285 Diag << static_cast<unsigned>(PointerKind);
4286 fixItNullability(S, Diag, FixItLoc, Nullability);
4287 };
4288 addFixIt(NullabilityKind::Nullable);
4289 addFixIt(NullabilityKind::NonNull);
4290}
4291
4292/// Complains about missing nullability if the file containing \p pointerLoc
4293/// has other uses of nullability (either the keywords or the \c assume_nonnull
4294/// pragma).
4295///
4296/// If the file has \e not seen other uses of nullability, this particular
4297/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4298static void
4299checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4300 SourceLocation pointerLoc,
4301 SourceLocation pointerEndLoc = SourceLocation()) {
4302 // Determine which file we're performing consistency checking for.
4303 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4304 if (file.isInvalid())
4305 return;
4306
4307 // If we haven't seen any type nullability in this file, we won't warn now
4308 // about anything.
4309 FileNullability &fileNullability = S.NullabilityMap[file];
4310 if (!fileNullability.SawTypeNullability) {
4311 // If this is the first pointer declarator in the file, and the appropriate
4312 // warning is on, record it in case we need to diagnose it retroactively.
4313 diag::kind diagKind;
4314 if (pointerKind == SimplePointerKind::Array)
4315 diagKind = diag::warn_nullability_missing_array;
4316 else
4317 diagKind = diag::warn_nullability_missing;
4318
4319 if (fileNullability.PointerLoc.isInvalid() &&
4320 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4321 fileNullability.PointerLoc = pointerLoc;
4322 fileNullability.PointerEndLoc = pointerEndLoc;
4323 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4324 }
4325
4326 return;
4327 }
4328
4329 // Complain about missing nullability.
4330 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4331}
4332
4333/// Marks that a nullability feature has been used in the file containing
4334/// \p loc.
4335///
4336/// If this file already had pointer types in it that were missing nullability,
4337/// the first such instance is retroactively diagnosed.
4338///
4339/// \sa checkNullabilityConsistency
4340static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4341 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4342 if (file.isInvalid())
4343 return;
4344
4345 FileNullability &fileNullability = S.NullabilityMap[file];
4346 if (fileNullability.SawTypeNullability)
4347 return;
4348 fileNullability.SawTypeNullability = true;
4349
4350 // If we haven't seen any type nullability before, now we have. Retroactively
4351 // diagnose the first unannotated pointer, if there was one.
4352 if (fileNullability.PointerLoc.isInvalid())
4353 return;
4354
4355 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4356 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4357 fileNullability.PointerEndLoc);
4358}
4359
4360/// Returns true if any of the declarator chunks before \p endIndex include a
4361/// level of indirection: array, pointer, reference, or pointer-to-member.
4362///
4363/// Because declarator chunks are stored in outer-to-inner order, testing
4364/// every chunk before \p endIndex is testing all chunks that embed the current
4365/// chunk as part of their type.
4366///
4367/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4368/// end index, in which case all chunks are tested.
4369static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4370 unsigned i = endIndex;
4371 while (i != 0) {
4372 // Walk outwards along the declarator chunks.
4373 --i;
4374 const DeclaratorChunk &DC = D.getTypeObject(i);
4375 switch (DC.Kind) {
4376 case DeclaratorChunk::Paren:
4377 break;
4378 case DeclaratorChunk::Array:
4379 case DeclaratorChunk::Pointer:
4380 case DeclaratorChunk::Reference:
4381 case DeclaratorChunk::MemberPointer:
4382 return true;
4383 case DeclaratorChunk::Function:
4384 case DeclaratorChunk::BlockPointer:
4385 case DeclaratorChunk::Pipe:
4386 // These are invalid anyway, so just ignore.
4387 break;
4388 }
4389 }
4390 return false;
4391}
4392
4393static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4394 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4395 Chunk.Kind == DeclaratorChunk::Array);
4396}
4397
4398template<typename AttrT>
4399static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4400 AL.setUsedAsTypeAttr();
4401 return ::new (Ctx) AttrT(Ctx, AL);
4402}
4403
4404static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4405 NullabilityKind NK) {
4406 switch (NK) {
4407 case NullabilityKind::NonNull:
4408 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4409
4410 case NullabilityKind::Nullable:
4411 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4412
4413 case NullabilityKind::NullableResult:
4414 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4415
4416 case NullabilityKind::Unspecified:
4417 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4418 }
4419 llvm_unreachable("unknown NullabilityKind")__builtin_unreachable();
4420}
4421
4422// Diagnose whether this is a case with the multiple addr spaces.
4423// Returns true if this is an invalid case.
4424// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4425// by qualifiers for two or more different address spaces."
4426static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4427 LangAS ASNew,
4428 SourceLocation AttrLoc) {
4429 if (ASOld != LangAS::Default) {
4430 if (ASOld != ASNew) {
4431 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4432 return true;
4433 }
4434 // Emit a warning if they are identical; it's likely unintended.
4435 S.Diag(AttrLoc,
4436 diag::warn_attribute_address_multiple_identical_qualifiers);
4437 }
4438 return false;
4439}
4440
4441static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4442 QualType declSpecType,
4443 TypeSourceInfo *TInfo) {
4444 // The TypeSourceInfo that this function returns will not be a null type.
4445 // If there is an error, this function will fill in a dummy type as fallback.
4446 QualType T = declSpecType;
4447 Declarator &D = state.getDeclarator();
4448 Sema &S = state.getSema();
4449 ASTContext &Context = S.Context;
4450 const LangOptions &LangOpts = S.getLangOpts();
4451
4452 // The name we're declaring, if any.
4453 DeclarationName Name;
4454 if (D.getIdentifier())
1
Taking false branch
4455 Name = D.getIdentifier();
4456
4457 // Does this declaration declare a typedef-name?
4458 bool IsTypedefName =
4459 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2
Assuming the condition is false
4460 D.getContext() == DeclaratorContext::AliasDecl ||
3
Assuming the condition is false
4461 D.getContext() == DeclaratorContext::AliasTemplate;
4
Assuming the condition is false
4462
4463 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4464 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4465 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4466 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4467
4468 // If T is 'decltype(auto)', the only declarators we can have are parens
4469 // and at most one function declarator if this is a function declaration.
4470 // If T is a deduced class template specialization type, we can have no
4471 // declarator chunks at all.
4472 if (auto *DT
5.1
'DT' is null
5.1
'DT' is null
5.1
'DT' is null
5.1
'DT' is null
5.1
'DT' is null
= T->getAs<DeducedType>()) {
5
Assuming the object is not a 'DeducedType'
6
Taking false branch
4473 const AutoType *AT = T->getAs<AutoType>();
4474 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4475 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4476 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4477 unsigned Index = E - I - 1;
4478 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4479 unsigned DiagId = IsClassTemplateDeduction
4480 ? diag::err_deduced_class_template_compound_type
4481 : diag::err_decltype_auto_compound_type;
4482 unsigned DiagKind = 0;
4483 switch (DeclChunk.Kind) {
4484 case DeclaratorChunk::Paren:
4485 // FIXME: Rejecting this is a little silly.
4486 if (IsClassTemplateDeduction) {
4487 DiagKind = 4;
4488 break;
4489 }
4490 continue;
4491 case DeclaratorChunk::Function: {
4492 if (IsClassTemplateDeduction) {
4493 DiagKind = 3;
4494 break;
4495 }
4496 unsigned FnIndex;
4497 if (D.isFunctionDeclarationContext() &&
4498 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4499 continue;
4500 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4501 break;
4502 }
4503 case DeclaratorChunk::Pointer:
4504 case DeclaratorChunk::BlockPointer:
4505 case DeclaratorChunk::MemberPointer:
4506 DiagKind = 0;
4507 break;
4508 case DeclaratorChunk::Reference:
4509 DiagKind = 1;
4510 break;
4511 case DeclaratorChunk::Array:
4512 DiagKind = 2;
4513 break;
4514 case DeclaratorChunk::Pipe:
4515 break;
4516 }
4517
4518 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4519 D.setInvalidType(true);
4520 break;
4521 }
4522 }
4523 }
4524
4525 // Determine whether we should infer _Nonnull on pointer types.
4526 Optional<NullabilityKind> inferNullability;
4527 bool inferNullabilityCS = false;
4528 bool inferNullabilityInnerOnly = false;
4529 bool inferNullabilityInnerOnlyComplete = false;
4530
4531 // Are we in an assume-nonnull region?
4532 bool inAssumeNonNullRegion = false;
4533 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4534 if (assumeNonNullLoc.isValid()) {
7
Taking false branch
4535 inAssumeNonNullRegion = true;
4536 recordNullabilitySeen(S, assumeNonNullLoc);
4537 }
4538
4539 // Whether to complain about missing nullability specifiers or not.
4540 enum {
4541 /// Never complain.
4542 CAMN_No,
4543 /// Complain on the inner pointers (but not the outermost
4544 /// pointer).
4545 CAMN_InnerPointers,
4546 /// Complain about any pointers that don't have nullability
4547 /// specified or inferred.
4548 CAMN_Yes
4549 } complainAboutMissingNullability = CAMN_No;
4550 unsigned NumPointersRemaining = 0;
4551 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4552
4553 if (IsTypedefName
7.1
'IsTypedefName' is false
7.1
'IsTypedefName' is false
7.1
'IsTypedefName' is false
7.1
'IsTypedefName' is false
7.1
'IsTypedefName' is false
) {
8
Taking false branch
4554 // For typedefs, we do not infer any nullability (the default),
4555 // and we only complain about missing nullability specifiers on
4556 // inner pointers.
4557 complainAboutMissingNullability = CAMN_InnerPointers;
4558
4559 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4560 !T->getNullability(S.Context)) {
4561 // Note that we allow but don't require nullability on dependent types.
4562 ++NumPointersRemaining;
4563 }
4564
4565 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4566 DeclaratorChunk &chunk = D.getTypeObject(i);
4567 switch (chunk.Kind) {
4568 case DeclaratorChunk::Array:
4569 case DeclaratorChunk::Function:
4570 case DeclaratorChunk::Pipe:
4571 break;
4572
4573 case DeclaratorChunk::BlockPointer:
4574 case DeclaratorChunk::MemberPointer:
4575 ++NumPointersRemaining;
4576 break;
4577
4578 case DeclaratorChunk::Paren:
4579 case DeclaratorChunk::Reference:
4580 continue;
4581
4582 case DeclaratorChunk::Pointer:
4583 ++NumPointersRemaining;
4584 continue;
4585 }
4586 }
4587 } else {
4588 bool isFunctionOrMethod = false;
4589 switch (auto context = state.getDeclarator().getContext()) {
9
Control jumps to 'case Block:' at line 4672
4590 case DeclaratorContext::ObjCParameter:
4591 case DeclaratorContext::ObjCResult:
4592 case DeclaratorContext::Prototype:
4593 case DeclaratorContext::TrailingReturn:
4594 case DeclaratorContext::TrailingReturnVar:
4595 isFunctionOrMethod = true;
4596 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4597
4598 case DeclaratorContext::Member:
4599 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4600 complainAboutMissingNullability = CAMN_No;
4601 break;
4602 }
4603
4604 // Weak properties are inferred to be nullable.
4605 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4606 inferNullability = NullabilityKind::Nullable;
4607 break;
4608 }
4609
4610 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4611
4612 case DeclaratorContext::File:
4613 case DeclaratorContext::KNRTypeList: {
4614 complainAboutMissingNullability = CAMN_Yes;
4615
4616 // Nullability inference depends on the type and declarator.
4617 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4618 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4619 case PointerDeclaratorKind::NonPointer:
4620 case PointerDeclaratorKind::MultiLevelPointer:
4621 // Cannot infer nullability.
4622 break;
4623
4624 case PointerDeclaratorKind::SingleLevelPointer:
4625 // Infer _Nonnull if we are in an assumes-nonnull region.
4626 if (inAssumeNonNullRegion) {
4627 complainAboutInferringWithinChunk = wrappingKind;
4628 inferNullability = NullabilityKind::NonNull;
4629 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4630 context == DeclaratorContext::ObjCResult);
4631 }
4632 break;
4633
4634 case PointerDeclaratorKind::CFErrorRefPointer:
4635 case PointerDeclaratorKind::NSErrorPointerPointer:
4636 // Within a function or method signature, infer _Nullable at both
4637 // levels.
4638 if (isFunctionOrMethod && inAssumeNonNullRegion)
4639 inferNullability = NullabilityKind::Nullable;
4640 break;
4641
4642 case PointerDeclaratorKind::MaybePointerToCFRef:
4643 if (isFunctionOrMethod) {
4644 // On pointer-to-pointer parameters marked cf_returns_retained or
4645 // cf_returns_not_retained, if the outer pointer is explicit then
4646 // infer the inner pointer as _Nullable.
4647 auto hasCFReturnsAttr =
4648 [](const ParsedAttributesView &AttrList) -> bool {
4649 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4650 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4651 };
4652 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4653 if (hasCFReturnsAttr(D.getAttributes()) ||
4654 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4655 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4656 inferNullability = NullabilityKind::Nullable;
4657 inferNullabilityInnerOnly = true;
4658 }
4659 }
4660 }
4661 break;
4662 }
4663 break;
4664 }
4665
4666 case DeclaratorContext::ConversionId:
4667 complainAboutMissingNullability = CAMN_Yes;
4668 break;
4669
4670 case DeclaratorContext::AliasDecl:
4671 case DeclaratorContext::AliasTemplate:
4672 case DeclaratorContext::Block:
4673 case DeclaratorContext::BlockLiteral:
4674 case DeclaratorContext::Condition:
4675 case DeclaratorContext::CXXCatch:
4676 case DeclaratorContext::CXXNew:
4677 case DeclaratorContext::ForInit:
4678 case DeclaratorContext::SelectionInit:
4679 case DeclaratorContext::LambdaExpr:
4680 case DeclaratorContext::LambdaExprParameter:
4681 case DeclaratorContext::ObjCCatch:
4682 case DeclaratorContext::TemplateParam:
4683 case DeclaratorContext::TemplateArg:
4684 case DeclaratorContext::TemplateTypeArg:
4685 case DeclaratorContext::TypeName:
4686 case DeclaratorContext::FunctionalCast:
4687 case DeclaratorContext::RequiresExpr:
4688 // Don't infer in these contexts.
4689 break;
10
Execution continues on line 4694
4690 }
4691 }
4692
4693 // Local function that returns true if its argument looks like a va_list.
4694 auto isVaList = [&S](QualType T) -> bool {
4695 auto *typedefTy = T->getAs<TypedefType>();
4696 if (!typedefTy)
4697 return false;
4698 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4699 do {
4700 if (typedefTy->getDecl() == vaListTypedef)
4701 return true;
4702 if (auto *name = typedefTy->getDecl()->getIdentifier())
4703 if (name->isStr("va_list"))
4704 return true;
4705 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4706 } while (typedefTy);
4707 return false;
4708 };
4709
4710 // Local function that checks the nullability for a given pointer declarator.
4711 // Returns true if _Nonnull was inferred.
4712 auto inferPointerNullability =
4713 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4714 SourceLocation pointerEndLoc,
4715 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4716 // We've seen a pointer.
4717 if (NumPointersRemaining > 0)
4718 --NumPointersRemaining;
4719
4720 // If a nullability attribute is present, there's nothing to do.
4721 if (hasNullabilityAttr(attrs))
4722 return nullptr;
4723
4724 // If we're supposed to infer nullability, do so now.
4725 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4726 ParsedAttr::Syntax syntax = inferNullabilityCS
4727 ? ParsedAttr::AS_ContextSensitiveKeyword
4728 : ParsedAttr::AS_Keyword;
4729 ParsedAttr *nullabilityAttr = Pool.create(
4730 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4731 nullptr, SourceLocation(), nullptr, 0, syntax);
4732
4733 attrs.addAtEnd(nullabilityAttr);
4734
4735 if (inferNullabilityCS) {
4736 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4737 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4738 }
4739
4740 if (pointerLoc.isValid() &&
4741 complainAboutInferringWithinChunk !=
4742 PointerWrappingDeclaratorKind::None) {
4743 auto Diag =
4744 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4745 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4746 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4747 }
4748
4749 if (inferNullabilityInnerOnly)
4750 inferNullabilityInnerOnlyComplete = true;
4751 return nullabilityAttr;
4752 }
4753
4754 // If we're supposed to complain about missing nullability, do so
4755 // now if it's truly missing.
4756 switch (complainAboutMissingNullability) {
4757 case CAMN_No:
4758 break;
4759
4760 case CAMN_InnerPointers:
4761 if (NumPointersRemaining == 0)
4762 break;
4763 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4764
4765 case CAMN_Yes:
4766 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4767 }
4768 return nullptr;
4769 };
4770
4771 // If the type itself could have nullability but does not, infer pointer
4772 // nullability and perform consistency checking.
4773 if (S.CodeSynthesisContexts.empty()) {
11
Taking false branch
4774 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4775 !T->getNullability(S.Context)) {
4776 if (isVaList(T)) {
4777 // Record that we've seen a pointer, but do nothing else.
4778 if (NumPointersRemaining > 0)
4779 --NumPointersRemaining;
4780 } else {
4781 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4782 if (T->isBlockPointerType())
4783 pointerKind = SimplePointerKind::BlockPointer;
4784 else if (T->isMemberPointerType())
4785 pointerKind = SimplePointerKind::MemberPointer;
4786
4787 if (auto *attr = inferPointerNullability(
4788 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4789 D.getDeclSpec().getEndLoc(),
4790 D.getMutableDeclSpec().getAttributes(),
4791 D.getMutableDeclSpec().getAttributePool())) {
4792 T = state.getAttributedType(
4793 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4794 }
4795 }
4796 }
4797
4798 if (complainAboutMissingNullability == CAMN_Yes &&
4799 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4800 D.isPrototypeContext() &&
4801 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4802 checkNullabilityConsistency(S, SimplePointerKind::Array,
4803 D.getDeclSpec().getTypeSpecTypeLoc());
4804 }
4805 }
4806
4807 bool ExpectNoDerefChunk =
4808 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4809
4810 // Walk the DeclTypeInfo, building the recursive type as we go.
4811 // DeclTypeInfos are ordered from the identifier out, which is
4812 // opposite of what we want :).
4813 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
12
Assuming 'i' is equal to 'e'
13
Loop condition is false. Execution continues on line 5497
4814 unsigned chunkIndex = e - i - 1;
4815 state.setCurrentChunkIndex(chunkIndex);
4816 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4817 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4818 switch (DeclType.Kind) {
4819 case DeclaratorChunk::Paren:
4820 if (i == 0)
4821 warnAboutRedundantParens(S, D, T);
4822 T = S.BuildParenType(T);
4823 break;
4824 case DeclaratorChunk::BlockPointer:
4825 // If blocks are disabled, emit an error.
4826 if (!LangOpts.Blocks)
4827 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4828
4829 // Handle pointer nullability.
4830 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4831 DeclType.EndLoc, DeclType.getAttrs(),
4832 state.getDeclarator().getAttributePool());
4833
4834 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4835 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4836 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4837 // qualified with const.
4838 if (LangOpts.OpenCL)
4839 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4840 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4841 }
4842 break;
4843 case DeclaratorChunk::Pointer:
4844 // Verify that we're not building a pointer to pointer to function with
4845 // exception specification.
4846 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4847 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4848 D.setInvalidType(true);
4849 // Build the type anyway.
4850 }
4851
4852 // Handle pointer nullability
4853 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4854 DeclType.EndLoc, DeclType.getAttrs(),
4855 state.getDeclarator().getAttributePool());
4856
4857 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4858 T = Context.getObjCObjectPointerType(T);
4859 if (DeclType.Ptr.TypeQuals)
4860 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4861 break;
4862 }
4863
4864 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4865 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4866 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4867 if (LangOpts.OpenCL) {
4868 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4869 T->isBlockPointerType()) {
4870 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4871 D.setInvalidType(true);
4872 }
4873 }
4874
4875 T = S.BuildPointerType(T, DeclType.Loc, Name);
4876 if (DeclType.Ptr.TypeQuals)
4877 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4878 break;
4879 case DeclaratorChunk::Reference: {
4880 // Verify that we're not building a reference to pointer to function with
4881 // exception specification.
4882 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4883 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4884 D.setInvalidType(true);
4885 // Build the type anyway.
4886 }
4887 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4888
4889 if (DeclType.Ref.HasRestrict)
4890 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4891 break;
4892 }
4893 case DeclaratorChunk::Array: {
4894 // Verify that we're not building an array of pointers to function with
4895 // exception specification.
4896 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4897 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4898 D.setInvalidType(true);
4899 // Build the type anyway.
4900 }
4901 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4902 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4903 ArrayType::ArraySizeModifier ASM;
4904 if (ATI.isStar)
4905 ASM = ArrayType::Star;
4906 else if (ATI.hasStatic)
4907 ASM = ArrayType::Static;
4908 else
4909 ASM = ArrayType::Normal;
4910 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4911 // FIXME: This check isn't quite right: it allows star in prototypes
4912 // for function definitions, and disallows some edge cases detailed
4913 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4914 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4915 ASM = ArrayType::Normal;
4916 D.setInvalidType(true);
4917 }
4918
4919 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4920 // shall appear only in a declaration of a function parameter with an
4921 // array type, ...
4922 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4923 if (!(D.isPrototypeContext() ||
4924 D.getContext() == DeclaratorContext::KNRTypeList)) {
4925 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4926 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4927 // Remove the 'static' and the type qualifiers.
4928 if (ASM == ArrayType::Static)
4929 ASM = ArrayType::Normal;
4930 ATI.TypeQuals = 0;
4931 D.setInvalidType(true);
4932 }
4933
4934 // C99 6.7.5.2p1: ... and then only in the outermost array type
4935 // derivation.
4936 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4937 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4938 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4939 if (ASM == ArrayType::Static)
4940 ASM = ArrayType::Normal;
4941 ATI.TypeQuals = 0;
4942 D.setInvalidType(true);
4943 }
4944 }
4945 const AutoType *AT = T->getContainedAutoType();
4946 // Allow arrays of auto if we are a generic lambda parameter.
4947 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4948 if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) {
4949 // We've already diagnosed this for decltype(auto).
4950 if (!AT->isDecltypeAuto())
4951 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4952 << getPrintableNameForEntity(Name) << T;
4953 T = QualType();
4954 break;
4955 }
4956
4957 // Array parameters can be marked nullable as well, although it's not
4958 // necessary if they're marked 'static'.
4959 if (complainAboutMissingNullability == CAMN_Yes &&
4960 !hasNullabilityAttr(DeclType.getAttrs()) &&
4961 ASM != ArrayType::Static &&
4962 D.isPrototypeContext() &&
4963 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4964 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4965 }
4966
4967 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4968 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4969 break;
4970 }
4971 case DeclaratorChunk::Function: {
4972 // If the function declarator has a prototype (i.e. it is not () and
4973 // does not have a K&R-style identifier list), then the arguments are part
4974 // of the type, otherwise the argument list is ().
4975 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4976 IsQualifiedFunction =
4977 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4978
4979 // Check for auto functions and trailing return type and adjust the
4980 // return type accordingly.
4981 if (!D.isInvalidType()) {
4982 // trailing-return-type is only required if we're declaring a function,
4983 // and not, for instance, a pointer to a function.
4984 if (D.getDeclSpec().hasAutoTypeSpec() &&
4985 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4986 if (!S.getLangOpts().CPlusPlus14) {
4987 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4988 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4989 ? diag::err_auto_missing_trailing_return
4990 : diag::err_deduced_return_type);
4991 T = Context.IntTy;
4992 D.setInvalidType(true);
4993 } else {
4994 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4995 diag::warn_cxx11_compat_deduced_return_type);
4996 }
4997 } else if (FTI.hasTrailingReturnType()) {
4998 // T must be exactly 'auto' at this point. See CWG issue 681.
4999 if (isa<ParenType>(T)) {
5000 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5001 << T << D.getSourceRange();
5002 D.setInvalidType(true);
5003 } else if (D.getName().getKind() ==
5004 UnqualifiedIdKind::IK_DeductionGuideName) {
5005 if (T != Context.DependentTy) {
5006 S.Diag(D.getDeclSpec().getBeginLoc(),
5007 diag::err_deduction_guide_with_complex_decl)
5008 << D.getSourceRange();
5009 D.setInvalidType(true);
5010 }
5011 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5012 (T.hasQualifiers() || !isa<AutoType>(T) ||
5013 cast<AutoType>(T)->getKeyword() !=
5014 AutoTypeKeyword::Auto ||
5015 cast<AutoType>(T)->isConstrained())) {
5016 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5017 diag::err_trailing_return_without_auto)
5018 << T << D.getDeclSpec().getSourceRange();
5019 D.setInvalidType(true);
5020 }
5021 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5022 if (T.isNull()) {
5023 // An error occurred parsing the trailing return type.
5024 T = Context.IntTy;
5025 D.setInvalidType(true);
5026 } else if (AutoType *Auto = T->getContainedAutoType()) {
5027 // If the trailing return type contains an `auto`, we may need to
5028 // invent a template parameter for it, for cases like
5029 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5030 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5031 if (D.getContext() == DeclaratorContext::Prototype)
5032 InventedParamInfo = &S.InventedParameterInfos.back();
5033 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5034 InventedParamInfo = S.getCurLambda();
5035 if (InventedParamInfo) {
5036 std::tie(T, TInfo) = InventTemplateParameter(
5037 state, T, TInfo, Auto, *InventedParamInfo);
5038 }
5039 }
5040 } else {
5041 // This function type is not the type of the entity being declared,
5042 // so checking the 'auto' is not the responsibility of this chunk.
5043 }
5044 }
5045
5046 // C99 6.7.5.3p1: The return type may not be a function or array type.
5047 // For conversion functions, we'll diagnose this particular error later.
5048 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5049 (D.getName().getKind() !=
5050 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5051 unsigned diagID = diag::err_func_returning_array_function;
5052 // Last processing chunk in block context means this function chunk
5053 // represents the block.
5054 if (chunkIndex == 0 &&
5055 D.getContext() == DeclaratorContext::BlockLiteral)
5056 diagID = diag::err_block_returning_array_function;
5057 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5058 T = Context.IntTy;
5059 D.setInvalidType(true);
5060 }
5061
5062 // Do not allow returning half FP value.
5063 // FIXME: This really should be in BuildFunctionType.
5064 if (T->isHalfType()) {
5065 if (S.getLangOpts().OpenCL) {
5066 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5067 S.getLangOpts())) {
5068 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5069 << T << 0 /*pointer hint*/;
5070 D.setInvalidType(true);
5071 }
5072 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5073 S.Diag(D.getIdentifierLoc(),
5074 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5075 D.setInvalidType(true);
5076 }
5077 }
5078
5079 if (LangOpts.OpenCL) {
5080 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5081 // function.
5082 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5083 T->isPipeType()) {
5084 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5085 << T << 1 /*hint off*/;
5086 D.setInvalidType(true);
5087 }
5088 // OpenCL doesn't support variadic functions and blocks
5089 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5090 // We also allow here any toolchain reserved identifiers.
5091 if (FTI.isVariadic &&
5092 !S.getOpenCLOptions().isAvailableOption(
5093 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5094 !(D.getIdentifier() &&
5095 ((D.getIdentifier()->getName() == "printf" &&
5096 (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
5097 D.getIdentifier()->getName().startswith("__")))) {
5098 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5099 D.setInvalidType(true);
5100 }
5101 }
5102
5103 // Methods cannot return interface types. All ObjC objects are
5104 // passed by reference.
5105 if (T->isObjCObjectType()) {
5106 SourceLocation DiagLoc, FixitLoc;
5107 if (TInfo) {
5108 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5109 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5110 } else {
5111 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5112 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5113 }
5114 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5115 << 0 << T
5116 << FixItHint::CreateInsertion(FixitLoc, "*");
5117
5118 T = Context.getObjCObjectPointerType(T);
5119 if (TInfo) {
5120 TypeLocBuilder TLB;
5121 TLB.pushFullCopy(TInfo->getTypeLoc());
5122 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5123 TLoc.setStarLoc(FixitLoc);
5124 TInfo = TLB.getTypeSourceInfo(Context, T);
5125 }
5126
5127 D.setInvalidType(true);
5128 }
5129
5130 // cv-qualifiers on return types are pointless except when the type is a
5131 // class type in C++.
5132 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5133 !(S.getLangOpts().CPlusPlus &&
5134 (T->isDependentType() || T->isRecordType()))) {
5135 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5136 D.getFunctionDefinitionKind() ==
5137 FunctionDefinitionKind::Definition) {
5138 // [6.9.1/3] qualified void return is invalid on a C
5139 // function definition. Apparently ok on declarations and
5140 // in C++ though (!)
5141 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5142 } else
5143 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5144
5145 // C++2a [dcl.fct]p12:
5146 // A volatile-qualified return type is deprecated
5147 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5148 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5149 }
5150
5151 // Objective-C ARC ownership qualifiers are ignored on the function
5152 // return type (by type canonicalization). Complain if this attribute
5153 // was written here.
5154 if (T.getQualifiers().hasObjCLifetime()) {
5155 SourceLocation AttrLoc;
5156 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5157 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5158 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5159 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5160 AttrLoc = AL.getLoc();
5161 break;
5162 }
5163 }
5164 }
5165 if (AttrLoc.isInvalid()) {
5166 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5167 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5168 AttrLoc = AL.getLoc();
5169 break;
5170 }
5171 }
5172 }
5173
5174 if (AttrLoc.isValid()) {
5175 // The ownership attributes are almost always written via
5176 // the predefined
5177 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5178 if (AttrLoc.isMacroID())
5179 AttrLoc =
5180 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5181
5182 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5183 << T.getQualifiers().getObjCLifetime();
5184 }
5185 }
5186
5187 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5188 // C++ [dcl.fct]p6:
5189 // Types shall not be defined in return or parameter types.
5190 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5191 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5192 << Context.getTypeDeclType(Tag);
5193 }
5194
5195 // Exception specs are not allowed in typedefs. Complain, but add it
5196 // anyway.
5197 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5198 S.Diag(FTI.getExceptionSpecLocBeg(),
5199 diag::err_exception_spec_in_typedef)
5200 << (D.getContext() == DeclaratorContext::AliasDecl ||
5201 D.getContext() == DeclaratorContext::AliasTemplate);
5202
5203 // If we see "T var();" or "T var(T());" at block scope, it is probably
5204 // an attempt to initialize a variable, not a function declaration.
5205 if (FTI.isAmbiguous)
5206 warnAboutAmbiguousFunction(S, D, DeclType, T);
5207
5208 FunctionType::ExtInfo EI(
5209 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5210
5211 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
5212 && !LangOpts.OpenCL) {
5213 // Simple void foo(), where the incoming T is the result type.
5214 T = Context.getFunctionNoProtoType(T, EI);
5215 } else {
5216 // We allow a zero-parameter variadic function in C if the
5217 // function is marked with the "overloadable" attribute. Scan
5218 // for this attribute now.
5219 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5220 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
5221 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5222
5223 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5224 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5225 // definition.
5226 S.Diag(FTI.Params[0].IdentLoc,
5227 diag::err_ident_list_in_fn_declaration);
5228 D.setInvalidType(true);
5229 // Recover by creating a K&R-style function type.
5230 T = Context.getFunctionNoProtoType(T, EI);
5231 break;
5232 }
5233
5234 FunctionProtoType::ExtProtoInfo EPI;
5235 EPI.ExtInfo = EI;
5236 EPI.Variadic = FTI.isVariadic;
5237 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5238 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5239 EPI.TypeQuals.addCVRUQualifiers(
5240 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5241 : 0);
5242 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5243 : FTI.RefQualifierIsLValueRef? RQ_LValue
5244 : RQ_RValue;
5245
5246 // Otherwise, we have a function with a parameter list that is
5247 // potentially variadic.
5248 SmallVector<QualType, 16> ParamTys;
5249 ParamTys.reserve(FTI.NumParams);
5250
5251 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5252 ExtParameterInfos(FTI.NumParams);
5253 bool HasAnyInterestingExtParameterInfos = false;
5254
5255 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5256 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5257 QualType ParamTy = Param->getType();
5258 assert(!ParamTy.isNull() && "Couldn't parse type?")((void)0);
5259
5260 // Look for 'void'. void is allowed only as a single parameter to a
5261 // function with no other parameters (C99 6.7.5.3p10). We record
5262 // int(void) as a FunctionProtoType with an empty parameter list.
5263 if (ParamTy->isVoidType()) {
5264 // If this is something like 'float(int, void)', reject it. 'void'
5265 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5266 // have parameters of incomplete type.
5267 if (FTI.NumParams != 1 || FTI.isVariadic) {
5268 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5269 ParamTy = Context.IntTy;
5270 Param->setType(ParamTy);
5271 } else if (FTI.Params[i].Ident) {
5272 // Reject, but continue to parse 'int(void abc)'.
5273 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5274 ParamTy = Context.IntTy;
5275 Param->setType(ParamTy);
5276 } else {
5277 // Reject, but continue to parse 'float(const void)'.
5278 if (ParamTy.hasQualifiers())
5279 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5280
5281 // Do not add 'void' to the list.
5282 break;
5283 }
5284 } else if (ParamTy->isHalfType()) {
5285 // Disallow half FP parameters.
5286 // FIXME: This really should be in BuildFunctionType.
5287 if (S.getLangOpts().OpenCL) {
5288 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5289 S.getLangOpts())) {
5290 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5291 << ParamTy << 0;
5292 D.setInvalidType();
5293 Param->setInvalidDecl();
5294 }
5295 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5296 S.Diag(Param->getLocation(),
5297 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5298 D.setInvalidType();
5299 }
5300 } else if (!FTI.hasPrototype) {
5301 if (ParamTy->isPromotableIntegerType()) {
5302 ParamTy = Context.getPromotedIntegerType(ParamTy);
5303 Param->setKNRPromoted(true);
5304 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
5305 if (BTy->getKind() == BuiltinType::Float) {
5306 ParamTy = Context.DoubleTy;
5307 Param->setKNRPromoted(true);
5308 }
5309 }
5310 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5311 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5312 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5313 << ParamTy << 1 /*hint off*/;
5314 D.setInvalidType();
5315 }
5316
5317 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5318 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5319 HasAnyInterestingExtParameterInfos = true;
5320 }
5321
5322 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5323 ExtParameterInfos[i] =
5324 ExtParameterInfos[i].withABI(attr->getABI());
5325 HasAnyInterestingExtParameterInfos = true;
5326 }
5327
5328 if (Param->hasAttr<PassObjectSizeAttr>()) {
5329 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5330 HasAnyInterestingExtParameterInfos = true;
5331 }
5332
5333 if (Param->hasAttr<NoEscapeAttr>()) {
5334 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5335 HasAnyInterestingExtParameterInfos = true;
5336 }
5337
5338 ParamTys.push_back(ParamTy);
5339 }
5340
5341 if (HasAnyInterestingExtParameterInfos) {
5342 EPI.ExtParameterInfos = ExtParameterInfos.data();
5343 checkExtParameterInfos(S, ParamTys, EPI,
5344 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5345 }
5346
5347 SmallVector<QualType, 4> Exceptions;
5348 SmallVector<ParsedType, 2> DynamicExceptions;
5349 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5350 Expr *NoexceptExpr = nullptr;
5351
5352 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5353 // FIXME: It's rather inefficient to have to split into two vectors
5354 // here.
5355 unsigned N = FTI.getNumExceptions();
5356 DynamicExceptions.reserve(N);
5357 DynamicExceptionRanges.reserve(N);
5358 for (unsigned I = 0; I != N; ++I) {
5359 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5360 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5361 }
5362 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5363 NoexceptExpr = FTI.NoexceptExpr;
5364 }
5365
5366 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5367 FTI.getExceptionSpecType(),
5368 DynamicExceptions,
5369 DynamicExceptionRanges,
5370 NoexceptExpr,
5371 Exceptions,
5372 EPI.ExceptionSpec);
5373
5374 // FIXME: Set address space from attrs for C++ mode here.
5375 // OpenCLCPlusPlus: A class member function has an address space.
5376 auto IsClassMember = [&]() {
5377 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5378 state.getDeclarator()
5379 .getCXXScopeSpec()
5380 .getScopeRep()
5381 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5382 state.getDeclarator().getContext() ==
5383 DeclaratorContext::Member ||
5384 state.getDeclarator().getContext() ==
5385 DeclaratorContext::LambdaExpr;
5386 };
5387
5388 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5389 LangAS ASIdx = LangAS::Default;
5390 // Take address space attr if any and mark as invalid to avoid adding
5391 // them later while creating QualType.
5392 if (FTI.MethodQualifiers)
5393 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5394 LangAS ASIdxNew = attr.asOpenCLLangAS();
5395 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5396 attr.getLoc()))
5397 D.setInvalidType(true);
5398 else
5399 ASIdx = ASIdxNew;
5400 }
5401 // If a class member function's address space is not set, set it to
5402 // __generic.
5403 LangAS AS =
5404 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5405 : ASIdx);
5406 EPI.TypeQuals.addAddressSpace(AS);
5407 }
5408 T = Context.getFunctionType(T, ParamTys, EPI);
5409 }
5410 break;
5411 }
5412 case DeclaratorChunk::MemberPointer: {
5413 // The scope spec must refer to a class, or be dependent.
5414 CXXScopeSpec &SS = DeclType.Mem.Scope();
5415 QualType ClsType;
5416
5417 // Handle pointer nullability.
5418 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5419 DeclType.EndLoc, DeclType.getAttrs(),
5420 state.getDeclarator().getAttributePool());
5421
5422 if (SS.isInvalid()) {
5423 // Avoid emitting extra errors if we already errored on the scope.
5424 D.setInvalidType(true);
5425 } else if (S.isDependentScopeSpecifier(SS) ||
5426 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
5427 NestedNameSpecifier *NNS = SS.getScopeRep();
5428 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5429 switch (NNS->getKind()) {
5430 case NestedNameSpecifier::Identifier:
5431 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5432 NNS->getAsIdentifier());
5433 break;
5434
5435 case NestedNameSpecifier::Namespace:
5436 case NestedNameSpecifier::NamespaceAlias:
5437 case NestedNameSpecifier::Global:
5438 case NestedNameSpecifier::Super:
5439 llvm_unreachable("Nested-name-specifier must name a type")__builtin_unreachable();
5440
5441 case NestedNameSpecifier::TypeSpec:
5442 case NestedNameSpecifier::TypeSpecWithTemplate:
5443 ClsType = QualType(NNS->getAsType(), 0);
5444 // Note: if the NNS has a prefix and ClsType is a nondependent
5445 // TemplateSpecializationType, then the NNS prefix is NOT included
5446 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5447 // NOTE: in particular, no wrap occurs if ClsType already is an
5448 // Elaborated, DependentName, or DependentTemplateSpecialization.
5449 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
5450 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5451 break;
5452 }
5453 } else {
5454 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5455 diag::err_illegal_decl_mempointer_in_nonclass)
5456 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5457 << DeclType.Mem.Scope().getRange();
5458 D.setInvalidType(true);
5459 }
5460
5461 if (!ClsType.isNull())
5462 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5463 D.getIdentifier());
5464 if (T.isNull()) {
5465 T = Context.IntTy;
5466 D.setInvalidType(true);
5467 } else if (DeclType.Mem.TypeQuals) {
5468 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5469 }
5470 break;
5471 }
5472
5473 case DeclaratorChunk::Pipe: {
5474 T = S.BuildReadPipeType(T, DeclType.Loc);
5475 processTypeAttrs(state, T, TAL_DeclSpec,
5476 D.getMutableDeclSpec().getAttributes());
5477 break;
5478 }
5479 }
5480
5481 if (T.isNull()) {
5482 D.setInvalidType(true);
5483 T = Context.IntTy;
5484 }
5485
5486 // See if there are any attributes on this declarator chunk.
5487 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5488
5489 if (DeclType.Kind != DeclaratorChunk::Paren) {
5490 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5491 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5492
5493 ExpectNoDerefChunk = state.didParseNoDeref();
5494 }
5495 }
5496
5497 if (ExpectNoDerefChunk)
14
Assuming 'ExpectNoDerefChunk' is false
15
Taking false branch
5498 S.Diag(state.getDeclarator().getBeginLoc(),
5499 diag::warn_noderef_on_non_pointer_or_array);
5500
5501 // GNU warning -Wstrict-prototypes
5502 // Warn if a function declaration is without a prototype.
5503 // This warning is issued for all kinds of unprototyped function
5504 // declarations (i.e. function type typedef, function pointer etc.)
5505 // C99 6.7.5.3p14:
5506 // The empty list in a function declarator that is not part of a definition
5507 // of that function specifies that no information about the number or types
5508 // of the parameters is supplied.
5509 if (!LangOpts.CPlusPlus &&
16
Assuming field 'CPlusPlus' is not equal to 0
5510 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration) {
5511 bool IsBlock = false;
5512 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5513 switch (DeclType.Kind) {
5514 case DeclaratorChunk::BlockPointer:
5515 IsBlock = true;
5516 break;
5517 case DeclaratorChunk::Function: {
5518 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5519 // We supress the warning when there's no LParen location, as this
5520 // indicates the declaration was an implicit declaration, which gets
5521 // warned about separately via -Wimplicit-function-declaration.
5522 if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
5523 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5524 << IsBlock
5525 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5526 IsBlock = false;
5527 break;
5528 }
5529 default:
5530 break;
5531 }
5532 }
5533 }
5534
5535 assert(!T.isNull() && "T must not be null after this point")((void)0);
5536
5537 if (LangOpts.CPlusPlus
16.1
Field 'CPlusPlus' is not equal to 0
16.1
Field 'CPlusPlus' is not equal to 0
16.1
Field 'CPlusPlus' is not equal to 0
16.1
Field 'CPlusPlus' is not equal to 0
16.1
Field 'CPlusPlus' is not equal to 0
&& T->isFunctionType()) {
17
Taking false branch
5538 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5539 assert(FnTy && "Why oh why is there not a FunctionProtoType here?")((void)0);
5540
5541 // C++ 8.3.5p4:
5542 // A cv-qualifier-seq shall only be part of the function type
5543 // for a nonstatic member function, the function type to which a pointer
5544 // to member refers, or the top-level function type of a function typedef
5545 // declaration.
5546 //
5547 // Core issue 547 also allows cv-qualifiers on function types that are
5548 // top-level template type arguments.
5549 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5550 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5551 Kind = DeductionGuide;
5552 else if (!D.getCXXScopeSpec().isSet()) {
5553 if ((D.getContext() == DeclaratorContext::Member ||
5554 D.getContext() == DeclaratorContext::LambdaExpr) &&
5555 !D.getDeclSpec().isFriendSpecified())
5556 Kind = Member;
5557 } else {
5558 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5559 if (!DC || DC->isRecord())
5560 Kind = Member;
5561 }
5562
5563 // C++11 [dcl.fct]p6 (w/DR1417):
5564 // An attempt to specify a function type with a cv-qualifier-seq or a
5565 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5566 // - the function type for a non-static member function,
5567 // - the function type to which a pointer to member refers,
5568 // - the top-level function type of a function typedef declaration or
5569 // alias-declaration,
5570 // - the type-id in the default argument of a type-parameter, or
5571 // - the type-id of a template-argument for a type-parameter
5572 //
5573 // FIXME: Checking this here is insufficient. We accept-invalid on:
5574 //
5575 // template<typename T> struct S { void f(T); };
5576 // S<int() const> s;
5577 //
5578 // ... for instance.
5579 if (IsQualifiedFunction &&
5580 !(Kind == Member &&
5581 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5582 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5583 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5584 SourceLocation Loc = D.getBeginLoc();
5585 SourceRange RemovalRange;
5586 unsigned I;
5587 if (D.isFunctionDeclarator(I)) {
5588 SmallVector<SourceLocation, 4> RemovalLocs;
5589 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5590 assert(Chunk.Kind == DeclaratorChunk::Function)((void)0);
5591
5592 if (Chunk.Fun.hasRefQualifier())
5593 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5594
5595 if (Chunk.Fun.hasMethodTypeQualifiers())
5596 Chunk.Fun.MethodQualifiers->forEachQualifier(
5597 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5598 SourceLocation SL) { RemovalLocs.push_back(SL); });
5599
5600 if (!RemovalLocs.empty()) {
5601 llvm::sort(RemovalLocs,
5602 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5603 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5604 Loc = RemovalLocs.front();
5605 }
5606 }
5607
5608 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5609 << Kind << D.isFunctionDeclarator() << T
5610 << getFunctionQualifiersAsString(FnTy)
5611 << FixItHint::CreateRemoval(RemovalRange);
5612
5613 // Strip the cv-qualifiers and ref-qualifiers from the type.
5614 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5615 EPI.TypeQuals.removeCVRQualifiers();
5616 EPI.RefQualifier = RQ_None;
5617
5618 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5619 EPI);
5620 // Rebuild any parens around the identifier in the function type.
5621 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5622 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5623 break;
5624 T = S.BuildParenType(T);
5625 }
5626 }
5627 }
5628
5629 // Apply any undistributed attributes from the declarator.
5630 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5631
5632 // Diagnose any ignored type attributes.
5633 state.diagnoseIgnoredTypeAttrs(T);
5634
5635 // C++0x [dcl.constexpr]p9:
5636 // A constexpr specifier used in an object declaration declares the object
5637 // as const.
5638 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
18
Assuming the condition is false
5639 T->isObjectType())
5640 T.addConst();
5641
5642 // C++2a [dcl.fct]p4:
5643 // A parameter with volatile-qualified type is deprecated
5644 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
19
Assuming the condition is false
5645 (D.getContext() == DeclaratorContext::Prototype ||
5646 D.getContext() == DeclaratorContext::LambdaExprParameter))
5647 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5648
5649 // If there was an ellipsis in the declarator, the declaration declares a
5650 // parameter pack whose type may be a pack expansion type.
5651 if (D.hasEllipsis()) {
20
Taking false branch
5652 // C++0x [dcl.fct]p13:
5653 // A declarator-id or abstract-declarator containing an ellipsis shall
5654 // only be used in a parameter-declaration. Such a parameter-declaration
5655 // is a parameter pack (14.5.3). [...]
5656 switch (D.getContext()) {
5657 case DeclaratorContext::Prototype:
5658 case DeclaratorContext::LambdaExprParameter:
5659 case DeclaratorContext::RequiresExpr:
5660 // C++0x [dcl.fct]p13:
5661 // [...] When it is part of a parameter-declaration-clause, the
5662 // parameter pack is a function parameter pack (14.5.3). The type T
5663 // of the declarator-id of the function parameter pack shall contain
5664 // a template parameter pack; each template parameter pack in T is
5665 // expanded by the function parameter pack.
5666 //
5667 // We represent function parameter packs as function parameters whose
5668 // type is a pack expansion.
5669 if (!T->containsUnexpandedParameterPack() &&
5670 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5671 S.Diag(D.getEllipsisLoc(),
5672 diag::err_function_parameter_pack_without_parameter_packs)
5673 << T << D.getSourceRange();
5674 D.setEllipsisLoc(SourceLocation());
5675 } else {
5676 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false);
5677 }
5678 break;
5679 case DeclaratorContext::TemplateParam:
5680 // C++0x [temp.param]p15:
5681 // If a template-parameter is a [...] is a parameter-declaration that
5682 // declares a parameter pack (8.3.5), then the template-parameter is a
5683 // template parameter pack (14.5.3).
5684 //
5685 // Note: core issue 778 clarifies that, if there are any unexpanded
5686 // parameter packs in the type of the non-type template parameter, then
5687 // it expands those parameter packs.
5688 if (T->containsUnexpandedParameterPack())
5689 T = Context.getPackExpansionType(T, None);
5690 else
5691 S.Diag(D.getEllipsisLoc(),
5692 LangOpts.CPlusPlus11
5693 ? diag::warn_cxx98_compat_variadic_templates
5694 : diag::ext_variadic_templates);
5695 break;
5696
5697 case DeclaratorContext::File:
5698 case DeclaratorContext::KNRTypeList:
5699 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5700 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5701 case DeclaratorContext::TypeName:
5702 case DeclaratorContext::FunctionalCast:
5703 case DeclaratorContext::CXXNew:
5704 case DeclaratorContext::AliasDecl:
5705 case DeclaratorContext::AliasTemplate:
5706 case DeclaratorContext::Member:
5707 case DeclaratorContext::Block:
5708 case DeclaratorContext::ForInit:
5709 case DeclaratorContext::SelectionInit:
5710 case DeclaratorContext::Condition:
5711 case DeclaratorContext::CXXCatch:
5712 case DeclaratorContext::ObjCCatch:
5713 case DeclaratorContext::BlockLiteral:
5714 case DeclaratorContext::LambdaExpr:
5715 case DeclaratorContext::ConversionId:
5716 case DeclaratorContext::TrailingReturn:
5717 case DeclaratorContext::TrailingReturnVar:
5718 case DeclaratorContext::TemplateArg:
5719 case DeclaratorContext::TemplateTypeArg:
5720 // FIXME: We may want to allow parameter packs in block-literal contexts
5721 // in the future.
5722 S.Diag(D.getEllipsisLoc(),
5723 diag::err_ellipsis_in_declarator_not_parameter);
5724 D.setEllipsisLoc(SourceLocation());
5725 break;
5726 }
5727 }
5728
5729 assert(!T.isNull() && "T must not be null at the end of this function")((void)0);
5730 if (D.isInvalidType())
21
Taking false branch
5731 return Context.getTrivialTypeSourceInfo(T);
5732
5733 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
22
Calling 'GetTypeSourceInfoForDeclarator'
5734}
5735
5736/// GetTypeForDeclarator - Convert the type for the specified
5737/// declarator to Type instances.
5738///
5739/// The result of this call will never be null, but the associated
5740/// type may be a null type if there's an unrecoverable error.
5741TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5742 // Determine the type of the declarator. Not all forms of declarator
5743 // have a type.
5744
5745 TypeProcessingState state(*this, D);
5746
5747 TypeSourceInfo *ReturnTypeInfo = nullptr;
5748 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5749 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5750 inferARCWriteback(state, T);
5751
5752 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5753}
5754
5755static void transferARCOwnershipToDeclSpec(Sema &S,
5756 QualType &declSpecTy,
5757 Qualifiers::ObjCLifetime ownership) {
5758 if (declSpecTy->isObjCRetainableType() &&
5759 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5760 Qualifiers qs;
5761 qs.addObjCLifetime(ownership);
5762 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5763 }
5764}
5765
5766static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5767 Qualifiers::ObjCLifetime ownership,
5768 unsigned chunkIndex) {
5769 Sema &S = state.getSema();
5770 Declarator &D = state.getDeclarator();
5771
5772 // Look for an explicit lifetime attribute.
5773 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5774 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5775 return;
5776
5777 const char *attrStr = nullptr;
5778 switch (ownership) {
5779 case Qualifiers::OCL_None: llvm_unreachable("no ownership!")__builtin_unreachable();
5780 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5781 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5782 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5783 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5784 }
5785
5786 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5787 Arg->Ident = &S.Context.Idents.get(attrStr);
5788 Arg->Loc = SourceLocation();
5789
5790 ArgsUnion Args(Arg);
5791
5792 // If there wasn't one, add one (with an invalid source location
5793 // so that we don't make an AttributedType for it).
5794 ParsedAttr *attr = D.getAttributePool().create(
5795 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5796 /*scope*/ nullptr, SourceLocation(),
5797 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5798 chunk.getAttrs().addAtEnd(attr);
5799 // TODO: mark whether we did this inference?
5800}
5801
5802/// Used for transferring ownership in casts resulting in l-values.
5803static void transferARCOwnership(TypeProcessingState &state,
5804 QualType &declSpecTy,
5805 Qualifiers::ObjCLifetime ownership) {
5806 Sema &S = state.getSema();
5807 Declarator &D = state.getDeclarator();
5808
5809 int inner = -1;
5810 bool hasIndirection = false;
5811 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5812 DeclaratorChunk &chunk = D.getTypeObject(i);
5813 switch (chunk.Kind) {
5814 case DeclaratorChunk::Paren:
5815 // Ignore parens.
5816 break;
5817
5818 case DeclaratorChunk::Array:
5819 case DeclaratorChunk::Reference:
5820 case DeclaratorChunk::Pointer:
5821 if (inner != -1)
5822 hasIndirection = true;
5823 inner = i;
5824 break;
5825
5826 case DeclaratorChunk::BlockPointer:
5827 if (inner != -1)
5828 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5829 return;
5830
5831 case DeclaratorChunk::Function:
5832 case DeclaratorChunk::MemberPointer:
5833 case DeclaratorChunk::Pipe:
5834 return;
5835 }
5836 }
5837
5838 if (inner == -1)
5839 return;
5840
5841 DeclaratorChunk &chunk = D.getTypeObject(inner);
5842 if (chunk.Kind == DeclaratorChunk::Pointer) {
5843 if (declSpecTy->isObjCRetainableType())
5844 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5845 if (declSpecTy->isObjCObjectType() && hasIndirection)
5846 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5847 } else {
5848 assert(chunk.Kind == DeclaratorChunk::Array ||((void)0)
5849 chunk.Kind == DeclaratorChunk::Reference)((void)0);
5850 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5851 }
5852}
5853
5854TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5855 TypeProcessingState state(*this, D);
5856
5857 TypeSourceInfo *ReturnTypeInfo = nullptr;
5858 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5859
5860 if (getLangOpts().ObjC) {
5861 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5862 if (ownership != Qualifiers::OCL_None)
5863 transferARCOwnership(state, declSpecTy, ownership);
5864 }
5865
5866 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5867}
5868
5869static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5870 TypeProcessingState &State) {
5871 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5872}
5873
5874namespace {
5875 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5876 Sema &SemaRef;
5877 ASTContext &Context;
5878 TypeProcessingState &State;
5879 const DeclSpec &DS;
5880
5881 public:
5882 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5883 const DeclSpec &DS)
5884 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5885
5886 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5887 Visit(TL.getModifiedLoc());
5888 fillAttributedTypeLoc(TL, State);
5889 }
5890 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5891 Visit(TL.getInnerLoc());
5892 TL.setExpansionLoc(
5893 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5894 }
5895 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5896 Visit(TL.getUnqualifiedLoc());
5897 }
5898 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5899 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5900 }
5901 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5902 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5903 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5904 // addition field. What we have is good enough for dispay of location
5905 // of 'fixit' on interface name.
5906 TL.setNameEndLoc(DS.getEndLoc());
5907 }
5908 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5909 TypeSourceInfo *RepTInfo = nullptr;
5910 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5911 TL.copy(RepTInfo->getTypeLoc());
5912 }
5913 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5914 TypeSourceInfo *RepTInfo = nullptr;
5915 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5916 TL.copy(RepTInfo->getTypeLoc());
5917 }
5918 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5919 TypeSourceInfo *TInfo = nullptr;
5920 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5921
5922 // If we got no declarator info from previous Sema routines,
5923 // just fill with the typespec loc.
5924 if (!TInfo) {
5925 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5926 return;
5927 }
5928
5929 TypeLoc OldTL = TInfo->getTypeLoc();
5930 if (TInfo->getType()->getAs<ElaboratedType>()) {
5931 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5932 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5933 .castAs<TemplateSpecializationTypeLoc>();
5934 TL.copy(NamedTL);
5935 } else {
5936 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5937 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())((void)0);
5938 }
5939
5940 }
5941 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5942 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)((void)0);
5943 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5944 TL.setParensRange(DS.getTypeofParensRange());
5945 }
5946 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5947 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)((void)0);
5948 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5949 TL.setParensRange(DS.getTypeofParensRange());
5950 assert(DS.getRepAsType())((void)0);
5951 TypeSourceInfo *TInfo = nullptr;
5952 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5953 TL.setUnderlyingTInfo(TInfo);
5954 }
5955 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5956 // FIXME: This holds only because we only have one unary transform.
5957 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)((void)0);
5958 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5959 TL.setParensRange(DS.getTypeofParensRange());
5960 assert(DS.getRepAsType())((void)0);
5961 TypeSourceInfo *TInfo = nullptr;
5962 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5963 TL.setUnderlyingTInfo(TInfo);
5964 }
5965 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5966 // By default, use the source location of the type specifier.
5967 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5968 if (TL.needsExtraLocalData()) {
5969 // Set info for the written builtin specifiers.
5970 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5971 // Try to have a meaningful source location.
5972 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
5973 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5974 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
5975 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5976 }
5977 }
5978 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5979 ElaboratedTypeKeyword Keyword
5980 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5981 if (DS.getTypeSpecType() == TST_typename) {
5982 TypeSourceInfo *TInfo = nullptr;
5983 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5984 if (TInfo) {
5985 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5986 return;
5987 }
5988 }
5989 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5990 ? DS.getTypeSpecTypeLoc()
5991 : SourceLocation());
5992 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5993 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5994 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5995 }
5996 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5997 assert(DS.getTypeSpecType() == TST_typename)((void)0);
5998 TypeSourceInfo *TInfo = nullptr;
5999 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6000 assert(TInfo)((void)0);
6001 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6002 }
6003 void VisitDependentTemplateSpecializationTypeLoc(
6004 DependentTemplateSpecializationTypeLoc TL) {
6005 assert(DS.getTypeSpecType() == TST_typename)((void)0);
6006 TypeSourceInfo *TInfo = nullptr;
6007 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6008 assert(TInfo)((void)0);
6009 TL.copy(
6010 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6011 }
6012 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6013 assert(DS.getTypeSpecType() == TST_auto ||((void)0)
6014 DS.getTypeSpecType() == TST_decltype_auto ||((void)0)
6015 DS.getTypeSpecType() == TST_auto_type ||((void)0)
6016 DS.getTypeSpecType() == TST_unspecified)((void)0);
6017 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6018 if (!DS.isConstrainedAuto())
6019 return;
6020 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6021 if (!TemplateId)
6022 return;
6023 if (DS.getTypeSpecScope().isNotEmpty())
6024 TL.setNestedNameSpecifierLoc(
6025 DS.getTypeSpecScope().getWithLocInContext(Context));
6026 else
6027 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
6028 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
6029 TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
6030 TL.setFoundDecl(nullptr);
6031 TL.setLAngleLoc(TemplateId->LAngleLoc);
6032 TL.setRAngleLoc(TemplateId->RAngleLoc);
6033 if (TemplateId->NumArgs == 0)
6034 return;
6035 TemplateArgumentListInfo TemplateArgsInfo;
6036 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6037 TemplateId->NumArgs);
6038 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6039 for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
6040 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
6041 }
6042 void VisitTagTypeLoc(TagTypeLoc TL) {
6043 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6044 }
6045 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6046 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6047 // or an _Atomic qualifier.
6048 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
32
Assuming the condition is true
33
Taking true branch
6049 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6050 TL.setParensRange(DS.getTypeofParensRange());
6051
6052 TypeSourceInfo *TInfo = nullptr;
6053 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
34
Calling 'Sema::GetTypeFromParser'
48
Returning from 'Sema::GetTypeFromParser'
6054 assert(TInfo)((void)0);
6055 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
49
Called C++ object pointer is null
6056 } else {
6057 TL.setKWLoc(DS.getAtomicSpecLoc());
6058 // No parens, to indicate this was spelled as an _Atomic qualifier.
6059 TL.setParensRange(SourceRange());
6060 Visit(TL.getValueLoc());
6061 }
6062 }
6063
6064 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6065 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6066
6067 TypeSourceInfo *TInfo = nullptr;
6068 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6069 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6070 }
6071
6072 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6073 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6074 }
6075
6076 void VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL) {
6077 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6078 }
6079