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
42 using namespace clang;
43
44 enum 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.
isOmittedBlockReturnType(const Declarator & D)52 static 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.
diagnoseBadTypeAttribute(Sema & S,const ParsedAttr & attr,QualType type)69 static 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_CASELIST \
108 case ParsedAttr::AT_ObjCGC: \
109 case ParsedAttr::AT_ObjCOwnership
110
111 // Calling convention attributes.
112 #define CALLING_CONV_ATTRS_CASELIST \
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_CASELIST \
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_CASELIST
139
140 // Microsoft-specific type qualifiers.
141 #define MS_TYPE_ATTRS_CASELIST \
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_CASELIST \
149 case ParsedAttr::AT_TypeNonNull: \
150 case ParsedAttr::AT_TypeNullable: \
151 case ParsedAttr::AT_TypeNullableResult: \
152 case ParsedAttr::AT_TypeNullUnspecified
153
154 namespace {
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:
TypeProcessingState(Sema & sema,Declarator & declarator)200 TypeProcessingState(Sema &sema, Declarator &declarator)
201 : sema(sema), declarator(declarator),
202 chunkIndex(declarator.getNumTypeObjects()), trivial(true),
203 hasSavedAttrs(false), parsedNoDeref(false) {}
204
getSema() const205 Sema &getSema() const {
206 return sema;
207 }
208
getDeclarator() const209 Declarator &getDeclarator() const {
210 return declarator;
211 }
212
isProcessingDeclSpec() const213 bool isProcessingDeclSpec() const {
214 return chunkIndex == declarator.getNumTypeObjects();
215 }
216
getCurrentChunkIndex() const217 unsigned getCurrentChunkIndex() const {
218 return chunkIndex;
219 }
220
setCurrentChunkIndex(unsigned idx)221 void setCurrentChunkIndex(unsigned idx) {
222 assert(idx <= declarator.getNumTypeObjects());
223 chunkIndex = idx;
224 }
225
getCurrentAttributes() const226 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.
saveDeclSpecAttrs()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.
addIgnoredTypeAttr(ParsedAttr & attr)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.
diagnoseIgnoredTypeAttrs(QualType type) const252 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.
getAttributedType(Attr * A,QualType ModifiedType,QualType EquivType)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.
ReplaceAutoType(QualType TypeWithAuto,QualType Replacement)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.
takeAttrForAttributedType(const AttributedType * AT)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*");
306 }
307
308 SourceLocation
getExpansionLocForMacroQualifiedType(const MacroQualifiedType * MQT) const309 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
310 auto FoundLoc = LocsForMacros.find(MQT);
311 assert(FoundLoc != LocsForMacros.end() &&
312 "Unable to find macro expansion location for MacroQualifedType");
313 return FoundLoc->second;
314 }
315
setExpansionLocForMacroQualifiedType(const MacroQualifiedType * MQT,SourceLocation Loc)316 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
317 SourceLocation Loc) {
318 LocsForMacros[MQT] = Loc;
319 }
320
setParsedNoDeref(bool parsed)321 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
322
didParseNoDeref() const323 bool didParseNoDeref() const { return parsedNoDeref; }
324
~TypeProcessingState()325 ~TypeProcessingState() {
326 if (trivial) return;
327
328 restoreDeclSpecAttrs();
329 }
330
331 private:
getMutableDeclSpec() const332 DeclSpec &getMutableDeclSpec() const {
333 return const_cast<DeclSpec&>(declarator.getDeclSpec());
334 }
335
restoreDeclSpecAttrs()336 void restoreDeclSpecAttrs() {
337 assert(hasSavedAttrs);
338
339 getMutableDeclSpec().getAttributes().clearListOnly();
340 for (ParsedAttr *AL : savedAttrs)
341 getMutableDeclSpec().getAttributes().addAtEnd(AL);
342 }
343 };
344 } // end anonymous namespace
345
moveAttrFromListToList(ParsedAttr & attr,ParsedAttributesView & fromList,ParsedAttributesView & toList)346 static 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.
354 enum 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
363 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
364 TypeAttrLocation TAL, ParsedAttributesView &attrs);
365
366 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
367 QualType &type);
368
369 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
370 ParsedAttr &attr, QualType &type);
371
372 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
373 QualType &type);
374
375 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
376 ParsedAttr &attr, QualType &type);
377
handleObjCPointerTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)378 static 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);
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).
maybeMovePastReturnType(Declarator & declarator,unsigned i,bool onlyBlockPointers)395 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
396 unsigned i,
397 bool onlyBlockPointers) {
398 assert(i <= declarator.getNumTypeObjects());
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;
437
438 case DeclaratorChunk::BlockPointer:
439 result = &ptrChunk;
440 goto continue_outer;
441 }
442 llvm_unreachable("bad declarator chunk kind");
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");
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.
distributeObjCPointerTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType type)463 static 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.
distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)519 static 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.
distributeFunctionTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType type)580 static 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.
distributeFunctionTypeAttrToInnermost(TypeProcessingState & state,ParsedAttr & attr,ParsedAttributesView & attrList,QualType & declSpecType)611 static 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.
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)630 static 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.
distributeFunctionTypeAttrFromDeclarator(TypeProcessingState & state,ParsedAttr & attr,QualType & declSpecType)656 static 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;
distributeTypeAttrsFromDeclarator(TypeProcessingState & state,QualType & declSpecType)681 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
682 QualType &declSpecType) {
683 // Collect all the type attributes from the declarator itself.
684 assert(!state.getDeclarator().getAttributes().empty() &&
685 "declarator has no attrs!");
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_CASELIST:
698 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
699 break;
700
701 FUNCTION_TYPE_ATTRS_CASELIST:
702 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
703 break;
704
705 MS_TYPE_ATTRS_CASELIST:
706 // Microsoft type attributes cannot go after the declarator-id.
707 continue;
708
709 NULLABILITY_TYPE_ATTRS_CASELIST:
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.
maybeSynthesizeBlockSignature(TypeProcessingState & state,QualType declSpecType)724 static 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);
777 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
778 }
779
diagnoseAndRemoveTypeQualifiers(Sema & S,const DeclSpec & DS,unsigned & TypeQuals,QualType TypeSoFar,unsigned RemoveTQs,unsigned DiagID)780 static 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.
checkOmittedBlockReturnType(Sema & S,Declarator & declarator,QualType Result)808 static 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.
applyObjCTypeArgs(Sema & S,SourceLocation loc,QualType type,ArrayRef<TypeSourceInfo * > typeArgs,SourceRange typeArgsRange,bool failOnError=false)838 static 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?");
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?");
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
BuildObjCTypeParamType(const ObjCTypeParamDecl * Decl,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc,bool FailOnError)1044 QualType 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
BuildObjCObjectType(QualType BaseType,SourceLocation Loc,SourceLocation TypeArgsLAngleLoc,ArrayRef<TypeSourceInfo * > TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc,bool FailOnError)1067 QualType 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
actOnObjCProtocolQualifierType(SourceLocation lAngleLoc,ArrayRef<Decl * > protocols,ArrayRef<SourceLocation> protocolLocs,SourceLocation rAngleLoc)1103 TypeResult 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
actOnObjCTypeArgsAndProtocolQualifiers(Scope * S,SourceLocation Loc,ParsedType BaseType,SourceLocation TypeArgsLAngleLoc,ArrayRef<ParsedType> TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<Decl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc)1142 TypeResult 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?");
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());
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());
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());
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
1252 static OpenCLAccessAttr::Spelling
getImageAccess(const ParsedAttributesView & Attrs)1253 getImageAccess(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.
ConvertDeclSpecToType(TypeProcessingState & state)1266 static 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 &&
1291 "Unknown TSS value");
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 &&
1305 "Unknown TSS value");
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 &&
1314 "Unknown TSS value");
1315 Result = Context.Char8Ty;
1316 break;
1317 case DeclSpec::TST_char16:
1318 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1319 "Unknown TSS value");
1320 Result = Context.Char16Ty;
1321 break;
1322 case DeclSpec::TST_char32:
1323 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1324 "Unknown TSS value");
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;
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");
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");
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 &&
1578 DS.getTypeSpecComplex() == 0 &&
1579 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1580 "No qualifiers on tag names!");
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 &&
1594 DS.getTypeSpecComplex() == 0 &&
1595 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1596 "Can't handle qualifiers on typedef names yet!");
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?");
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?");
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?");
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?");
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?");
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"); \
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");
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");
1860 return Result;
1861 }
1862
getPrintableNameForEntity(DeclarationName Entity)1863 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1864 if (Entity)
1865 return Entity.getAsString();
1866
1867 return "type name";
1868 }
1869
BuildQualifiedType(QualType T,SourceLocation Loc,Qualifiers Qs,const DeclSpec * DS)1870 QualType 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
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVRAU,const DeclSpec * DS)1917 QualType 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.
BuildParenType(QualType T)1962 QualType Sema::BuildParenType(QualType T) {
1963 return Context.getParenType(T);
1964 }
1965
1966 /// Given that we're building a pointer or reference to the given
inferARCLifetimeForPointee(Sema & S,QualType type,SourceLocation loc,bool isReference)1967 static 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!");
2012
2013 Qualifiers qs;
2014 qs.addObjCLifetime(implicitLifetime);
2015 return S.Context.getQualifiedType(type, qs);
2016 }
2017
getFunctionQualifiersAsString(const FunctionProtoType * FnTy)2018 static 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
2041 namespace {
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.
2052 enum 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.
checkQualifiedFunction(Sema & S,QualType T,SourceLocation Loc,QualifiedFunctionKind QFK)2057 static 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
CheckQualifiedFunctionForTypeId(QualType T,SourceLocation Loc)2071 bool 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.
deduceOpenCLPointeeAddrSpace(Sema & S,QualType PointeeType)2083 static 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.
BuildPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)2107 QualType 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");
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.
BuildReferenceType(QualType T,bool SpelledAsLValue,SourceLocation Loc,DeclarationName Entity)2152 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2153 SourceLocation Loc,
2154 DeclarationName Entity) {
2155 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2156 "Unresolved overloaded function type");
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.
BuildReadPipeType(QualType T,SourceLocation Loc)2219 QualType 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.
BuildWritePipeType(QualType T,SourceLocation Loc)2231 QualType 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.
BuildExtIntType(bool IsUnsigned,Expr * BitWidth,SourceLocation Loc)2243 QualType 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().
checkArraySize(Sema & S,Expr * & ArraySize,llvm::APSInt & SizeVal,unsigned VLADiag,bool VLAIsError)2280 static 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.
BuildArrayType(QualType T,ArrayType::ArraySizeModifier ASM,Expr * ArraySize,unsigned Quals,SourceRange Brackets,DeclarationName Entity)2348 QualType 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
BuildVectorType(QualType CurType,Expr * SizeExpr,SourceLocation AttrLoc)2566 QualType 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.
BuildExtVectorType(QualType T,Expr * ArraySize,SourceLocation AttrLoc)2629 QualType 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
BuildMatrixType(QualType ElementTy,Expr * NumRows,Expr * NumCols,SourceLocation AttrLoc)2675 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2676 SourceLocation AttrLoc) {
2677 assert(Context.getLangOpts().MatrixTypes &&
2678 "Should never build a matrix type when it is disabled");
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
CheckFunctionReturnType(QualType T,SourceLocation Loc)2750 bool 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.
checkExtParameterInfos(Sema & S,ArrayRef<QualType> paramTypes,const FunctionProtoType::ExtProtoInfo & EPI,llvm::function_ref<SourceLocation (unsigned)> getParamLoc)2788 static 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");
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");
2847 }
2848 }
2849
BuildFunctionType(QualType T,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc,DeclarationName Entity,const FunctionProtoType::ExtProtoInfo & EPI)2850 QualType 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.
BuildMemberPointerType(QualType T,QualType Class,SourceLocation Loc,DeclarationName Entity)2904 QualType 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.
BuildBlockPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)2962 QualType 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
GetTypeFromParser(ParsedType Ty,TypeSourceInfo ** TInfo)2979 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2980 QualType QT = Ty.get();
2981 if (QT.isNull()) {
2982 if (TInfo) *TInfo = nullptr;
2983 return QualType();
2984 }
2985
2986 TypeSourceInfo *DI = nullptr;
2987 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2988 QT = LIT->getType();
2989 DI = LIT->getTypeSourceInfo();
2990 }
2991
2992 if (TInfo) *TInfo = DI;
2993 return QT;
2994 }
2995
2996 static 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.
inferARCWriteback(TypeProcessingState & state,QualType & declSpecType)3003 static 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
diagnoseIgnoredQualifiers(unsigned DiagID,unsigned Quals,SourceLocation FallbackLoc,SourceLocation ConstQualLoc,SourceLocation VolatileQualLoc,SourceLocation RestrictQualLoc,SourceLocation AtomicQualLoc,SourceLocation UnalignedQualLoc)3099 void 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.
diagnoseRedundantReturnTypeQualifiers(Sema & S,QualType RetTy,Declarator & D,unsigned FunctionChunkIndex)3150 static 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");
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
3220 static std::pair<QualType, TypeSourceInfo *>
InventTemplateParameter(TypeProcessingState & state,QualType T,TypeSourceInfo * TrailingTSI,AutoType * Auto,InventedTemplateParameterInfo & Info)3221 InventTemplateParameter(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
3317 static TypeSourceInfo *
3318 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3319 QualType T, TypeSourceInfo *ReturnTypeInfo);
3320
GetDeclSpecTypeForDeclarator(TypeProcessingState & state,TypeSourceInfo * & ReturnTypeInfo)3321 static 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!");
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");
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;
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;
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) &&
3550 "unknown auto type");
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");
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");
3643 return T;
3644 }
3645
3646 /// Produce an appropriate diagnostic for an ambiguity between a function
3647 /// declarator and a C++ direct-initializer.
warnAboutAmbiguousFunction(Sema & S,Declarator & D,DeclaratorChunk & DeclType,QualType RT)3648 static 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");
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.
warnAboutRedundantParens(Sema & S,Declarator & D,QualType T)3745 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3746 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3747 assert(Paren.Kind == DeclaratorChunk::Paren &&
3748 "do not have redundant top-level parentheses");
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;
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.
getCCForDeclaratorChunk(Sema & S,Declarator & D,const ParsedAttributesView & AttrList,const DeclaratorChunk::FunctionTypeInfo & FTI,unsigned ChunkIndex)3864 static 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);
3868
3869 // Check for an explicit CC attribute.
3870 for (const ParsedAttr &AL : AttrList) {
3871 switch (AL.getKind()) {
3872 CALLING_CONV_ATTRS_CASELIST : {
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());
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
3944 namespace {
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
getNullabilityKeyword(NullabilityKind nullability)3955 IdentifierInfo *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.");
3978 }
3979
3980 /// Retrieve the identifier "NSError".
getNSErrorIdent()3981 IdentifierInfo *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.
hasNullabilityAttr(const ParsedAttributesView & attrs)3990 static 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
4002 namespace {
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.
4036 static PointerDeclaratorKind
classifyPointerDeclarator(Sema & S,QualType type,Declarator & declarator,PointerWrappingDeclaratorKind & wrappingKind)4037 classifyPointerDeclarator(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
isCFError(RecordDecl * RD)4165 bool 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
getNullabilityCompletenessCheckFileID(Sema & S,SourceLocation loc)4190 static 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.
4229 template <typename DiagBuilderT>
fixItNullability(Sema & S,DiagBuilderT & Diag,SourceLocation PointerLoc,NullabilityKind Nullability)4230 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4231 SourceLocation PointerLoc,
4232 NullabilityKind Nullability) {
4233 assert(PointerLoc.isValid());
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
emitNullabilityConsistencyWarning(Sema & S,SimplePointerKind PointerKind,SourceLocation PointerLoc,SourceLocation PointerEndLoc)4265 static void emitNullabilityConsistencyWarning(Sema &S,
4266 SimplePointerKind PointerKind,
4267 SourceLocation PointerLoc,
4268 SourceLocation PointerEndLoc) {
4269 assert(PointerLoc.isValid());
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().
4298 static void
checkNullabilityConsistency(Sema & S,SimplePointerKind pointerKind,SourceLocation pointerLoc,SourceLocation pointerEndLoc=SourceLocation ())4299 checkNullabilityConsistency(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
recordNullabilitySeen(Sema & S,SourceLocation loc)4340 static 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.
hasOuterPointerLikeChunk(const Declarator & D,unsigned endIndex)4369 static 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
IsNoDerefableChunk(DeclaratorChunk Chunk)4393 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4394 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4395 Chunk.Kind == DeclaratorChunk::Array);
4396 }
4397
4398 template<typename AttrT>
createSimpleAttr(ASTContext & Ctx,ParsedAttr & AL)4399 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4400 AL.setUsedAsTypeAttr();
4401 return ::new (Ctx) AttrT(Ctx, AL);
4402 }
4403
createNullabilityAttr(ASTContext & Ctx,ParsedAttr & Attr,NullabilityKind NK)4404 static 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");
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."
DiagnoseMultipleAddrSpaceAttributes(Sema & S,LangAS ASOld,LangAS ASNew,SourceLocation AttrLoc)4426 static 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
GetFullTypeForDeclarator(TypeProcessingState & state,QualType declSpecType,TypeSourceInfo * TInfo)4441 static 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())
4455 Name = D.getIdentifier();
4456
4457 // Does this declaration declare a typedef-name?
4458 bool IsTypedefName =
4459 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4460 D.getContext() == DeclaratorContext::AliasDecl ||
4461 D.getContext() == DeclaratorContext::AliasTemplate;
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 = T->getAs<DeducedType>()) {
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()) {
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) {
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()) {
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;
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;
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;
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;
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()) {
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) {
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?");
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");
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)
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 &&
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");
5536
5537 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5538 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5539 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
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);
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 &&
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 &&
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()) {
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");
5730 if (D.isInvalidType())
5731 return Context.getTrivialTypeSourceInfo(T);
5732
5733 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
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.
GetTypeForDeclarator(Declarator & D,Scope * S)5741 TypeSourceInfo *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
transferARCOwnershipToDeclSpec(Sema & S,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)5755 static 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
transferARCOwnershipToDeclaratorChunk(TypeProcessingState & state,Qualifiers::ObjCLifetime ownership,unsigned chunkIndex)5766 static 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!");
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.
transferARCOwnership(TypeProcessingState & state,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)5803 static 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 ||
5849 chunk.Kind == DeclaratorChunk::Reference);
5850 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5851 }
5852 }
5853
GetTypeForDeclaratorCast(Declarator & D,QualType FromTy)5854 TypeSourceInfo *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
fillAttributedTypeLoc(AttributedTypeLoc TL,TypeProcessingState & State)5869 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5870 TypeProcessingState &State) {
5871 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5872 }
5873
5874 namespace {
5875 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5876 Sema &SemaRef;
5877 ASTContext &Context;
5878 TypeProcessingState &State;
5879 const DeclSpec &DS;
5880
5881 public:
TypeSpecLocFiller(Sema & S,ASTContext & Context,TypeProcessingState & State,const DeclSpec & DS)5882 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5883 const DeclSpec &DS)
5884 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5885
VisitAttributedTypeLoc(AttributedTypeLoc TL)5886 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5887 Visit(TL.getModifiedLoc());
5888 fillAttributedTypeLoc(TL, State);
5889 }
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)5890 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5891 Visit(TL.getInnerLoc());
5892 TL.setExpansionLoc(
5893 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5894 }
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)5895 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5896 Visit(TL.getUnqualifiedLoc());
5897 }
VisitTypedefTypeLoc(TypedefTypeLoc TL)5898 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5899 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5900 }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)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 }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)5908 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5909 TypeSourceInfo *RepTInfo = nullptr;
5910 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5911 TL.copy(RepTInfo->getTypeLoc());
5912 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)5913 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5914 TypeSourceInfo *RepTInfo = nullptr;
5915 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5916 TL.copy(RepTInfo->getTypeLoc());
5917 }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)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());
5938 }
5939
5940 }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)5941 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5942 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5943 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5944 TL.setParensRange(DS.getTypeofParensRange());
5945 }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)5946 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5947 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5948 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5949 TL.setParensRange(DS.getTypeofParensRange());
5950 assert(DS.getRepAsType());
5951 TypeSourceInfo *TInfo = nullptr;
5952 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5953 TL.setUnderlyingTInfo(TInfo);
5954 }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)5955 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5956 // FIXME: This holds only because we only have one unary transform.
5957 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5958 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5959 TL.setParensRange(DS.getTypeofParensRange());
5960 assert(DS.getRepAsType());
5961 TypeSourceInfo *TInfo = nullptr;
5962 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5963 TL.setUnderlyingTInfo(TInfo);
5964 }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)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 }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)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 }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)5996 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5997 assert(DS.getTypeSpecType() == TST_typename);
5998 TypeSourceInfo *TInfo = nullptr;
5999 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6000 assert(TInfo);
6001 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6002 }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)6003 void VisitDependentTemplateSpecializationTypeLoc(
6004 DependentTemplateSpecializationTypeLoc TL) {
6005 assert(DS.getTypeSpecType() == TST_typename);
6006 TypeSourceInfo *TInfo = nullptr;
6007 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6008 assert(TInfo);
6009 TL.copy(
6010 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6011 }
VisitAutoTypeLoc(AutoTypeLoc TL)6012 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6013 assert(DS.getTypeSpecType() == TST_auto ||
6014 DS.getTypeSpecType() == TST_decltype_auto ||
6015 DS.getTypeSpecType() == TST_auto_type ||
6016 DS.getTypeSpecType() == TST_unspecified);
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 }
VisitTagTypeLoc(TagTypeLoc TL)6042 void VisitTagTypeLoc(TagTypeLoc TL) {
6043 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6044 }
VisitAtomicTypeLoc(AtomicTypeLoc TL)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) {
6049 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6050 TL.setParensRange(DS.getTypeofParensRange());
6051
6052 TypeSourceInfo *TInfo = nullptr;
6053 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6054 assert(TInfo);
6055 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
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
VisitPipeTypeLoc(PipeTypeLoc TL)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
VisitExtIntTypeLoc(ExtIntTypeLoc TL)6072 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6073 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6074 }
6075
VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL)6076 void VisitDependentExtIntTypeLoc(DependentExtIntTypeLoc TL) {
6077 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6078 }
6079
VisitTypeLoc(TypeLoc TL)6080 void VisitTypeLoc(TypeLoc TL) {
6081 // FIXME: add other typespec types and change this to an assert.
6082 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6083 }
6084 };
6085
6086 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6087 ASTContext &Context;
6088 TypeProcessingState &State;
6089 const DeclaratorChunk &Chunk;
6090
6091 public:
DeclaratorLocFiller(ASTContext & Context,TypeProcessingState & State,const DeclaratorChunk & Chunk)6092 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6093 const DeclaratorChunk &Chunk)
6094 : Context(Context), State(State), Chunk(Chunk) {}
6095
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)6096 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6097 llvm_unreachable("qualified type locs not expected here!");
6098 }
VisitDecayedTypeLoc(DecayedTypeLoc TL)6099 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6100 llvm_unreachable("decayed type locs not expected here!");
6101 }
6102
VisitAttributedTypeLoc(AttributedTypeLoc TL)6103 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6104 fillAttributedTypeLoc(TL, State);
6105 }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)6106 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6107 // nothing
6108 }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)6109 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6110 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6111 TL.setCaretLoc(Chunk.Loc);
6112 }
VisitPointerTypeLoc(PointerTypeLoc TL)6113 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6114 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6115 TL.setStarLoc(Chunk.Loc);
6116 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)6117 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6118 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6119 TL.setStarLoc(Chunk.Loc);
6120 }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)6121 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6122 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6123 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6124 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6125
6126 const Type* ClsTy = TL.getClass();
6127 QualType ClsQT = QualType(ClsTy, 0);
6128 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6129 // Now copy source location info into the type loc component.
6130 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6131 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6132 case NestedNameSpecifier::Identifier:
6133 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6134 {
6135 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6136 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6137 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6138 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6139 }
6140 break;
6141
6142 case NestedNameSpecifier::TypeSpec:
6143 case NestedNameSpecifier::TypeSpecWithTemplate:
6144 if (isa<ElaboratedType>(ClsTy)) {
6145 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6146 ETLoc.setElaboratedKeywordLoc(SourceLocation());
6147 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6148 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6149 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6150 } else {
6151 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6152 }
6153 break;
6154
6155 case NestedNameSpecifier::Namespace:
6156 case NestedNameSpecifier::NamespaceAlias:
6157 case NestedNameSpecifier::Global:
6158 case NestedNameSpecifier::Super:
6159 llvm_unreachable("Nested-name-specifier must name a type");
6160 }
6161
6162 // Finally fill in MemberPointerLocInfo fields.
6163 TL.setStarLoc(Chunk.Mem.StarLoc);
6164 TL.setClassTInfo(ClsTInfo);
6165 }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)6166 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6167 assert(Chunk.Kind == DeclaratorChunk::Reference);
6168 // 'Amp' is misleading: this might have been originally
6169 /// spelled with AmpAmp.
6170 TL.setAmpLoc(Chunk.Loc);
6171 }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)6172 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6173 assert(Chunk.Kind == DeclaratorChunk::Reference);
6174 assert(!Chunk.Ref.LValueRef);
6175 TL.setAmpAmpLoc(Chunk.Loc);
6176 }
VisitArrayTypeLoc(ArrayTypeLoc TL)6177 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6178 assert(Chunk.Kind == DeclaratorChunk::Array);
6179 TL.setLBracketLoc(Chunk.Loc);
6180 TL.setRBracketLoc(Chunk.EndLoc);
6181 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6182 }
VisitFunctionTypeLoc(FunctionTypeLoc TL)6183 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6184 assert(Chunk.Kind == DeclaratorChunk::Function);
6185 TL.setLocalRangeBegin(Chunk.Loc);
6186 TL.setLocalRangeEnd(Chunk.EndLoc);
6187
6188 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6189 TL.setLParenLoc(FTI.getLParenLoc());
6190 TL.setRParenLoc(FTI.getRParenLoc());
6191 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6192 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6193 TL.setParam(tpi++, Param);
6194 }
6195 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6196 }
VisitParenTypeLoc(ParenTypeLoc TL)6197 void VisitParenTypeLoc(ParenTypeLoc TL) {
6198 assert(Chunk.Kind == DeclaratorChunk::Paren);
6199 TL.setLParenLoc(Chunk.Loc);
6200 TL.setRParenLoc(Chunk.EndLoc);
6201 }
VisitPipeTypeLoc(PipeTypeLoc TL)6202 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6203 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6204 TL.setKWLoc(Chunk.Loc);
6205 }
VisitExtIntTypeLoc(ExtIntTypeLoc TL)6206 void VisitExtIntTypeLoc(ExtIntTypeLoc TL) {
6207 TL.setNameLoc(Chunk.Loc);
6208 }
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)6209 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6210 TL.setExpansionLoc(Chunk.Loc);
6211 }
VisitVectorTypeLoc(VectorTypeLoc TL)6212 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL)6213 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6214 TL.setNameLoc(Chunk.Loc);
6215 }
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)6216 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6217 TL.setNameLoc(Chunk.Loc);
6218 }
6219 void
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)6220 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6221 TL.setNameLoc(Chunk.Loc);
6222 }
6223
VisitTypeLoc(TypeLoc TL)6224 void VisitTypeLoc(TypeLoc TL) {
6225 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6226 }
6227 };
6228 } // end anonymous namespace
6229
fillAtomicQualLoc(AtomicTypeLoc ATL,const DeclaratorChunk & Chunk)6230 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6231 SourceLocation Loc;
6232 switch (Chunk.Kind) {
6233 case DeclaratorChunk::Function:
6234 case DeclaratorChunk::Array:
6235 case DeclaratorChunk::Paren:
6236 case DeclaratorChunk::Pipe:
6237 llvm_unreachable("cannot be _Atomic qualified");
6238
6239 case DeclaratorChunk::Pointer:
6240 Loc = Chunk.Ptr.AtomicQualLoc;
6241 break;
6242
6243 case DeclaratorChunk::BlockPointer:
6244 case DeclaratorChunk::Reference:
6245 case DeclaratorChunk::MemberPointer:
6246 // FIXME: Provide a source location for the _Atomic keyword.
6247 break;
6248 }
6249
6250 ATL.setKWLoc(Loc);
6251 ATL.setParensRange(SourceRange());
6252 }
6253
6254 static void
fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,const ParsedAttributesView & Attrs)6255 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6256 const ParsedAttributesView &Attrs) {
6257 for (const ParsedAttr &AL : Attrs) {
6258 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6259 DASTL.setAttrNameLoc(AL.getLoc());
6260 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6261 DASTL.setAttrOperandParensRange(SourceRange());
6262 return;
6263 }
6264 }
6265
6266 llvm_unreachable(
6267 "no address_space attribute found at the expected location!");
6268 }
6269
fillMatrixTypeLoc(MatrixTypeLoc MTL,const ParsedAttributesView & Attrs)6270 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6271 const ParsedAttributesView &Attrs) {
6272 for (const ParsedAttr &AL : Attrs) {
6273 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6274 MTL.setAttrNameLoc(AL.getLoc());
6275 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6276 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6277 MTL.setAttrOperandParensRange(SourceRange());
6278 return;
6279 }
6280 }
6281
6282 llvm_unreachable("no matrix_type attribute found at the expected location!");
6283 }
6284
6285 /// Create and instantiate a TypeSourceInfo with type source information.
6286 ///
6287 /// \param T QualType referring to the type as written in source code.
6288 ///
6289 /// \param ReturnTypeInfo For declarators whose return type does not show
6290 /// up in the normal place in the declaration specifiers (such as a C++
6291 /// conversion function), this pointer will refer to a type source information
6292 /// for that return type.
6293 static TypeSourceInfo *
GetTypeSourceInfoForDeclarator(TypeProcessingState & State,QualType T,TypeSourceInfo * ReturnTypeInfo)6294 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6295 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6296 Sema &S = State.getSema();
6297 Declarator &D = State.getDeclarator();
6298
6299 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6300 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6301
6302 // Handle parameter packs whose type is a pack expansion.
6303 if (isa<PackExpansionType>(T)) {
6304 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6305 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6306 }
6307
6308 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6309 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6310 // declarator chunk.
6311 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6312 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6313 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6314 }
6315
6316 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
6317 TL.setExpansionLoc(
6318 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6319 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6320 }
6321
6322 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
6323 fillAttributedTypeLoc(TL, State);
6324 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6325 }
6326
6327 while (DependentAddressSpaceTypeLoc TL =
6328 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
6329 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6330 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6331 }
6332
6333 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>())
6334 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs());
6335
6336 // FIXME: Ordering here?
6337 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
6338 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6339
6340 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6341 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6342 }
6343
6344 // If we have different source information for the return type, use
6345 // that. This really only applies to C++ conversion functions.
6346 if (ReturnTypeInfo) {
6347 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6348 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6349 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6350 } else {
6351 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6352 }
6353
6354 return TInfo;
6355 }
6356
6357 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
CreateParsedType(QualType T,TypeSourceInfo * TInfo)6358 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6359 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6360 // and Sema during declaration parsing. Try deallocating/caching them when
6361 // it's appropriate, instead of allocating them and keeping them around.
6362 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6363 TypeAlignment);
6364 new (LocT) LocInfoType(T, TInfo);
6365 assert(LocT->getTypeClass() != T->getTypeClass() &&
6366 "LocInfoType's TypeClass conflicts with an existing Type class");
6367 return ParsedType::make(QualType(LocT, 0));
6368 }
6369
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const6370 void LocInfoType::getAsStringInternal(std::string &Str,
6371 const PrintingPolicy &Policy) const {
6372 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6373 " was used directly instead of getting the QualType through"
6374 " GetTypeFromParser");
6375 }
6376
ActOnTypeName(Scope * S,Declarator & D)6377 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6378 // C99 6.7.6: Type names have no identifier. This is already validated by
6379 // the parser.
6380 assert(D.getIdentifier() == nullptr &&
6381 "Type name should have no identifier!");
6382
6383 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6384 QualType T = TInfo->getType();
6385 if (D.isInvalidType())
6386 return true;
6387
6388 // Make sure there are no unused decl attributes on the declarator.
6389 // We don't want to do this for ObjC parameters because we're going
6390 // to apply them to the actual parameter declaration.
6391 // Likewise, we don't want to do this for alias declarations, because
6392 // we are actually going to build a declaration from this eventually.
6393 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6394 D.getContext() != DeclaratorContext::AliasDecl &&
6395 D.getContext() != DeclaratorContext::AliasTemplate)
6396 checkUnusedDeclAttributes(D);
6397
6398 if (getLangOpts().CPlusPlus) {
6399 // Check that there are no default arguments (C++ only).
6400 CheckExtraCXXDefaultArguments(D);
6401 }
6402
6403 return CreateParsedType(T, TInfo);
6404 }
6405
ActOnObjCInstanceType(SourceLocation Loc)6406 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6407 QualType T = Context.getObjCInstanceType();
6408 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6409 return CreateParsedType(T, TInfo);
6410 }
6411
6412 //===----------------------------------------------------------------------===//
6413 // Type Attribute Processing
6414 //===----------------------------------------------------------------------===//
6415
6416 /// Build an AddressSpace index from a constant expression and diagnose any
6417 /// errors related to invalid address_spaces. Returns true on successfully
6418 /// building an AddressSpace index.
BuildAddressSpaceIndex(Sema & S,LangAS & ASIdx,const Expr * AddrSpace,SourceLocation AttrLoc)6419 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6420 const Expr *AddrSpace,
6421 SourceLocation AttrLoc) {
6422 if (!AddrSpace->isValueDependent()) {
6423 Optional<llvm::APSInt> OptAddrSpace =
6424 AddrSpace->getIntegerConstantExpr(S.Context);
6425 if (!OptAddrSpace) {
6426 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6427 << "'address_space'" << AANT_ArgumentIntegerConstant
6428 << AddrSpace->getSourceRange();
6429 return false;
6430 }
6431 llvm::APSInt &addrSpace = *OptAddrSpace;
6432
6433 // Bounds checking.
6434 if (addrSpace.isSigned()) {
6435 if (addrSpace.isNegative()) {
6436 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6437 << AddrSpace->getSourceRange();
6438 return false;
6439 }
6440 addrSpace.setIsSigned(false);
6441 }
6442
6443 llvm::APSInt max(addrSpace.getBitWidth());
6444 max =
6445 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6446
6447 if (addrSpace > max) {
6448 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6449 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6450 return false;
6451 }
6452
6453 ASIdx =
6454 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6455 return true;
6456 }
6457
6458 // Default value for DependentAddressSpaceTypes
6459 ASIdx = LangAS::Default;
6460 return true;
6461 }
6462
6463 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6464 /// is uninstantiated. If instantiated it will apply the appropriate address
6465 /// space to the type. This function allows dependent template variables to be
6466 /// used in conjunction with the address_space attribute
BuildAddressSpaceAttr(QualType & T,LangAS ASIdx,Expr * AddrSpace,SourceLocation AttrLoc)6467 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6468 SourceLocation AttrLoc) {
6469 if (!AddrSpace->isValueDependent()) {
6470 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6471 AttrLoc))
6472 return QualType();
6473
6474 return Context.getAddrSpaceQualType(T, ASIdx);
6475 }
6476
6477 // A check with similar intentions as checking if a type already has an
6478 // address space except for on a dependent types, basically if the
6479 // current type is already a DependentAddressSpaceType then its already
6480 // lined up to have another address space on it and we can't have
6481 // multiple address spaces on the one pointer indirection
6482 if (T->getAs<DependentAddressSpaceType>()) {
6483 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6484 return QualType();
6485 }
6486
6487 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6488 }
6489
BuildAddressSpaceAttr(QualType & T,Expr * AddrSpace,SourceLocation AttrLoc)6490 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6491 SourceLocation AttrLoc) {
6492 LangAS ASIdx;
6493 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6494 return QualType();
6495 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6496 }
6497
6498 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6499 /// specified type. The attribute contains 1 argument, the id of the address
6500 /// space for the type.
HandleAddressSpaceTypeAttribute(QualType & Type,const ParsedAttr & Attr,TypeProcessingState & State)6501 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6502 const ParsedAttr &Attr,
6503 TypeProcessingState &State) {
6504 Sema &S = State.getSema();
6505
6506 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6507 // qualified by an address-space qualifier."
6508 if (Type->isFunctionType()) {
6509 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6510 Attr.setInvalid();
6511 return;
6512 }
6513
6514 LangAS ASIdx;
6515 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6516
6517 // Check the attribute arguments.
6518 if (Attr.getNumArgs() != 1) {
6519 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6520 << 1;
6521 Attr.setInvalid();
6522 return;
6523 }
6524
6525 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6526 LangAS ASIdx;
6527 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6528 Attr.setInvalid();
6529 return;
6530 }
6531
6532 ASTContext &Ctx = S.Context;
6533 auto *ASAttr =
6534 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6535
6536 // If the expression is not value dependent (not templated), then we can
6537 // apply the address space qualifiers just to the equivalent type.
6538 // Otherwise, we make an AttributedType with the modified and equivalent
6539 // type the same, and wrap it in a DependentAddressSpaceType. When this
6540 // dependent type is resolved, the qualifier is added to the equivalent type
6541 // later.
6542 QualType T;
6543 if (!ASArgExpr->isValueDependent()) {
6544 QualType EquivType =
6545 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6546 if (EquivType.isNull()) {
6547 Attr.setInvalid();
6548 return;
6549 }
6550 T = State.getAttributedType(ASAttr, Type, EquivType);
6551 } else {
6552 T = State.getAttributedType(ASAttr, Type, Type);
6553 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6554 }
6555
6556 if (!T.isNull())
6557 Type = T;
6558 else
6559 Attr.setInvalid();
6560 } else {
6561 // The keyword-based type attributes imply which address space to use.
6562 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6563 : Attr.asOpenCLLangAS();
6564
6565 if (ASIdx == LangAS::Default)
6566 llvm_unreachable("Invalid address space");
6567
6568 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6569 Attr.getLoc())) {
6570 Attr.setInvalid();
6571 return;
6572 }
6573
6574 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6575 }
6576 }
6577
6578 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6579 /// attribute on the specified type.
6580 ///
6581 /// Returns 'true' if the attribute was handled.
handleObjCOwnershipTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)6582 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6583 ParsedAttr &attr, QualType &type) {
6584 bool NonObjCPointer = false;
6585
6586 if (!type->isDependentType() && !type->isUndeducedType()) {
6587 if (const PointerType *ptr = type->getAs<PointerType>()) {
6588 QualType pointee = ptr->getPointeeType();
6589 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6590 return false;
6591 // It is important not to lose the source info that there was an attribute
6592 // applied to non-objc pointer. We will create an attributed type but
6593 // its type will be the same as the original type.
6594 NonObjCPointer = true;
6595 } else if (!type->isObjCRetainableType()) {
6596 return false;
6597 }
6598
6599 // Don't accept an ownership attribute in the declspec if it would
6600 // just be the return type of a block pointer.
6601 if (state.isProcessingDeclSpec()) {
6602 Declarator &D = state.getDeclarator();
6603 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6604 /*onlyBlockPointers=*/true))
6605 return false;
6606 }
6607 }
6608
6609 Sema &S = state.getSema();
6610 SourceLocation AttrLoc = attr.getLoc();
6611 if (AttrLoc.isMacroID())
6612 AttrLoc =
6613 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6614
6615 if (!attr.isArgIdent(0)) {
6616 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6617 << AANT_ArgumentString;
6618 attr.setInvalid();
6619 return true;
6620 }
6621
6622 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6623 Qualifiers::ObjCLifetime lifetime;
6624 if (II->isStr("none"))
6625 lifetime = Qualifiers::OCL_ExplicitNone;
6626 else if (II->isStr("strong"))
6627 lifetime = Qualifiers::OCL_Strong;
6628 else if (II->isStr("weak"))
6629 lifetime = Qualifiers::OCL_Weak;
6630 else if (II->isStr("autoreleasing"))
6631 lifetime = Qualifiers::OCL_Autoreleasing;
6632 else {
6633 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6634 attr.setInvalid();
6635 return true;
6636 }
6637
6638 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6639 // outside of ARC mode.
6640 if (!S.getLangOpts().ObjCAutoRefCount &&
6641 lifetime != Qualifiers::OCL_Weak &&
6642 lifetime != Qualifiers::OCL_ExplicitNone) {
6643 return true;
6644 }
6645
6646 SplitQualType underlyingType = type.split();
6647
6648 // Check for redundant/conflicting ownership qualifiers.
6649 if (Qualifiers::ObjCLifetime previousLifetime
6650 = type.getQualifiers().getObjCLifetime()) {
6651 // If it's written directly, that's an error.
6652 if (S.Context.hasDirectOwnershipQualifier(type)) {
6653 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6654 << type;
6655 return true;
6656 }
6657
6658 // Otherwise, if the qualifiers actually conflict, pull sugar off
6659 // and remove the ObjCLifetime qualifiers.
6660 if (previousLifetime != lifetime) {
6661 // It's possible to have multiple local ObjCLifetime qualifiers. We
6662 // can't stop after we reach a type that is directly qualified.
6663 const Type *prevTy = nullptr;
6664 while (!prevTy || prevTy != underlyingType.Ty) {
6665 prevTy = underlyingType.Ty;
6666 underlyingType = underlyingType.getSingleStepDesugaredType();
6667 }
6668 underlyingType.Quals.removeObjCLifetime();
6669 }
6670 }
6671
6672 underlyingType.Quals.addObjCLifetime(lifetime);
6673
6674 if (NonObjCPointer) {
6675 StringRef name = attr.getAttrName()->getName();
6676 switch (lifetime) {
6677 case Qualifiers::OCL_None:
6678 case Qualifiers::OCL_ExplicitNone:
6679 break;
6680 case Qualifiers::OCL_Strong: name = "__strong"; break;
6681 case Qualifiers::OCL_Weak: name = "__weak"; break;
6682 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6683 }
6684 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6685 << TDS_ObjCObjOrBlock << type;
6686 }
6687
6688 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6689 // because having both 'T' and '__unsafe_unretained T' exist in the type
6690 // system causes unfortunate widespread consistency problems. (For example,
6691 // they're not considered compatible types, and we mangle them identicially
6692 // as template arguments.) These problems are all individually fixable,
6693 // but it's easier to just not add the qualifier and instead sniff it out
6694 // in specific places using isObjCInertUnsafeUnretainedType().
6695 //
6696 // Doing this does means we miss some trivial consistency checks that
6697 // would've triggered in ARC, but that's better than trying to solve all
6698 // the coexistence problems with __unsafe_unretained.
6699 if (!S.getLangOpts().ObjCAutoRefCount &&
6700 lifetime == Qualifiers::OCL_ExplicitNone) {
6701 type = state.getAttributedType(
6702 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6703 type, type);
6704 return true;
6705 }
6706
6707 QualType origType = type;
6708 if (!NonObjCPointer)
6709 type = S.Context.getQualifiedType(underlyingType);
6710
6711 // If we have a valid source location for the attribute, use an
6712 // AttributedType instead.
6713 if (AttrLoc.isValid()) {
6714 type = state.getAttributedType(::new (S.Context)
6715 ObjCOwnershipAttr(S.Context, attr, II),
6716 origType, type);
6717 }
6718
6719 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6720 unsigned diagnostic, QualType type) {
6721 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6722 S.DelayedDiagnostics.add(
6723 sema::DelayedDiagnostic::makeForbiddenType(
6724 S.getSourceManager().getExpansionLoc(loc),
6725 diagnostic, type, /*ignored*/ 0));
6726 } else {
6727 S.Diag(loc, diagnostic);
6728 }
6729 };
6730
6731 // Sometimes, __weak isn't allowed.
6732 if (lifetime == Qualifiers::OCL_Weak &&
6733 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6734
6735 // Use a specialized diagnostic if the runtime just doesn't support them.
6736 unsigned diagnostic =
6737 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6738 : diag::err_arc_weak_no_runtime);
6739
6740 // In any case, delay the diagnostic until we know what we're parsing.
6741 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6742
6743 attr.setInvalid();
6744 return true;
6745 }
6746
6747 // Forbid __weak for class objects marked as
6748 // objc_arc_weak_reference_unavailable
6749 if (lifetime == Qualifiers::OCL_Weak) {
6750 if (const ObjCObjectPointerType *ObjT =
6751 type->getAs<ObjCObjectPointerType>()) {
6752 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6753 if (Class->isArcWeakrefUnavailable()) {
6754 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6755 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6756 diag::note_class_declared);
6757 }
6758 }
6759 }
6760 }
6761
6762 return true;
6763 }
6764
6765 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6766 /// attribute on the specified type. Returns true to indicate that
6767 /// the attribute was handled, false to indicate that the type does
6768 /// not permit the attribute.
handleObjCGCTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)6769 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6770 QualType &type) {
6771 Sema &S = state.getSema();
6772
6773 // Delay if this isn't some kind of pointer.
6774 if (!type->isPointerType() &&
6775 !type->isObjCObjectPointerType() &&
6776 !type->isBlockPointerType())
6777 return false;
6778
6779 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6780 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6781 attr.setInvalid();
6782 return true;
6783 }
6784
6785 // Check the attribute arguments.
6786 if (!attr.isArgIdent(0)) {
6787 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6788 << attr << AANT_ArgumentString;
6789 attr.setInvalid();
6790 return true;
6791 }
6792 Qualifiers::GC GCAttr;
6793 if (attr.getNumArgs() > 1) {
6794 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6795 << 1;
6796 attr.setInvalid();
6797 return true;
6798 }
6799
6800 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6801 if (II->isStr("weak"))
6802 GCAttr = Qualifiers::Weak;
6803 else if (II->isStr("strong"))
6804 GCAttr = Qualifiers::Strong;
6805 else {
6806 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6807 << attr << II;
6808 attr.setInvalid();
6809 return true;
6810 }
6811
6812 QualType origType = type;
6813 type = S.Context.getObjCGCQualType(origType, GCAttr);
6814
6815 // Make an attributed type to preserve the source information.
6816 if (attr.getLoc().isValid())
6817 type = state.getAttributedType(
6818 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6819
6820 return true;
6821 }
6822
6823 namespace {
6824 /// A helper class to unwrap a type down to a function for the
6825 /// purposes of applying attributes there.
6826 ///
6827 /// Use:
6828 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6829 /// if (unwrapped.isFunctionType()) {
6830 /// const FunctionType *fn = unwrapped.get();
6831 /// // change fn somehow
6832 /// T = unwrapped.wrap(fn);
6833 /// }
6834 struct FunctionTypeUnwrapper {
6835 enum WrapKind {
6836 Desugar,
6837 Attributed,
6838 Parens,
6839 Array,
6840 Pointer,
6841 BlockPointer,
6842 Reference,
6843 MemberPointer,
6844 MacroQualified,
6845 };
6846
6847 QualType Original;
6848 const FunctionType *Fn;
6849 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6850
FunctionTypeUnwrapper__anon6856d05d1311::FunctionTypeUnwrapper6851 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6852 while (true) {
6853 const Type *Ty = T.getTypePtr();
6854 if (isa<FunctionType>(Ty)) {
6855 Fn = cast<FunctionType>(Ty);
6856 return;
6857 } else if (isa<ParenType>(Ty)) {
6858 T = cast<ParenType>(Ty)->getInnerType();
6859 Stack.push_back(Parens);
6860 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
6861 isa<IncompleteArrayType>(Ty)) {
6862 T = cast<ArrayType>(Ty)->getElementType();
6863 Stack.push_back(Array);
6864 } else if (isa<PointerType>(Ty)) {
6865 T = cast<PointerType>(Ty)->getPointeeType();
6866 Stack.push_back(Pointer);
6867 } else if (isa<BlockPointerType>(Ty)) {
6868 T = cast<BlockPointerType>(Ty)->getPointeeType();
6869 Stack.push_back(BlockPointer);
6870 } else if (isa<MemberPointerType>(Ty)) {
6871 T = cast<MemberPointerType>(Ty)->getPointeeType();
6872 Stack.push_back(MemberPointer);
6873 } else if (isa<ReferenceType>(Ty)) {
6874 T = cast<ReferenceType>(Ty)->getPointeeType();
6875 Stack.push_back(Reference);
6876 } else if (isa<AttributedType>(Ty)) {
6877 T = cast<AttributedType>(Ty)->getEquivalentType();
6878 Stack.push_back(Attributed);
6879 } else if (isa<MacroQualifiedType>(Ty)) {
6880 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
6881 Stack.push_back(MacroQualified);
6882 } else {
6883 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6884 if (Ty == DTy) {
6885 Fn = nullptr;
6886 return;
6887 }
6888
6889 T = QualType(DTy, 0);
6890 Stack.push_back(Desugar);
6891 }
6892 }
6893 }
6894
isFunctionType__anon6856d05d1311::FunctionTypeUnwrapper6895 bool isFunctionType() const { return (Fn != nullptr); }
get__anon6856d05d1311::FunctionTypeUnwrapper6896 const FunctionType *get() const { return Fn; }
6897
wrap__anon6856d05d1311::FunctionTypeUnwrapper6898 QualType wrap(Sema &S, const FunctionType *New) {
6899 // If T wasn't modified from the unwrapped type, do nothing.
6900 if (New == get()) return Original;
6901
6902 Fn = New;
6903 return wrap(S.Context, Original, 0);
6904 }
6905
6906 private:
wrap__anon6856d05d1311::FunctionTypeUnwrapper6907 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6908 if (I == Stack.size())
6909 return C.getQualifiedType(Fn, Old.getQualifiers());
6910
6911 // Build up the inner type, applying the qualifiers from the old
6912 // type to the new type.
6913 SplitQualType SplitOld = Old.split();
6914
6915 // As a special case, tail-recurse if there are no qualifiers.
6916 if (SplitOld.Quals.empty())
6917 return wrap(C, SplitOld.Ty, I);
6918 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6919 }
6920
wrap__anon6856d05d1311::FunctionTypeUnwrapper6921 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6922 if (I == Stack.size()) return QualType(Fn, 0);
6923
6924 switch (static_cast<WrapKind>(Stack[I++])) {
6925 case Desugar:
6926 // This is the point at which we potentially lose source
6927 // information.
6928 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6929
6930 case Attributed:
6931 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6932
6933 case Parens: {
6934 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6935 return C.getParenType(New);
6936 }
6937
6938 case MacroQualified:
6939 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
6940
6941 case Array: {
6942 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
6943 QualType New = wrap(C, CAT->getElementType(), I);
6944 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
6945 CAT->getSizeModifier(),
6946 CAT->getIndexTypeCVRQualifiers());
6947 }
6948
6949 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
6950 QualType New = wrap(C, VAT->getElementType(), I);
6951 return C.getVariableArrayType(
6952 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
6953 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
6954 }
6955
6956 const auto *IAT = cast<IncompleteArrayType>(Old);
6957 QualType New = wrap(C, IAT->getElementType(), I);
6958 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
6959 IAT->getIndexTypeCVRQualifiers());
6960 }
6961
6962 case Pointer: {
6963 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6964 return C.getPointerType(New);
6965 }
6966
6967 case BlockPointer: {
6968 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6969 return C.getBlockPointerType(New);
6970 }
6971
6972 case MemberPointer: {
6973 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6974 QualType New = wrap(C, OldMPT->getPointeeType(), I);
6975 return C.getMemberPointerType(New, OldMPT->getClass());
6976 }
6977
6978 case Reference: {
6979 const ReferenceType *OldRef = cast<ReferenceType>(Old);
6980 QualType New = wrap(C, OldRef->getPointeeType(), I);
6981 if (isa<LValueReferenceType>(OldRef))
6982 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6983 else
6984 return C.getRValueReferenceType(New);
6985 }
6986 }
6987
6988 llvm_unreachable("unknown wrapping kind");
6989 }
6990 };
6991 } // end anonymous namespace
6992
handleMSPointerTypeQualifierAttr(TypeProcessingState & State,ParsedAttr & PAttr,QualType & Type)6993 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6994 ParsedAttr &PAttr, QualType &Type) {
6995 Sema &S = State.getSema();
6996
6997 Attr *A;
6998 switch (PAttr.getKind()) {
6999 default: llvm_unreachable("Unknown attribute kind");
7000 case ParsedAttr::AT_Ptr32:
7001 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7002 break;
7003 case ParsedAttr::AT_Ptr64:
7004 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7005 break;
7006 case ParsedAttr::AT_SPtr:
7007 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7008 break;
7009 case ParsedAttr::AT_UPtr:
7010 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7011 break;
7012 }
7013
7014 std::bitset<attr::LastAttr> Attrs;
7015 attr::Kind NewAttrKind = A->getKind();
7016 QualType Desugared = Type;
7017 const AttributedType *AT = dyn_cast<AttributedType>(Type);
7018 while (AT) {
7019 Attrs[AT->getAttrKind()] = true;
7020 Desugared = AT->getModifiedType();
7021 AT = dyn_cast<AttributedType>(Desugared);
7022 }
7023
7024 // You cannot specify duplicate type attributes, so if the attribute has
7025 // already been applied, flag it.
7026 if (Attrs[NewAttrKind]) {
7027 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7028 return true;
7029 }
7030 Attrs[NewAttrKind] = true;
7031
7032 // You cannot have both __sptr and __uptr on the same type, nor can you
7033 // have __ptr32 and __ptr64.
7034 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7035 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7036 << "'__ptr32'"
7037 << "'__ptr64'";
7038 return true;
7039 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7040 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7041 << "'__sptr'"
7042 << "'__uptr'";
7043 return true;
7044 }
7045
7046 // Pointer type qualifiers can only operate on pointer types, but not
7047 // pointer-to-member types.
7048 //
7049 // FIXME: Should we really be disallowing this attribute if there is any
7050 // type sugar between it and the pointer (other than attributes)? Eg, this
7051 // disallows the attribute on a parenthesized pointer.
7052 // And if so, should we really allow *any* type attribute?
7053 if (!isa<PointerType>(Desugared)) {
7054 if (Type->isMemberPointerType())
7055 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7056 else
7057 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7058 return true;
7059 }
7060
7061 // Add address space to type based on its attributes.
7062 LangAS ASIdx = LangAS::Default;
7063 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0);
7064 if (PtrWidth == 32) {
7065 if (Attrs[attr::Ptr64])
7066 ASIdx = LangAS::ptr64;
7067 else if (Attrs[attr::UPtr])
7068 ASIdx = LangAS::ptr32_uptr;
7069 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7070 if (Attrs[attr::UPtr])
7071 ASIdx = LangAS::ptr32_uptr;
7072 else
7073 ASIdx = LangAS::ptr32_sptr;
7074 }
7075
7076 QualType Pointee = Type->getPointeeType();
7077 if (ASIdx != LangAS::Default)
7078 Pointee = S.Context.getAddrSpaceQualType(
7079 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7080 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7081 return false;
7082 }
7083
7084 /// Map a nullability attribute kind to a nullability kind.
mapNullabilityAttrKind(ParsedAttr::Kind kind)7085 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7086 switch (kind) {
7087 case ParsedAttr::AT_TypeNonNull:
7088 return NullabilityKind::NonNull;
7089
7090 case ParsedAttr::AT_TypeNullable:
7091 return NullabilityKind::Nullable;
7092
7093 case ParsedAttr::AT_TypeNullableResult:
7094 return NullabilityKind::NullableResult;
7095
7096 case ParsedAttr::AT_TypeNullUnspecified:
7097 return NullabilityKind::Unspecified;
7098
7099 default:
7100 llvm_unreachable("not a nullability attribute kind");
7101 }
7102 }
7103
7104 /// Applies a nullability type specifier to the given type, if possible.
7105 ///
7106 /// \param state The type processing state.
7107 ///
7108 /// \param type The type to which the nullability specifier will be
7109 /// added. On success, this type will be updated appropriately.
7110 ///
7111 /// \param attr The attribute as written on the type.
7112 ///
7113 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7114 /// array type (e.g., because it will decay to a pointer).
7115 ///
7116 /// \returns true if a problem has been diagnosed, false on success.
checkNullabilityTypeSpecifier(TypeProcessingState & state,QualType & type,ParsedAttr & attr,bool allowOnArrayType)7117 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7118 QualType &type,
7119 ParsedAttr &attr,
7120 bool allowOnArrayType) {
7121 Sema &S = state.getSema();
7122
7123 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7124 SourceLocation nullabilityLoc = attr.getLoc();
7125 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7126
7127 recordNullabilitySeen(S, nullabilityLoc);
7128
7129 // Check for existing nullability attributes on the type.
7130 QualType desugared = type;
7131 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7132 // Check whether there is already a null
7133 if (auto existingNullability = attributed->getImmediateNullability()) {
7134 // Duplicated nullability.
7135 if (nullability == *existingNullability) {
7136 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7137 << DiagNullabilityKind(nullability, isContextSensitive)
7138 << FixItHint::CreateRemoval(nullabilityLoc);
7139
7140 break;
7141 }
7142
7143 // Conflicting nullability.
7144 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7145 << DiagNullabilityKind(nullability, isContextSensitive)
7146 << DiagNullabilityKind(*existingNullability, false);
7147 return true;
7148 }
7149
7150 desugared = attributed->getModifiedType();
7151 }
7152
7153 // If there is already a different nullability specifier, complain.
7154 // This (unlike the code above) looks through typedefs that might
7155 // have nullability specifiers on them, which means we cannot
7156 // provide a useful Fix-It.
7157 if (auto existingNullability = desugared->getNullability(S.Context)) {
7158 if (nullability != *existingNullability) {
7159 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7160 << DiagNullabilityKind(nullability, isContextSensitive)
7161 << DiagNullabilityKind(*existingNullability, false);
7162
7163 // Try to find the typedef with the existing nullability specifier.
7164 if (auto typedefType = desugared->getAs<TypedefType>()) {
7165 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7166 QualType underlyingType = typedefDecl->getUnderlyingType();
7167 if (auto typedefNullability
7168 = AttributedType::stripOuterNullability(underlyingType)) {
7169 if (*typedefNullability == *existingNullability) {
7170 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7171 << DiagNullabilityKind(*existingNullability, false);
7172 }
7173 }
7174 }
7175
7176 return true;
7177 }
7178 }
7179
7180 // If this definitely isn't a pointer type, reject the specifier.
7181 if (!desugared->canHaveNullability() &&
7182 !(allowOnArrayType && desugared->isArrayType())) {
7183 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7184 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7185 return true;
7186 }
7187
7188 // For the context-sensitive keywords/Objective-C property
7189 // attributes, require that the type be a single-level pointer.
7190 if (isContextSensitive) {
7191 // Make sure that the pointee isn't itself a pointer type.
7192 const Type *pointeeType = nullptr;
7193 if (desugared->isArrayType())
7194 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7195 else if (desugared->isAnyPointerType())
7196 pointeeType = desugared->getPointeeType().getTypePtr();
7197
7198 if (pointeeType && (pointeeType->isAnyPointerType() ||
7199 pointeeType->isObjCObjectPointerType() ||
7200 pointeeType->isMemberPointerType())) {
7201 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7202 << DiagNullabilityKind(nullability, true)
7203 << type;
7204 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7205 << DiagNullabilityKind(nullability, false)
7206 << type
7207 << FixItHint::CreateReplacement(nullabilityLoc,
7208 getNullabilitySpelling(nullability));
7209 return true;
7210 }
7211 }
7212
7213 // Form the attributed type.
7214 type = state.getAttributedType(
7215 createNullabilityAttr(S.Context, attr, nullability), type, type);
7216 return false;
7217 }
7218
7219 /// Check the application of the Objective-C '__kindof' qualifier to
7220 /// the given type.
checkObjCKindOfType(TypeProcessingState & state,QualType & type,ParsedAttr & attr)7221 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7222 ParsedAttr &attr) {
7223 Sema &S = state.getSema();
7224
7225 if (isa<ObjCTypeParamType>(type)) {
7226 // Build the attributed type to record where __kindof occurred.
7227 type = state.getAttributedType(
7228 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7229 return false;
7230 }
7231
7232 // Find out if it's an Objective-C object or object pointer type;
7233 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7234 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7235 : type->getAs<ObjCObjectType>();
7236
7237 // If not, we can't apply __kindof.
7238 if (!objType) {
7239 // FIXME: Handle dependent types that aren't yet object types.
7240 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7241 << type;
7242 return true;
7243 }
7244
7245 // Rebuild the "equivalent" type, which pushes __kindof down into
7246 // the object type.
7247 // There is no need to apply kindof on an unqualified id type.
7248 QualType equivType = S.Context.getObjCObjectType(
7249 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7250 objType->getProtocols(),
7251 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7252
7253 // If we started with an object pointer type, rebuild it.
7254 if (ptrType) {
7255 equivType = S.Context.getObjCObjectPointerType(equivType);
7256 if (auto nullability = type->getNullability(S.Context)) {
7257 // We create a nullability attribute from the __kindof attribute.
7258 // Make sure that will make sense.
7259 assert(attr.getAttributeSpellingListIndex() == 0 &&
7260 "multiple spellings for __kindof?");
7261 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7262 A->setImplicit(true);
7263 equivType = state.getAttributedType(A, equivType, equivType);
7264 }
7265 }
7266
7267 // Build the attributed type to record where __kindof occurred.
7268 type = state.getAttributedType(
7269 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7270 return false;
7271 }
7272
7273 /// Distribute a nullability type attribute that cannot be applied to
7274 /// the type specifier to a pointer, block pointer, or member pointer
7275 /// declarator, complaining if necessary.
7276 ///
7277 /// \returns true if the nullability annotation was distributed, false
7278 /// otherwise.
distributeNullabilityTypeAttr(TypeProcessingState & state,QualType type,ParsedAttr & attr)7279 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7280 QualType type, ParsedAttr &attr) {
7281 Declarator &declarator = state.getDeclarator();
7282
7283 /// Attempt to move the attribute to the specified chunk.
7284 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7285 // If there is already a nullability attribute there, don't add
7286 // one.
7287 if (hasNullabilityAttr(chunk.getAttrs()))
7288 return false;
7289
7290 // Complain about the nullability qualifier being in the wrong
7291 // place.
7292 enum {
7293 PK_Pointer,
7294 PK_BlockPointer,
7295 PK_MemberPointer,
7296 PK_FunctionPointer,
7297 PK_MemberFunctionPointer,
7298 } pointerKind
7299 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7300 : PK_Pointer)
7301 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7302 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7303
7304 auto diag = state.getSema().Diag(attr.getLoc(),
7305 diag::warn_nullability_declspec)
7306 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7307 attr.isContextSensitiveKeywordAttribute())
7308 << type
7309 << static_cast<unsigned>(pointerKind);
7310
7311 // FIXME: MemberPointer chunks don't carry the location of the *.
7312 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7313 diag << FixItHint::CreateRemoval(attr.getLoc())
7314 << FixItHint::CreateInsertion(
7315 state.getSema().getPreprocessor().getLocForEndOfToken(
7316 chunk.Loc),
7317 " " + attr.getAttrName()->getName().str() + " ");
7318 }
7319
7320 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7321 chunk.getAttrs());
7322 return true;
7323 };
7324
7325 // Move it to the outermost pointer, member pointer, or block
7326 // pointer declarator.
7327 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7328 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7329 switch (chunk.Kind) {
7330 case DeclaratorChunk::Pointer:
7331 case DeclaratorChunk::BlockPointer:
7332 case DeclaratorChunk::MemberPointer:
7333 return moveToChunk(chunk, false);
7334
7335 case DeclaratorChunk::Paren:
7336 case DeclaratorChunk::Array:
7337 continue;
7338
7339 case DeclaratorChunk::Function:
7340 // Try to move past the return type to a function/block/member
7341 // function pointer.
7342 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7343 declarator, i,
7344 /*onlyBlockPointers=*/false)) {
7345 return moveToChunk(*dest, true);
7346 }
7347
7348 return false;
7349
7350 // Don't walk through these.
7351 case DeclaratorChunk::Reference:
7352 case DeclaratorChunk::Pipe:
7353 return false;
7354 }
7355 }
7356
7357 return false;
7358 }
7359
getCCTypeAttr(ASTContext & Ctx,ParsedAttr & Attr)7360 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7361 assert(!Attr.isInvalid());
7362 switch (Attr.getKind()) {
7363 default:
7364 llvm_unreachable("not a calling convention attribute");
7365 case ParsedAttr::AT_CDecl:
7366 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7367 case ParsedAttr::AT_FastCall:
7368 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7369 case ParsedAttr::AT_StdCall:
7370 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7371 case ParsedAttr::AT_ThisCall:
7372 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7373 case ParsedAttr::AT_RegCall:
7374 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7375 case ParsedAttr::AT_Pascal:
7376 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7377 case ParsedAttr::AT_SwiftCall:
7378 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7379 case ParsedAttr::AT_SwiftAsyncCall:
7380 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7381 case ParsedAttr::AT_VectorCall:
7382 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7383 case ParsedAttr::AT_AArch64VectorPcs:
7384 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7385 case ParsedAttr::AT_Pcs: {
7386 // The attribute may have had a fixit applied where we treated an
7387 // identifier as a string literal. The contents of the string are valid,
7388 // but the form may not be.
7389 StringRef Str;
7390 if (Attr.isArgExpr(0))
7391 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7392 else
7393 Str = Attr.getArgAsIdent(0)->Ident->getName();
7394 PcsAttr::PCSType Type;
7395 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7396 llvm_unreachable("already validated the attribute");
7397 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7398 }
7399 case ParsedAttr::AT_IntelOclBicc:
7400 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7401 case ParsedAttr::AT_MSABI:
7402 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7403 case ParsedAttr::AT_SysVABI:
7404 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7405 case ParsedAttr::AT_PreserveMost:
7406 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7407 case ParsedAttr::AT_PreserveAll:
7408 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7409 }
7410 llvm_unreachable("unexpected attribute kind!");
7411 }
7412
7413 /// Process an individual function attribute. Returns true to
7414 /// indicate that the attribute was handled, false if it wasn't.
handleFunctionTypeAttr(TypeProcessingState & state,ParsedAttr & attr,QualType & type)7415 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7416 QualType &type) {
7417 Sema &S = state.getSema();
7418
7419 FunctionTypeUnwrapper unwrapped(S, type);
7420
7421 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7422 if (S.CheckAttrNoArgs(attr))
7423 return true;
7424
7425 // Delay if this is not a function type.
7426 if (!unwrapped.isFunctionType())
7427 return false;
7428
7429 // Otherwise we can process right away.
7430 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7431 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7432 return true;
7433 }
7434
7435 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7436 // Delay if this is not a function type.
7437 if (!unwrapped.isFunctionType())
7438 return false;
7439
7440 // Ignore if we don't have CMSE enabled.
7441 if (!S.getLangOpts().Cmse) {
7442 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7443 attr.setInvalid();
7444 return true;
7445 }
7446
7447 // Otherwise we can process right away.
7448 FunctionType::ExtInfo EI =
7449 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7450 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7451 return true;
7452 }
7453
7454 // ns_returns_retained is not always a type attribute, but if we got
7455 // here, we're treating it as one right now.
7456 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7457 if (attr.getNumArgs()) return true;
7458
7459 // Delay if this is not a function type.
7460 if (!unwrapped.isFunctionType())
7461 return false;
7462
7463 // Check whether the return type is reasonable.
7464 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7465 unwrapped.get()->getReturnType()))
7466 return true;
7467
7468 // Only actually change the underlying type in ARC builds.
7469 QualType origType = type;
7470 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7471 FunctionType::ExtInfo EI
7472 = unwrapped.get()->getExtInfo().withProducesResult(true);
7473 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7474 }
7475 type = state.getAttributedType(
7476 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7477 origType, type);
7478 return true;
7479 }
7480
7481 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7482 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7483 return true;
7484
7485 // Delay if this is not a function type.
7486 if (!unwrapped.isFunctionType())
7487 return false;
7488
7489 FunctionType::ExtInfo EI =
7490 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7491 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7492 return true;
7493 }
7494
7495 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7496 if (!S.getLangOpts().CFProtectionBranch) {
7497 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7498 attr.setInvalid();
7499 return true;
7500 }
7501
7502 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7503 return true;
7504
7505 // If this is not a function type, warning will be asserted by subject
7506 // check.
7507 if (!unwrapped.isFunctionType())
7508 return true;
7509
7510 FunctionType::ExtInfo EI =
7511 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7512 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7513 return true;
7514 }
7515
7516 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7517 unsigned value;
7518 if (S.CheckRegparmAttr(attr, value))
7519 return true;
7520
7521 // Delay if this is not a function type.
7522 if (!unwrapped.isFunctionType())
7523 return false;
7524
7525 // Diagnose regparm with fastcall.
7526 const FunctionType *fn = unwrapped.get();
7527 CallingConv CC = fn->getCallConv();
7528 if (CC == CC_X86FastCall) {
7529 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7530 << FunctionType::getNameForCallConv(CC)
7531 << "regparm";
7532 attr.setInvalid();
7533 return true;
7534 }
7535
7536 FunctionType::ExtInfo EI =
7537 unwrapped.get()->getExtInfo().withRegParm(value);
7538 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7539 return true;
7540 }
7541
7542 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7543 // Delay if this is not a function type.
7544 if (!unwrapped.isFunctionType())
7545 return false;
7546
7547 if (S.CheckAttrNoArgs(attr)) {
7548 attr.setInvalid();
7549 return true;
7550 }
7551
7552 // Otherwise we can process right away.
7553 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7554
7555 // MSVC ignores nothrow if it is in conflict with an explicit exception
7556 // specification.
7557 if (Proto->hasExceptionSpec()) {
7558 switch (Proto->getExceptionSpecType()) {
7559 case EST_None:
7560 llvm_unreachable("This doesn't have an exception spec!");
7561
7562 case EST_DynamicNone:
7563 case EST_BasicNoexcept:
7564 case EST_NoexceptTrue:
7565 case EST_NoThrow:
7566 // Exception spec doesn't conflict with nothrow, so don't warn.
7567 LLVM_FALLTHROUGH;
7568 case EST_Unparsed:
7569 case EST_Uninstantiated:
7570 case EST_DependentNoexcept:
7571 case EST_Unevaluated:
7572 // We don't have enough information to properly determine if there is a
7573 // conflict, so suppress the warning.
7574 break;
7575 case EST_Dynamic:
7576 case EST_MSAny:
7577 case EST_NoexceptFalse:
7578 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
7579 break;
7580 }
7581 return true;
7582 }
7583
7584 type = unwrapped.wrap(
7585 S, S.Context
7586 .getFunctionTypeWithExceptionSpec(
7587 QualType{Proto, 0},
7588 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
7589 ->getAs<FunctionType>());
7590 return true;
7591 }
7592
7593 // Delay if the type didn't work out to a function.
7594 if (!unwrapped.isFunctionType()) return false;
7595
7596 // Otherwise, a calling convention.
7597 CallingConv CC;
7598 if (S.CheckCallingConvAttr(attr, CC))
7599 return true;
7600
7601 const FunctionType *fn = unwrapped.get();
7602 CallingConv CCOld = fn->getCallConv();
7603 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
7604
7605 if (CCOld != CC) {
7606 // Error out on when there's already an attribute on the type
7607 // and the CCs don't match.
7608 if (S.getCallingConvAttributedType(type)) {
7609 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7610 << FunctionType::getNameForCallConv(CC)
7611 << FunctionType::getNameForCallConv(CCOld);
7612 attr.setInvalid();
7613 return true;
7614 }
7615 }
7616
7617 // Diagnose use of variadic functions with calling conventions that
7618 // don't support them (e.g. because they're callee-cleanup).
7619 // We delay warning about this on unprototyped function declarations
7620 // until after redeclaration checking, just in case we pick up a
7621 // prototype that way. And apparently we also "delay" warning about
7622 // unprototyped function types in general, despite not necessarily having
7623 // much ability to diagnose it later.
7624 if (!supportsVariadicCall(CC)) {
7625 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
7626 if (FnP && FnP->isVariadic()) {
7627 // stdcall and fastcall are ignored with a warning for GCC and MS
7628 // compatibility.
7629 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7630 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7631 << FunctionType::getNameForCallConv(CC)
7632 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7633
7634 attr.setInvalid();
7635 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7636 << FunctionType::getNameForCallConv(CC);
7637 }
7638 }
7639
7640 // Also diagnose fastcall with regparm.
7641 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7642 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7643 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7644 attr.setInvalid();
7645 return true;
7646 }
7647
7648 // Modify the CC from the wrapped function type, wrap it all back, and then
7649 // wrap the whole thing in an AttributedType as written. The modified type
7650 // might have a different CC if we ignored the attribute.
7651 QualType Equivalent;
7652 if (CCOld == CC) {
7653 Equivalent = type;
7654 } else {
7655 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7656 Equivalent =
7657 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7658 }
7659 type = state.getAttributedType(CCAttr, type, Equivalent);
7660 return true;
7661 }
7662
hasExplicitCallingConv(QualType T)7663 bool Sema::hasExplicitCallingConv(QualType T) {
7664 const AttributedType *AT;
7665
7666 // Stop if we'd be stripping off a typedef sugar node to reach the
7667 // AttributedType.
7668 while ((AT = T->getAs<AttributedType>()) &&
7669 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7670 if (AT->isCallingConv())
7671 return true;
7672 T = AT->getModifiedType();
7673 }
7674 return false;
7675 }
7676
adjustMemberFunctionCC(QualType & T,bool IsStatic,bool IsCtorOrDtor,SourceLocation Loc)7677 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7678 SourceLocation Loc) {
7679 FunctionTypeUnwrapper Unwrapped(*this, T);
7680 const FunctionType *FT = Unwrapped.get();
7681 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7682 cast<FunctionProtoType>(FT)->isVariadic());
7683 CallingConv CurCC = FT->getCallConv();
7684 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7685
7686 if (CurCC == ToCC)
7687 return;
7688
7689 // MS compiler ignores explicit calling convention attributes on structors. We
7690 // should do the same.
7691 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7692 // Issue a warning on ignored calling convention -- except of __stdcall.
7693 // Again, this is what MS compiler does.
7694 if (CurCC != CC_X86StdCall)
7695 Diag(Loc, diag::warn_cconv_unsupported)
7696 << FunctionType::getNameForCallConv(CurCC)
7697 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7698 // Default adjustment.
7699 } else {
7700 // Only adjust types with the default convention. For example, on Windows
7701 // we should adjust a __cdecl type to __thiscall for instance methods, and a
7702 // __thiscall type to __cdecl for static methods.
7703 CallingConv DefaultCC =
7704 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7705
7706 if (CurCC != DefaultCC || DefaultCC == ToCC)
7707 return;
7708
7709 if (hasExplicitCallingConv(T))
7710 return;
7711 }
7712
7713 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7714 QualType Wrapped = Unwrapped.wrap(*this, FT);
7715 T = Context.getAdjustedType(T, Wrapped);
7716 }
7717
7718 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
7719 /// and float scalars, although arrays, pointers, and function return values are
7720 /// allowed in conjunction with this construct. Aggregates with this attribute
7721 /// are invalid, even if they are of the same size as a corresponding scalar.
7722 /// The raw attribute should contain precisely 1 argument, the vector size for
7723 /// the variable, measured in bytes. If curType and rawAttr are well formed,
7724 /// this routine will return a new vector type.
HandleVectorSizeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7725 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7726 Sema &S) {
7727 // Check the attribute arguments.
7728 if (Attr.getNumArgs() != 1) {
7729 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7730 << 1;
7731 Attr.setInvalid();
7732 return;
7733 }
7734
7735 Expr *SizeExpr = Attr.getArgAsExpr(0);
7736 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7737 if (!T.isNull())
7738 CurType = T;
7739 else
7740 Attr.setInvalid();
7741 }
7742
7743 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7744 /// a type.
HandleExtVectorTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7745 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7746 Sema &S) {
7747 // check the attribute arguments.
7748 if (Attr.getNumArgs() != 1) {
7749 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7750 << 1;
7751 return;
7752 }
7753
7754 Expr *SizeExpr = Attr.getArgAsExpr(0);
7755 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
7756 if (!T.isNull())
7757 CurType = T;
7758 }
7759
isPermittedNeonBaseType(QualType & Ty,VectorType::VectorKind VecKind,Sema & S)7760 static bool isPermittedNeonBaseType(QualType &Ty,
7761 VectorType::VectorKind VecKind, Sema &S) {
7762 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7763 if (!BTy)
7764 return false;
7765
7766 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7767
7768 // Signed poly is mathematically wrong, but has been baked into some ABIs by
7769 // now.
7770 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7771 Triple.getArch() == llvm::Triple::aarch64_32 ||
7772 Triple.getArch() == llvm::Triple::aarch64_be;
7773 if (VecKind == VectorType::NeonPolyVector) {
7774 if (IsPolyUnsigned) {
7775 // AArch64 polynomial vectors are unsigned.
7776 return BTy->getKind() == BuiltinType::UChar ||
7777 BTy->getKind() == BuiltinType::UShort ||
7778 BTy->getKind() == BuiltinType::ULong ||
7779 BTy->getKind() == BuiltinType::ULongLong;
7780 } else {
7781 // AArch32 polynomial vectors are signed.
7782 return BTy->getKind() == BuiltinType::SChar ||
7783 BTy->getKind() == BuiltinType::Short ||
7784 BTy->getKind() == BuiltinType::LongLong;
7785 }
7786 }
7787
7788 // Non-polynomial vector types: the usual suspects are allowed, as well as
7789 // float64_t on AArch64.
7790 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
7791 BTy->getKind() == BuiltinType::Double)
7792 return true;
7793
7794 return BTy->getKind() == BuiltinType::SChar ||
7795 BTy->getKind() == BuiltinType::UChar ||
7796 BTy->getKind() == BuiltinType::Short ||
7797 BTy->getKind() == BuiltinType::UShort ||
7798 BTy->getKind() == BuiltinType::Int ||
7799 BTy->getKind() == BuiltinType::UInt ||
7800 BTy->getKind() == BuiltinType::Long ||
7801 BTy->getKind() == BuiltinType::ULong ||
7802 BTy->getKind() == BuiltinType::LongLong ||
7803 BTy->getKind() == BuiltinType::ULongLong ||
7804 BTy->getKind() == BuiltinType::Float ||
7805 BTy->getKind() == BuiltinType::Half ||
7806 BTy->getKind() == BuiltinType::BFloat16;
7807 }
7808
verifyValidIntegerConstantExpr(Sema & S,const ParsedAttr & Attr,llvm::APSInt & Result)7809 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
7810 llvm::APSInt &Result) {
7811 const auto *AttrExpr = Attr.getArgAsExpr(0);
7812 if (!AttrExpr->isTypeDependent() && !AttrExpr->isValueDependent()) {
7813 if (Optional<llvm::APSInt> Res =
7814 AttrExpr->getIntegerConstantExpr(S.Context)) {
7815 Result = *Res;
7816 return true;
7817 }
7818 }
7819 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7820 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
7821 Attr.setInvalid();
7822 return false;
7823 }
7824
7825 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7826 /// "neon_polyvector_type" attributes are used to create vector types that
7827 /// are mangled according to ARM's ABI. Otherwise, these types are identical
7828 /// to those created with the "vector_size" attribute. Unlike "vector_size"
7829 /// the argument to these Neon attributes is the number of vector elements,
7830 /// not the vector size in bytes. The vector width and element type must
7831 /// match one of the standard Neon vector types.
HandleNeonVectorTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S,VectorType::VectorKind VecKind)7832 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7833 Sema &S, VectorType::VectorKind VecKind) {
7834 // Target must have NEON (or MVE, whose vectors are similar enough
7835 // not to need a separate attribute)
7836 if (!S.Context.getTargetInfo().hasFeature("neon") &&
7837 !S.Context.getTargetInfo().hasFeature("mve")) {
7838 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
7839 << Attr << "'neon' or 'mve'";
7840 Attr.setInvalid();
7841 return;
7842 }
7843 // Check the attribute arguments.
7844 if (Attr.getNumArgs() != 1) {
7845 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7846 << 1;
7847 Attr.setInvalid();
7848 return;
7849 }
7850 // The number of elements must be an ICE.
7851 llvm::APSInt numEltsInt(32);
7852 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
7853 return;
7854
7855 // Only certain element types are supported for Neon vectors.
7856 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7857 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7858 Attr.setInvalid();
7859 return;
7860 }
7861
7862 // The total size of the vector must be 64 or 128 bits.
7863 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7864 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7865 unsigned vecSize = typeSize * numElts;
7866 if (vecSize != 64 && vecSize != 128) {
7867 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7868 Attr.setInvalid();
7869 return;
7870 }
7871
7872 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7873 }
7874
7875 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
7876 /// used to create fixed-length versions of sizeless SVE types defined by
7877 /// the ACLE, such as svint32_t and svbool_t.
HandleArmSveVectorBitsTypeAttr(QualType & CurType,ParsedAttr & Attr,Sema & S)7878 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
7879 Sema &S) {
7880 // Target must have SVE.
7881 if (!S.Context.getTargetInfo().hasFeature("sve")) {
7882 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
7883 Attr.setInvalid();
7884 return;
7885 }
7886
7887 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified.
7888 if (!S.getLangOpts().ArmSveVectorBits) {
7889 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
7890 << Attr;
7891 Attr.setInvalid();
7892 return;
7893 }
7894
7895 // Check the attribute arguments.
7896 if (Attr.getNumArgs() != 1) {
7897 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
7898 << Attr << 1;
7899 Attr.setInvalid();
7900 return;
7901 }
7902
7903 // The vector size must be an integer constant expression.
7904 llvm::APSInt SveVectorSizeInBits(32);
7905 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
7906 return;
7907
7908 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
7909
7910 // The attribute vector size must match -msve-vector-bits.
7911 if (VecSize != S.getLangOpts().ArmSveVectorBits) {
7912 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
7913 << VecSize << S.getLangOpts().ArmSveVectorBits;
7914 Attr.setInvalid();
7915 return;
7916 }
7917
7918 // Attribute can only be attached to a single SVE vector or predicate type.
7919 if (!CurType->isVLSTBuiltinType()) {
7920 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
7921 << Attr << CurType;
7922 Attr.setInvalid();
7923 return;
7924 }
7925
7926 const auto *BT = CurType->castAs<BuiltinType>();
7927
7928 QualType EltType = CurType->getSveEltType(S.Context);
7929 unsigned TypeSize = S.Context.getTypeSize(EltType);
7930 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector;
7931 if (BT->getKind() == BuiltinType::SveBool) {
7932 // Predicates are represented as i8.
7933 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
7934 VecKind = VectorType::SveFixedLengthPredicateVector;
7935 } else
7936 VecSize /= TypeSize;
7937 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
7938 }
7939
HandleArmMveStrictPolymorphismAttr(TypeProcessingState & State,QualType & CurType,ParsedAttr & Attr)7940 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
7941 QualType &CurType,
7942 ParsedAttr &Attr) {
7943 const VectorType *VT = dyn_cast<VectorType>(CurType);
7944 if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
7945 State.getSema().Diag(Attr.getLoc(),
7946 diag::err_attribute_arm_mve_polymorphism);
7947 Attr.setInvalid();
7948 return;
7949 }
7950
7951 CurType =
7952 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
7953 State.getSema().Context, Attr),
7954 CurType, CurType);
7955 }
7956
7957 /// Handle OpenCL Access Qualifier Attribute.
HandleOpenCLAccessAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)7958 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7959 Sema &S) {
7960 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7961 if (!(CurType->isImageType() || CurType->isPipeType())) {
7962 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7963 Attr.setInvalid();
7964 return;
7965 }
7966
7967 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7968 QualType BaseTy = TypedefTy->desugar();
7969
7970 std::string PrevAccessQual;
7971 if (BaseTy->isPipeType()) {
7972 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7973 OpenCLAccessAttr *Attr =
7974 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7975 PrevAccessQual = Attr->getSpelling();
7976 } else {
7977 PrevAccessQual = "read_only";
7978 }
7979 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7980
7981 switch (ImgType->getKind()) {
7982 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7983 case BuiltinType::Id: \
7984 PrevAccessQual = #Access; \
7985 break;
7986 #include "clang/Basic/OpenCLImageTypes.def"
7987 default:
7988 llvm_unreachable("Unable to find corresponding image type.");
7989 }
7990 } else {
7991 llvm_unreachable("unexpected type");
7992 }
7993 StringRef AttrName = Attr.getAttrName()->getName();
7994 if (PrevAccessQual == AttrName.ltrim("_")) {
7995 // Duplicated qualifiers
7996 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
7997 << AttrName << Attr.getRange();
7998 } else {
7999 // Contradicting qualifiers
8000 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8001 }
8002
8003 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8004 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8005 } else if (CurType->isPipeType()) {
8006 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8007 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8008 CurType = S.Context.getWritePipeType(ElemType);
8009 }
8010 }
8011 }
8012
8013 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
HandleMatrixTypeAttr(QualType & CurType,const ParsedAttr & Attr,Sema & S)8014 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8015 Sema &S) {
8016 if (!S.getLangOpts().MatrixTypes) {
8017 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8018 return;
8019 }
8020
8021 if (Attr.getNumArgs() != 2) {
8022 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8023 << Attr << 2;
8024 return;
8025 }
8026
8027 Expr *RowsExpr = Attr.getArgAsExpr(0);
8028 Expr *ColsExpr = Attr.getArgAsExpr(1);
8029 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8030 if (!T.isNull())
8031 CurType = T;
8032 }
8033
HandleLifetimeBoundAttr(TypeProcessingState & State,QualType & CurType,ParsedAttr & Attr)8034 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8035 QualType &CurType,
8036 ParsedAttr &Attr) {
8037 if (State.getDeclarator().isDeclarationOfFunction()) {
8038 CurType = State.getAttributedType(
8039 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8040 CurType, CurType);
8041 }
8042 }
8043
isAddressSpaceKind(const ParsedAttr & attr)8044 static bool isAddressSpaceKind(const ParsedAttr &attr) {
8045 auto attrKind = attr.getKind();
8046
8047 return attrKind == ParsedAttr::AT_AddressSpace ||
8048 attrKind == ParsedAttr::AT_OpenCLPrivateAddressSpace ||
8049 attrKind == ParsedAttr::AT_OpenCLGlobalAddressSpace ||
8050 attrKind == ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace ||
8051 attrKind == ParsedAttr::AT_OpenCLGlobalHostAddressSpace ||
8052 attrKind == ParsedAttr::AT_OpenCLLocalAddressSpace ||
8053 attrKind == ParsedAttr::AT_OpenCLConstantAddressSpace ||
8054 attrKind == ParsedAttr::AT_OpenCLGenericAddressSpace;
8055 }
8056
processTypeAttrs(TypeProcessingState & state,QualType & type,TypeAttrLocation TAL,ParsedAttributesView & attrs)8057 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8058 TypeAttrLocation TAL,
8059 ParsedAttributesView &attrs) {
8060 // Scan through and apply attributes to this type where it makes sense. Some
8061 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8062 // type, but others can be present in the type specifiers even though they
8063 // apply to the decl. Here we apply type attributes and ignore the rest.
8064
8065 // This loop modifies the list pretty frequently, but we still need to make
8066 // sure we visit every element once. Copy the attributes list, and iterate
8067 // over that.
8068 ParsedAttributesView AttrsCopy{attrs};
8069
8070 state.setParsedNoDeref(false);
8071
8072 for (ParsedAttr &attr : AttrsCopy) {
8073
8074 // Skip attributes that were marked to be invalid.
8075 if (attr.isInvalid())
8076 continue;
8077
8078 if (attr.isStandardAttributeSyntax()) {
8079 // [[gnu::...]] attributes are treated as declaration attributes, so may
8080 // not appertain to a DeclaratorChunk. If we handle them as type
8081 // attributes, accept them in that position and diagnose the GCC
8082 // incompatibility.
8083 if (attr.isGNUScope()) {
8084 bool IsTypeAttr = attr.isTypeAttr();
8085 if (TAL == TAL_DeclChunk) {
8086 state.getSema().Diag(attr.getLoc(),
8087 IsTypeAttr
8088 ? diag::warn_gcc_ignores_type_attr
8089 : diag::warn_cxx11_gnu_attribute_on_type)
8090 << attr;
8091 if (!IsTypeAttr)
8092 continue;
8093 }
8094 } else if (TAL != TAL_DeclChunk && !isAddressSpaceKind(attr)) {
8095 // Otherwise, only consider type processing for a C++11 attribute if
8096 // it's actually been applied to a type.
8097 // We also allow C++11 address_space and
8098 // OpenCL language address space attributes to pass through.
8099 continue;
8100 }
8101 }
8102
8103 // If this is an attribute we can handle, do so now,
8104 // otherwise, add it to the FnAttrs list for rechaining.
8105 switch (attr.getKind()) {
8106 default:
8107 // A [[]] attribute on a declarator chunk must appertain to a type.
8108 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
8109 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8110 << attr;
8111 attr.setUsedAsTypeAttr();
8112 }
8113 break;
8114
8115 case ParsedAttr::UnknownAttribute:
8116 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk)
8117 state.getSema().Diag(attr.getLoc(),
8118 diag::warn_unknown_attribute_ignored)
8119 << attr << attr.getRange();
8120 break;
8121
8122 case ParsedAttr::IgnoredAttribute:
8123 break;
8124
8125 case ParsedAttr::AT_MayAlias:
8126 // FIXME: This attribute needs to actually be handled, but if we ignore
8127 // it it breaks large amounts of Linux software.
8128 attr.setUsedAsTypeAttr();
8129 break;
8130 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8131 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8132 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8133 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8134 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8135 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8136 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8137 case ParsedAttr::AT_AddressSpace:
8138 HandleAddressSpaceTypeAttribute(type, attr, state);
8139 attr.setUsedAsTypeAttr();
8140 break;
8141 OBJC_POINTER_TYPE_ATTRS_CASELIST:
8142 if (!handleObjCPointerTypeAttr(state, attr, type))
8143 distributeObjCPointerTypeAttr(state, attr, type);
8144 attr.setUsedAsTypeAttr();
8145 break;
8146 case ParsedAttr::AT_VectorSize:
8147 HandleVectorSizeAttr(type, attr, state.getSema());
8148 attr.setUsedAsTypeAttr();
8149 break;
8150 case ParsedAttr::AT_ExtVectorType:
8151 HandleExtVectorTypeAttr(type, attr, state.getSema());
8152 attr.setUsedAsTypeAttr();
8153 break;
8154 case ParsedAttr::AT_NeonVectorType:
8155 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8156 VectorType::NeonVector);
8157 attr.setUsedAsTypeAttr();
8158 break;
8159 case ParsedAttr::AT_NeonPolyVectorType:
8160 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8161 VectorType::NeonPolyVector);
8162 attr.setUsedAsTypeAttr();
8163 break;
8164 case ParsedAttr::AT_ArmSveVectorBits:
8165 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8166 attr.setUsedAsTypeAttr();
8167 break;
8168 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8169 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8170 attr.setUsedAsTypeAttr();
8171 break;
8172 }
8173 case ParsedAttr::AT_OpenCLAccess:
8174 HandleOpenCLAccessAttr(type, attr, state.getSema());
8175 attr.setUsedAsTypeAttr();
8176 break;
8177 case ParsedAttr::AT_LifetimeBound:
8178 if (TAL == TAL_DeclChunk)
8179 HandleLifetimeBoundAttr(state, type, attr);
8180 break;
8181
8182 case ParsedAttr::AT_NoDeref: {
8183 ASTContext &Ctx = state.getSema().Context;
8184 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8185 type, type);
8186 attr.setUsedAsTypeAttr();
8187 state.setParsedNoDeref(true);
8188 break;
8189 }
8190
8191 case ParsedAttr::AT_MatrixType:
8192 HandleMatrixTypeAttr(type, attr, state.getSema());
8193 attr.setUsedAsTypeAttr();
8194 break;
8195
8196 MS_TYPE_ATTRS_CASELIST:
8197 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8198 attr.setUsedAsTypeAttr();
8199 break;
8200
8201
8202 NULLABILITY_TYPE_ATTRS_CASELIST:
8203 // Either add nullability here or try to distribute it. We
8204 // don't want to distribute the nullability specifier past any
8205 // dependent type, because that complicates the user model.
8206 if (type->canHaveNullability() || type->isDependentType() ||
8207 type->isArrayType() ||
8208 !distributeNullabilityTypeAttr(state, type, attr)) {
8209 unsigned endIndex;
8210 if (TAL == TAL_DeclChunk)
8211 endIndex = state.getCurrentChunkIndex();
8212 else
8213 endIndex = state.getDeclarator().getNumTypeObjects();
8214 bool allowOnArrayType =
8215 state.getDeclarator().isPrototypeContext() &&
8216 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8217 if (checkNullabilityTypeSpecifier(
8218 state,
8219 type,
8220 attr,
8221 allowOnArrayType)) {
8222 attr.setInvalid();
8223 }
8224
8225 attr.setUsedAsTypeAttr();
8226 }
8227 break;
8228
8229 case ParsedAttr::AT_ObjCKindOf:
8230 // '__kindof' must be part of the decl-specifiers.
8231 switch (TAL) {
8232 case TAL_DeclSpec:
8233 break;
8234
8235 case TAL_DeclChunk:
8236 case TAL_DeclName:
8237 state.getSema().Diag(attr.getLoc(),
8238 diag::err_objc_kindof_wrong_position)
8239 << FixItHint::CreateRemoval(attr.getLoc())
8240 << FixItHint::CreateInsertion(
8241 state.getDeclarator().getDeclSpec().getBeginLoc(),
8242 "__kindof ");
8243 break;
8244 }
8245
8246 // Apply it regardless.
8247 if (checkObjCKindOfType(state, type, attr))
8248 attr.setInvalid();
8249 break;
8250
8251 case ParsedAttr::AT_NoThrow:
8252 // Exception Specifications aren't generally supported in C mode throughout
8253 // clang, so revert to attribute-based handling for C.
8254 if (!state.getSema().getLangOpts().CPlusPlus)
8255 break;
8256 LLVM_FALLTHROUGH;
8257 FUNCTION_TYPE_ATTRS_CASELIST:
8258 attr.setUsedAsTypeAttr();
8259
8260 // Never process function type attributes as part of the
8261 // declaration-specifiers.
8262 if (TAL == TAL_DeclSpec)
8263 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8264
8265 // Otherwise, handle the possible delays.
8266 else if (!handleFunctionTypeAttr(state, attr, type))
8267 distributeFunctionTypeAttr(state, attr, type);
8268 break;
8269 case ParsedAttr::AT_AcquireHandle: {
8270 if (!type->isFunctionType())
8271 return;
8272
8273 if (attr.getNumArgs() != 1) {
8274 state.getSema().Diag(attr.getLoc(),
8275 diag::err_attribute_wrong_number_arguments)
8276 << attr << 1;
8277 attr.setInvalid();
8278 return;
8279 }
8280
8281 StringRef HandleType;
8282 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8283 return;
8284 type = state.getAttributedType(
8285 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8286 type, type);
8287 attr.setUsedAsTypeAttr();
8288 break;
8289 }
8290 }
8291
8292 // Handle attributes that are defined in a macro. We do not want this to be
8293 // applied to ObjC builtin attributes.
8294 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8295 !type.getQualifiers().hasObjCLifetime() &&
8296 !type.getQualifiers().hasObjCGCAttr() &&
8297 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8298 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8299 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8300 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8301 state.setExpansionLocForMacroQualifiedType(
8302 cast<MacroQualifiedType>(type.getTypePtr()),
8303 attr.getMacroExpansionLoc());
8304 }
8305 }
8306
8307 if (!state.getSema().getLangOpts().OpenCL ||
8308 type.getAddressSpace() != LangAS::Default)
8309 return;
8310 }
8311
completeExprArrayBound(Expr * E)8312 void Sema::completeExprArrayBound(Expr *E) {
8313 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8314 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8315 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8316 auto *Def = Var->getDefinition();
8317 if (!Def) {
8318 SourceLocation PointOfInstantiation = E->getExprLoc();
8319 runWithSufficientStackSpace(PointOfInstantiation, [&] {
8320 InstantiateVariableDefinition(PointOfInstantiation, Var);
8321 });
8322 Def = Var->getDefinition();
8323
8324 // If we don't already have a point of instantiation, and we managed
8325 // to instantiate a definition, this is the point of instantiation.
8326 // Otherwise, we don't request an end-of-TU instantiation, so this is
8327 // not a point of instantiation.
8328 // FIXME: Is this really the right behavior?
8329 if (Var->getPointOfInstantiation().isInvalid() && Def) {
8330 assert(Var->getTemplateSpecializationKind() ==
8331 TSK_ImplicitInstantiation &&
8332 "explicit instantiation with no point of instantiation");
8333 Var->setTemplateSpecializationKind(
8334 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8335 }
8336 }
8337
8338 // Update the type to the definition's type both here and within the
8339 // expression.
8340 if (Def) {
8341 DRE->setDecl(Def);
8342 QualType T = Def->getType();
8343 DRE->setType(T);
8344 // FIXME: Update the type on all intervening expressions.
8345 E->setType(T);
8346 }
8347
8348 // We still go on to try to complete the type independently, as it
8349 // may also require instantiations or diagnostics if it remains
8350 // incomplete.
8351 }
8352 }
8353 }
8354 }
8355
getCompletedType(Expr * E)8356 QualType Sema::getCompletedType(Expr *E) {
8357 // Incomplete array types may be completed by the initializer attached to
8358 // their definitions. For static data members of class templates and for
8359 // variable templates, we need to instantiate the definition to get this
8360 // initializer and complete the type.
8361 if (E->getType()->isIncompleteArrayType())
8362 completeExprArrayBound(E);
8363
8364 // FIXME: Are there other cases which require instantiating something other
8365 // than the type to complete the type of an expression?
8366
8367 return E->getType();
8368 }
8369
8370 /// Ensure that the type of the given expression is complete.
8371 ///
8372 /// This routine checks whether the expression \p E has a complete type. If the
8373 /// expression refers to an instantiable construct, that instantiation is
8374 /// performed as needed to complete its type. Furthermore
8375 /// Sema::RequireCompleteType is called for the expression's type (or in the
8376 /// case of a reference type, the referred-to type).
8377 ///
8378 /// \param E The expression whose type is required to be complete.
8379 /// \param Kind Selects which completeness rules should be applied.
8380 /// \param Diagnoser The object that will emit a diagnostic if the type is
8381 /// incomplete.
8382 ///
8383 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8384 /// otherwise.
RequireCompleteExprType(Expr * E,CompleteTypeKind Kind,TypeDiagnoser & Diagnoser)8385 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8386 TypeDiagnoser &Diagnoser) {
8387 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
8388 Diagnoser);
8389 }
8390
RequireCompleteExprType(Expr * E,unsigned DiagID)8391 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8392 BoundTypeDiagnoser<> Diagnoser(DiagID);
8393 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8394 }
8395
8396 /// Ensure that the type T is a complete type.
8397 ///
8398 /// This routine checks whether the type @p T is complete in any
8399 /// context where a complete type is required. If @p T is a complete
8400 /// type, returns false. If @p T is a class template specialization,
8401 /// this routine then attempts to perform class template
8402 /// instantiation. If instantiation fails, or if @p T is incomplete
8403 /// and cannot be completed, issues the diagnostic @p diag (giving it
8404 /// the type @p T) and returns true.
8405 ///
8406 /// @param Loc The location in the source that the incomplete type
8407 /// diagnostic should refer to.
8408 ///
8409 /// @param T The type that this routine is examining for completeness.
8410 ///
8411 /// @param Kind Selects which completeness rules should be applied.
8412 ///
8413 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8414 /// @c false otherwise.
RequireCompleteType(SourceLocation Loc,QualType T,CompleteTypeKind Kind,TypeDiagnoser & Diagnoser)8415 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8416 CompleteTypeKind Kind,
8417 TypeDiagnoser &Diagnoser) {
8418 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8419 return true;
8420 if (const TagType *Tag = T->getAs<TagType>()) {
8421 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8422 Tag->getDecl()->setCompleteDefinitionRequired();
8423 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
8424 }
8425 }
8426 return false;
8427 }
8428
hasStructuralCompatLayout(Decl * D,Decl * Suggested)8429 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
8430 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
8431 if (!Suggested)
8432 return false;
8433
8434 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
8435 // and isolate from other C++ specific checks.
8436 StructuralEquivalenceContext Ctx(
8437 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
8438 StructuralEquivalenceKind::Default,
8439 false /*StrictTypeSpelling*/, true /*Complain*/,
8440 true /*ErrorOnTagTypeMismatch*/);
8441 return Ctx.IsEquivalent(D, Suggested);
8442 }
8443
8444 /// Determine whether there is any declaration of \p D that was ever a
8445 /// definition (perhaps before module merging) and is currently visible.
8446 /// \param D The definition of the entity.
8447 /// \param Suggested Filled in with the declaration that should be made visible
8448 /// in order to provide a definition of this entity.
8449 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8450 /// not defined. This only matters for enums with a fixed underlying
8451 /// type, since in all other cases, a type is complete if and only if it
8452 /// is defined.
hasVisibleDefinition(NamedDecl * D,NamedDecl ** Suggested,bool OnlyNeedComplete)8453 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
8454 bool OnlyNeedComplete) {
8455 // Easy case: if we don't have modules, all declarations are visible.
8456 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
8457 return true;
8458
8459 // If this definition was instantiated from a template, map back to the
8460 // pattern from which it was instantiated.
8461 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
8462 // We're in the middle of defining it; this definition should be treated
8463 // as visible.
8464 return true;
8465 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
8466 if (auto *Pattern = RD->getTemplateInstantiationPattern())
8467 RD = Pattern;
8468 D = RD->getDefinition();
8469 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
8470 if (auto *Pattern = ED->getTemplateInstantiationPattern())
8471 ED = Pattern;
8472 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
8473 // If the enum has a fixed underlying type, it may have been forward
8474 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
8475 // the enum and assign it the underlying type of `int`. Since we're only
8476 // looking for a complete type (not a definition), any visible declaration
8477 // of it will do.
8478 *Suggested = nullptr;
8479 for (auto *Redecl : ED->redecls()) {
8480 if (isVisible(Redecl))
8481 return true;
8482 if (Redecl->isThisDeclarationADefinition() ||
8483 (Redecl->isCanonicalDecl() && !*Suggested))
8484 *Suggested = Redecl;
8485 }
8486 return false;
8487 }
8488 D = ED->getDefinition();
8489 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8490 if (auto *Pattern = FD->getTemplateInstantiationPattern())
8491 FD = Pattern;
8492 D = FD->getDefinition();
8493 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
8494 if (auto *Pattern = VD->getTemplateInstantiationPattern())
8495 VD = Pattern;
8496 D = VD->getDefinition();
8497 }
8498 assert(D && "missing definition for pattern of instantiated definition");
8499
8500 *Suggested = D;
8501
8502 auto DefinitionIsVisible = [&] {
8503 // The (primary) definition might be in a visible module.
8504 if (isVisible(D))
8505 return true;
8506
8507 // A visible module might have a merged definition instead.
8508 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
8509 : hasVisibleMergedDefinition(D)) {
8510 if (CodeSynthesisContexts.empty() &&
8511 !getLangOpts().ModulesLocalVisibility) {
8512 // Cache the fact that this definition is implicitly visible because
8513 // there is a visible merged definition.
8514 D->setVisibleDespiteOwningModule();
8515 }
8516 return true;
8517 }
8518
8519 return false;
8520 };
8521
8522 if (DefinitionIsVisible())
8523 return true;
8524
8525 // The external source may have additional definitions of this entity that are
8526 // visible, so complete the redeclaration chain now and ask again.
8527 if (auto *Source = Context.getExternalSource()) {
8528 Source->CompleteRedeclChain(D);
8529 return DefinitionIsVisible();
8530 }
8531
8532 return false;
8533 }
8534
8535 /// Locks in the inheritance model for the given class and all of its bases.
assignInheritanceModel(Sema & S,CXXRecordDecl * RD)8536 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
8537 RD = RD->getMostRecentNonInjectedDecl();
8538 if (!RD->hasAttr<MSInheritanceAttr>()) {
8539 MSInheritanceModel IM;
8540 bool BestCase = false;
8541 switch (S.MSPointerToMemberRepresentationMethod) {
8542 case LangOptions::PPTMK_BestCase:
8543 BestCase = true;
8544 IM = RD->calculateInheritanceModel();
8545 break;
8546 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
8547 IM = MSInheritanceModel::Single;
8548 break;
8549 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
8550 IM = MSInheritanceModel::Multiple;
8551 break;
8552 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
8553 IM = MSInheritanceModel::Unspecified;
8554 break;
8555 }
8556
8557 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
8558 ? S.ImplicitMSInheritanceAttrLoc
8559 : RD->getSourceRange();
8560 RD->addAttr(MSInheritanceAttr::CreateImplicit(
8561 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
8562 MSInheritanceAttr::Spelling(IM)));
8563 S.Consumer.AssignInheritanceModel(RD);
8564 }
8565 }
8566
8567 /// The implementation of RequireCompleteType
RequireCompleteTypeImpl(SourceLocation Loc,QualType T,CompleteTypeKind Kind,TypeDiagnoser * Diagnoser)8568 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
8569 CompleteTypeKind Kind,
8570 TypeDiagnoser *Diagnoser) {
8571 // FIXME: Add this assertion to make sure we always get instantiation points.
8572 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
8573 // FIXME: Add this assertion to help us flush out problems with
8574 // checking for dependent types and type-dependent expressions.
8575 //
8576 // assert(!T->isDependentType() &&
8577 // "Can't ask whether a dependent type is complete");
8578
8579 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
8580 if (!MPTy->getClass()->isDependentType()) {
8581 if (getLangOpts().CompleteMemberPointers &&
8582 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
8583 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
8584 diag::err_memptr_incomplete))
8585 return true;
8586
8587 // We lock in the inheritance model once somebody has asked us to ensure
8588 // that a pointer-to-member type is complete.
8589 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8590 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
8591 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
8592 }
8593 }
8594 }
8595
8596 NamedDecl *Def = nullptr;
8597 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
8598 bool Incomplete = (T->isIncompleteType(&Def) ||
8599 (!AcceptSizeless && T->isSizelessBuiltinType()));
8600
8601 // Check that any necessary explicit specializations are visible. For an
8602 // enum, we just need the declaration, so don't check this.
8603 if (Def && !isa<EnumDecl>(Def))
8604 checkSpecializationVisibility(Loc, Def);
8605
8606 // If we have a complete type, we're done.
8607 if (!Incomplete) {
8608 // If we know about the definition but it is not visible, complain.
8609 NamedDecl *SuggestedDef = nullptr;
8610 if (Def &&
8611 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
8612 // If the user is going to see an error here, recover by making the
8613 // definition visible.
8614 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
8615 if (Diagnoser && SuggestedDef)
8616 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
8617 /*Recover*/TreatAsComplete);
8618 return !TreatAsComplete;
8619 } else if (Def && !TemplateInstCallbacks.empty()) {
8620 CodeSynthesisContext TempInst;
8621 TempInst.Kind = CodeSynthesisContext::Memoization;
8622 TempInst.Template = Def;
8623 TempInst.Entity = Def;
8624 TempInst.PointOfInstantiation = Loc;
8625 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
8626 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
8627 }
8628
8629 return false;
8630 }
8631
8632 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8633 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8634
8635 // Give the external source a chance to provide a definition of the type.
8636 // This is kept separate from completing the redeclaration chain so that
8637 // external sources such as LLDB can avoid synthesizing a type definition
8638 // unless it's actually needed.
8639 if (Tag || IFace) {
8640 // Avoid diagnosing invalid decls as incomplete.
8641 if (Def->isInvalidDecl())
8642 return true;
8643
8644 // Give the external AST source a chance to complete the type.
8645 if (auto *Source = Context.getExternalSource()) {
8646 if (Tag && Tag->hasExternalLexicalStorage())
8647 Source->CompleteType(Tag);
8648 if (IFace && IFace->hasExternalLexicalStorage())
8649 Source->CompleteType(IFace);
8650 // If the external source completed the type, go through the motions
8651 // again to ensure we're allowed to use the completed type.
8652 if (!T->isIncompleteType())
8653 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8654 }
8655 }
8656
8657 // If we have a class template specialization or a class member of a
8658 // class template specialization, or an array with known size of such,
8659 // try to instantiate it.
8660 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8661 bool Instantiated = false;
8662 bool Diagnosed = false;
8663 if (RD->isDependentContext()) {
8664 // Don't try to instantiate a dependent class (eg, a member template of
8665 // an instantiated class template specialization).
8666 // FIXME: Can this ever happen?
8667 } else if (auto *ClassTemplateSpec =
8668 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8669 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
8670 runWithSufficientStackSpace(Loc, [&] {
8671 Diagnosed = InstantiateClassTemplateSpecialization(
8672 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
8673 /*Complain=*/Diagnoser);
8674 });
8675 Instantiated = true;
8676 }
8677 } else {
8678 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
8679 if (!RD->isBeingDefined() && Pattern) {
8680 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
8681 assert(MSI && "Missing member specialization information?");
8682 // This record was instantiated from a class within a template.
8683 if (MSI->getTemplateSpecializationKind() !=
8684 TSK_ExplicitSpecialization) {
8685 runWithSufficientStackSpace(Loc, [&] {
8686 Diagnosed = InstantiateClass(Loc, RD, Pattern,
8687 getTemplateInstantiationArgs(RD),
8688 TSK_ImplicitInstantiation,
8689 /*Complain=*/Diagnoser);
8690 });
8691 Instantiated = true;
8692 }
8693 }
8694 }
8695
8696 if (Instantiated) {
8697 // Instantiate* might have already complained that the template is not
8698 // defined, if we asked it to.
8699 if (Diagnoser && Diagnosed)
8700 return true;
8701 // If we instantiated a definition, check that it's usable, even if
8702 // instantiation produced an error, so that repeated calls to this
8703 // function give consistent answers.
8704 if (!T->isIncompleteType())
8705 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8706 }
8707 }
8708
8709 // FIXME: If we didn't instantiate a definition because of an explicit
8710 // specialization declaration, check that it's visible.
8711
8712 if (!Diagnoser)
8713 return true;
8714
8715 Diagnoser->diagnose(*this, Loc, T);
8716
8717 // If the type was a forward declaration of a class/struct/union
8718 // type, produce a note.
8719 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
8720 Diag(Tag->getLocation(),
8721 Tag->isBeingDefined() ? diag::note_type_being_defined
8722 : diag::note_forward_declaration)
8723 << Context.getTagDeclType(Tag);
8724
8725 // If the Objective-C class was a forward declaration, produce a note.
8726 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
8727 Diag(IFace->getLocation(), diag::note_forward_class);
8728
8729 // If we have external information that we can use to suggest a fix,
8730 // produce a note.
8731 if (ExternalSource)
8732 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
8733
8734 return true;
8735 }
8736
RequireCompleteType(SourceLocation Loc,QualType T,CompleteTypeKind Kind,unsigned DiagID)8737 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8738 CompleteTypeKind Kind, unsigned DiagID) {
8739 BoundTypeDiagnoser<> Diagnoser(DiagID);
8740 return RequireCompleteType(Loc, T, Kind, Diagnoser);
8741 }
8742
8743 /// Get diagnostic %select index for tag kind for
8744 /// literal type diagnostic message.
8745 /// WARNING: Indexes apply to particular diagnostics only!
8746 ///
8747 /// \returns diagnostic %select index.
getLiteralDiagFromTagKind(TagTypeKind Tag)8748 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
8749 switch (Tag) {
8750 case TTK_Struct: return 0;
8751 case TTK_Interface: return 1;
8752 case TTK_Class: return 2;
8753 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
8754 }
8755 }
8756
8757 /// Ensure that the type T is a literal type.
8758 ///
8759 /// This routine checks whether the type @p T is a literal type. If @p T is an
8760 /// incomplete type, an attempt is made to complete it. If @p T is a literal
8761 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
8762 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
8763 /// it the type @p T), along with notes explaining why the type is not a
8764 /// literal type, and returns true.
8765 ///
8766 /// @param Loc The location in the source that the non-literal type
8767 /// diagnostic should refer to.
8768 ///
8769 /// @param T The type that this routine is examining for literalness.
8770 ///
8771 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
8772 ///
8773 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
8774 /// @c false otherwise.
RequireLiteralType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)8775 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
8776 TypeDiagnoser &Diagnoser) {
8777 assert(!T->isDependentType() && "type should not be dependent");
8778
8779 QualType ElemType = Context.getBaseElementType(T);
8780 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
8781 T->isLiteralType(Context))
8782 return false;
8783
8784 Diagnoser.diagnose(*this, Loc, T);
8785
8786 if (T->isVariableArrayType())
8787 return true;
8788
8789 const RecordType *RT = ElemType->getAs<RecordType>();
8790 if (!RT)
8791 return true;
8792
8793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
8794
8795 // A partially-defined class type can't be a literal type, because a literal
8796 // class type must have a trivial destructor (which can't be checked until
8797 // the class definition is complete).
8798 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
8799 return true;
8800
8801 // [expr.prim.lambda]p3:
8802 // This class type is [not] a literal type.
8803 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
8804 Diag(RD->getLocation(), diag::note_non_literal_lambda);
8805 return true;
8806 }
8807
8808 // If the class has virtual base classes, then it's not an aggregate, and
8809 // cannot have any constexpr constructors or a trivial default constructor,
8810 // so is non-literal. This is better to diagnose than the resulting absence
8811 // of constexpr constructors.
8812 if (RD->getNumVBases()) {
8813 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
8814 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
8815 for (const auto &I : RD->vbases())
8816 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
8817 << I.getSourceRange();
8818 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
8819 !RD->hasTrivialDefaultConstructor()) {
8820 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
8821 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
8822 for (const auto &I : RD->bases()) {
8823 if (!I.getType()->isLiteralType(Context)) {
8824 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
8825 << RD << I.getType() << I.getSourceRange();
8826 return true;
8827 }
8828 }
8829 for (const auto *I : RD->fields()) {
8830 if (!I->getType()->isLiteralType(Context) ||
8831 I->getType().isVolatileQualified()) {
8832 Diag(I->getLocation(), diag::note_non_literal_field)
8833 << RD << I << I->getType()
8834 << I->getType().isVolatileQualified();
8835 return true;
8836 }
8837 }
8838 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
8839 : !RD->hasTrivialDestructor()) {
8840 // All fields and bases are of literal types, so have trivial or constexpr
8841 // destructors. If this class's destructor is non-trivial / non-constexpr,
8842 // it must be user-declared.
8843 CXXDestructorDecl *Dtor = RD->getDestructor();
8844 assert(Dtor && "class has literal fields and bases but no dtor?");
8845 if (!Dtor)
8846 return true;
8847
8848 if (getLangOpts().CPlusPlus20) {
8849 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
8850 << RD;
8851 } else {
8852 Diag(Dtor->getLocation(), Dtor->isUserProvided()
8853 ? diag::note_non_literal_user_provided_dtor
8854 : diag::note_non_literal_nontrivial_dtor)
8855 << RD;
8856 if (!Dtor->isUserProvided())
8857 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8858 /*Diagnose*/ true);
8859 }
8860 }
8861
8862 return true;
8863 }
8864
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID)8865 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8866 BoundTypeDiagnoser<> Diagnoser(DiagID);
8867 return RequireLiteralType(Loc, T, Diagnoser);
8868 }
8869
8870 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8871 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8872 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
getElaboratedType(ElaboratedTypeKeyword Keyword,const CXXScopeSpec & SS,QualType T,TagDecl * OwnedTagDecl)8873 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
8874 const CXXScopeSpec &SS, QualType T,
8875 TagDecl *OwnedTagDecl) {
8876 if (T.isNull())
8877 return T;
8878 NestedNameSpecifier *NNS;
8879 if (SS.isValid())
8880 NNS = SS.getScopeRep();
8881 else {
8882 if (Keyword == ETK_None)
8883 return T;
8884 NNS = nullptr;
8885 }
8886 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8887 }
8888
BuildTypeofExprType(Expr * E,SourceLocation Loc)8889 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
8890 assert(!E->hasPlaceholderType() && "unexpected placeholder");
8891
8892 if (!getLangOpts().CPlusPlus && E->refersToBitField())
8893 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8894
8895 if (!E->isTypeDependent()) {
8896 QualType T = E->getType();
8897 if (const TagType *TT = T->getAs<TagType>())
8898 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8899 }
8900 return Context.getTypeOfExprType(E);
8901 }
8902
8903 /// getDecltypeForParenthesizedExpr - Given an expr, will return the type for
8904 /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
8905 /// and class member access into account.
getDecltypeForParenthesizedExpr(Expr * E)8906 QualType Sema::getDecltypeForParenthesizedExpr(Expr *E) {
8907 // C++11 [dcl.type.simple]p4:
8908 // [...]
8909 QualType T = E->getType();
8910 switch (E->getValueKind()) {
8911 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8912 // type of e;
8913 case VK_XValue:
8914 return Context.getRValueReferenceType(T);
8915 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8916 // type of e;
8917 case VK_LValue:
8918 return Context.getLValueReferenceType(T);
8919 // - otherwise, decltype(e) is the type of e.
8920 case VK_PRValue:
8921 return T;
8922 }
8923 llvm_unreachable("Unknown value kind");
8924 }
8925
8926 /// getDecltypeForExpr - Given an expr, will return the decltype for
8927 /// that expression, according to the rules in C++11
8928 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
getDecltypeForExpr(Sema & S,Expr * E)8929 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
8930 if (E->isTypeDependent())
8931 return S.Context.DependentTy;
8932
8933 Expr *IDExpr = E;
8934 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
8935 IDExpr = ImplCastExpr->getSubExpr();
8936
8937 // C++11 [dcl.type.simple]p4:
8938 // The type denoted by decltype(e) is defined as follows:
8939
8940 // C++20:
8941 // - if E is an unparenthesized id-expression naming a non-type
8942 // template-parameter (13.2), decltype(E) is the type of the
8943 // template-parameter after performing any necessary type deduction
8944 // Note that this does not pick up the implicit 'const' for a template
8945 // parameter object. This rule makes no difference before C++20 so we apply
8946 // it unconditionally.
8947 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
8948 return SNTTPE->getParameterType(S.Context);
8949
8950 // - if e is an unparenthesized id-expression or an unparenthesized class
8951 // member access (5.2.5), decltype(e) is the type of the entity named
8952 // by e. If there is no such entity, or if e names a set of overloaded
8953 // functions, the program is ill-formed;
8954 //
8955 // We apply the same rules for Objective-C ivar and property references.
8956 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
8957 const ValueDecl *VD = DRE->getDecl();
8958 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(VD))
8959 return TPO->getType().getUnqualifiedType();
8960 return VD->getType();
8961 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(IDExpr)) {
8962 if (const ValueDecl *VD = ME->getMemberDecl())
8963 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8964 return VD->getType();
8965 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
8966 return IR->getDecl()->getType();
8967 } else if (const ObjCPropertyRefExpr *PR =
8968 dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
8969 if (PR->isExplicitProperty())
8970 return PR->getExplicitProperty()->getType();
8971 } else if (auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
8972 return PE->getType();
8973 }
8974
8975 // C++11 [expr.lambda.prim]p18:
8976 // Every occurrence of decltype((x)) where x is a possibly
8977 // parenthesized id-expression that names an entity of automatic
8978 // storage duration is treated as if x were transformed into an
8979 // access to a corresponding data member of the closure type that
8980 // would have been declared if x were an odr-use of the denoted
8981 // entity.
8982 using namespace sema;
8983 if (S.getCurLambda()) {
8984 if (isa<ParenExpr>(IDExpr)) {
8985 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
8986 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8987 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8988 if (!T.isNull())
8989 return S.Context.getLValueReferenceType(T);
8990 }
8991 }
8992 }
8993 }
8994
8995 return S.getDecltypeForParenthesizedExpr(E);
8996 }
8997
BuildDecltypeType(Expr * E,SourceLocation Loc,bool AsUnevaluated)8998 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8999 bool AsUnevaluated) {
9000 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9001
9002 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9003 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9004 // The expression operand for decltype is in an unevaluated expression
9005 // context, so side effects could result in unintended consequences.
9006 // Exclude instantiation-dependent expressions, because 'decltype' is often
9007 // used to build SFINAE gadgets.
9008 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9009 }
9010
9011 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
9012 }
9013
BuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)9014 QualType Sema::BuildUnaryTransformType(QualType BaseType,
9015 UnaryTransformType::UTTKind UKind,
9016 SourceLocation Loc) {
9017 switch (UKind) {
9018 case UnaryTransformType::EnumUnderlyingType:
9019 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
9020 Diag(Loc, diag::err_only_enums_have_underlying_types);
9021 return QualType();
9022 } else {
9023 QualType Underlying = BaseType;
9024 if (!BaseType->isDependentType()) {
9025 // The enum could be incomplete if we're parsing its definition or
9026 // recovering from an error.
9027 NamedDecl *FwdDecl = nullptr;
9028 if (BaseType->isIncompleteType(&FwdDecl)) {
9029 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9030 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9031 return QualType();
9032 }
9033
9034 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9035 assert(ED && "EnumType has no EnumDecl");
9036
9037 DiagnoseUseOfDecl(ED, Loc);
9038
9039 Underlying = ED->getIntegerType();
9040 assert(!Underlying.isNull());
9041 }
9042 return Context.getUnaryTransformType(BaseType, Underlying,
9043 UnaryTransformType::EnumUnderlyingType);
9044 }
9045 }
9046 llvm_unreachable("unknown unary transform type");
9047 }
9048
BuildAtomicType(QualType T,SourceLocation Loc)9049 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9050 if (!T->isDependentType()) {
9051 // FIXME: It isn't entirely clear whether incomplete atomic types
9052 // are allowed or not; for simplicity, ban them for the moment.
9053 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9054 return QualType();
9055
9056 int DisallowedKind = -1;
9057 if (T->isArrayType())
9058 DisallowedKind = 1;
9059 else if (T->isFunctionType())
9060 DisallowedKind = 2;
9061 else if (T->isReferenceType())
9062 DisallowedKind = 3;
9063 else if (T->isAtomicType())
9064 DisallowedKind = 4;
9065 else if (T.hasQualifiers())
9066 DisallowedKind = 5;
9067 else if (T->isSizelessType())
9068 DisallowedKind = 6;
9069 else if (!T.isTriviallyCopyableType(Context))
9070 // Some other non-trivially-copyable type (probably a C++ class)
9071 DisallowedKind = 7;
9072 else if (T->isExtIntType()) {
9073 DisallowedKind = 8;
9074 }
9075
9076 if (DisallowedKind != -1) {
9077 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9078 return QualType();
9079 }
9080
9081 // FIXME: Do we need any handling for ARC here?
9082 }
9083
9084 // Build the pointer type.
9085 return Context.getAtomicType(T);
9086 }
9087