1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.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/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/ErrorHandling.h"
37
38 using namespace clang;
39
40 enum TypeDiagSelector {
41 TDS_Function,
42 TDS_Pointer,
43 TDS_ObjCObjOrBlock
44 };
45
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
isOmittedBlockReturnType(const Declarator & D)48 static bool isOmittedBlockReturnType(const Declarator &D) {
49 if (D.getContext() != Declarator::BlockLiteralContext ||
50 D.getDeclSpec().hasTypeSpecifier())
51 return false;
52
53 if (D.getNumTypeObjects() == 0)
54 return true; // ^{ ... }
55
56 if (D.getNumTypeObjects() == 1 &&
57 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58 return true; // ^(int X, float Y) { ... }
59
60 return false;
61 }
62
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
diagnoseBadTypeAttribute(Sema & S,const AttributeList & attr,QualType type)65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
66 QualType type) {
67 TypeDiagSelector WhichType;
68 bool useExpansionLoc = true;
69 switch (attr.getKind()) {
70 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
71 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
72 default:
73 // Assume everything else was a function attribute.
74 WhichType = TDS_Function;
75 useExpansionLoc = false;
76 break;
77 }
78
79 SourceLocation loc = attr.getLoc();
80 StringRef name = attr.getName()->getName();
81
82 // The GC attributes are usually written with macros; special-case them.
83 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
84 : nullptr;
85 if (useExpansionLoc && loc.isMacroID() && II) {
86 if (II->isStr("strong")) {
87 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88 } else if (II->isStr("weak")) {
89 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90 }
91 }
92
93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
94 << type;
95 }
96
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100 case AttributeList::AT_ObjCGC: \
101 case AttributeList::AT_ObjCOwnership
102
103 // Calling convention attributes.
104 #define CALLING_CONV_ATTRS_CASELIST \
105 case AttributeList::AT_CDecl: \
106 case AttributeList::AT_FastCall: \
107 case AttributeList::AT_StdCall: \
108 case AttributeList::AT_ThisCall: \
109 case AttributeList::AT_Pascal: \
110 case AttributeList::AT_SwiftCall: \
111 case AttributeList::AT_VectorCall: \
112 case AttributeList::AT_MSABI: \
113 case AttributeList::AT_SysVABI: \
114 case AttributeList::AT_Pcs: \
115 case AttributeList::AT_IntelOclBicc: \
116 case AttributeList::AT_PreserveMost: \
117 case AttributeList::AT_PreserveAll
118
119 // Function type attributes.
120 #define FUNCTION_TYPE_ATTRS_CASELIST \
121 case AttributeList::AT_NoReturn: \
122 case AttributeList::AT_Regparm: \
123 CALLING_CONV_ATTRS_CASELIST
124
125 // Microsoft-specific type qualifiers.
126 #define MS_TYPE_ATTRS_CASELIST \
127 case AttributeList::AT_Ptr32: \
128 case AttributeList::AT_Ptr64: \
129 case AttributeList::AT_SPtr: \
130 case AttributeList::AT_UPtr
131
132 // Nullability qualifiers.
133 #define NULLABILITY_TYPE_ATTRS_CASELIST \
134 case AttributeList::AT_TypeNonNull: \
135 case AttributeList::AT_TypeNullable: \
136 case AttributeList::AT_TypeNullUnspecified
137
138 namespace {
139 /// An object which stores processing state for the entire
140 /// GetTypeForDeclarator process.
141 class TypeProcessingState {
142 Sema &sema;
143
144 /// The declarator being processed.
145 Declarator &declarator;
146
147 /// The index of the declarator chunk we're currently processing.
148 /// May be the total number of valid chunks, indicating the
149 /// DeclSpec.
150 unsigned chunkIndex;
151
152 /// Whether there are non-trivial modifications to the decl spec.
153 bool trivial;
154
155 /// Whether we saved the attributes in the decl spec.
156 bool hasSavedAttrs;
157
158 /// The original set of attributes on the DeclSpec.
159 SmallVector<AttributeList*, 2> savedAttrs;
160
161 /// A list of attributes to diagnose the uselessness of when the
162 /// processing is complete.
163 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
164
165 public:
TypeProcessingState(Sema & sema,Declarator & declarator)166 TypeProcessingState(Sema &sema, Declarator &declarator)
167 : sema(sema), declarator(declarator),
168 chunkIndex(declarator.getNumTypeObjects()),
169 trivial(true), hasSavedAttrs(false) {}
170
getSema() const171 Sema &getSema() const {
172 return sema;
173 }
174
getDeclarator() const175 Declarator &getDeclarator() const {
176 return declarator;
177 }
178
isProcessingDeclSpec() const179 bool isProcessingDeclSpec() const {
180 return chunkIndex == declarator.getNumTypeObjects();
181 }
182
getCurrentChunkIndex() const183 unsigned getCurrentChunkIndex() const {
184 return chunkIndex;
185 }
186
setCurrentChunkIndex(unsigned idx)187 void setCurrentChunkIndex(unsigned idx) {
188 assert(idx <= declarator.getNumTypeObjects());
189 chunkIndex = idx;
190 }
191
getCurrentAttrListRef() const192 AttributeList *&getCurrentAttrListRef() const {
193 if (isProcessingDeclSpec())
194 return getMutableDeclSpec().getAttributes().getListRef();
195 return declarator.getTypeObject(chunkIndex).getAttrListRef();
196 }
197
198 /// Save the current set of attributes on the DeclSpec.
saveDeclSpecAttrs()199 void saveDeclSpecAttrs() {
200 // Don't try to save them multiple times.
201 if (hasSavedAttrs) return;
202
203 DeclSpec &spec = getMutableDeclSpec();
204 for (AttributeList *attr = spec.getAttributes().getList(); attr;
205 attr = attr->getNext())
206 savedAttrs.push_back(attr);
207 trivial &= savedAttrs.empty();
208 hasSavedAttrs = true;
209 }
210
211 /// Record that we had nowhere to put the given type attribute.
212 /// We will diagnose such attributes later.
addIgnoredTypeAttr(AttributeList & attr)213 void addIgnoredTypeAttr(AttributeList &attr) {
214 ignoredTypeAttrs.push_back(&attr);
215 }
216
217 /// Diagnose all the ignored type attributes, given that the
218 /// declarator worked out to the given type.
diagnoseIgnoredTypeAttrs(QualType type) const219 void diagnoseIgnoredTypeAttrs(QualType type) const {
220 for (auto *Attr : ignoredTypeAttrs)
221 diagnoseBadTypeAttribute(getSema(), *Attr, type);
222 }
223
~TypeProcessingState()224 ~TypeProcessingState() {
225 if (trivial) return;
226
227 restoreDeclSpecAttrs();
228 }
229
230 private:
getMutableDeclSpec() const231 DeclSpec &getMutableDeclSpec() const {
232 return const_cast<DeclSpec&>(declarator.getDeclSpec());
233 }
234
restoreDeclSpecAttrs()235 void restoreDeclSpecAttrs() {
236 assert(hasSavedAttrs);
237
238 if (savedAttrs.empty()) {
239 getMutableDeclSpec().getAttributes().set(nullptr);
240 return;
241 }
242
243 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
244 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
245 savedAttrs[i]->setNext(savedAttrs[i+1]);
246 savedAttrs.back()->setNext(nullptr);
247 }
248 };
249 } // end anonymous namespace
250
spliceAttrIntoList(AttributeList & attr,AttributeList * & head)251 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
252 attr.setNext(head);
253 head = &attr;
254 }
255
spliceAttrOutOfList(AttributeList & attr,AttributeList * & head)256 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
257 if (head == &attr) {
258 head = attr.getNext();
259 return;
260 }
261
262 AttributeList *cur = head;
263 while (true) {
264 assert(cur && cur->getNext() && "ran out of attrs?");
265 if (cur->getNext() == &attr) {
266 cur->setNext(attr.getNext());
267 return;
268 }
269 cur = cur->getNext();
270 }
271 }
272
moveAttrFromListToList(AttributeList & attr,AttributeList * & fromList,AttributeList * & toList)273 static void moveAttrFromListToList(AttributeList &attr,
274 AttributeList *&fromList,
275 AttributeList *&toList) {
276 spliceAttrOutOfList(attr, fromList);
277 spliceAttrIntoList(attr, toList);
278 }
279
280 /// The location of a type attribute.
281 enum TypeAttrLocation {
282 /// The attribute is in the decl-specifier-seq.
283 TAL_DeclSpec,
284 /// The attribute is part of a DeclaratorChunk.
285 TAL_DeclChunk,
286 /// The attribute is immediately after the declaration's name.
287 TAL_DeclName
288 };
289
290 static void processTypeAttrs(TypeProcessingState &state,
291 QualType &type, TypeAttrLocation TAL,
292 AttributeList *attrs);
293
294 static bool handleFunctionTypeAttr(TypeProcessingState &state,
295 AttributeList &attr,
296 QualType &type);
297
298 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
299 AttributeList &attr,
300 QualType &type);
301
302 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
303 AttributeList &attr, QualType &type);
304
305 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
306 AttributeList &attr, QualType &type);
307
handleObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)308 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
309 AttributeList &attr, QualType &type) {
310 if (attr.getKind() == AttributeList::AT_ObjCGC)
311 return handleObjCGCTypeAttr(state, attr, type);
312 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
313 return handleObjCOwnershipTypeAttr(state, attr, type);
314 }
315
316 /// Given the index of a declarator chunk, check whether that chunk
317 /// directly specifies the return type of a function and, if so, find
318 /// an appropriate place for it.
319 ///
320 /// \param i - a notional index which the search will start
321 /// immediately inside
322 ///
323 /// \param onlyBlockPointers Whether we should only look into block
324 /// pointer types (vs. all pointer types).
maybeMovePastReturnType(Declarator & declarator,unsigned i,bool onlyBlockPointers)325 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
326 unsigned i,
327 bool onlyBlockPointers) {
328 assert(i <= declarator.getNumTypeObjects());
329
330 DeclaratorChunk *result = nullptr;
331
332 // First, look inwards past parens for a function declarator.
333 for (; i != 0; --i) {
334 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
335 switch (fnChunk.Kind) {
336 case DeclaratorChunk::Paren:
337 continue;
338
339 // If we find anything except a function, bail out.
340 case DeclaratorChunk::Pointer:
341 case DeclaratorChunk::BlockPointer:
342 case DeclaratorChunk::Array:
343 case DeclaratorChunk::Reference:
344 case DeclaratorChunk::MemberPointer:
345 case DeclaratorChunk::Pipe:
346 return result;
347
348 // If we do find a function declarator, scan inwards from that,
349 // looking for a (block-)pointer declarator.
350 case DeclaratorChunk::Function:
351 for (--i; i != 0; --i) {
352 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
353 switch (ptrChunk.Kind) {
354 case DeclaratorChunk::Paren:
355 case DeclaratorChunk::Array:
356 case DeclaratorChunk::Function:
357 case DeclaratorChunk::Reference:
358 case DeclaratorChunk::Pipe:
359 continue;
360
361 case DeclaratorChunk::MemberPointer:
362 case DeclaratorChunk::Pointer:
363 if (onlyBlockPointers)
364 continue;
365
366 // fallthrough
367
368 case DeclaratorChunk::BlockPointer:
369 result = &ptrChunk;
370 goto continue_outer;
371 }
372 llvm_unreachable("bad declarator chunk kind");
373 }
374
375 // If we run out of declarators doing that, we're done.
376 return result;
377 }
378 llvm_unreachable("bad declarator chunk kind");
379
380 // Okay, reconsider from our new point.
381 continue_outer: ;
382 }
383
384 // Ran out of chunks, bail out.
385 return result;
386 }
387
388 /// Given that an objc_gc attribute was written somewhere on a
389 /// declaration *other* than on the declarator itself (for which, use
390 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
391 /// didn't apply in whatever position it was written in, try to move
392 /// it to a more appropriate position.
distributeObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)393 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
394 AttributeList &attr,
395 QualType type) {
396 Declarator &declarator = state.getDeclarator();
397
398 // Move it to the outermost normal or block pointer declarator.
399 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
400 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
401 switch (chunk.Kind) {
402 case DeclaratorChunk::Pointer:
403 case DeclaratorChunk::BlockPointer: {
404 // But don't move an ARC ownership attribute to the return type
405 // of a block.
406 DeclaratorChunk *destChunk = nullptr;
407 if (state.isProcessingDeclSpec() &&
408 attr.getKind() == AttributeList::AT_ObjCOwnership)
409 destChunk = maybeMovePastReturnType(declarator, i - 1,
410 /*onlyBlockPointers=*/true);
411 if (!destChunk) destChunk = &chunk;
412
413 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
414 destChunk->getAttrListRef());
415 return;
416 }
417
418 case DeclaratorChunk::Paren:
419 case DeclaratorChunk::Array:
420 continue;
421
422 // We may be starting at the return type of a block.
423 case DeclaratorChunk::Function:
424 if (state.isProcessingDeclSpec() &&
425 attr.getKind() == AttributeList::AT_ObjCOwnership) {
426 if (DeclaratorChunk *dest = maybeMovePastReturnType(
427 declarator, i,
428 /*onlyBlockPointers=*/true)) {
429 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
430 dest->getAttrListRef());
431 return;
432 }
433 }
434 goto error;
435
436 // Don't walk through these.
437 case DeclaratorChunk::Reference:
438 case DeclaratorChunk::MemberPointer:
439 case DeclaratorChunk::Pipe:
440 goto error;
441 }
442 }
443 error:
444
445 diagnoseBadTypeAttribute(state.getSema(), attr, type);
446 }
447
448 /// Distribute an objc_gc type attribute that was written on the
449 /// declarator.
450 static void
distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)451 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
452 AttributeList &attr,
453 QualType &declSpecType) {
454 Declarator &declarator = state.getDeclarator();
455
456 // objc_gc goes on the innermost pointer to something that's not a
457 // pointer.
458 unsigned innermost = -1U;
459 bool considerDeclSpec = true;
460 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
461 DeclaratorChunk &chunk = declarator.getTypeObject(i);
462 switch (chunk.Kind) {
463 case DeclaratorChunk::Pointer:
464 case DeclaratorChunk::BlockPointer:
465 innermost = i;
466 continue;
467
468 case DeclaratorChunk::Reference:
469 case DeclaratorChunk::MemberPointer:
470 case DeclaratorChunk::Paren:
471 case DeclaratorChunk::Array:
472 case DeclaratorChunk::Pipe:
473 continue;
474
475 case DeclaratorChunk::Function:
476 considerDeclSpec = false;
477 goto done;
478 }
479 }
480 done:
481
482 // That might actually be the decl spec if we weren't blocked by
483 // anything in the declarator.
484 if (considerDeclSpec) {
485 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
486 // Splice the attribute into the decl spec. Prevents the
487 // attribute from being applied multiple times and gives
488 // the source-location-filler something to work with.
489 state.saveDeclSpecAttrs();
490 moveAttrFromListToList(attr, declarator.getAttrListRef(),
491 declarator.getMutableDeclSpec().getAttributes().getListRef());
492 return;
493 }
494 }
495
496 // Otherwise, if we found an appropriate chunk, splice the attribute
497 // into it.
498 if (innermost != -1U) {
499 moveAttrFromListToList(attr, declarator.getAttrListRef(),
500 declarator.getTypeObject(innermost).getAttrListRef());
501 return;
502 }
503
504 // Otherwise, diagnose when we're done building the type.
505 spliceAttrOutOfList(attr, declarator.getAttrListRef());
506 state.addIgnoredTypeAttr(attr);
507 }
508
509 /// A function type attribute was written somewhere in a declaration
510 /// *other* than on the declarator itself or in the decl spec. Given
511 /// that it didn't apply in whatever position it was written in, try
512 /// to move it to a more appropriate position.
distributeFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)513 static void distributeFunctionTypeAttr(TypeProcessingState &state,
514 AttributeList &attr,
515 QualType type) {
516 Declarator &declarator = state.getDeclarator();
517
518 // Try to push the attribute from the return type of a function to
519 // the function itself.
520 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
521 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
522 switch (chunk.Kind) {
523 case DeclaratorChunk::Function:
524 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
525 chunk.getAttrListRef());
526 return;
527
528 case DeclaratorChunk::Paren:
529 case DeclaratorChunk::Pointer:
530 case DeclaratorChunk::BlockPointer:
531 case DeclaratorChunk::Array:
532 case DeclaratorChunk::Reference:
533 case DeclaratorChunk::MemberPointer:
534 case DeclaratorChunk::Pipe:
535 continue;
536 }
537 }
538
539 diagnoseBadTypeAttribute(state.getSema(), attr, type);
540 }
541
542 /// Try to distribute a function type attribute to the innermost
543 /// function chunk or type. Returns true if the attribute was
544 /// distributed, false if no location was found.
545 static bool
distributeFunctionTypeAttrToInnermost(TypeProcessingState & state,AttributeList & attr,AttributeList * & attrList,QualType & declSpecType)546 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
547 AttributeList &attr,
548 AttributeList *&attrList,
549 QualType &declSpecType) {
550 Declarator &declarator = state.getDeclarator();
551
552 // Put it on the innermost function chunk, if there is one.
553 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
554 DeclaratorChunk &chunk = declarator.getTypeObject(i);
555 if (chunk.Kind != DeclaratorChunk::Function) continue;
556
557 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
558 return true;
559 }
560
561 return handleFunctionTypeAttr(state, attr, declSpecType);
562 }
563
564 /// A function type attribute was written in the decl spec. Try to
565 /// apply it somewhere.
566 static void
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)567 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
568 AttributeList &attr,
569 QualType &declSpecType) {
570 state.saveDeclSpecAttrs();
571
572 // C++11 attributes before the decl specifiers actually appertain to
573 // the declarators. Move them straight there. We don't support the
574 // 'put them wherever you like' semantics we allow for GNU attributes.
575 if (attr.isCXX11Attribute()) {
576 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
577 state.getDeclarator().getAttrListRef());
578 return;
579 }
580
581 // Try to distribute to the innermost.
582 if (distributeFunctionTypeAttrToInnermost(state, attr,
583 state.getCurrentAttrListRef(),
584 declSpecType))
585 return;
586
587 // If that failed, diagnose the bad attribute when the declarator is
588 // fully built.
589 state.addIgnoredTypeAttr(attr);
590 }
591
592 /// A function type attribute was written on the declarator. Try to
593 /// apply it somewhere.
594 static void
distributeFunctionTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)595 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
596 AttributeList &attr,
597 QualType &declSpecType) {
598 Declarator &declarator = state.getDeclarator();
599
600 // Try to distribute to the innermost.
601 if (distributeFunctionTypeAttrToInnermost(state, attr,
602 declarator.getAttrListRef(),
603 declSpecType))
604 return;
605
606 // If that failed, diagnose the bad attribute when the declarator is
607 // fully built.
608 spliceAttrOutOfList(attr, declarator.getAttrListRef());
609 state.addIgnoredTypeAttr(attr);
610 }
611
612 /// \brief Given that there are attributes written on the declarator
613 /// itself, try to distribute any type attributes to the appropriate
614 /// declarator chunk.
615 ///
616 /// These are attributes like the following:
617 /// int f ATTR;
618 /// int (f ATTR)();
619 /// but not necessarily this:
620 /// int f() ATTR;
distributeTypeAttrsFromDeclarator(TypeProcessingState & state,QualType & declSpecType)621 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
622 QualType &declSpecType) {
623 // Collect all the type attributes from the declarator itself.
624 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
625 AttributeList *attr = state.getDeclarator().getAttributes();
626 AttributeList *next;
627 do {
628 next = attr->getNext();
629
630 // Do not distribute C++11 attributes. They have strict rules for what
631 // they appertain to.
632 if (attr->isCXX11Attribute())
633 continue;
634
635 switch (attr->getKind()) {
636 OBJC_POINTER_TYPE_ATTRS_CASELIST:
637 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
638 break;
639
640 case AttributeList::AT_NSReturnsRetained:
641 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
642 break;
643 // fallthrough
644
645 FUNCTION_TYPE_ATTRS_CASELIST:
646 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
647 break;
648
649 MS_TYPE_ATTRS_CASELIST:
650 // Microsoft type attributes cannot go after the declarator-id.
651 continue;
652
653 NULLABILITY_TYPE_ATTRS_CASELIST:
654 // Nullability specifiers cannot go after the declarator-id.
655
656 // Objective-C __kindof does not get distributed.
657 case AttributeList::AT_ObjCKindOf:
658 continue;
659
660 default:
661 break;
662 }
663 } while ((attr = next));
664 }
665
666 /// Add a synthetic '()' to a block-literal declarator if it is
667 /// required, given the return type.
maybeSynthesizeBlockSignature(TypeProcessingState & state,QualType declSpecType)668 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
669 QualType declSpecType) {
670 Declarator &declarator = state.getDeclarator();
671
672 // First, check whether the declarator would produce a function,
673 // i.e. whether the innermost semantic chunk is a function.
674 if (declarator.isFunctionDeclarator()) {
675 // If so, make that declarator a prototyped declarator.
676 declarator.getFunctionTypeInfo().hasPrototype = true;
677 return;
678 }
679
680 // If there are any type objects, the type as written won't name a
681 // function, regardless of the decl spec type. This is because a
682 // block signature declarator is always an abstract-declarator, and
683 // abstract-declarators can't just be parentheses chunks. Therefore
684 // we need to build a function chunk unless there are no type
685 // objects and the decl spec type is a function.
686 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
687 return;
688
689 // Note that there *are* cases with invalid declarators where
690 // declarators consist solely of parentheses. In general, these
691 // occur only in failed efforts to make function declarators, so
692 // faking up the function chunk is still the right thing to do.
693
694 // Otherwise, we need to fake up a function declarator.
695 SourceLocation loc = declarator.getLocStart();
696
697 // ...and *prepend* it to the declarator.
698 SourceLocation NoLoc;
699 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
700 /*HasProto=*/true,
701 /*IsAmbiguous=*/false,
702 /*LParenLoc=*/NoLoc,
703 /*ArgInfo=*/nullptr,
704 /*NumArgs=*/0,
705 /*EllipsisLoc=*/NoLoc,
706 /*RParenLoc=*/NoLoc,
707 /*TypeQuals=*/0,
708 /*RefQualifierIsLvalueRef=*/true,
709 /*RefQualifierLoc=*/NoLoc,
710 /*ConstQualifierLoc=*/NoLoc,
711 /*VolatileQualifierLoc=*/NoLoc,
712 /*RestrictQualifierLoc=*/NoLoc,
713 /*MutableLoc=*/NoLoc, EST_None,
714 /*ESpecRange=*/SourceRange(),
715 /*Exceptions=*/nullptr,
716 /*ExceptionRanges=*/nullptr,
717 /*NumExceptions=*/0,
718 /*NoexceptExpr=*/nullptr,
719 /*ExceptionSpecTokens=*/nullptr,
720 loc, loc, declarator));
721
722 // For consistency, make sure the state still has us as processing
723 // the decl spec.
724 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
725 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
726 }
727
diagnoseAndRemoveTypeQualifiers(Sema & S,const DeclSpec & DS,unsigned & TypeQuals,QualType TypeSoFar,unsigned RemoveTQs,unsigned DiagID)728 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
729 unsigned &TypeQuals,
730 QualType TypeSoFar,
731 unsigned RemoveTQs,
732 unsigned DiagID) {
733 // If this occurs outside a template instantiation, warn the user about
734 // it; they probably didn't mean to specify a redundant qualifier.
735 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
736 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
737 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
738 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
739 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
740 if (!(RemoveTQs & Qual.first))
741 continue;
742
743 if (S.ActiveTemplateInstantiations.empty()) {
744 if (TypeQuals & Qual.first)
745 S.Diag(Qual.second, DiagID)
746 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
747 << FixItHint::CreateRemoval(Qual.second);
748 }
749
750 TypeQuals &= ~Qual.first;
751 }
752 }
753
754 /// Return true if this is omitted block return type. Also check type
755 /// attributes and type qualifiers when returning true.
checkOmittedBlockReturnType(Sema & S,Declarator & declarator,QualType Result)756 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
757 QualType Result) {
758 if (!isOmittedBlockReturnType(declarator))
759 return false;
760
761 // Warn if we see type attributes for omitted return type on a block literal.
762 AttributeList *&attrs =
763 declarator.getMutableDeclSpec().getAttributes().getListRef();
764 AttributeList *prev = nullptr;
765 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
766 AttributeList &attr = *cur;
767 // Skip attributes that were marked to be invalid or non-type
768 // attributes.
769 if (attr.isInvalid() || !attr.isTypeAttr()) {
770 prev = cur;
771 continue;
772 }
773 S.Diag(attr.getLoc(),
774 diag::warn_block_literal_attributes_on_omitted_return_type)
775 << attr.getName();
776 // Remove cur from the list.
777 if (prev) {
778 prev->setNext(cur->getNext());
779 prev = cur;
780 } else {
781 attrs = cur->getNext();
782 }
783 }
784
785 // Warn if we see type qualifiers for omitted return type on a block literal.
786 const DeclSpec &DS = declarator.getDeclSpec();
787 unsigned TypeQuals = DS.getTypeQualifiers();
788 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
789 diag::warn_block_literal_qualifiers_on_omitted_return_type);
790 declarator.getMutableDeclSpec().ClearTypeQualifiers();
791
792 return true;
793 }
794
795 /// Apply Objective-C type arguments to the given type.
applyObjCTypeArgs(Sema & S,SourceLocation loc,QualType type,ArrayRef<TypeSourceInfo * > typeArgs,SourceRange typeArgsRange,bool failOnError=false)796 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
797 ArrayRef<TypeSourceInfo *> typeArgs,
798 SourceRange typeArgsRange,
799 bool failOnError = false) {
800 // We can only apply type arguments to an Objective-C class type.
801 const auto *objcObjectType = type->getAs<ObjCObjectType>();
802 if (!objcObjectType || !objcObjectType->getInterface()) {
803 S.Diag(loc, diag::err_objc_type_args_non_class)
804 << type
805 << typeArgsRange;
806
807 if (failOnError)
808 return QualType();
809 return type;
810 }
811
812 // The class type must be parameterized.
813 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
814 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
815 if (!typeParams) {
816 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
817 << objcClass->getDeclName()
818 << FixItHint::CreateRemoval(typeArgsRange);
819
820 if (failOnError)
821 return QualType();
822
823 return type;
824 }
825
826 // The type must not already be specialized.
827 if (objcObjectType->isSpecialized()) {
828 S.Diag(loc, diag::err_objc_type_args_specialized_class)
829 << type
830 << FixItHint::CreateRemoval(typeArgsRange);
831
832 if (failOnError)
833 return QualType();
834
835 return type;
836 }
837
838 // Check the type arguments.
839 SmallVector<QualType, 4> finalTypeArgs;
840 unsigned numTypeParams = typeParams->size();
841 bool anyPackExpansions = false;
842 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
843 TypeSourceInfo *typeArgInfo = typeArgs[i];
844 QualType typeArg = typeArgInfo->getType();
845
846 // Type arguments cannot have explicit qualifiers or nullability.
847 // We ignore indirect sources of these, e.g. behind typedefs or
848 // template arguments.
849 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
850 bool diagnosed = false;
851 SourceRange rangeToRemove;
852 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
853 rangeToRemove = attr.getLocalSourceRange();
854 if (attr.getTypePtr()->getImmediateNullability()) {
855 typeArg = attr.getTypePtr()->getModifiedType();
856 S.Diag(attr.getLocStart(),
857 diag::err_objc_type_arg_explicit_nullability)
858 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
859 diagnosed = true;
860 }
861 }
862
863 if (!diagnosed) {
864 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
865 << typeArg << typeArg.getQualifiers().getAsString()
866 << FixItHint::CreateRemoval(rangeToRemove);
867 }
868 }
869
870 // Remove qualifiers even if they're non-local.
871 typeArg = typeArg.getUnqualifiedType();
872
873 finalTypeArgs.push_back(typeArg);
874
875 if (typeArg->getAs<PackExpansionType>())
876 anyPackExpansions = true;
877
878 // Find the corresponding type parameter, if there is one.
879 ObjCTypeParamDecl *typeParam = nullptr;
880 if (!anyPackExpansions) {
881 if (i < numTypeParams) {
882 typeParam = typeParams->begin()[i];
883 } else {
884 // Too many arguments.
885 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
886 << false
887 << objcClass->getDeclName()
888 << (unsigned)typeArgs.size()
889 << numTypeParams;
890 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
891 << objcClass;
892
893 if (failOnError)
894 return QualType();
895
896 return type;
897 }
898 }
899
900 // Objective-C object pointer types must be substitutable for the bounds.
901 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
902 // If we don't have a type parameter to match against, assume
903 // everything is fine. There was a prior pack expansion that
904 // means we won't be able to match anything.
905 if (!typeParam) {
906 assert(anyPackExpansions && "Too many arguments?");
907 continue;
908 }
909
910 // Retrieve the bound.
911 QualType bound = typeParam->getUnderlyingType();
912 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
913
914 // Determine whether the type argument is substitutable for the bound.
915 if (typeArgObjC->isObjCIdType()) {
916 // When the type argument is 'id', the only acceptable type
917 // parameter bound is 'id'.
918 if (boundObjC->isObjCIdType())
919 continue;
920 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
921 // Otherwise, we follow the assignability rules.
922 continue;
923 }
924
925 // Diagnose the mismatch.
926 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
927 diag::err_objc_type_arg_does_not_match_bound)
928 << typeArg << bound << typeParam->getDeclName();
929 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
930 << typeParam->getDeclName();
931
932 if (failOnError)
933 return QualType();
934
935 return type;
936 }
937
938 // Block pointer types are permitted for unqualified 'id' bounds.
939 if (typeArg->isBlockPointerType()) {
940 // If we don't have a type parameter to match against, assume
941 // everything is fine. There was a prior pack expansion that
942 // means we won't be able to match anything.
943 if (!typeParam) {
944 assert(anyPackExpansions && "Too many arguments?");
945 continue;
946 }
947
948 // Retrieve the bound.
949 QualType bound = typeParam->getUnderlyingType();
950 if (bound->isBlockCompatibleObjCPointerType(S.Context))
951 continue;
952
953 // Diagnose the mismatch.
954 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
955 diag::err_objc_type_arg_does_not_match_bound)
956 << typeArg << bound << typeParam->getDeclName();
957 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
958 << typeParam->getDeclName();
959
960 if (failOnError)
961 return QualType();
962
963 return type;
964 }
965
966 // Dependent types will be checked at instantiation time.
967 if (typeArg->isDependentType()) {
968 continue;
969 }
970
971 // Diagnose non-id-compatible type arguments.
972 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
973 diag::err_objc_type_arg_not_id_compatible)
974 << typeArg
975 << typeArgInfo->getTypeLoc().getSourceRange();
976
977 if (failOnError)
978 return QualType();
979
980 return type;
981 }
982
983 // Make sure we didn't have the wrong number of arguments.
984 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
985 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
986 << (typeArgs.size() < typeParams->size())
987 << objcClass->getDeclName()
988 << (unsigned)finalTypeArgs.size()
989 << (unsigned)numTypeParams;
990 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
991 << objcClass;
992
993 if (failOnError)
994 return QualType();
995
996 return type;
997 }
998
999 // Success. Form the specialized type.
1000 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1001 }
1002
1003 /// Apply Objective-C protocol qualifiers to the given type.
applyObjCProtocolQualifiers(Sema & S,SourceLocation loc,SourceRange range,QualType type,ArrayRef<ObjCProtocolDecl * > protocols,const SourceLocation * protocolLocs,bool failOnError=false)1004 static QualType applyObjCProtocolQualifiers(
1005 Sema &S, SourceLocation loc, SourceRange range, QualType type,
1006 ArrayRef<ObjCProtocolDecl *> protocols,
1007 const SourceLocation *protocolLocs,
1008 bool failOnError = false) {
1009 ASTContext &ctx = S.Context;
1010 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
1011 // FIXME: Check for protocols to which the class type is already
1012 // known to conform.
1013
1014 return ctx.getObjCObjectType(objT->getBaseType(),
1015 objT->getTypeArgsAsWritten(),
1016 protocols,
1017 objT->isKindOfTypeAsWritten());
1018 }
1019
1020 if (type->isObjCObjectType()) {
1021 // Silently overwrite any existing protocol qualifiers.
1022 // TODO: determine whether that's the right thing to do.
1023
1024 // FIXME: Check for protocols to which the class type is already
1025 // known to conform.
1026 return ctx.getObjCObjectType(type, { }, protocols, false);
1027 }
1028
1029 // id<protocol-list>
1030 if (type->isObjCIdType()) {
1031 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
1032 type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
1033 objPtr->isKindOfType());
1034 return ctx.getObjCObjectPointerType(type);
1035 }
1036
1037 // Class<protocol-list>
1038 if (type->isObjCClassType()) {
1039 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
1040 type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
1041 objPtr->isKindOfType());
1042 return ctx.getObjCObjectPointerType(type);
1043 }
1044
1045 S.Diag(loc, diag::err_invalid_protocol_qualifiers)
1046 << range;
1047
1048 if (failOnError)
1049 return QualType();
1050
1051 return type;
1052 }
1053
BuildObjCObjectType(QualType BaseType,SourceLocation Loc,SourceLocation TypeArgsLAngleLoc,ArrayRef<TypeSourceInfo * > TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc,bool FailOnError)1054 QualType Sema::BuildObjCObjectType(QualType BaseType,
1055 SourceLocation Loc,
1056 SourceLocation TypeArgsLAngleLoc,
1057 ArrayRef<TypeSourceInfo *> TypeArgs,
1058 SourceLocation TypeArgsRAngleLoc,
1059 SourceLocation ProtocolLAngleLoc,
1060 ArrayRef<ObjCProtocolDecl *> Protocols,
1061 ArrayRef<SourceLocation> ProtocolLocs,
1062 SourceLocation ProtocolRAngleLoc,
1063 bool FailOnError) {
1064 QualType Result = BaseType;
1065 if (!TypeArgs.empty()) {
1066 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1067 SourceRange(TypeArgsLAngleLoc,
1068 TypeArgsRAngleLoc),
1069 FailOnError);
1070 if (FailOnError && Result.isNull())
1071 return QualType();
1072 }
1073
1074 if (!Protocols.empty()) {
1075 Result = applyObjCProtocolQualifiers(*this, Loc,
1076 SourceRange(ProtocolLAngleLoc,
1077 ProtocolRAngleLoc),
1078 Result, Protocols,
1079 ProtocolLocs.data(),
1080 FailOnError);
1081 if (FailOnError && Result.isNull())
1082 return QualType();
1083 }
1084
1085 return Result;
1086 }
1087
actOnObjCProtocolQualifierType(SourceLocation lAngleLoc,ArrayRef<Decl * > protocols,ArrayRef<SourceLocation> protocolLocs,SourceLocation rAngleLoc)1088 TypeResult Sema::actOnObjCProtocolQualifierType(
1089 SourceLocation lAngleLoc,
1090 ArrayRef<Decl *> protocols,
1091 ArrayRef<SourceLocation> protocolLocs,
1092 SourceLocation rAngleLoc) {
1093 // Form id<protocol-list>.
1094 QualType Result = Context.getObjCObjectType(
1095 Context.ObjCBuiltinIdTy, { },
1096 llvm::makeArrayRef(
1097 (ObjCProtocolDecl * const *)protocols.data(),
1098 protocols.size()),
1099 false);
1100 Result = Context.getObjCObjectPointerType(Result);
1101
1102 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1103 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1104
1105 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1106 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1107
1108 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1109 .castAs<ObjCObjectTypeLoc>();
1110 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1111 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1112
1113 // No type arguments.
1114 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1115 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1116
1117 // Fill in protocol qualifiers.
1118 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1119 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1120 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1121 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1122
1123 // We're done. Return the completed type to the parser.
1124 return CreateParsedType(Result, ResultTInfo);
1125 }
1126
actOnObjCTypeArgsAndProtocolQualifiers(Scope * S,SourceLocation Loc,ParsedType BaseType,SourceLocation TypeArgsLAngleLoc,ArrayRef<ParsedType> TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<Decl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc)1127 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1128 Scope *S,
1129 SourceLocation Loc,
1130 ParsedType BaseType,
1131 SourceLocation TypeArgsLAngleLoc,
1132 ArrayRef<ParsedType> TypeArgs,
1133 SourceLocation TypeArgsRAngleLoc,
1134 SourceLocation ProtocolLAngleLoc,
1135 ArrayRef<Decl *> Protocols,
1136 ArrayRef<SourceLocation> ProtocolLocs,
1137 SourceLocation ProtocolRAngleLoc) {
1138 TypeSourceInfo *BaseTypeInfo = nullptr;
1139 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1140 if (T.isNull())
1141 return true;
1142
1143 // Handle missing type-source info.
1144 if (!BaseTypeInfo)
1145 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1146
1147 // Extract type arguments.
1148 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1149 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1150 TypeSourceInfo *TypeArgInfo = nullptr;
1151 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1152 if (TypeArg.isNull()) {
1153 ActualTypeArgInfos.clear();
1154 break;
1155 }
1156
1157 assert(TypeArgInfo && "No type source info?");
1158 ActualTypeArgInfos.push_back(TypeArgInfo);
1159 }
1160
1161 // Build the object type.
1162 QualType Result = BuildObjCObjectType(
1163 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1164 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1165 ProtocolLAngleLoc,
1166 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1167 Protocols.size()),
1168 ProtocolLocs, ProtocolRAngleLoc,
1169 /*FailOnError=*/false);
1170
1171 if (Result == T)
1172 return BaseType;
1173
1174 // Create source information for this type.
1175 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1176 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1177
1178 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1179 // object pointer type. Fill in source information for it.
1180 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1181 // The '*' is implicit.
1182 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1183 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1184 }
1185
1186 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1187
1188 // Type argument information.
1189 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1190 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1191 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1192 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1193 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1194 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1195 } else {
1196 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1197 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1198 }
1199
1200 // Protocol qualifier information.
1201 if (ObjCObjectTL.getNumProtocols() > 0) {
1202 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1203 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1204 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1205 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1206 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1207 } else {
1208 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1209 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1210 }
1211
1212 // Base type.
1213 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1214 if (ObjCObjectTL.getType() == T)
1215 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1216 else
1217 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1218
1219 // We're done. Return the completed type to the parser.
1220 return CreateParsedType(Result, ResultTInfo);
1221 }
1222
getImageAccessAttrStr(AttributeList * attrs)1223 static StringRef getImageAccessAttrStr(AttributeList *attrs) {
1224 if (attrs) {
1225
1226 AttributeList *Next;
1227 do {
1228 AttributeList &Attr = *attrs;
1229 Next = Attr.getNext();
1230 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1231 return Attr.getName()->getName();
1232 }
1233 } while (Next);
1234 }
1235 return "";
1236 }
1237
1238 /// \brief Convert the specified declspec to the appropriate type
1239 /// object.
1240 /// \param state Specifies the declarator containing the declaration specifier
1241 /// to be converted, along with other associated processing state.
1242 /// \returns The type described by the declaration specifiers. This function
1243 /// never returns null.
ConvertDeclSpecToType(TypeProcessingState & state)1244 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1245 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1246 // checking.
1247
1248 Sema &S = state.getSema();
1249 Declarator &declarator = state.getDeclarator();
1250 const DeclSpec &DS = declarator.getDeclSpec();
1251 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1252 if (DeclLoc.isInvalid())
1253 DeclLoc = DS.getLocStart();
1254
1255 ASTContext &Context = S.Context;
1256
1257 QualType Result;
1258 switch (DS.getTypeSpecType()) {
1259 case DeclSpec::TST_void:
1260 Result = Context.VoidTy;
1261 break;
1262 case DeclSpec::TST_char:
1263 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1264 Result = Context.CharTy;
1265 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1266 Result = Context.SignedCharTy;
1267 else {
1268 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1269 "Unknown TSS value");
1270 Result = Context.UnsignedCharTy;
1271 }
1272 break;
1273 case DeclSpec::TST_wchar:
1274 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1275 Result = Context.WCharTy;
1276 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1277 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1278 << DS.getSpecifierName(DS.getTypeSpecType(),
1279 Context.getPrintingPolicy());
1280 Result = Context.getSignedWCharType();
1281 } else {
1282 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1283 "Unknown TSS value");
1284 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1285 << DS.getSpecifierName(DS.getTypeSpecType(),
1286 Context.getPrintingPolicy());
1287 Result = Context.getUnsignedWCharType();
1288 }
1289 break;
1290 case DeclSpec::TST_char16:
1291 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1292 "Unknown TSS value");
1293 Result = Context.Char16Ty;
1294 break;
1295 case DeclSpec::TST_char32:
1296 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1297 "Unknown TSS value");
1298 Result = Context.Char32Ty;
1299 break;
1300 case DeclSpec::TST_unspecified:
1301 // If this is a missing declspec in a block literal return context, then it
1302 // is inferred from the return statements inside the block.
1303 // The declspec is always missing in a lambda expr context; it is either
1304 // specified with a trailing return type or inferred.
1305 if (S.getLangOpts().CPlusPlus14 &&
1306 declarator.getContext() == Declarator::LambdaExprContext) {
1307 // In C++1y, a lambda's implicit return type is 'auto'.
1308 Result = Context.getAutoDeductType();
1309 break;
1310 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1311 checkOmittedBlockReturnType(S, declarator,
1312 Context.DependentTy)) {
1313 Result = Context.DependentTy;
1314 break;
1315 }
1316
1317 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1318 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1319 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1320 // Note that the one exception to this is function definitions, which are
1321 // allowed to be completely missing a declspec. This is handled in the
1322 // parser already though by it pretending to have seen an 'int' in this
1323 // case.
1324 if (S.getLangOpts().ImplicitInt) {
1325 // In C89 mode, we only warn if there is a completely missing declspec
1326 // when one is not allowed.
1327 if (DS.isEmpty()) {
1328 S.Diag(DeclLoc, diag::ext_missing_declspec)
1329 << DS.getSourceRange()
1330 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1331 }
1332 } else if (!DS.hasTypeSpecifier()) {
1333 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1334 // "At least one type specifier shall be given in the declaration
1335 // specifiers in each declaration, and in the specifier-qualifier list in
1336 // each struct declaration and type name."
1337 if (S.getLangOpts().CPlusPlus) {
1338 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1339 << DS.getSourceRange();
1340
1341 // When this occurs in C++ code, often something is very broken with the
1342 // value being declared, poison it as invalid so we don't get chains of
1343 // errors.
1344 declarator.setInvalidType(true);
1345 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1346 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1347 << DS.getSourceRange();
1348 declarator.setInvalidType(true);
1349 } else {
1350 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1351 << DS.getSourceRange();
1352 }
1353 }
1354
1355 // FALL THROUGH.
1356 case DeclSpec::TST_int: {
1357 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1358 switch (DS.getTypeSpecWidth()) {
1359 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1360 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1361 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1362 case DeclSpec::TSW_longlong:
1363 Result = Context.LongLongTy;
1364
1365 // 'long long' is a C99 or C++11 feature.
1366 if (!S.getLangOpts().C99) {
1367 if (S.getLangOpts().CPlusPlus)
1368 S.Diag(DS.getTypeSpecWidthLoc(),
1369 S.getLangOpts().CPlusPlus11 ?
1370 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1371 else
1372 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1373 }
1374 break;
1375 }
1376 } else {
1377 switch (DS.getTypeSpecWidth()) {
1378 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1379 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1380 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1381 case DeclSpec::TSW_longlong:
1382 Result = Context.UnsignedLongLongTy;
1383
1384 // 'long long' is a C99 or C++11 feature.
1385 if (!S.getLangOpts().C99) {
1386 if (S.getLangOpts().CPlusPlus)
1387 S.Diag(DS.getTypeSpecWidthLoc(),
1388 S.getLangOpts().CPlusPlus11 ?
1389 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1390 else
1391 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1392 }
1393 break;
1394 }
1395 }
1396 break;
1397 }
1398 case DeclSpec::TST_int128:
1399 if (!S.Context.getTargetInfo().hasInt128Type())
1400 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1401 << "__int128";
1402 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1403 Result = Context.UnsignedInt128Ty;
1404 else
1405 Result = Context.Int128Ty;
1406 break;
1407 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1408 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1409 case DeclSpec::TST_double:
1410 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1411 Result = Context.LongDoubleTy;
1412 else
1413 Result = Context.DoubleTy;
1414
1415 if (S.getLangOpts().OpenCL &&
1416 !((S.getLangOpts().OpenCLVersion >= 120) ||
1417 S.getOpenCLOptions().cl_khr_fp64)) {
1418 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1419 << Result << "cl_khr_fp64";
1420 declarator.setInvalidType(true);
1421 }
1422 break;
1423 case DeclSpec::TST_float128:
1424 if (!S.Context.getTargetInfo().hasFloat128Type())
1425 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1426 << "__float128";
1427 Result = Context.Float128Ty;
1428 break;
1429 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1430 break;
1431 case DeclSpec::TST_decimal32: // _Decimal32
1432 case DeclSpec::TST_decimal64: // _Decimal64
1433 case DeclSpec::TST_decimal128: // _Decimal128
1434 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1435 Result = Context.IntTy;
1436 declarator.setInvalidType(true);
1437 break;
1438 case DeclSpec::TST_class:
1439 case DeclSpec::TST_enum:
1440 case DeclSpec::TST_union:
1441 case DeclSpec::TST_struct:
1442 case DeclSpec::TST_interface: {
1443 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1444 if (!D) {
1445 // This can happen in C++ with ambiguous lookups.
1446 Result = Context.IntTy;
1447 declarator.setInvalidType(true);
1448 break;
1449 }
1450
1451 // If the type is deprecated or unavailable, diagnose it.
1452 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1453
1454 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1455 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1456
1457 // TypeQuals handled by caller.
1458 Result = Context.getTypeDeclType(D);
1459
1460 // In both C and C++, make an ElaboratedType.
1461 ElaboratedTypeKeyword Keyword
1462 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1463 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1464 break;
1465 }
1466 case DeclSpec::TST_typename: {
1467 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1468 DS.getTypeSpecSign() == 0 &&
1469 "Can't handle qualifiers on typedef names yet!");
1470 Result = S.GetTypeFromParser(DS.getRepAsType());
1471 if (Result.isNull()) {
1472 declarator.setInvalidType(true);
1473 } else if (S.getLangOpts().OpenCL) {
1474 if (Result->getAs<AtomicType>()) {
1475 StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
1476 bool NoExtTypes =
1477 llvm::StringSwitch<bool>(TypeName)
1478 .Cases("atomic_int", "atomic_uint", "atomic_float",
1479 "atomic_flag", true)
1480 .Default(false);
1481 if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1482 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1483 << Result << "cl_khr_int64_base_atomics";
1484 declarator.setInvalidType(true);
1485 }
1486 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1487 !NoExtTypes) {
1488 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1489 << Result << "cl_khr_int64_extended_atomics";
1490 declarator.setInvalidType(true);
1491 }
1492 if (!S.getOpenCLOptions().cl_khr_fp64 &&
1493 !TypeName.compare("atomic_double")) {
1494 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1495 << Result << "cl_khr_fp64";
1496 declarator.setInvalidType(true);
1497 }
1498 } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
1499 (Result->isOCLImage2dArrayMSAADepthROType() ||
1500 Result->isOCLImage2dArrayMSAADepthWOType() ||
1501 Result->isOCLImage2dArrayMSAADepthRWType() ||
1502 Result->isOCLImage2dArrayMSAAROType() ||
1503 Result->isOCLImage2dArrayMSAARWType() ||
1504 Result->isOCLImage2dArrayMSAAWOType() ||
1505 Result->isOCLImage2dMSAADepthROType() ||
1506 Result->isOCLImage2dMSAADepthRWType() ||
1507 Result->isOCLImage2dMSAADepthWOType() ||
1508 Result->isOCLImage2dMSAAROType() ||
1509 Result->isOCLImage2dMSAARWType() ||
1510 Result->isOCLImage2dMSAAWOType())) {
1511 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1512 << Result << "cl_khr_gl_msaa_sharing";
1513 declarator.setInvalidType(true);
1514 }
1515 }
1516
1517 // TypeQuals handled by caller.
1518 break;
1519 }
1520 case DeclSpec::TST_typeofType:
1521 // FIXME: Preserve type source info.
1522 Result = S.GetTypeFromParser(DS.getRepAsType());
1523 assert(!Result.isNull() && "Didn't get a type for typeof?");
1524 if (!Result->isDependentType())
1525 if (const TagType *TT = Result->getAs<TagType>())
1526 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1527 // TypeQuals handled by caller.
1528 Result = Context.getTypeOfType(Result);
1529 break;
1530 case DeclSpec::TST_typeofExpr: {
1531 Expr *E = DS.getRepAsExpr();
1532 assert(E && "Didn't get an expression for typeof?");
1533 // TypeQuals handled by caller.
1534 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1535 if (Result.isNull()) {
1536 Result = Context.IntTy;
1537 declarator.setInvalidType(true);
1538 }
1539 break;
1540 }
1541 case DeclSpec::TST_decltype: {
1542 Expr *E = DS.getRepAsExpr();
1543 assert(E && "Didn't get an expression for decltype?");
1544 // TypeQuals handled by caller.
1545 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1546 if (Result.isNull()) {
1547 Result = Context.IntTy;
1548 declarator.setInvalidType(true);
1549 }
1550 break;
1551 }
1552 case DeclSpec::TST_underlyingType:
1553 Result = S.GetTypeFromParser(DS.getRepAsType());
1554 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1555 Result = S.BuildUnaryTransformType(Result,
1556 UnaryTransformType::EnumUnderlyingType,
1557 DS.getTypeSpecTypeLoc());
1558 if (Result.isNull()) {
1559 Result = Context.IntTy;
1560 declarator.setInvalidType(true);
1561 }
1562 break;
1563
1564 case DeclSpec::TST_auto:
1565 // TypeQuals handled by caller.
1566 // If auto is mentioned in a lambda parameter context, convert it to a
1567 // template parameter type immediately, with the appropriate depth and
1568 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1569 // being analyzed (which tracks the invented type template parameter).
1570 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1571 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1572 assert(LSI && "No LambdaScopeInfo on the stack!");
1573 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1574 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1575 const bool IsParameterPack = declarator.hasEllipsis();
1576
1577 // Turns out we must create the TemplateTypeParmDecl here to
1578 // retrieve the corresponding template parameter type.
1579 TemplateTypeParmDecl *CorrespondingTemplateParam =
1580 TemplateTypeParmDecl::Create(Context,
1581 // Temporarily add to the TranslationUnit DeclContext. When the
1582 // associated TemplateParameterList is attached to a template
1583 // declaration (such as FunctionTemplateDecl), the DeclContext
1584 // for each template parameter gets updated appropriately via
1585 // a call to AdoptTemplateParameterList.
1586 Context.getTranslationUnitDecl(),
1587 /*KeyLoc*/ SourceLocation(),
1588 /*NameLoc*/ declarator.getLocStart(),
1589 TemplateParameterDepth,
1590 AutoParameterPosition, // our template param index
1591 /* Identifier*/ nullptr, false, IsParameterPack);
1592 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1593 // Replace the 'auto' in the function parameter with this invented
1594 // template type parameter.
1595 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1596 } else {
1597 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1598 }
1599 break;
1600
1601 case DeclSpec::TST_auto_type:
1602 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1603 break;
1604
1605 case DeclSpec::TST_decltype_auto:
1606 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1607 /*IsDependent*/ false);
1608 break;
1609
1610 case DeclSpec::TST_unknown_anytype:
1611 Result = Context.UnknownAnyTy;
1612 break;
1613
1614 case DeclSpec::TST_atomic:
1615 Result = S.GetTypeFromParser(DS.getRepAsType());
1616 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1617 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1618 if (Result.isNull()) {
1619 Result = Context.IntTy;
1620 declarator.setInvalidType(true);
1621 }
1622 break;
1623
1624 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1625 case DeclSpec::TST_##ImgType##_t: \
1626 Result = llvm::StringSwitch<QualType>( \
1627 getImageAccessAttrStr(DS.getAttributes().getList())) \
1628 .Cases("write_only", "__write_only", Context.Id##WOTy) \
1629 .Cases("read_write", "__read_write", Context.Id##RWTy) \
1630 .Default(Context.Id##ROTy); \
1631 break;
1632 #include "clang/Basic/OpenCLImageTypes.def"
1633
1634 case DeclSpec::TST_error:
1635 Result = Context.IntTy;
1636 declarator.setInvalidType(true);
1637 break;
1638 }
1639
1640 // Handle complex types.
1641 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1642 if (S.getLangOpts().Freestanding)
1643 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1644 Result = Context.getComplexType(Result);
1645 } else if (DS.isTypeAltiVecVector()) {
1646 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1647 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1648 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1649 if (DS.isTypeAltiVecPixel())
1650 VecKind = VectorType::AltiVecPixel;
1651 else if (DS.isTypeAltiVecBool())
1652 VecKind = VectorType::AltiVecBool;
1653 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1654 }
1655
1656 // FIXME: Imaginary.
1657 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1658 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1659
1660 // Before we process any type attributes, synthesize a block literal
1661 // function declarator if necessary.
1662 if (declarator.getContext() == Declarator::BlockLiteralContext)
1663 maybeSynthesizeBlockSignature(state, Result);
1664
1665 // Apply any type attributes from the decl spec. This may cause the
1666 // list of type attributes to be temporarily saved while the type
1667 // attributes are pushed around.
1668 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1669 if (!DS.isTypeSpecPipe())
1670 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1671
1672 // Apply const/volatile/restrict qualifiers to T.
1673 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1674 // Warn about CV qualifiers on function types.
1675 // C99 6.7.3p8:
1676 // If the specification of a function type includes any type qualifiers,
1677 // the behavior is undefined.
1678 // C++11 [dcl.fct]p7:
1679 // The effect of a cv-qualifier-seq in a function declarator is not the
1680 // same as adding cv-qualification on top of the function type. In the
1681 // latter case, the cv-qualifiers are ignored.
1682 if (TypeQuals && Result->isFunctionType()) {
1683 diagnoseAndRemoveTypeQualifiers(
1684 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1685 S.getLangOpts().CPlusPlus
1686 ? diag::warn_typecheck_function_qualifiers_ignored
1687 : diag::warn_typecheck_function_qualifiers_unspecified);
1688 // No diagnostic for 'restrict' or '_Atomic' applied to a
1689 // function type; we'll diagnose those later, in BuildQualifiedType.
1690 }
1691
1692 // C++11 [dcl.ref]p1:
1693 // Cv-qualified references are ill-formed except when the
1694 // cv-qualifiers are introduced through the use of a typedef-name
1695 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1696 //
1697 // There don't appear to be any other contexts in which a cv-qualified
1698 // reference type could be formed, so the 'ill-formed' clause here appears
1699 // to never happen.
1700 if (TypeQuals && Result->isReferenceType()) {
1701 diagnoseAndRemoveTypeQualifiers(
1702 S, DS, TypeQuals, Result,
1703 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1704 diag::warn_typecheck_reference_qualifiers);
1705 }
1706
1707 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1708 // than once in the same specifier-list or qualifier-list, either directly
1709 // or via one or more typedefs."
1710 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1711 && TypeQuals & Result.getCVRQualifiers()) {
1712 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1713 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1714 << "const";
1715 }
1716
1717 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1718 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1719 << "volatile";
1720 }
1721
1722 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1723 // produce a warning in this case.
1724 }
1725
1726 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1727
1728 // If adding qualifiers fails, just use the unqualified type.
1729 if (Qualified.isNull())
1730 declarator.setInvalidType(true);
1731 else
1732 Result = Qualified;
1733 }
1734
1735 assert(!Result.isNull() && "This function should not return a null type");
1736 return Result;
1737 }
1738
getPrintableNameForEntity(DeclarationName Entity)1739 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1740 if (Entity)
1741 return Entity.getAsString();
1742
1743 return "type name";
1744 }
1745
BuildQualifiedType(QualType T,SourceLocation Loc,Qualifiers Qs,const DeclSpec * DS)1746 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1747 Qualifiers Qs, const DeclSpec *DS) {
1748 if (T.isNull())
1749 return QualType();
1750
1751 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1752 // object or incomplete types shall not be restrict-qualified."
1753 if (Qs.hasRestrict()) {
1754 unsigned DiagID = 0;
1755 QualType ProblemTy;
1756
1757 if (T->isAnyPointerType() || T->isReferenceType() ||
1758 T->isMemberPointerType()) {
1759 QualType EltTy;
1760 if (T->isObjCObjectPointerType())
1761 EltTy = T;
1762 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1763 EltTy = PTy->getPointeeType();
1764 else
1765 EltTy = T->getPointeeType();
1766
1767 // If we have a pointer or reference, the pointee must have an object
1768 // incomplete type.
1769 if (!EltTy->isIncompleteOrObjectType()) {
1770 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1771 ProblemTy = EltTy;
1772 }
1773 } else if (!T->isDependentType()) {
1774 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1775 ProblemTy = T;
1776 }
1777
1778 if (DiagID) {
1779 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1780 Qs.removeRestrict();
1781 }
1782 }
1783
1784 return Context.getQualifiedType(T, Qs);
1785 }
1786
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVRAU,const DeclSpec * DS)1787 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1788 unsigned CVRAU, const DeclSpec *DS) {
1789 if (T.isNull())
1790 return QualType();
1791
1792 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1793 // TQ_unaligned;
1794 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1795
1796 // C11 6.7.3/5:
1797 // If the same qualifier appears more than once in the same
1798 // specifier-qualifier-list, either directly or via one or more typedefs,
1799 // the behavior is the same as if it appeared only once.
1800 //
1801 // It's not specified what happens when the _Atomic qualifier is applied to
1802 // a type specified with the _Atomic specifier, but we assume that this
1803 // should be treated as if the _Atomic qualifier appeared multiple times.
1804 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1805 // C11 6.7.3/5:
1806 // If other qualifiers appear along with the _Atomic qualifier in a
1807 // specifier-qualifier-list, the resulting type is the so-qualified
1808 // atomic type.
1809 //
1810 // Don't need to worry about array types here, since _Atomic can't be
1811 // applied to such types.
1812 SplitQualType Split = T.getSplitUnqualifiedType();
1813 T = BuildAtomicType(QualType(Split.Ty, 0),
1814 DS ? DS->getAtomicSpecLoc() : Loc);
1815 if (T.isNull())
1816 return T;
1817 Split.Quals.addCVRQualifiers(CVR);
1818 return BuildQualifiedType(T, Loc, Split.Quals);
1819 }
1820
1821 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1822 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1823 return BuildQualifiedType(T, Loc, Q, DS);
1824 }
1825
1826 /// \brief Build a paren type including \p T.
BuildParenType(QualType T)1827 QualType Sema::BuildParenType(QualType T) {
1828 return Context.getParenType(T);
1829 }
1830
1831 /// Given that we're building a pointer or reference to the given
inferARCLifetimeForPointee(Sema & S,QualType type,SourceLocation loc,bool isReference)1832 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1833 SourceLocation loc,
1834 bool isReference) {
1835 // Bail out if retention is unrequired or already specified.
1836 if (!type->isObjCLifetimeType() ||
1837 type.getObjCLifetime() != Qualifiers::OCL_None)
1838 return type;
1839
1840 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1841
1842 // If the object type is const-qualified, we can safely use
1843 // __unsafe_unretained. This is safe (because there are no read
1844 // barriers), and it'll be safe to coerce anything but __weak* to
1845 // the resulting type.
1846 if (type.isConstQualified()) {
1847 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1848
1849 // Otherwise, check whether the static type does not require
1850 // retaining. This currently only triggers for Class (possibly
1851 // protocol-qualifed, and arrays thereof).
1852 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1853 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1854
1855 // If we are in an unevaluated context, like sizeof, skip adding a
1856 // qualification.
1857 } else if (S.isUnevaluatedContext()) {
1858 return type;
1859
1860 // If that failed, give an error and recover using __strong. __strong
1861 // is the option most likely to prevent spurious second-order diagnostics,
1862 // like when binding a reference to a field.
1863 } else {
1864 // These types can show up in private ivars in system headers, so
1865 // we need this to not be an error in those cases. Instead we
1866 // want to delay.
1867 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1868 S.DelayedDiagnostics.add(
1869 sema::DelayedDiagnostic::makeForbiddenType(loc,
1870 diag::err_arc_indirect_no_ownership, type, isReference));
1871 } else {
1872 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1873 }
1874 implicitLifetime = Qualifiers::OCL_Strong;
1875 }
1876 assert(implicitLifetime && "didn't infer any lifetime!");
1877
1878 Qualifiers qs;
1879 qs.addObjCLifetime(implicitLifetime);
1880 return S.Context.getQualifiedType(type, qs);
1881 }
1882
getFunctionQualifiersAsString(const FunctionProtoType * FnTy)1883 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1884 std::string Quals =
1885 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1886
1887 switch (FnTy->getRefQualifier()) {
1888 case RQ_None:
1889 break;
1890
1891 case RQ_LValue:
1892 if (!Quals.empty())
1893 Quals += ' ';
1894 Quals += '&';
1895 break;
1896
1897 case RQ_RValue:
1898 if (!Quals.empty())
1899 Quals += ' ';
1900 Quals += "&&";
1901 break;
1902 }
1903
1904 return Quals;
1905 }
1906
1907 namespace {
1908 /// Kinds of declarator that cannot contain a qualified function type.
1909 ///
1910 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1911 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1912 /// at the topmost level of a type.
1913 ///
1914 /// Parens and member pointers are permitted. We don't diagnose array and
1915 /// function declarators, because they don't allow function types at all.
1916 ///
1917 /// The values of this enum are used in diagnostics.
1918 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1919 } // end anonymous namespace
1920
1921 /// Check whether the type T is a qualified function type, and if it is,
1922 /// diagnose that it cannot be contained within the given kind of declarator.
checkQualifiedFunction(Sema & S,QualType T,SourceLocation Loc,QualifiedFunctionKind QFK)1923 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1924 QualifiedFunctionKind QFK) {
1925 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1926 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1927 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1928 return false;
1929
1930 S.Diag(Loc, diag::err_compound_qualified_function_type)
1931 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1932 << getFunctionQualifiersAsString(FPT);
1933 return true;
1934 }
1935
1936 /// \brief Build a pointer type.
1937 ///
1938 /// \param T The type to which we'll be building a pointer.
1939 ///
1940 /// \param Loc The location of the entity whose type involves this
1941 /// pointer type or, if there is no such entity, the location of the
1942 /// type that will have pointer type.
1943 ///
1944 /// \param Entity The name of the entity that involves the pointer
1945 /// type, if known.
1946 ///
1947 /// \returns A suitable pointer type, if there are no
1948 /// errors. Otherwise, returns a NULL type.
BuildPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)1949 QualType Sema::BuildPointerType(QualType T,
1950 SourceLocation Loc, DeclarationName Entity) {
1951 if (T->isReferenceType()) {
1952 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1953 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1954 << getPrintableNameForEntity(Entity) << T;
1955 return QualType();
1956 }
1957
1958 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1959 return QualType();
1960
1961 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1962
1963 // In ARC, it is forbidden to build pointers to unqualified pointers.
1964 if (getLangOpts().ObjCAutoRefCount)
1965 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1966
1967 // Build the pointer type.
1968 return Context.getPointerType(T);
1969 }
1970
1971 /// \brief Build a reference type.
1972 ///
1973 /// \param T The type to which we'll be building a reference.
1974 ///
1975 /// \param Loc The location of the entity whose type involves this
1976 /// reference type or, if there is no such entity, the location of the
1977 /// type that will have reference type.
1978 ///
1979 /// \param Entity The name of the entity that involves the reference
1980 /// type, if known.
1981 ///
1982 /// \returns A suitable reference type, if there are no
1983 /// errors. Otherwise, returns a NULL type.
BuildReferenceType(QualType T,bool SpelledAsLValue,SourceLocation Loc,DeclarationName Entity)1984 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1985 SourceLocation Loc,
1986 DeclarationName Entity) {
1987 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1988 "Unresolved overloaded function type");
1989
1990 // C++0x [dcl.ref]p6:
1991 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1992 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1993 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1994 // the type "lvalue reference to T", while an attempt to create the type
1995 // "rvalue reference to cv TR" creates the type TR.
1996 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1997
1998 // C++ [dcl.ref]p4: There shall be no references to references.
1999 //
2000 // According to C++ DR 106, references to references are only
2001 // diagnosed when they are written directly (e.g., "int & &"),
2002 // but not when they happen via a typedef:
2003 //
2004 // typedef int& intref;
2005 // typedef intref& intref2;
2006 //
2007 // Parser::ParseDeclaratorInternal diagnoses the case where
2008 // references are written directly; here, we handle the
2009 // collapsing of references-to-references as described in C++0x.
2010 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2011
2012 // C++ [dcl.ref]p1:
2013 // A declarator that specifies the type "reference to cv void"
2014 // is ill-formed.
2015 if (T->isVoidType()) {
2016 Diag(Loc, diag::err_reference_to_void);
2017 return QualType();
2018 }
2019
2020 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2021 return QualType();
2022
2023 // In ARC, it is forbidden to build references to unqualified pointers.
2024 if (getLangOpts().ObjCAutoRefCount)
2025 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2026
2027 // Handle restrict on references.
2028 if (LValueRef)
2029 return Context.getLValueReferenceType(T, SpelledAsLValue);
2030 return Context.getRValueReferenceType(T);
2031 }
2032
2033 /// \brief Build a Pipe type.
2034 ///
2035 /// \param T The type to which we'll be building a Pipe.
2036 ///
2037 /// \param Loc We do not use it for now.
2038 ///
2039 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2040 /// NULL type.
BuildPipeType(QualType T,SourceLocation Loc)2041 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
2042 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2043
2044 // Build the pipe type.
2045 return Context.getPipeType(T);
2046 }
2047
2048 /// Check whether the specified array size makes the array type a VLA. If so,
2049 /// return true, if not, return the size of the array in SizeVal.
isArraySizeVLA(Sema & S,Expr * ArraySize,llvm::APSInt & SizeVal)2050 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2051 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2052 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2053 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2054 public:
2055 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2056
2057 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2058 }
2059
2060 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2061 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2062 }
2063 } Diagnoser;
2064
2065 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2066 S.LangOpts.GNUMode ||
2067 S.LangOpts.OpenCL).isInvalid();
2068 }
2069
2070 /// \brief Build an array type.
2071 ///
2072 /// \param T The type of each element in the array.
2073 ///
2074 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2075 ///
2076 /// \param ArraySize Expression describing the size of the array.
2077 ///
2078 /// \param Brackets The range from the opening '[' to the closing ']'.
2079 ///
2080 /// \param Entity The name of the entity that involves the array
2081 /// type, if known.
2082 ///
2083 /// \returns A suitable array type, if there are no errors. Otherwise,
2084 /// returns a NULL type.
BuildArrayType(QualType T,ArrayType::ArraySizeModifier ASM,Expr * ArraySize,unsigned Quals,SourceRange Brackets,DeclarationName Entity)2085 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2086 Expr *ArraySize, unsigned Quals,
2087 SourceRange Brackets, DeclarationName Entity) {
2088
2089 SourceLocation Loc = Brackets.getBegin();
2090 if (getLangOpts().CPlusPlus) {
2091 // C++ [dcl.array]p1:
2092 // T is called the array element type; this type shall not be a reference
2093 // type, the (possibly cv-qualified) type void, a function type or an
2094 // abstract class type.
2095 //
2096 // C++ [dcl.array]p3:
2097 // When several "array of" specifications are adjacent, [...] only the
2098 // first of the constant expressions that specify the bounds of the arrays
2099 // may be omitted.
2100 //
2101 // Note: function types are handled in the common path with C.
2102 if (T->isReferenceType()) {
2103 Diag(Loc, diag::err_illegal_decl_array_of_references)
2104 << getPrintableNameForEntity(Entity) << T;
2105 return QualType();
2106 }
2107
2108 if (T->isVoidType() || T->isIncompleteArrayType()) {
2109 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2110 return QualType();
2111 }
2112
2113 if (RequireNonAbstractType(Brackets.getBegin(), T,
2114 diag::err_array_of_abstract_type))
2115 return QualType();
2116
2117 // Mentioning a member pointer type for an array type causes us to lock in
2118 // an inheritance model, even if it's inside an unused typedef.
2119 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2120 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2121 if (!MPTy->getClass()->isDependentType())
2122 (void)isCompleteType(Loc, T);
2123
2124 } else {
2125 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2126 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2127 if (RequireCompleteType(Loc, T,
2128 diag::err_illegal_decl_array_incomplete_type))
2129 return QualType();
2130 }
2131
2132 if (T->isFunctionType()) {
2133 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2134 << getPrintableNameForEntity(Entity) << T;
2135 return QualType();
2136 }
2137
2138 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2139 // If the element type is a struct or union that contains a variadic
2140 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2141 if (EltTy->getDecl()->hasFlexibleArrayMember())
2142 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2143 } else if (T->isObjCObjectType()) {
2144 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2145 return QualType();
2146 }
2147
2148 // Do placeholder conversions on the array size expression.
2149 if (ArraySize && ArraySize->hasPlaceholderType()) {
2150 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2151 if (Result.isInvalid()) return QualType();
2152 ArraySize = Result.get();
2153 }
2154
2155 // Do lvalue-to-rvalue conversions on the array size expression.
2156 if (ArraySize && !ArraySize->isRValue()) {
2157 ExprResult Result = DefaultLvalueConversion(ArraySize);
2158 if (Result.isInvalid())
2159 return QualType();
2160
2161 ArraySize = Result.get();
2162 }
2163
2164 // C99 6.7.5.2p1: The size expression shall have integer type.
2165 // C++11 allows contextual conversions to such types.
2166 if (!getLangOpts().CPlusPlus11 &&
2167 ArraySize && !ArraySize->isTypeDependent() &&
2168 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2169 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2170 << ArraySize->getType() << ArraySize->getSourceRange();
2171 return QualType();
2172 }
2173
2174 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2175 if (!ArraySize) {
2176 if (ASM == ArrayType::Star)
2177 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2178 else
2179 T = Context.getIncompleteArrayType(T, ASM, Quals);
2180 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2181 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2182 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2183 !T->isConstantSizeType()) ||
2184 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2185 // Even in C++11, don't allow contextual conversions in the array bound
2186 // of a VLA.
2187 if (getLangOpts().CPlusPlus11 &&
2188 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2189 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2190 << ArraySize->getType() << ArraySize->getSourceRange();
2191 return QualType();
2192 }
2193
2194 // C99: an array with an element type that has a non-constant-size is a VLA.
2195 // C99: an array with a non-ICE size is a VLA. We accept any expression
2196 // that we can fold to a non-zero positive value as an extension.
2197 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2198 } else {
2199 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2200 // have a value greater than zero.
2201 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2202 if (Entity)
2203 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2204 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2205 else
2206 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2207 << ArraySize->getSourceRange();
2208 return QualType();
2209 }
2210 if (ConstVal == 0) {
2211 // GCC accepts zero sized static arrays. We allow them when
2212 // we're not in a SFINAE context.
2213 Diag(ArraySize->getLocStart(),
2214 isSFINAEContext()? diag::err_typecheck_zero_array_size
2215 : diag::ext_typecheck_zero_array_size)
2216 << ArraySize->getSourceRange();
2217
2218 if (ASM == ArrayType::Static) {
2219 Diag(ArraySize->getLocStart(),
2220 diag::warn_typecheck_zero_static_array_size)
2221 << ArraySize->getSourceRange();
2222 ASM = ArrayType::Normal;
2223 }
2224 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2225 !T->isIncompleteType() && !T->isUndeducedType()) {
2226 // Is the array too large?
2227 unsigned ActiveSizeBits
2228 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2229 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2230 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2231 << ConstVal.toString(10)
2232 << ArraySize->getSourceRange();
2233 return QualType();
2234 }
2235 }
2236
2237 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2238 }
2239
2240 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2241 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2242 Diag(Loc, diag::err_opencl_vla);
2243 return QualType();
2244 }
2245 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2246 if (!getLangOpts().C99) {
2247 if (T->isVariableArrayType()) {
2248 // Prohibit the use of VLAs during template argument deduction.
2249 if (isSFINAEContext()) {
2250 Diag(Loc, diag::err_vla_in_sfinae);
2251 return QualType();
2252 }
2253 // Just extwarn about VLAs.
2254 else
2255 Diag(Loc, diag::ext_vla);
2256 } else if (ASM != ArrayType::Normal || Quals != 0)
2257 Diag(Loc,
2258 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2259 : diag::ext_c99_array_usage) << ASM;
2260 }
2261
2262 if (T->isVariableArrayType()) {
2263 // Warn about VLAs for -Wvla.
2264 Diag(Loc, diag::warn_vla_used);
2265 }
2266
2267 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2268 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2269 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2270 if (getLangOpts().OpenCL) {
2271 const QualType ArrType = Context.getBaseElementType(T);
2272 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2273 ArrType->isSamplerT() || ArrType->isImageType()) {
2274 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2275 return QualType();
2276 }
2277 }
2278
2279 return T;
2280 }
2281
2282 /// \brief Build an ext-vector type.
2283 ///
2284 /// Run the required checks for the extended vector type.
BuildExtVectorType(QualType T,Expr * ArraySize,SourceLocation AttrLoc)2285 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2286 SourceLocation AttrLoc) {
2287 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2288 // in conjunction with complex types (pointers, arrays, functions, etc.).
2289 //
2290 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2291 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2292 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2293 // of bool aren't allowed.
2294 if ((!T->isDependentType() && !T->isIntegerType() &&
2295 !T->isRealFloatingType()) ||
2296 T->isBooleanType()) {
2297 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2298 return QualType();
2299 }
2300
2301 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2302 llvm::APSInt vecSize(32);
2303 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2304 Diag(AttrLoc, diag::err_attribute_argument_type)
2305 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2306 << ArraySize->getSourceRange();
2307 return QualType();
2308 }
2309
2310 // Unlike gcc's vector_size attribute, the size is specified as the
2311 // number of elements, not the number of bytes.
2312 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2313
2314 if (vectorSize == 0) {
2315 Diag(AttrLoc, diag::err_attribute_zero_size)
2316 << ArraySize->getSourceRange();
2317 return QualType();
2318 }
2319
2320 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2321 Diag(AttrLoc, diag::err_attribute_size_too_large)
2322 << ArraySize->getSourceRange();
2323 return QualType();
2324 }
2325
2326 return Context.getExtVectorType(T, vectorSize);
2327 }
2328
2329 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2330 }
2331
CheckFunctionReturnType(QualType T,SourceLocation Loc)2332 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2333 if (T->isArrayType() || T->isFunctionType()) {
2334 Diag(Loc, diag::err_func_returning_array_function)
2335 << T->isFunctionType() << T;
2336 return true;
2337 }
2338
2339 // Functions cannot return half FP.
2340 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2341 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2342 FixItHint::CreateInsertion(Loc, "*");
2343 return true;
2344 }
2345
2346 // Methods cannot return interface types. All ObjC objects are
2347 // passed by reference.
2348 if (T->isObjCObjectType()) {
2349 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2350 return 0;
2351 }
2352
2353 return false;
2354 }
2355
2356 /// Check the extended parameter information. Most of the necessary
2357 /// checking should occur when applying the parameter attribute; the
2358 /// only other checks required are positional restrictions.
checkExtParameterInfos(Sema & S,ArrayRef<QualType> paramTypes,const FunctionProtoType::ExtProtoInfo & EPI,llvm::function_ref<SourceLocation (unsigned)> getParamLoc)2359 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2360 const FunctionProtoType::ExtProtoInfo &EPI,
2361 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2362 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2363
2364 bool hasCheckedSwiftCall = false;
2365 auto checkForSwiftCC = [&](unsigned paramIndex) {
2366 // Only do this once.
2367 if (hasCheckedSwiftCall) return;
2368 hasCheckedSwiftCall = true;
2369 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2370 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2371 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2372 };
2373
2374 for (size_t paramIndex = 0, numParams = paramTypes.size();
2375 paramIndex != numParams; ++paramIndex) {
2376 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2377 // Nothing interesting to check for orindary-ABI parameters.
2378 case ParameterABI::Ordinary:
2379 continue;
2380
2381 // swift_indirect_result parameters must be a prefix of the function
2382 // arguments.
2383 case ParameterABI::SwiftIndirectResult:
2384 checkForSwiftCC(paramIndex);
2385 if (paramIndex != 0 &&
2386 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2387 != ParameterABI::SwiftIndirectResult) {
2388 S.Diag(getParamLoc(paramIndex),
2389 diag::err_swift_indirect_result_not_first);
2390 }
2391 continue;
2392
2393 // swift_context parameters must be the last parameter except for
2394 // a possible swift_error parameter.
2395 case ParameterABI::SwiftContext:
2396 checkForSwiftCC(paramIndex);
2397 if (!(paramIndex == numParams - 1 ||
2398 (paramIndex == numParams - 2 &&
2399 EPI.ExtParameterInfos[numParams - 1].getABI()
2400 == ParameterABI::SwiftErrorResult))) {
2401 S.Diag(getParamLoc(paramIndex),
2402 diag::err_swift_context_not_before_swift_error_result);
2403 }
2404 continue;
2405
2406 // swift_error parameters must be the last parameter.
2407 case ParameterABI::SwiftErrorResult:
2408 checkForSwiftCC(paramIndex);
2409 if (paramIndex != numParams - 1) {
2410 S.Diag(getParamLoc(paramIndex),
2411 diag::err_swift_error_result_not_last);
2412 } else if (paramIndex == 0 ||
2413 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2414 != ParameterABI::SwiftContext) {
2415 S.Diag(getParamLoc(paramIndex),
2416 diag::err_swift_error_result_not_after_swift_context);
2417 }
2418 continue;
2419 }
2420 llvm_unreachable("bad ABI kind");
2421 }
2422 }
2423
BuildFunctionType(QualType T,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc,DeclarationName Entity,const FunctionProtoType::ExtProtoInfo & EPI)2424 QualType Sema::BuildFunctionType(QualType T,
2425 MutableArrayRef<QualType> ParamTypes,
2426 SourceLocation Loc, DeclarationName Entity,
2427 const FunctionProtoType::ExtProtoInfo &EPI) {
2428 bool Invalid = false;
2429
2430 Invalid |= CheckFunctionReturnType(T, Loc);
2431
2432 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2433 // FIXME: Loc is too inprecise here, should use proper locations for args.
2434 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2435 if (ParamType->isVoidType()) {
2436 Diag(Loc, diag::err_param_with_void_type);
2437 Invalid = true;
2438 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2439 // Disallow half FP arguments.
2440 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2441 FixItHint::CreateInsertion(Loc, "*");
2442 Invalid = true;
2443 }
2444
2445 ParamTypes[Idx] = ParamType;
2446 }
2447
2448 if (EPI.ExtParameterInfos) {
2449 checkExtParameterInfos(*this, ParamTypes, EPI,
2450 [=](unsigned i) { return Loc; });
2451 }
2452
2453 if (Invalid)
2454 return QualType();
2455
2456 return Context.getFunctionType(T, ParamTypes, EPI);
2457 }
2458
2459 /// \brief Build a member pointer type \c T Class::*.
2460 ///
2461 /// \param T the type to which the member pointer refers.
2462 /// \param Class the class type into which the member pointer points.
2463 /// \param Loc the location where this type begins
2464 /// \param Entity the name of the entity that will have this member pointer type
2465 ///
2466 /// \returns a member pointer type, if successful, or a NULL type if there was
2467 /// an error.
BuildMemberPointerType(QualType T,QualType Class,SourceLocation Loc,DeclarationName Entity)2468 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2469 SourceLocation Loc,
2470 DeclarationName Entity) {
2471 // Verify that we're not building a pointer to pointer to function with
2472 // exception specification.
2473 if (CheckDistantExceptionSpec(T)) {
2474 Diag(Loc, diag::err_distant_exception_spec);
2475 return QualType();
2476 }
2477
2478 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2479 // with reference type, or "cv void."
2480 if (T->isReferenceType()) {
2481 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2482 << getPrintableNameForEntity(Entity) << T;
2483 return QualType();
2484 }
2485
2486 if (T->isVoidType()) {
2487 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2488 << getPrintableNameForEntity(Entity);
2489 return QualType();
2490 }
2491
2492 if (!Class->isDependentType() && !Class->isRecordType()) {
2493 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2494 return QualType();
2495 }
2496
2497 // Adjust the default free function calling convention to the default method
2498 // calling convention.
2499 bool IsCtorOrDtor =
2500 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2501 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2502 if (T->isFunctionType())
2503 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2504
2505 return Context.getMemberPointerType(T, Class.getTypePtr());
2506 }
2507
2508 /// \brief Build a block pointer type.
2509 ///
2510 /// \param T The type to which we'll be building a block pointer.
2511 ///
2512 /// \param Loc The source location, used for diagnostics.
2513 ///
2514 /// \param Entity The name of the entity that involves the block pointer
2515 /// type, if known.
2516 ///
2517 /// \returns A suitable block pointer type, if there are no
2518 /// errors. Otherwise, returns a NULL type.
BuildBlockPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)2519 QualType Sema::BuildBlockPointerType(QualType T,
2520 SourceLocation Loc,
2521 DeclarationName Entity) {
2522 if (!T->isFunctionType()) {
2523 Diag(Loc, diag::err_nonfunction_block_type);
2524 return QualType();
2525 }
2526
2527 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2528 return QualType();
2529
2530 return Context.getBlockPointerType(T);
2531 }
2532
GetTypeFromParser(ParsedType Ty,TypeSourceInfo ** TInfo)2533 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2534 QualType QT = Ty.get();
2535 if (QT.isNull()) {
2536 if (TInfo) *TInfo = nullptr;
2537 return QualType();
2538 }
2539
2540 TypeSourceInfo *DI = nullptr;
2541 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2542 QT = LIT->getType();
2543 DI = LIT->getTypeSourceInfo();
2544 }
2545
2546 if (TInfo) *TInfo = DI;
2547 return QT;
2548 }
2549
2550 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2551 Qualifiers::ObjCLifetime ownership,
2552 unsigned chunkIndex);
2553
2554 /// Given that this is the declaration of a parameter under ARC,
2555 /// attempt to infer attributes and such for pointer-to-whatever
2556 /// types.
inferARCWriteback(TypeProcessingState & state,QualType & declSpecType)2557 static void inferARCWriteback(TypeProcessingState &state,
2558 QualType &declSpecType) {
2559 Sema &S = state.getSema();
2560 Declarator &declarator = state.getDeclarator();
2561
2562 // TODO: should we care about decl qualifiers?
2563
2564 // Check whether the declarator has the expected form. We walk
2565 // from the inside out in order to make the block logic work.
2566 unsigned outermostPointerIndex = 0;
2567 bool isBlockPointer = false;
2568 unsigned numPointers = 0;
2569 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2570 unsigned chunkIndex = i;
2571 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2572 switch (chunk.Kind) {
2573 case DeclaratorChunk::Paren:
2574 // Ignore parens.
2575 break;
2576
2577 case DeclaratorChunk::Reference:
2578 case DeclaratorChunk::Pointer:
2579 // Count the number of pointers. Treat references
2580 // interchangeably as pointers; if they're mis-ordered, normal
2581 // type building will discover that.
2582 outermostPointerIndex = chunkIndex;
2583 numPointers++;
2584 break;
2585
2586 case DeclaratorChunk::BlockPointer:
2587 // If we have a pointer to block pointer, that's an acceptable
2588 // indirect reference; anything else is not an application of
2589 // the rules.
2590 if (numPointers != 1) return;
2591 numPointers++;
2592 outermostPointerIndex = chunkIndex;
2593 isBlockPointer = true;
2594
2595 // We don't care about pointer structure in return values here.
2596 goto done;
2597
2598 case DeclaratorChunk::Array: // suppress if written (id[])?
2599 case DeclaratorChunk::Function:
2600 case DeclaratorChunk::MemberPointer:
2601 case DeclaratorChunk::Pipe:
2602 return;
2603 }
2604 }
2605 done:
2606
2607 // If we have *one* pointer, then we want to throw the qualifier on
2608 // the declaration-specifiers, which means that it needs to be a
2609 // retainable object type.
2610 if (numPointers == 1) {
2611 // If it's not a retainable object type, the rule doesn't apply.
2612 if (!declSpecType->isObjCRetainableType()) return;
2613
2614 // If it already has lifetime, don't do anything.
2615 if (declSpecType.getObjCLifetime()) return;
2616
2617 // Otherwise, modify the type in-place.
2618 Qualifiers qs;
2619
2620 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2621 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2622 else
2623 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2624 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2625
2626 // If we have *two* pointers, then we want to throw the qualifier on
2627 // the outermost pointer.
2628 } else if (numPointers == 2) {
2629 // If we don't have a block pointer, we need to check whether the
2630 // declaration-specifiers gave us something that will turn into a
2631 // retainable object pointer after we slap the first pointer on it.
2632 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2633 return;
2634
2635 // Look for an explicit lifetime attribute there.
2636 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2637 if (chunk.Kind != DeclaratorChunk::Pointer &&
2638 chunk.Kind != DeclaratorChunk::BlockPointer)
2639 return;
2640 for (const AttributeList *attr = chunk.getAttrs(); attr;
2641 attr = attr->getNext())
2642 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2643 return;
2644
2645 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2646 outermostPointerIndex);
2647
2648 // Any other number of pointers/references does not trigger the rule.
2649 } else return;
2650
2651 // TODO: mark whether we did this inference?
2652 }
2653
diagnoseIgnoredQualifiers(unsigned DiagID,unsigned Quals,SourceLocation FallbackLoc,SourceLocation ConstQualLoc,SourceLocation VolatileQualLoc,SourceLocation RestrictQualLoc,SourceLocation AtomicQualLoc,SourceLocation UnalignedQualLoc)2654 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2655 SourceLocation FallbackLoc,
2656 SourceLocation ConstQualLoc,
2657 SourceLocation VolatileQualLoc,
2658 SourceLocation RestrictQualLoc,
2659 SourceLocation AtomicQualLoc,
2660 SourceLocation UnalignedQualLoc) {
2661 if (!Quals)
2662 return;
2663
2664 struct Qual {
2665 const char *Name;
2666 unsigned Mask;
2667 SourceLocation Loc;
2668 } const QualKinds[5] = {
2669 { "const", DeclSpec::TQ_const, ConstQualLoc },
2670 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2671 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2672 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2673 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2674 };
2675
2676 SmallString<32> QualStr;
2677 unsigned NumQuals = 0;
2678 SourceLocation Loc;
2679 FixItHint FixIts[5];
2680
2681 // Build a string naming the redundant qualifiers.
2682 for (auto &E : QualKinds) {
2683 if (Quals & E.Mask) {
2684 if (!QualStr.empty()) QualStr += ' ';
2685 QualStr += E.Name;
2686
2687 // If we have a location for the qualifier, offer a fixit.
2688 SourceLocation QualLoc = E.Loc;
2689 if (QualLoc.isValid()) {
2690 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2691 if (Loc.isInvalid() ||
2692 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2693 Loc = QualLoc;
2694 }
2695
2696 ++NumQuals;
2697 }
2698 }
2699
2700 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2701 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2702 }
2703
2704 // Diagnose pointless type qualifiers on the return type of a function.
diagnoseRedundantReturnTypeQualifiers(Sema & S,QualType RetTy,Declarator & D,unsigned FunctionChunkIndex)2705 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2706 Declarator &D,
2707 unsigned FunctionChunkIndex) {
2708 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2709 // FIXME: TypeSourceInfo doesn't preserve location information for
2710 // qualifiers.
2711 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2712 RetTy.getLocalCVRQualifiers(),
2713 D.getIdentifierLoc());
2714 return;
2715 }
2716
2717 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2718 End = D.getNumTypeObjects();
2719 OuterChunkIndex != End; ++OuterChunkIndex) {
2720 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2721 switch (OuterChunk.Kind) {
2722 case DeclaratorChunk::Paren:
2723 continue;
2724
2725 case DeclaratorChunk::Pointer: {
2726 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2727 S.diagnoseIgnoredQualifiers(
2728 diag::warn_qual_return_type,
2729 PTI.TypeQuals,
2730 SourceLocation(),
2731 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2732 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2733 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2734 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2735 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2736 return;
2737 }
2738
2739 case DeclaratorChunk::Function:
2740 case DeclaratorChunk::BlockPointer:
2741 case DeclaratorChunk::Reference:
2742 case DeclaratorChunk::Array:
2743 case DeclaratorChunk::MemberPointer:
2744 case DeclaratorChunk::Pipe:
2745 // FIXME: We can't currently provide an accurate source location and a
2746 // fix-it hint for these.
2747 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2748 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2749 RetTy.getCVRQualifiers() | AtomicQual,
2750 D.getIdentifierLoc());
2751 return;
2752 }
2753
2754 llvm_unreachable("unknown declarator chunk kind");
2755 }
2756
2757 // If the qualifiers come from a conversion function type, don't diagnose
2758 // them -- they're not necessarily redundant, since such a conversion
2759 // operator can be explicitly called as "x.operator const int()".
2760 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2761 return;
2762
2763 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2764 // which are present there.
2765 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2766 D.getDeclSpec().getTypeQualifiers(),
2767 D.getIdentifierLoc(),
2768 D.getDeclSpec().getConstSpecLoc(),
2769 D.getDeclSpec().getVolatileSpecLoc(),
2770 D.getDeclSpec().getRestrictSpecLoc(),
2771 D.getDeclSpec().getAtomicSpecLoc(),
2772 D.getDeclSpec().getUnalignedSpecLoc());
2773 }
2774
GetDeclSpecTypeForDeclarator(TypeProcessingState & state,TypeSourceInfo * & ReturnTypeInfo)2775 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2776 TypeSourceInfo *&ReturnTypeInfo) {
2777 Sema &SemaRef = state.getSema();
2778 Declarator &D = state.getDeclarator();
2779 QualType T;
2780 ReturnTypeInfo = nullptr;
2781
2782 // The TagDecl owned by the DeclSpec.
2783 TagDecl *OwnedTagDecl = nullptr;
2784
2785 switch (D.getName().getKind()) {
2786 case UnqualifiedId::IK_ImplicitSelfParam:
2787 case UnqualifiedId::IK_OperatorFunctionId:
2788 case UnqualifiedId::IK_Identifier:
2789 case UnqualifiedId::IK_LiteralOperatorId:
2790 case UnqualifiedId::IK_TemplateId:
2791 T = ConvertDeclSpecToType(state);
2792
2793 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2794 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2795 // Owned declaration is embedded in declarator.
2796 OwnedTagDecl->setEmbeddedInDeclarator(true);
2797 }
2798 break;
2799
2800 case UnqualifiedId::IK_ConstructorName:
2801 case UnqualifiedId::IK_ConstructorTemplateId:
2802 case UnqualifiedId::IK_DestructorName:
2803 // Constructors and destructors don't have return types. Use
2804 // "void" instead.
2805 T = SemaRef.Context.VoidTy;
2806 processTypeAttrs(state, T, TAL_DeclSpec,
2807 D.getDeclSpec().getAttributes().getList());
2808 break;
2809
2810 case UnqualifiedId::IK_ConversionFunctionId:
2811 // The result type of a conversion function is the type that it
2812 // converts to.
2813 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2814 &ReturnTypeInfo);
2815 break;
2816 }
2817
2818 if (D.getAttributes())
2819 distributeTypeAttrsFromDeclarator(state, T);
2820
2821 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2822 if (D.getDeclSpec().containsPlaceholderType()) {
2823 int Error = -1;
2824
2825 switch (D.getContext()) {
2826 case Declarator::LambdaExprContext:
2827 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2828 case Declarator::ObjCParameterContext:
2829 case Declarator::ObjCResultContext:
2830 case Declarator::PrototypeContext:
2831 Error = 0;
2832 break;
2833 case Declarator::LambdaExprParameterContext:
2834 // In C++14, generic lambdas allow 'auto' in their parameters.
2835 if (!(SemaRef.getLangOpts().CPlusPlus14
2836 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2837 Error = 16;
2838 break;
2839 case Declarator::MemberContext: {
2840 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2841 D.isFunctionDeclarator())
2842 break;
2843 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2844 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2845 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2846 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2847 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2848 case TTK_Class: Error = 5; /* Class member */ break;
2849 case TTK_Interface: Error = 6; /* Interface member */ break;
2850 }
2851 break;
2852 }
2853 case Declarator::CXXCatchContext:
2854 case Declarator::ObjCCatchContext:
2855 Error = 7; // Exception declaration
2856 break;
2857 case Declarator::TemplateParamContext:
2858 Error = 8; // Template parameter
2859 break;
2860 case Declarator::BlockLiteralContext:
2861 Error = 9; // Block literal
2862 break;
2863 case Declarator::TemplateTypeArgContext:
2864 Error = 10; // Template type argument
2865 break;
2866 case Declarator::AliasDeclContext:
2867 case Declarator::AliasTemplateContext:
2868 Error = 12; // Type alias
2869 break;
2870 case Declarator::TrailingReturnContext:
2871 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2872 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2873 Error = 13; // Function return type
2874 break;
2875 case Declarator::ConversionIdContext:
2876 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2877 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2878 Error = 14; // conversion-type-id
2879 break;
2880 case Declarator::TypeNameContext:
2881 Error = 15; // Generic
2882 break;
2883 case Declarator::FileContext:
2884 case Declarator::BlockContext:
2885 case Declarator::ForContext:
2886 case Declarator::InitStmtContext:
2887 case Declarator::ConditionContext:
2888 break;
2889 case Declarator::CXXNewContext:
2890 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2891 Error = 17; // 'new' type
2892 break;
2893 case Declarator::KNRTypeListContext:
2894 Error = 18; // K&R function parameter
2895 break;
2896 }
2897
2898 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2899 Error = 11;
2900
2901 // In Objective-C it is an error to use 'auto' on a function declarator
2902 // (and everywhere for '__auto_type').
2903 if (D.isFunctionDeclarator() &&
2904 (!SemaRef.getLangOpts().CPlusPlus11 ||
2905 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
2906 Error = 13;
2907
2908 bool HaveTrailing = false;
2909
2910 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2911 // contains a trailing return type. That is only legal at the outermost
2912 // level. Check all declarator chunks (outermost first) anyway, to give
2913 // better diagnostics.
2914 // We don't support '__auto_type' with trailing return types.
2915 if (SemaRef.getLangOpts().CPlusPlus11 &&
2916 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
2917 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2918 unsigned chunkIndex = e - i - 1;
2919 state.setCurrentChunkIndex(chunkIndex);
2920 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2921 if (DeclType.Kind == DeclaratorChunk::Function) {
2922 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2923 if (FTI.hasTrailingReturnType()) {
2924 HaveTrailing = true;
2925 Error = -1;
2926 break;
2927 }
2928 }
2929 }
2930 }
2931
2932 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2933 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2934 AutoRange = D.getName().getSourceRange();
2935
2936 if (Error != -1) {
2937 unsigned Keyword;
2938 switch (D.getDeclSpec().getTypeSpecType()) {
2939 case DeclSpec::TST_auto: Keyword = 0; break;
2940 case DeclSpec::TST_decltype_auto: Keyword = 1; break;
2941 case DeclSpec::TST_auto_type: Keyword = 2; break;
2942 default: llvm_unreachable("unknown auto TypeSpecType");
2943 }
2944 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2945 << Keyword << Error << AutoRange;
2946 T = SemaRef.Context.IntTy;
2947 D.setInvalidType(true);
2948 } else if (!HaveTrailing) {
2949 // If there was a trailing return type, we already got
2950 // warn_cxx98_compat_trailing_return_type in the parser.
2951 SemaRef.Diag(AutoRange.getBegin(),
2952 diag::warn_cxx98_compat_auto_type_specifier)
2953 << AutoRange;
2954 }
2955 }
2956
2957 if (SemaRef.getLangOpts().CPlusPlus &&
2958 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2959 // Check the contexts where C++ forbids the declaration of a new class
2960 // or enumeration in a type-specifier-seq.
2961 unsigned DiagID = 0;
2962 switch (D.getContext()) {
2963 case Declarator::TrailingReturnContext:
2964 // Class and enumeration definitions are syntactically not allowed in
2965 // trailing return types.
2966 llvm_unreachable("parser should not have allowed this");
2967 break;
2968 case Declarator::FileContext:
2969 case Declarator::MemberContext:
2970 case Declarator::BlockContext:
2971 case Declarator::ForContext:
2972 case Declarator::InitStmtContext:
2973 case Declarator::BlockLiteralContext:
2974 case Declarator::LambdaExprContext:
2975 // C++11 [dcl.type]p3:
2976 // A type-specifier-seq shall not define a class or enumeration unless
2977 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2978 // the declaration of a template-declaration.
2979 case Declarator::AliasDeclContext:
2980 break;
2981 case Declarator::AliasTemplateContext:
2982 DiagID = diag::err_type_defined_in_alias_template;
2983 break;
2984 case Declarator::TypeNameContext:
2985 case Declarator::ConversionIdContext:
2986 case Declarator::TemplateParamContext:
2987 case Declarator::CXXNewContext:
2988 case Declarator::CXXCatchContext:
2989 case Declarator::ObjCCatchContext:
2990 case Declarator::TemplateTypeArgContext:
2991 DiagID = diag::err_type_defined_in_type_specifier;
2992 break;
2993 case Declarator::PrototypeContext:
2994 case Declarator::LambdaExprParameterContext:
2995 case Declarator::ObjCParameterContext:
2996 case Declarator::ObjCResultContext:
2997 case Declarator::KNRTypeListContext:
2998 // C++ [dcl.fct]p6:
2999 // Types shall not be defined in return or parameter types.
3000 DiagID = diag::err_type_defined_in_param_type;
3001 break;
3002 case Declarator::ConditionContext:
3003 // C++ 6.4p2:
3004 // The type-specifier-seq shall not contain typedef and shall not declare
3005 // a new class or enumeration.
3006 DiagID = diag::err_type_defined_in_condition;
3007 break;
3008 }
3009
3010 if (DiagID != 0) {
3011 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3012 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3013 D.setInvalidType(true);
3014 }
3015 }
3016
3017 assert(!T.isNull() && "This function should not return a null type");
3018 return T;
3019 }
3020
3021 /// Produce an appropriate diagnostic for an ambiguity between a function
3022 /// declarator and a C++ direct-initializer.
warnAboutAmbiguousFunction(Sema & S,Declarator & D,DeclaratorChunk & DeclType,QualType RT)3023 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3024 DeclaratorChunk &DeclType, QualType RT) {
3025 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3026 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3027
3028 // If the return type is void there is no ambiguity.
3029 if (RT->isVoidType())
3030 return;
3031
3032 // An initializer for a non-class type can have at most one argument.
3033 if (!RT->isRecordType() && FTI.NumParams > 1)
3034 return;
3035
3036 // An initializer for a reference must have exactly one argument.
3037 if (RT->isReferenceType() && FTI.NumParams != 1)
3038 return;
3039
3040 // Only warn if this declarator is declaring a function at block scope, and
3041 // doesn't have a storage class (such as 'extern') specified.
3042 if (!D.isFunctionDeclarator() ||
3043 D.getFunctionDefinitionKind() != FDK_Declaration ||
3044 !S.CurContext->isFunctionOrMethod() ||
3045 D.getDeclSpec().getStorageClassSpec()
3046 != DeclSpec::SCS_unspecified)
3047 return;
3048
3049 // Inside a condition, a direct initializer is not permitted. We allow one to
3050 // be parsed in order to give better diagnostics in condition parsing.
3051 if (D.getContext() == Declarator::ConditionContext)
3052 return;
3053
3054 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3055
3056 S.Diag(DeclType.Loc,
3057 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3058 : diag::warn_empty_parens_are_function_decl)
3059 << ParenRange;
3060
3061 // If the declaration looks like:
3062 // T var1,
3063 // f();
3064 // and name lookup finds a function named 'f', then the ',' was
3065 // probably intended to be a ';'.
3066 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3067 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3068 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3069 if (Comma.getFileID() != Name.getFileID() ||
3070 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3071 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3072 Sema::LookupOrdinaryName);
3073 if (S.LookupName(Result, S.getCurScope()))
3074 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3075 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3076 << D.getIdentifier();
3077 }
3078 }
3079
3080 if (FTI.NumParams > 0) {
3081 // For a declaration with parameters, eg. "T var(T());", suggest adding
3082 // parens around the first parameter to turn the declaration into a
3083 // variable declaration.
3084 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3085 SourceLocation B = Range.getBegin();
3086 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3087 // FIXME: Maybe we should suggest adding braces instead of parens
3088 // in C++11 for classes that don't have an initializer_list constructor.
3089 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3090 << FixItHint::CreateInsertion(B, "(")
3091 << FixItHint::CreateInsertion(E, ")");
3092 } else {
3093 // For a declaration without parameters, eg. "T var();", suggest replacing
3094 // the parens with an initializer to turn the declaration into a variable
3095 // declaration.
3096 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3097
3098 // Empty parens mean value-initialization, and no parens mean
3099 // default initialization. These are equivalent if the default
3100 // constructor is user-provided or if zero-initialization is a
3101 // no-op.
3102 if (RD && RD->hasDefinition() &&
3103 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3104 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3105 << FixItHint::CreateRemoval(ParenRange);
3106 else {
3107 std::string Init =
3108 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3109 if (Init.empty() && S.LangOpts.CPlusPlus11)
3110 Init = "{}";
3111 if (!Init.empty())
3112 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3113 << FixItHint::CreateReplacement(ParenRange, Init);
3114 }
3115 }
3116 }
3117
3118 /// Helper for figuring out the default CC for a function declarator type. If
3119 /// this is the outermost chunk, then we can determine the CC from the
3120 /// declarator context. If not, then this could be either a member function
3121 /// type or normal function type.
3122 static CallingConv
getCCForDeclaratorChunk(Sema & S,Declarator & D,const DeclaratorChunk::FunctionTypeInfo & FTI,unsigned ChunkIndex)3123 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3124 const DeclaratorChunk::FunctionTypeInfo &FTI,
3125 unsigned ChunkIndex) {
3126 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3127
3128 // Check for an explicit CC attribute.
3129 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3130 switch (Attr->getKind()) {
3131 CALLING_CONV_ATTRS_CASELIST: {
3132 // Ignore attributes that don't validate or can't apply to the
3133 // function type. We'll diagnose the failure to apply them in
3134 // handleFunctionTypeAttr.
3135 CallingConv CC;
3136 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3137 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3138 return CC;
3139 }
3140 break;
3141 }
3142
3143 default:
3144 break;
3145 }
3146 }
3147
3148 bool IsCXXInstanceMethod = false;
3149
3150 if (S.getLangOpts().CPlusPlus) {
3151 // Look inwards through parentheses to see if this chunk will form a
3152 // member pointer type or if we're the declarator. Any type attributes
3153 // between here and there will override the CC we choose here.
3154 unsigned I = ChunkIndex;
3155 bool FoundNonParen = false;
3156 while (I && !FoundNonParen) {
3157 --I;
3158 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3159 FoundNonParen = true;
3160 }
3161
3162 if (FoundNonParen) {
3163 // If we're not the declarator, we're a regular function type unless we're
3164 // in a member pointer.
3165 IsCXXInstanceMethod =
3166 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3167 } else if (D.getContext() == Declarator::LambdaExprContext) {
3168 // This can only be a call operator for a lambda, which is an instance
3169 // method.
3170 IsCXXInstanceMethod = true;
3171 } else {
3172 // We're the innermost decl chunk, so must be a function declarator.
3173 assert(D.isFunctionDeclarator());
3174
3175 // If we're inside a record, we're declaring a method, but it could be
3176 // explicitly or implicitly static.
3177 IsCXXInstanceMethod =
3178 D.isFirstDeclarationOfMember() &&
3179 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3180 !D.isStaticMember();
3181 }
3182 }
3183
3184 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3185 IsCXXInstanceMethod);
3186
3187 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3188 // and AMDGPU targets, hence it cannot be treated as a calling
3189 // convention attribute. This is the simplest place to infer
3190 // calling convention for OpenCL kernels.
3191 if (S.getLangOpts().OpenCL) {
3192 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3193 Attr; Attr = Attr->getNext()) {
3194 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3195 llvm::Triple::ArchType arch = S.Context.getTargetInfo().getTriple().getArch();
3196 if (arch == llvm::Triple::spir || arch == llvm::Triple::spir64 ||
3197 arch == llvm::Triple::amdgcn) {
3198 CC = CC_OpenCLKernel;
3199 }
3200 break;
3201 }
3202 }
3203 }
3204
3205 return CC;
3206 }
3207
3208 namespace {
3209 /// A simple notion of pointer kinds, which matches up with the various
3210 /// pointer declarators.
3211 enum class SimplePointerKind {
3212 Pointer,
3213 BlockPointer,
3214 MemberPointer,
3215 };
3216 } // end anonymous namespace
3217
getNullabilityKeyword(NullabilityKind nullability)3218 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3219 switch (nullability) {
3220 case NullabilityKind::NonNull:
3221 if (!Ident__Nonnull)
3222 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3223 return Ident__Nonnull;
3224
3225 case NullabilityKind::Nullable:
3226 if (!Ident__Nullable)
3227 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3228 return Ident__Nullable;
3229
3230 case NullabilityKind::Unspecified:
3231 if (!Ident__Null_unspecified)
3232 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3233 return Ident__Null_unspecified;
3234 }
3235 llvm_unreachable("Unknown nullability kind.");
3236 }
3237
3238 /// Retrieve the identifier "NSError".
getNSErrorIdent()3239 IdentifierInfo *Sema::getNSErrorIdent() {
3240 if (!Ident_NSError)
3241 Ident_NSError = PP.getIdentifierInfo("NSError");
3242
3243 return Ident_NSError;
3244 }
3245
3246 /// Check whether there is a nullability attribute of any kind in the given
3247 /// attribute list.
hasNullabilityAttr(const AttributeList * attrs)3248 static bool hasNullabilityAttr(const AttributeList *attrs) {
3249 for (const AttributeList *attr = attrs; attr;
3250 attr = attr->getNext()) {
3251 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3252 attr->getKind() == AttributeList::AT_TypeNullable ||
3253 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3254 return true;
3255 }
3256
3257 return false;
3258 }
3259
3260 namespace {
3261 /// Describes the kind of a pointer a declarator describes.
3262 enum class PointerDeclaratorKind {
3263 // Not a pointer.
3264 NonPointer,
3265 // Single-level pointer.
3266 SingleLevelPointer,
3267 // Multi-level pointer (of any pointer kind).
3268 MultiLevelPointer,
3269 // CFFooRef*
3270 MaybePointerToCFRef,
3271 // CFErrorRef*
3272 CFErrorRefPointer,
3273 // NSError**
3274 NSErrorPointerPointer,
3275 };
3276 } // end anonymous namespace
3277
3278 /// Classify the given declarator, whose type-specified is \c type, based on
3279 /// what kind of pointer it refers to.
3280 ///
3281 /// This is used to determine the default nullability.
classifyPointerDeclarator(Sema & S,QualType type,Declarator & declarator)3282 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
3283 QualType type,
3284 Declarator &declarator) {
3285 unsigned numNormalPointers = 0;
3286
3287 // For any dependent type, we consider it a non-pointer.
3288 if (type->isDependentType())
3289 return PointerDeclaratorKind::NonPointer;
3290
3291 // Look through the declarator chunks to identify pointers.
3292 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3293 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3294 switch (chunk.Kind) {
3295 case DeclaratorChunk::Array:
3296 case DeclaratorChunk::Function:
3297 case DeclaratorChunk::Pipe:
3298 break;
3299
3300 case DeclaratorChunk::BlockPointer:
3301 case DeclaratorChunk::MemberPointer:
3302 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3303 : PointerDeclaratorKind::SingleLevelPointer;
3304
3305 case DeclaratorChunk::Paren:
3306 case DeclaratorChunk::Reference:
3307 continue;
3308
3309 case DeclaratorChunk::Pointer:
3310 ++numNormalPointers;
3311 if (numNormalPointers > 2)
3312 return PointerDeclaratorKind::MultiLevelPointer;
3313 continue;
3314 }
3315 }
3316
3317 // Then, dig into the type specifier itself.
3318 unsigned numTypeSpecifierPointers = 0;
3319 do {
3320 // Decompose normal pointers.
3321 if (auto ptrType = type->getAs<PointerType>()) {
3322 ++numNormalPointers;
3323
3324 if (numNormalPointers > 2)
3325 return PointerDeclaratorKind::MultiLevelPointer;
3326
3327 type = ptrType->getPointeeType();
3328 ++numTypeSpecifierPointers;
3329 continue;
3330 }
3331
3332 // Decompose block pointers.
3333 if (type->getAs<BlockPointerType>()) {
3334 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3335 : PointerDeclaratorKind::SingleLevelPointer;
3336 }
3337
3338 // Decompose member pointers.
3339 if (type->getAs<MemberPointerType>()) {
3340 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3341 : PointerDeclaratorKind::SingleLevelPointer;
3342 }
3343
3344 // Look at Objective-C object pointers.
3345 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3346 ++numNormalPointers;
3347 ++numTypeSpecifierPointers;
3348
3349 // If this is NSError**, report that.
3350 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3351 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3352 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3353 return PointerDeclaratorKind::NSErrorPointerPointer;
3354 }
3355 }
3356
3357 break;
3358 }
3359
3360 // Look at Objective-C class types.
3361 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3362 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3363 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3364 return PointerDeclaratorKind::NSErrorPointerPointer;;
3365 }
3366
3367 break;
3368 }
3369
3370 // If at this point we haven't seen a pointer, we won't see one.
3371 if (numNormalPointers == 0)
3372 return PointerDeclaratorKind::NonPointer;
3373
3374 if (auto recordType = type->getAs<RecordType>()) {
3375 RecordDecl *recordDecl = recordType->getDecl();
3376
3377 bool isCFError = false;
3378 if (S.CFError) {
3379 // If we already know about CFError, test it directly.
3380 isCFError = (S.CFError == recordDecl);
3381 } else {
3382 // Check whether this is CFError, which we identify based on its bridge
3383 // to NSError.
3384 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3385 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3386 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3387 S.CFError = recordDecl;
3388 isCFError = true;
3389 }
3390 }
3391 }
3392 }
3393
3394 // If this is CFErrorRef*, report it as such.
3395 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3396 return PointerDeclaratorKind::CFErrorRefPointer;
3397 }
3398 break;
3399 }
3400
3401 break;
3402 } while (true);
3403
3404 switch (numNormalPointers) {
3405 case 0:
3406 return PointerDeclaratorKind::NonPointer;
3407
3408 case 1:
3409 return PointerDeclaratorKind::SingleLevelPointer;
3410
3411 case 2:
3412 return PointerDeclaratorKind::MaybePointerToCFRef;
3413
3414 default:
3415 return PointerDeclaratorKind::MultiLevelPointer;
3416 }
3417 }
3418
getNullabilityCompletenessCheckFileID(Sema & S,SourceLocation loc)3419 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3420 SourceLocation loc) {
3421 // If we're anywhere in a function, method, or closure context, don't perform
3422 // completeness checks.
3423 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3424 if (ctx->isFunctionOrMethod())
3425 return FileID();
3426
3427 if (ctx->isFileContext())
3428 break;
3429 }
3430
3431 // We only care about the expansion location.
3432 loc = S.SourceMgr.getExpansionLoc(loc);
3433 FileID file = S.SourceMgr.getFileID(loc);
3434 if (file.isInvalid())
3435 return FileID();
3436
3437 // Retrieve file information.
3438 bool invalid = false;
3439 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3440 if (invalid || !sloc.isFile())
3441 return FileID();
3442
3443 // We don't want to perform completeness checks on the main file or in
3444 // system headers.
3445 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3446 if (fileInfo.getIncludeLoc().isInvalid())
3447 return FileID();
3448 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3449 S.Diags.getSuppressSystemWarnings()) {
3450 return FileID();
3451 }
3452
3453 return file;
3454 }
3455
3456 /// Check for consistent use of nullability.
checkNullabilityConsistency(TypeProcessingState & state,SimplePointerKind pointerKind,SourceLocation pointerLoc)3457 static void checkNullabilityConsistency(TypeProcessingState &state,
3458 SimplePointerKind pointerKind,
3459 SourceLocation pointerLoc) {
3460 Sema &S = state.getSema();
3461
3462 // Determine which file we're performing consistency checking for.
3463 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3464 if (file.isInvalid())
3465 return;
3466
3467 // If we haven't seen any type nullability in this file, we won't warn now
3468 // about anything.
3469 FileNullability &fileNullability = S.NullabilityMap[file];
3470 if (!fileNullability.SawTypeNullability) {
3471 // If this is the first pointer declarator in the file, record it.
3472 if (fileNullability.PointerLoc.isInvalid() &&
3473 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
3474 pointerLoc)) {
3475 fileNullability.PointerLoc = pointerLoc;
3476 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3477 }
3478
3479 return;
3480 }
3481
3482 // Complain about missing nullability.
3483 S.Diag(pointerLoc, diag::warn_nullability_missing)
3484 << static_cast<unsigned>(pointerKind);
3485 }
3486
GetFullTypeForDeclarator(TypeProcessingState & state,QualType declSpecType,TypeSourceInfo * TInfo)3487 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3488 QualType declSpecType,
3489 TypeSourceInfo *TInfo) {
3490 // The TypeSourceInfo that this function returns will not be a null type.
3491 // If there is an error, this function will fill in a dummy type as fallback.
3492 QualType T = declSpecType;
3493 Declarator &D = state.getDeclarator();
3494 Sema &S = state.getSema();
3495 ASTContext &Context = S.Context;
3496 const LangOptions &LangOpts = S.getLangOpts();
3497
3498 // The name we're declaring, if any.
3499 DeclarationName Name;
3500 if (D.getIdentifier())
3501 Name = D.getIdentifier();
3502
3503 // Does this declaration declare a typedef-name?
3504 bool IsTypedefName =
3505 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3506 D.getContext() == Declarator::AliasDeclContext ||
3507 D.getContext() == Declarator::AliasTemplateContext;
3508
3509 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3510 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3511 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3512 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3513
3514 // If T is 'decltype(auto)', the only declarators we can have are parens
3515 // and at most one function declarator if this is a function declaration.
3516 if (const AutoType *AT = T->getAs<AutoType>()) {
3517 if (AT->isDecltypeAuto()) {
3518 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3519 unsigned Index = E - I - 1;
3520 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3521 unsigned DiagId = diag::err_decltype_auto_compound_type;
3522 unsigned DiagKind = 0;
3523 switch (DeclChunk.Kind) {
3524 case DeclaratorChunk::Paren:
3525 continue;
3526 case DeclaratorChunk::Function: {
3527 unsigned FnIndex;
3528 if (D.isFunctionDeclarationContext() &&
3529 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3530 continue;
3531 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3532 break;
3533 }
3534 case DeclaratorChunk::Pointer:
3535 case DeclaratorChunk::BlockPointer:
3536 case DeclaratorChunk::MemberPointer:
3537 DiagKind = 0;
3538 break;
3539 case DeclaratorChunk::Reference:
3540 DiagKind = 1;
3541 break;
3542 case DeclaratorChunk::Array:
3543 DiagKind = 2;
3544 break;
3545 case DeclaratorChunk::Pipe:
3546 break;
3547 }
3548
3549 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3550 D.setInvalidType(true);
3551 break;
3552 }
3553 }
3554 }
3555
3556 // Determine whether we should infer _Nonnull on pointer types.
3557 Optional<NullabilityKind> inferNullability;
3558 bool inferNullabilityCS = false;
3559 bool inferNullabilityInnerOnly = false;
3560 bool inferNullabilityInnerOnlyComplete = false;
3561
3562 // Are we in an assume-nonnull region?
3563 bool inAssumeNonNullRegion = false;
3564 if (S.PP.getPragmaAssumeNonNullLoc().isValid()) {
3565 inAssumeNonNullRegion = true;
3566 // Determine which file we saw the assume-nonnull region in.
3567 FileID file = getNullabilityCompletenessCheckFileID(
3568 S, S.PP.getPragmaAssumeNonNullLoc());
3569 if (file.isValid()) {
3570 FileNullability &fileNullability = S.NullabilityMap[file];
3571
3572 // If we haven't seen any type nullability before, now we have.
3573 if (!fileNullability.SawTypeNullability) {
3574 if (fileNullability.PointerLoc.isValid()) {
3575 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3576 << static_cast<unsigned>(fileNullability.PointerKind);
3577 }
3578
3579 fileNullability.SawTypeNullability = true;
3580 }
3581 }
3582 }
3583
3584 // Whether to complain about missing nullability specifiers or not.
3585 enum {
3586 /// Never complain.
3587 CAMN_No,
3588 /// Complain on the inner pointers (but not the outermost
3589 /// pointer).
3590 CAMN_InnerPointers,
3591 /// Complain about any pointers that don't have nullability
3592 /// specified or inferred.
3593 CAMN_Yes
3594 } complainAboutMissingNullability = CAMN_No;
3595 unsigned NumPointersRemaining = 0;
3596
3597 if (IsTypedefName) {
3598 // For typedefs, we do not infer any nullability (the default),
3599 // and we only complain about missing nullability specifiers on
3600 // inner pointers.
3601 complainAboutMissingNullability = CAMN_InnerPointers;
3602
3603 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3604 ++NumPointersRemaining;
3605 }
3606
3607 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3608 DeclaratorChunk &chunk = D.getTypeObject(i);
3609 switch (chunk.Kind) {
3610 case DeclaratorChunk::Array:
3611 case DeclaratorChunk::Function:
3612 case DeclaratorChunk::Pipe:
3613 break;
3614
3615 case DeclaratorChunk::BlockPointer:
3616 case DeclaratorChunk::MemberPointer:
3617 ++NumPointersRemaining;
3618 break;
3619
3620 case DeclaratorChunk::Paren:
3621 case DeclaratorChunk::Reference:
3622 continue;
3623
3624 case DeclaratorChunk::Pointer:
3625 ++NumPointersRemaining;
3626 continue;
3627 }
3628 }
3629 } else {
3630 bool isFunctionOrMethod = false;
3631 switch (auto context = state.getDeclarator().getContext()) {
3632 case Declarator::ObjCParameterContext:
3633 case Declarator::ObjCResultContext:
3634 case Declarator::PrototypeContext:
3635 case Declarator::TrailingReturnContext:
3636 isFunctionOrMethod = true;
3637 // fallthrough
3638
3639 case Declarator::MemberContext:
3640 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3641 complainAboutMissingNullability = CAMN_No;
3642 break;
3643 }
3644
3645 // Weak properties are inferred to be nullable.
3646 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3647 inferNullability = NullabilityKind::Nullable;
3648 break;
3649 }
3650
3651 // fallthrough
3652
3653 case Declarator::FileContext:
3654 case Declarator::KNRTypeListContext:
3655 complainAboutMissingNullability = CAMN_Yes;
3656
3657 // Nullability inference depends on the type and declarator.
3658 switch (classifyPointerDeclarator(S, T, D)) {
3659 case PointerDeclaratorKind::NonPointer:
3660 case PointerDeclaratorKind::MultiLevelPointer:
3661 // Cannot infer nullability.
3662 break;
3663
3664 case PointerDeclaratorKind::SingleLevelPointer:
3665 // Infer _Nonnull if we are in an assumes-nonnull region.
3666 if (inAssumeNonNullRegion) {
3667 inferNullability = NullabilityKind::NonNull;
3668 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3669 context == Declarator::ObjCResultContext);
3670 }
3671 break;
3672
3673 case PointerDeclaratorKind::CFErrorRefPointer:
3674 case PointerDeclaratorKind::NSErrorPointerPointer:
3675 // Within a function or method signature, infer _Nullable at both
3676 // levels.
3677 if (isFunctionOrMethod && inAssumeNonNullRegion)
3678 inferNullability = NullabilityKind::Nullable;
3679 break;
3680
3681 case PointerDeclaratorKind::MaybePointerToCFRef:
3682 if (isFunctionOrMethod) {
3683 // On pointer-to-pointer parameters marked cf_returns_retained or
3684 // cf_returns_not_retained, if the outer pointer is explicit then
3685 // infer the inner pointer as _Nullable.
3686 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3687 while (NextAttr) {
3688 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3689 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3690 return true;
3691 NextAttr = NextAttr->getNext();
3692 }
3693 return false;
3694 };
3695 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3696 if (hasCFReturnsAttr(D.getAttributes()) ||
3697 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3698 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3699 inferNullability = NullabilityKind::Nullable;
3700 inferNullabilityInnerOnly = true;
3701 }
3702 }
3703 }
3704 break;
3705 }
3706 break;
3707
3708 case Declarator::ConversionIdContext:
3709 complainAboutMissingNullability = CAMN_Yes;
3710 break;
3711
3712 case Declarator::AliasDeclContext:
3713 case Declarator::AliasTemplateContext:
3714 case Declarator::BlockContext:
3715 case Declarator::BlockLiteralContext:
3716 case Declarator::ConditionContext:
3717 case Declarator::CXXCatchContext:
3718 case Declarator::CXXNewContext:
3719 case Declarator::ForContext:
3720 case Declarator::InitStmtContext:
3721 case Declarator::LambdaExprContext:
3722 case Declarator::LambdaExprParameterContext:
3723 case Declarator::ObjCCatchContext:
3724 case Declarator::TemplateParamContext:
3725 case Declarator::TemplateTypeArgContext:
3726 case Declarator::TypeNameContext:
3727 // Don't infer in these contexts.
3728 break;
3729 }
3730 }
3731
3732 // Local function that checks the nullability for a given pointer declarator.
3733 // Returns true if _Nonnull was inferred.
3734 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3735 SourceLocation pointerLoc,
3736 AttributeList *&attrs) -> AttributeList * {
3737 // We've seen a pointer.
3738 if (NumPointersRemaining > 0)
3739 --NumPointersRemaining;
3740
3741 // If a nullability attribute is present, there's nothing to do.
3742 if (hasNullabilityAttr(attrs))
3743 return nullptr;
3744
3745 // If we're supposed to infer nullability, do so now.
3746 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3747 AttributeList::Syntax syntax
3748 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3749 : AttributeList::AS_Keyword;
3750 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3751 .create(
3752 S.getNullabilityKeyword(
3753 *inferNullability),
3754 SourceRange(pointerLoc),
3755 nullptr, SourceLocation(),
3756 nullptr, 0, syntax);
3757
3758 spliceAttrIntoList(*nullabilityAttr, attrs);
3759
3760 if (inferNullabilityCS) {
3761 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3762 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3763 }
3764
3765 if (inferNullabilityInnerOnly)
3766 inferNullabilityInnerOnlyComplete = true;
3767 return nullabilityAttr;
3768 }
3769
3770 // If we're supposed to complain about missing nullability, do so
3771 // now if it's truly missing.
3772 switch (complainAboutMissingNullability) {
3773 case CAMN_No:
3774 break;
3775
3776 case CAMN_InnerPointers:
3777 if (NumPointersRemaining == 0)
3778 break;
3779 // Fallthrough.
3780
3781 case CAMN_Yes:
3782 checkNullabilityConsistency(state, pointerKind, pointerLoc);
3783 }
3784 return nullptr;
3785 };
3786
3787 // If the type itself could have nullability but does not, infer pointer
3788 // nullability and perform consistency checking.
3789 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3790 !T->getNullability(S.Context)) {
3791 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3792 if (T->isBlockPointerType())
3793 pointerKind = SimplePointerKind::BlockPointer;
3794 else if (T->isMemberPointerType())
3795 pointerKind = SimplePointerKind::MemberPointer;
3796
3797 if (auto *attr = inferPointerNullability(
3798 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3799 D.getMutableDeclSpec().getAttributes().getListRef())) {
3800 T = Context.getAttributedType(
3801 AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3802 attr->setUsedAsTypeAttr();
3803 }
3804 }
3805
3806 // Walk the DeclTypeInfo, building the recursive type as we go.
3807 // DeclTypeInfos are ordered from the identifier out, which is
3808 // opposite of what we want :).
3809 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3810 unsigned chunkIndex = e - i - 1;
3811 state.setCurrentChunkIndex(chunkIndex);
3812 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3813 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3814 switch (DeclType.Kind) {
3815 case DeclaratorChunk::Paren:
3816 T = S.BuildParenType(T);
3817 break;
3818 case DeclaratorChunk::BlockPointer:
3819 // If blocks are disabled, emit an error.
3820 if (!LangOpts.Blocks)
3821 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
3822
3823 // Handle pointer nullability.
3824 inferPointerNullability(SimplePointerKind::BlockPointer,
3825 DeclType.Loc, DeclType.getAttrListRef());
3826
3827 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3828 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
3829 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
3830 // qualified with const.
3831 if (LangOpts.OpenCL)
3832 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
3833 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3834 }
3835 break;
3836 case DeclaratorChunk::Pointer:
3837 // Verify that we're not building a pointer to pointer to function with
3838 // exception specification.
3839 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3840 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3841 D.setInvalidType(true);
3842 // Build the type anyway.
3843 }
3844
3845 // Handle pointer nullability
3846 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3847 DeclType.getAttrListRef());
3848
3849 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3850 T = Context.getObjCObjectPointerType(T);
3851 if (DeclType.Ptr.TypeQuals)
3852 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3853 break;
3854 }
3855
3856 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
3857 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
3858 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
3859 if (LangOpts.OpenCL) {
3860 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
3861 T->isBlockPointerType()) {
3862 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
3863 D.setInvalidType(true);
3864 }
3865 }
3866
3867 T = S.BuildPointerType(T, DeclType.Loc, Name);
3868 if (DeclType.Ptr.TypeQuals)
3869 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3870 break;
3871 case DeclaratorChunk::Reference: {
3872 // Verify that we're not building a reference to pointer to function with
3873 // exception specification.
3874 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3875 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3876 D.setInvalidType(true);
3877 // Build the type anyway.
3878 }
3879 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3880
3881 if (DeclType.Ref.HasRestrict)
3882 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3883 break;
3884 }
3885 case DeclaratorChunk::Array: {
3886 // Verify that we're not building an array of pointers to function with
3887 // exception specification.
3888 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3889 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3890 D.setInvalidType(true);
3891 // Build the type anyway.
3892 }
3893 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3894 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3895 ArrayType::ArraySizeModifier ASM;
3896 if (ATI.isStar)
3897 ASM = ArrayType::Star;
3898 else if (ATI.hasStatic)
3899 ASM = ArrayType::Static;
3900 else
3901 ASM = ArrayType::Normal;
3902 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3903 // FIXME: This check isn't quite right: it allows star in prototypes
3904 // for function definitions, and disallows some edge cases detailed
3905 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3906 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3907 ASM = ArrayType::Normal;
3908 D.setInvalidType(true);
3909 }
3910
3911 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3912 // shall appear only in a declaration of a function parameter with an
3913 // array type, ...
3914 if (ASM == ArrayType::Static || ATI.TypeQuals) {
3915 if (!(D.isPrototypeContext() ||
3916 D.getContext() == Declarator::KNRTypeListContext)) {
3917 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3918 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3919 // Remove the 'static' and the type qualifiers.
3920 if (ASM == ArrayType::Static)
3921 ASM = ArrayType::Normal;
3922 ATI.TypeQuals = 0;
3923 D.setInvalidType(true);
3924 }
3925
3926 // C99 6.7.5.2p1: ... and then only in the outermost array type
3927 // derivation.
3928 unsigned x = chunkIndex;
3929 while (x != 0) {
3930 // Walk outwards along the declarator chunks.
3931 x--;
3932 const DeclaratorChunk &DC = D.getTypeObject(x);
3933 switch (DC.Kind) {
3934 case DeclaratorChunk::Paren:
3935 continue;
3936 case DeclaratorChunk::Array:
3937 case DeclaratorChunk::Pointer:
3938 case DeclaratorChunk::Reference:
3939 case DeclaratorChunk::MemberPointer:
3940 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3941 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3942 if (ASM == ArrayType::Static)
3943 ASM = ArrayType::Normal;
3944 ATI.TypeQuals = 0;
3945 D.setInvalidType(true);
3946 break;
3947 case DeclaratorChunk::Function:
3948 case DeclaratorChunk::BlockPointer:
3949 case DeclaratorChunk::Pipe:
3950 // These are invalid anyway, so just ignore.
3951 break;
3952 }
3953 }
3954 }
3955 const AutoType *AT = T->getContainedAutoType();
3956 // Allow arrays of auto if we are a generic lambda parameter.
3957 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3958 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3959 // We've already diagnosed this for decltype(auto).
3960 if (!AT->isDecltypeAuto())
3961 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3962 << getPrintableNameForEntity(Name) << T;
3963 T = QualType();
3964 break;
3965 }
3966
3967 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3968 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3969 break;
3970 }
3971 case DeclaratorChunk::Function: {
3972 // If the function declarator has a prototype (i.e. it is not () and
3973 // does not have a K&R-style identifier list), then the arguments are part
3974 // of the type, otherwise the argument list is ().
3975 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3976 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3977
3978 // Check for auto functions and trailing return type and adjust the
3979 // return type accordingly.
3980 if (!D.isInvalidType()) {
3981 // trailing-return-type is only required if we're declaring a function,
3982 // and not, for instance, a pointer to a function.
3983 if (D.getDeclSpec().containsPlaceholderType() &&
3984 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3985 !S.getLangOpts().CPlusPlus14) {
3986 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3987 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3988 ? diag::err_auto_missing_trailing_return
3989 : diag::err_deduced_return_type);
3990 T = Context.IntTy;
3991 D.setInvalidType(true);
3992 } else if (FTI.hasTrailingReturnType()) {
3993 // T must be exactly 'auto' at this point. See CWG issue 681.
3994 if (isa<ParenType>(T)) {
3995 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3996 diag::err_trailing_return_in_parens)
3997 << T << D.getDeclSpec().getSourceRange();
3998 D.setInvalidType(true);
3999 } else if (D.getContext() != Declarator::LambdaExprContext &&
4000 (T.hasQualifiers() || !isa<AutoType>(T) ||
4001 cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
4002 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4003 diag::err_trailing_return_without_auto)
4004 << T << D.getDeclSpec().getSourceRange();
4005 D.setInvalidType(true);
4006 }
4007 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4008 if (T.isNull()) {
4009 // An error occurred parsing the trailing return type.
4010 T = Context.IntTy;
4011 D.setInvalidType(true);
4012 }
4013 }
4014 }
4015
4016 // C99 6.7.5.3p1: The return type may not be a function or array type.
4017 // For conversion functions, we'll diagnose this particular error later.
4018 if ((T->isArrayType() || T->isFunctionType()) &&
4019 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4020 unsigned diagID = diag::err_func_returning_array_function;
4021 // Last processing chunk in block context means this function chunk
4022 // represents the block.
4023 if (chunkIndex == 0 &&
4024 D.getContext() == Declarator::BlockLiteralContext)
4025 diagID = diag::err_block_returning_array_function;
4026 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4027 T = Context.IntTy;
4028 D.setInvalidType(true);
4029 }
4030
4031 // Do not allow returning half FP value.
4032 // FIXME: This really should be in BuildFunctionType.
4033 if (T->isHalfType()) {
4034 if (S.getLangOpts().OpenCL) {
4035 if (!S.getOpenCLOptions().cl_khr_fp16) {
4036 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4037 << T << 0 /*pointer hint*/;
4038 D.setInvalidType(true);
4039 }
4040 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4041 S.Diag(D.getIdentifierLoc(),
4042 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4043 D.setInvalidType(true);
4044 }
4045 }
4046
4047 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4048 // function.
4049 if (LangOpts.OpenCL && (T->isBlockPointerType() || T->isImageType() ||
4050 T->isSamplerT() || T->isPipeType())) {
4051 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4052 << T << 1 /*hint off*/;
4053 D.setInvalidType(true);
4054 }
4055
4056 // Methods cannot return interface types. All ObjC objects are
4057 // passed by reference.
4058 if (T->isObjCObjectType()) {
4059 SourceLocation DiagLoc, FixitLoc;
4060 if (TInfo) {
4061 DiagLoc = TInfo->getTypeLoc().getLocStart();
4062 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4063 } else {
4064 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4065 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4066 }
4067 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4068 << 0 << T
4069 << FixItHint::CreateInsertion(FixitLoc, "*");
4070
4071 T = Context.getObjCObjectPointerType(T);
4072 if (TInfo) {
4073 TypeLocBuilder TLB;
4074 TLB.pushFullCopy(TInfo->getTypeLoc());
4075 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4076 TLoc.setStarLoc(FixitLoc);
4077 TInfo = TLB.getTypeSourceInfo(Context, T);
4078 }
4079
4080 D.setInvalidType(true);
4081 }
4082
4083 // cv-qualifiers on return types are pointless except when the type is a
4084 // class type in C++.
4085 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4086 !(S.getLangOpts().CPlusPlus &&
4087 (T->isDependentType() || T->isRecordType()))) {
4088 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4089 D.getFunctionDefinitionKind() == FDK_Definition) {
4090 // [6.9.1/3] qualified void return is invalid on a C
4091 // function definition. Apparently ok on declarations and
4092 // in C++ though (!)
4093 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4094 } else
4095 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4096 }
4097
4098 // Objective-C ARC ownership qualifiers are ignored on the function
4099 // return type (by type canonicalization). Complain if this attribute
4100 // was written here.
4101 if (T.getQualifiers().hasObjCLifetime()) {
4102 SourceLocation AttrLoc;
4103 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4104 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4105 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4106 Attr; Attr = Attr->getNext()) {
4107 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4108 AttrLoc = Attr->getLoc();
4109 break;
4110 }
4111 }
4112 }
4113 if (AttrLoc.isInvalid()) {
4114 for (const AttributeList *Attr
4115 = D.getDeclSpec().getAttributes().getList();
4116 Attr; Attr = Attr->getNext()) {
4117 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4118 AttrLoc = Attr->getLoc();
4119 break;
4120 }
4121 }
4122 }
4123
4124 if (AttrLoc.isValid()) {
4125 // The ownership attributes are almost always written via
4126 // the predefined
4127 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4128 if (AttrLoc.isMacroID())
4129 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4130
4131 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4132 << T.getQualifiers().getObjCLifetime();
4133 }
4134 }
4135
4136 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4137 // C++ [dcl.fct]p6:
4138 // Types shall not be defined in return or parameter types.
4139 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4140 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4141 << Context.getTypeDeclType(Tag);
4142 }
4143
4144 // Exception specs are not allowed in typedefs. Complain, but add it
4145 // anyway.
4146 if (IsTypedefName && FTI.getExceptionSpecType())
4147 S.Diag(FTI.getExceptionSpecLocBeg(),
4148 diag::err_exception_spec_in_typedef)
4149 << (D.getContext() == Declarator::AliasDeclContext ||
4150 D.getContext() == Declarator::AliasTemplateContext);
4151
4152 // If we see "T var();" or "T var(T());" at block scope, it is probably
4153 // an attempt to initialize a variable, not a function declaration.
4154 if (FTI.isAmbiguous)
4155 warnAboutAmbiguousFunction(S, D, DeclType, T);
4156
4157 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4158
4159 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4160 // Simple void foo(), where the incoming T is the result type.
4161 T = Context.getFunctionNoProtoType(T, EI);
4162 } else {
4163 // We allow a zero-parameter variadic function in C if the
4164 // function is marked with the "overloadable" attribute. Scan
4165 // for this attribute now.
4166 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4167 bool Overloadable = false;
4168 for (const AttributeList *Attrs = D.getAttributes();
4169 Attrs; Attrs = Attrs->getNext()) {
4170 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4171 Overloadable = true;
4172 break;
4173 }
4174 }
4175
4176 if (!Overloadable)
4177 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4178 }
4179
4180 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4181 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4182 // definition.
4183 S.Diag(FTI.Params[0].IdentLoc,
4184 diag::err_ident_list_in_fn_declaration);
4185 D.setInvalidType(true);
4186 // Recover by creating a K&R-style function type.
4187 T = Context.getFunctionNoProtoType(T, EI);
4188 break;
4189 }
4190
4191 FunctionProtoType::ExtProtoInfo EPI;
4192 EPI.ExtInfo = EI;
4193 EPI.Variadic = FTI.isVariadic;
4194 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4195 EPI.TypeQuals = FTI.TypeQuals;
4196 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4197 : FTI.RefQualifierIsLValueRef? RQ_LValue
4198 : RQ_RValue;
4199
4200 // Otherwise, we have a function with a parameter list that is
4201 // potentially variadic.
4202 SmallVector<QualType, 16> ParamTys;
4203 ParamTys.reserve(FTI.NumParams);
4204
4205 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4206 ExtParameterInfos(FTI.NumParams);
4207 bool HasAnyInterestingExtParameterInfos = false;
4208
4209 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4210 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4211 QualType ParamTy = Param->getType();
4212 assert(!ParamTy.isNull() && "Couldn't parse type?");
4213
4214 // Look for 'void'. void is allowed only as a single parameter to a
4215 // function with no other parameters (C99 6.7.5.3p10). We record
4216 // int(void) as a FunctionProtoType with an empty parameter list.
4217 if (ParamTy->isVoidType()) {
4218 // If this is something like 'float(int, void)', reject it. 'void'
4219 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4220 // have parameters of incomplete type.
4221 if (FTI.NumParams != 1 || FTI.isVariadic) {
4222 S.Diag(DeclType.Loc, diag::err_void_only_param);
4223 ParamTy = Context.IntTy;
4224 Param->setType(ParamTy);
4225 } else if (FTI.Params[i].Ident) {
4226 // Reject, but continue to parse 'int(void abc)'.
4227 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4228 ParamTy = Context.IntTy;
4229 Param->setType(ParamTy);
4230 } else {
4231 // Reject, but continue to parse 'float(const void)'.
4232 if (ParamTy.hasQualifiers())
4233 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4234
4235 // Do not add 'void' to the list.
4236 break;
4237 }
4238 } else if (ParamTy->isHalfType()) {
4239 // Disallow half FP parameters.
4240 // FIXME: This really should be in BuildFunctionType.
4241 if (S.getLangOpts().OpenCL) {
4242 if (!S.getOpenCLOptions().cl_khr_fp16) {
4243 S.Diag(Param->getLocation(),
4244 diag::err_opencl_half_param) << ParamTy;
4245 D.setInvalidType();
4246 Param->setInvalidDecl();
4247 }
4248 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4249 S.Diag(Param->getLocation(),
4250 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4251 D.setInvalidType();
4252 }
4253 } else if (!FTI.hasPrototype) {
4254 if (ParamTy->isPromotableIntegerType()) {
4255 ParamTy = Context.getPromotedIntegerType(ParamTy);
4256 Param->setKNRPromoted(true);
4257 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4258 if (BTy->getKind() == BuiltinType::Float) {
4259 ParamTy = Context.DoubleTy;
4260 Param->setKNRPromoted(true);
4261 }
4262 }
4263 }
4264
4265 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4266 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4267 HasAnyInterestingExtParameterInfos = true;
4268 }
4269
4270 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4271 ExtParameterInfos[i] =
4272 ExtParameterInfos[i].withABI(attr->getABI());
4273 HasAnyInterestingExtParameterInfos = true;
4274 }
4275
4276 ParamTys.push_back(ParamTy);
4277 }
4278
4279 if (HasAnyInterestingExtParameterInfos) {
4280 EPI.ExtParameterInfos = ExtParameterInfos.data();
4281 checkExtParameterInfos(S, ParamTys, EPI,
4282 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4283 }
4284
4285 SmallVector<QualType, 4> Exceptions;
4286 SmallVector<ParsedType, 2> DynamicExceptions;
4287 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4288 Expr *NoexceptExpr = nullptr;
4289
4290 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4291 // FIXME: It's rather inefficient to have to split into two vectors
4292 // here.
4293 unsigned N = FTI.NumExceptions;
4294 DynamicExceptions.reserve(N);
4295 DynamicExceptionRanges.reserve(N);
4296 for (unsigned I = 0; I != N; ++I) {
4297 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4298 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4299 }
4300 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4301 NoexceptExpr = FTI.NoexceptExpr;
4302 }
4303
4304 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4305 FTI.getExceptionSpecType(),
4306 DynamicExceptions,
4307 DynamicExceptionRanges,
4308 NoexceptExpr,
4309 Exceptions,
4310 EPI.ExceptionSpec);
4311
4312 T = Context.getFunctionType(T, ParamTys, EPI);
4313 }
4314 break;
4315 }
4316 case DeclaratorChunk::MemberPointer: {
4317 // The scope spec must refer to a class, or be dependent.
4318 CXXScopeSpec &SS = DeclType.Mem.Scope();
4319 QualType ClsType;
4320
4321 // Handle pointer nullability.
4322 inferPointerNullability(SimplePointerKind::MemberPointer,
4323 DeclType.Loc, DeclType.getAttrListRef());
4324
4325 if (SS.isInvalid()) {
4326 // Avoid emitting extra errors if we already errored on the scope.
4327 D.setInvalidType(true);
4328 } else if (S.isDependentScopeSpecifier(SS) ||
4329 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4330 NestedNameSpecifier *NNS = SS.getScopeRep();
4331 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4332 switch (NNS->getKind()) {
4333 case NestedNameSpecifier::Identifier:
4334 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4335 NNS->getAsIdentifier());
4336 break;
4337
4338 case NestedNameSpecifier::Namespace:
4339 case NestedNameSpecifier::NamespaceAlias:
4340 case NestedNameSpecifier::Global:
4341 case NestedNameSpecifier::Super:
4342 llvm_unreachable("Nested-name-specifier must name a type");
4343
4344 case NestedNameSpecifier::TypeSpec:
4345 case NestedNameSpecifier::TypeSpecWithTemplate:
4346 ClsType = QualType(NNS->getAsType(), 0);
4347 // Note: if the NNS has a prefix and ClsType is a nondependent
4348 // TemplateSpecializationType, then the NNS prefix is NOT included
4349 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4350 // NOTE: in particular, no wrap occurs if ClsType already is an
4351 // Elaborated, DependentName, or DependentTemplateSpecialization.
4352 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4353 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4354 break;
4355 }
4356 } else {
4357 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4358 diag::err_illegal_decl_mempointer_in_nonclass)
4359 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4360 << DeclType.Mem.Scope().getRange();
4361 D.setInvalidType(true);
4362 }
4363
4364 if (!ClsType.isNull())
4365 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4366 D.getIdentifier());
4367 if (T.isNull()) {
4368 T = Context.IntTy;
4369 D.setInvalidType(true);
4370 } else if (DeclType.Mem.TypeQuals) {
4371 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4372 }
4373 break;
4374 }
4375
4376 case DeclaratorChunk::Pipe: {
4377 T = S.BuildPipeType(T, DeclType.Loc );
4378 break;
4379 }
4380 }
4381
4382 if (T.isNull()) {
4383 D.setInvalidType(true);
4384 T = Context.IntTy;
4385 }
4386
4387 // See if there are any attributes on this declarator chunk.
4388 processTypeAttrs(state, T, TAL_DeclChunk,
4389 const_cast<AttributeList *>(DeclType.getAttrs()));
4390 }
4391
4392 assert(!T.isNull() && "T must not be null after this point");
4393
4394 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4395 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4396 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4397
4398 // C++ 8.3.5p4:
4399 // A cv-qualifier-seq shall only be part of the function type
4400 // for a nonstatic member function, the function type to which a pointer
4401 // to member refers, or the top-level function type of a function typedef
4402 // declaration.
4403 //
4404 // Core issue 547 also allows cv-qualifiers on function types that are
4405 // top-level template type arguments.
4406 bool FreeFunction;
4407 if (!D.getCXXScopeSpec().isSet()) {
4408 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4409 D.getContext() != Declarator::LambdaExprContext) ||
4410 D.getDeclSpec().isFriendSpecified());
4411 } else {
4412 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4413 FreeFunction = (DC && !DC->isRecord());
4414 }
4415
4416 // C++11 [dcl.fct]p6 (w/DR1417):
4417 // An attempt to specify a function type with a cv-qualifier-seq or a
4418 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4419 // - the function type for a non-static member function,
4420 // - the function type to which a pointer to member refers,
4421 // - the top-level function type of a function typedef declaration or
4422 // alias-declaration,
4423 // - the type-id in the default argument of a type-parameter, or
4424 // - the type-id of a template-argument for a type-parameter
4425 //
4426 // FIXME: Checking this here is insufficient. We accept-invalid on:
4427 //
4428 // template<typename T> struct S { void f(T); };
4429 // S<int() const> s;
4430 //
4431 // ... for instance.
4432 if (IsQualifiedFunction &&
4433 !(!FreeFunction &&
4434 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4435 !IsTypedefName &&
4436 D.getContext() != Declarator::TemplateTypeArgContext) {
4437 SourceLocation Loc = D.getLocStart();
4438 SourceRange RemovalRange;
4439 unsigned I;
4440 if (D.isFunctionDeclarator(I)) {
4441 SmallVector<SourceLocation, 4> RemovalLocs;
4442 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4443 assert(Chunk.Kind == DeclaratorChunk::Function);
4444 if (Chunk.Fun.hasRefQualifier())
4445 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4446 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4447 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4448 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4449 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4450 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4451 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4452 if (!RemovalLocs.empty()) {
4453 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4454 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4455 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4456 Loc = RemovalLocs.front();
4457 }
4458 }
4459
4460 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4461 << FreeFunction << D.isFunctionDeclarator() << T
4462 << getFunctionQualifiersAsString(FnTy)
4463 << FixItHint::CreateRemoval(RemovalRange);
4464
4465 // Strip the cv-qualifiers and ref-qualifiers from the type.
4466 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4467 EPI.TypeQuals = 0;
4468 EPI.RefQualifier = RQ_None;
4469
4470 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4471 EPI);
4472 // Rebuild any parens around the identifier in the function type.
4473 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4474 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4475 break;
4476 T = S.BuildParenType(T);
4477 }
4478 }
4479 }
4480
4481 // Apply any undistributed attributes from the declarator.
4482 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4483
4484 // Diagnose any ignored type attributes.
4485 state.diagnoseIgnoredTypeAttrs(T);
4486
4487 // C++0x [dcl.constexpr]p9:
4488 // A constexpr specifier used in an object declaration declares the object
4489 // as const.
4490 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4491 T.addConst();
4492 }
4493
4494 // If there was an ellipsis in the declarator, the declaration declares a
4495 // parameter pack whose type may be a pack expansion type.
4496 if (D.hasEllipsis()) {
4497 // C++0x [dcl.fct]p13:
4498 // A declarator-id or abstract-declarator containing an ellipsis shall
4499 // only be used in a parameter-declaration. Such a parameter-declaration
4500 // is a parameter pack (14.5.3). [...]
4501 switch (D.getContext()) {
4502 case Declarator::PrototypeContext:
4503 case Declarator::LambdaExprParameterContext:
4504 // C++0x [dcl.fct]p13:
4505 // [...] When it is part of a parameter-declaration-clause, the
4506 // parameter pack is a function parameter pack (14.5.3). The type T
4507 // of the declarator-id of the function parameter pack shall contain
4508 // a template parameter pack; each template parameter pack in T is
4509 // expanded by the function parameter pack.
4510 //
4511 // We represent function parameter packs as function parameters whose
4512 // type is a pack expansion.
4513 if (!T->containsUnexpandedParameterPack()) {
4514 S.Diag(D.getEllipsisLoc(),
4515 diag::err_function_parameter_pack_without_parameter_packs)
4516 << T << D.getSourceRange();
4517 D.setEllipsisLoc(SourceLocation());
4518 } else {
4519 T = Context.getPackExpansionType(T, None);
4520 }
4521 break;
4522 case Declarator::TemplateParamContext:
4523 // C++0x [temp.param]p15:
4524 // If a template-parameter is a [...] is a parameter-declaration that
4525 // declares a parameter pack (8.3.5), then the template-parameter is a
4526 // template parameter pack (14.5.3).
4527 //
4528 // Note: core issue 778 clarifies that, if there are any unexpanded
4529 // parameter packs in the type of the non-type template parameter, then
4530 // it expands those parameter packs.
4531 if (T->containsUnexpandedParameterPack())
4532 T = Context.getPackExpansionType(T, None);
4533 else
4534 S.Diag(D.getEllipsisLoc(),
4535 LangOpts.CPlusPlus11
4536 ? diag::warn_cxx98_compat_variadic_templates
4537 : diag::ext_variadic_templates);
4538 break;
4539
4540 case Declarator::FileContext:
4541 case Declarator::KNRTypeListContext:
4542 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4543 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4544 case Declarator::TypeNameContext:
4545 case Declarator::CXXNewContext:
4546 case Declarator::AliasDeclContext:
4547 case Declarator::AliasTemplateContext:
4548 case Declarator::MemberContext:
4549 case Declarator::BlockContext:
4550 case Declarator::ForContext:
4551 case Declarator::InitStmtContext:
4552 case Declarator::ConditionContext:
4553 case Declarator::CXXCatchContext:
4554 case Declarator::ObjCCatchContext:
4555 case Declarator::BlockLiteralContext:
4556 case Declarator::LambdaExprContext:
4557 case Declarator::ConversionIdContext:
4558 case Declarator::TrailingReturnContext:
4559 case Declarator::TemplateTypeArgContext:
4560 // FIXME: We may want to allow parameter packs in block-literal contexts
4561 // in the future.
4562 S.Diag(D.getEllipsisLoc(),
4563 diag::err_ellipsis_in_declarator_not_parameter);
4564 D.setEllipsisLoc(SourceLocation());
4565 break;
4566 }
4567 }
4568
4569 assert(!T.isNull() && "T must not be null at the end of this function");
4570 if (D.isInvalidType())
4571 return Context.getTrivialTypeSourceInfo(T);
4572
4573 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4574 }
4575
4576 /// GetTypeForDeclarator - Convert the type for the specified
4577 /// declarator to Type instances.
4578 ///
4579 /// The result of this call will never be null, but the associated
4580 /// type may be a null type if there's an unrecoverable error.
GetTypeForDeclarator(Declarator & D,Scope * S)4581 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4582 // Determine the type of the declarator. Not all forms of declarator
4583 // have a type.
4584
4585 TypeProcessingState state(*this, D);
4586
4587 TypeSourceInfo *ReturnTypeInfo = nullptr;
4588 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4589
4590 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4591 inferARCWriteback(state, T);
4592
4593 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4594 }
4595
transferARCOwnershipToDeclSpec(Sema & S,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)4596 static void transferARCOwnershipToDeclSpec(Sema &S,
4597 QualType &declSpecTy,
4598 Qualifiers::ObjCLifetime ownership) {
4599 if (declSpecTy->isObjCRetainableType() &&
4600 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4601 Qualifiers qs;
4602 qs.addObjCLifetime(ownership);
4603 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4604 }
4605 }
4606
transferARCOwnershipToDeclaratorChunk(TypeProcessingState & state,Qualifiers::ObjCLifetime ownership,unsigned chunkIndex)4607 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4608 Qualifiers::ObjCLifetime ownership,
4609 unsigned chunkIndex) {
4610 Sema &S = state.getSema();
4611 Declarator &D = state.getDeclarator();
4612
4613 // Look for an explicit lifetime attribute.
4614 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4615 for (const AttributeList *attr = chunk.getAttrs(); attr;
4616 attr = attr->getNext())
4617 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4618 return;
4619
4620 const char *attrStr = nullptr;
4621 switch (ownership) {
4622 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4623 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4624 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4625 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4626 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4627 }
4628
4629 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4630 Arg->Ident = &S.Context.Idents.get(attrStr);
4631 Arg->Loc = SourceLocation();
4632
4633 ArgsUnion Args(Arg);
4634
4635 // If there wasn't one, add one (with an invalid source location
4636 // so that we don't make an AttributedType for it).
4637 AttributeList *attr = D.getAttributePool()
4638 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4639 /*scope*/ nullptr, SourceLocation(),
4640 /*args*/ &Args, 1, AttributeList::AS_GNU);
4641 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4642
4643 // TODO: mark whether we did this inference?
4644 }
4645
4646 /// \brief Used for transferring ownership in casts resulting in l-values.
transferARCOwnership(TypeProcessingState & state,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)4647 static void transferARCOwnership(TypeProcessingState &state,
4648 QualType &declSpecTy,
4649 Qualifiers::ObjCLifetime ownership) {
4650 Sema &S = state.getSema();
4651 Declarator &D = state.getDeclarator();
4652
4653 int inner = -1;
4654 bool hasIndirection = false;
4655 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4656 DeclaratorChunk &chunk = D.getTypeObject(i);
4657 switch (chunk.Kind) {
4658 case DeclaratorChunk::Paren:
4659 // Ignore parens.
4660 break;
4661
4662 case DeclaratorChunk::Array:
4663 case DeclaratorChunk::Reference:
4664 case DeclaratorChunk::Pointer:
4665 if (inner != -1)
4666 hasIndirection = true;
4667 inner = i;
4668 break;
4669
4670 case DeclaratorChunk::BlockPointer:
4671 if (inner != -1)
4672 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4673 return;
4674
4675 case DeclaratorChunk::Function:
4676 case DeclaratorChunk::MemberPointer:
4677 case DeclaratorChunk::Pipe:
4678 return;
4679 }
4680 }
4681
4682 if (inner == -1)
4683 return;
4684
4685 DeclaratorChunk &chunk = D.getTypeObject(inner);
4686 if (chunk.Kind == DeclaratorChunk::Pointer) {
4687 if (declSpecTy->isObjCRetainableType())
4688 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4689 if (declSpecTy->isObjCObjectType() && hasIndirection)
4690 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4691 } else {
4692 assert(chunk.Kind == DeclaratorChunk::Array ||
4693 chunk.Kind == DeclaratorChunk::Reference);
4694 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4695 }
4696 }
4697
GetTypeForDeclaratorCast(Declarator & D,QualType FromTy)4698 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4699 TypeProcessingState state(*this, D);
4700
4701 TypeSourceInfo *ReturnTypeInfo = nullptr;
4702 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4703
4704 if (getLangOpts().ObjC1) {
4705 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4706 if (ownership != Qualifiers::OCL_None)
4707 transferARCOwnership(state, declSpecTy, ownership);
4708 }
4709
4710 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4711 }
4712
4713 /// Map an AttributedType::Kind to an AttributeList::Kind.
getAttrListKind(AttributedType::Kind kind)4714 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4715 switch (kind) {
4716 case AttributedType::attr_address_space:
4717 return AttributeList::AT_AddressSpace;
4718 case AttributedType::attr_regparm:
4719 return AttributeList::AT_Regparm;
4720 case AttributedType::attr_vector_size:
4721 return AttributeList::AT_VectorSize;
4722 case AttributedType::attr_neon_vector_type:
4723 return AttributeList::AT_NeonVectorType;
4724 case AttributedType::attr_neon_polyvector_type:
4725 return AttributeList::AT_NeonPolyVectorType;
4726 case AttributedType::attr_objc_gc:
4727 return AttributeList::AT_ObjCGC;
4728 case AttributedType::attr_objc_ownership:
4729 case AttributedType::attr_objc_inert_unsafe_unretained:
4730 return AttributeList::AT_ObjCOwnership;
4731 case AttributedType::attr_noreturn:
4732 return AttributeList::AT_NoReturn;
4733 case AttributedType::attr_cdecl:
4734 return AttributeList::AT_CDecl;
4735 case AttributedType::attr_fastcall:
4736 return AttributeList::AT_FastCall;
4737 case AttributedType::attr_stdcall:
4738 return AttributeList::AT_StdCall;
4739 case AttributedType::attr_thiscall:
4740 return AttributeList::AT_ThisCall;
4741 case AttributedType::attr_pascal:
4742 return AttributeList::AT_Pascal;
4743 case AttributedType::attr_swiftcall:
4744 return AttributeList::AT_SwiftCall;
4745 case AttributedType::attr_vectorcall:
4746 return AttributeList::AT_VectorCall;
4747 case AttributedType::attr_pcs:
4748 case AttributedType::attr_pcs_vfp:
4749 return AttributeList::AT_Pcs;
4750 case AttributedType::attr_inteloclbicc:
4751 return AttributeList::AT_IntelOclBicc;
4752 case AttributedType::attr_ms_abi:
4753 return AttributeList::AT_MSABI;
4754 case AttributedType::attr_sysv_abi:
4755 return AttributeList::AT_SysVABI;
4756 case AttributedType::attr_preserve_most:
4757 return AttributeList::AT_PreserveMost;
4758 case AttributedType::attr_preserve_all:
4759 return AttributeList::AT_PreserveAll;
4760 case AttributedType::attr_ptr32:
4761 return AttributeList::AT_Ptr32;
4762 case AttributedType::attr_ptr64:
4763 return AttributeList::AT_Ptr64;
4764 case AttributedType::attr_sptr:
4765 return AttributeList::AT_SPtr;
4766 case AttributedType::attr_uptr:
4767 return AttributeList::AT_UPtr;
4768 case AttributedType::attr_nonnull:
4769 return AttributeList::AT_TypeNonNull;
4770 case AttributedType::attr_nullable:
4771 return AttributeList::AT_TypeNullable;
4772 case AttributedType::attr_null_unspecified:
4773 return AttributeList::AT_TypeNullUnspecified;
4774 case AttributedType::attr_objc_kindof:
4775 return AttributeList::AT_ObjCKindOf;
4776 }
4777 llvm_unreachable("unexpected attribute kind!");
4778 }
4779
fillAttributedTypeLoc(AttributedTypeLoc TL,const AttributeList * attrs,const AttributeList * DeclAttrs=nullptr)4780 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4781 const AttributeList *attrs,
4782 const AttributeList *DeclAttrs = nullptr) {
4783 // DeclAttrs and attrs cannot be both empty.
4784 assert((attrs || DeclAttrs) &&
4785 "no type attributes in the expected location!");
4786
4787 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4788 // Try to search for an attribute of matching kind in attrs list.
4789 while (attrs && attrs->getKind() != parsedKind)
4790 attrs = attrs->getNext();
4791 if (!attrs) {
4792 // No matching type attribute in attrs list found.
4793 // Try searching through C++11 attributes in the declarator attribute list.
4794 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4795 DeclAttrs->getKind() != parsedKind))
4796 DeclAttrs = DeclAttrs->getNext();
4797 attrs = DeclAttrs;
4798 }
4799
4800 assert(attrs && "no matching type attribute in expected location!");
4801
4802 TL.setAttrNameLoc(attrs->getLoc());
4803 if (TL.hasAttrExprOperand()) {
4804 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4805 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4806 } else if (TL.hasAttrEnumOperand()) {
4807 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4808 "unexpected attribute operand kind");
4809 if (attrs->isArgIdent(0))
4810 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4811 else
4812 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4813 }
4814
4815 // FIXME: preserve this information to here.
4816 if (TL.hasAttrOperand())
4817 TL.setAttrOperandParensRange(SourceRange());
4818 }
4819
4820 namespace {
4821 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4822 ASTContext &Context;
4823 const DeclSpec &DS;
4824
4825 public:
TypeSpecLocFiller(ASTContext & Context,const DeclSpec & DS)4826 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4827 : Context(Context), DS(DS) {}
4828
VisitAttributedTypeLoc(AttributedTypeLoc TL)4829 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4830 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4831 Visit(TL.getModifiedLoc());
4832 }
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)4833 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4834 Visit(TL.getUnqualifiedLoc());
4835 }
VisitTypedefTypeLoc(TypedefTypeLoc TL)4836 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4837 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4838 }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)4839 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4840 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4841 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4842 // addition field. What we have is good enough for dispay of location
4843 // of 'fixit' on interface name.
4844 TL.setNameEndLoc(DS.getLocEnd());
4845 }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)4846 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4847 TypeSourceInfo *RepTInfo = nullptr;
4848 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4849 TL.copy(RepTInfo->getTypeLoc());
4850 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)4851 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4852 TypeSourceInfo *RepTInfo = nullptr;
4853 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4854 TL.copy(RepTInfo->getTypeLoc());
4855 }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)4856 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4857 TypeSourceInfo *TInfo = nullptr;
4858 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4859
4860 // If we got no declarator info from previous Sema routines,
4861 // just fill with the typespec loc.
4862 if (!TInfo) {
4863 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4864 return;
4865 }
4866
4867 TypeLoc OldTL = TInfo->getTypeLoc();
4868 if (TInfo->getType()->getAs<ElaboratedType>()) {
4869 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4870 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4871 .castAs<TemplateSpecializationTypeLoc>();
4872 TL.copy(NamedTL);
4873 } else {
4874 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4875 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4876 }
4877
4878 }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)4879 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4880 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4881 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4882 TL.setParensRange(DS.getTypeofParensRange());
4883 }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)4884 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4885 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4886 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4887 TL.setParensRange(DS.getTypeofParensRange());
4888 assert(DS.getRepAsType());
4889 TypeSourceInfo *TInfo = nullptr;
4890 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4891 TL.setUnderlyingTInfo(TInfo);
4892 }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)4893 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4894 // FIXME: This holds only because we only have one unary transform.
4895 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4896 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4897 TL.setParensRange(DS.getTypeofParensRange());
4898 assert(DS.getRepAsType());
4899 TypeSourceInfo *TInfo = nullptr;
4900 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4901 TL.setUnderlyingTInfo(TInfo);
4902 }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)4903 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4904 // By default, use the source location of the type specifier.
4905 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4906 if (TL.needsExtraLocalData()) {
4907 // Set info for the written builtin specifiers.
4908 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4909 // Try to have a meaningful source location.
4910 if (TL.getWrittenSignSpec() != TSS_unspecified)
4911 // Sign spec loc overrides the others (e.g., 'unsigned long').
4912 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4913 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4914 // Width spec loc overrides type spec loc (e.g., 'short int').
4915 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4916 }
4917 }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)4918 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4919 ElaboratedTypeKeyword Keyword
4920 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4921 if (DS.getTypeSpecType() == TST_typename) {
4922 TypeSourceInfo *TInfo = nullptr;
4923 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4924 if (TInfo) {
4925 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4926 return;
4927 }
4928 }
4929 TL.setElaboratedKeywordLoc(Keyword != ETK_None
4930 ? DS.getTypeSpecTypeLoc()
4931 : SourceLocation());
4932 const CXXScopeSpec& SS = DS.getTypeSpecScope();
4933 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4934 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4935 }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)4936 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4937 assert(DS.getTypeSpecType() == TST_typename);
4938 TypeSourceInfo *TInfo = nullptr;
4939 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4940 assert(TInfo);
4941 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4942 }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)4943 void VisitDependentTemplateSpecializationTypeLoc(
4944 DependentTemplateSpecializationTypeLoc TL) {
4945 assert(DS.getTypeSpecType() == TST_typename);
4946 TypeSourceInfo *TInfo = nullptr;
4947 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4948 assert(TInfo);
4949 TL.copy(
4950 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4951 }
VisitTagTypeLoc(TagTypeLoc TL)4952 void VisitTagTypeLoc(TagTypeLoc TL) {
4953 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4954 }
VisitAtomicTypeLoc(AtomicTypeLoc TL)4955 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4956 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4957 // or an _Atomic qualifier.
4958 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4959 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4960 TL.setParensRange(DS.getTypeofParensRange());
4961
4962 TypeSourceInfo *TInfo = nullptr;
4963 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4964 assert(TInfo);
4965 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4966 } else {
4967 TL.setKWLoc(DS.getAtomicSpecLoc());
4968 // No parens, to indicate this was spelled as an _Atomic qualifier.
4969 TL.setParensRange(SourceRange());
4970 Visit(TL.getValueLoc());
4971 }
4972 }
4973
VisitPipeTypeLoc(PipeTypeLoc TL)4974 void VisitPipeTypeLoc(PipeTypeLoc TL) {
4975 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4976
4977 TypeSourceInfo *TInfo = nullptr;
4978 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4979 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4980 }
4981
VisitTypeLoc(TypeLoc TL)4982 void VisitTypeLoc(TypeLoc TL) {
4983 // FIXME: add other typespec types and change this to an assert.
4984 TL.initialize(Context, DS.getTypeSpecTypeLoc());
4985 }
4986 };
4987
4988 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4989 ASTContext &Context;
4990 const DeclaratorChunk &Chunk;
4991
4992 public:
DeclaratorLocFiller(ASTContext & Context,const DeclaratorChunk & Chunk)4993 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4994 : Context(Context), Chunk(Chunk) {}
4995
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)4996 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4997 llvm_unreachable("qualified type locs not expected here!");
4998 }
VisitDecayedTypeLoc(DecayedTypeLoc TL)4999 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5000 llvm_unreachable("decayed type locs not expected here!");
5001 }
5002
VisitAttributedTypeLoc(AttributedTypeLoc TL)5003 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5004 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5005 }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)5006 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5007 // nothing
5008 }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)5009 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5010 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5011 TL.setCaretLoc(Chunk.Loc);
5012 }
VisitPointerTypeLoc(PointerTypeLoc TL)5013 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5014 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5015 TL.setStarLoc(Chunk.Loc);
5016 }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)5017 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5018 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5019 TL.setStarLoc(Chunk.Loc);
5020 }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)5021 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5022 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5023 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5024 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5025
5026 const Type* ClsTy = TL.getClass();
5027 QualType ClsQT = QualType(ClsTy, 0);
5028 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5029 // Now copy source location info into the type loc component.
5030 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5031 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5032 case NestedNameSpecifier::Identifier:
5033 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5034 {
5035 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5036 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5037 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5038 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5039 }
5040 break;
5041
5042 case NestedNameSpecifier::TypeSpec:
5043 case NestedNameSpecifier::TypeSpecWithTemplate:
5044 if (isa<ElaboratedType>(ClsTy)) {
5045 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5046 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5047 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5048 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5049 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5050 } else {
5051 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5052 }
5053 break;
5054
5055 case NestedNameSpecifier::Namespace:
5056 case NestedNameSpecifier::NamespaceAlias:
5057 case NestedNameSpecifier::Global:
5058 case NestedNameSpecifier::Super:
5059 llvm_unreachable("Nested-name-specifier must name a type");
5060 }
5061
5062 // Finally fill in MemberPointerLocInfo fields.
5063 TL.setStarLoc(Chunk.Loc);
5064 TL.setClassTInfo(ClsTInfo);
5065 }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)5066 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5067 assert(Chunk.Kind == DeclaratorChunk::Reference);
5068 // 'Amp' is misleading: this might have been originally
5069 /// spelled with AmpAmp.
5070 TL.setAmpLoc(Chunk.Loc);
5071 }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)5072 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5073 assert(Chunk.Kind == DeclaratorChunk::Reference);
5074 assert(!Chunk.Ref.LValueRef);
5075 TL.setAmpAmpLoc(Chunk.Loc);
5076 }
VisitArrayTypeLoc(ArrayTypeLoc TL)5077 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5078 assert(Chunk.Kind == DeclaratorChunk::Array);
5079 TL.setLBracketLoc(Chunk.Loc);
5080 TL.setRBracketLoc(Chunk.EndLoc);
5081 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5082 }
VisitFunctionTypeLoc(FunctionTypeLoc TL)5083 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5084 assert(Chunk.Kind == DeclaratorChunk::Function);
5085 TL.setLocalRangeBegin(Chunk.Loc);
5086 TL.setLocalRangeEnd(Chunk.EndLoc);
5087
5088 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5089 TL.setLParenLoc(FTI.getLParenLoc());
5090 TL.setRParenLoc(FTI.getRParenLoc());
5091 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5092 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5093 TL.setParam(tpi++, Param);
5094 }
5095 // FIXME: exception specs
5096 }
VisitParenTypeLoc(ParenTypeLoc TL)5097 void VisitParenTypeLoc(ParenTypeLoc TL) {
5098 assert(Chunk.Kind == DeclaratorChunk::Paren);
5099 TL.setLParenLoc(Chunk.Loc);
5100 TL.setRParenLoc(Chunk.EndLoc);
5101 }
VisitPipeTypeLoc(PipeTypeLoc TL)5102 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5103 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5104 TL.setKWLoc(Chunk.Loc);
5105 }
5106
VisitTypeLoc(TypeLoc TL)5107 void VisitTypeLoc(TypeLoc TL) {
5108 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5109 }
5110 };
5111 } // end anonymous namespace
5112
fillAtomicQualLoc(AtomicTypeLoc ATL,const DeclaratorChunk & Chunk)5113 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5114 SourceLocation Loc;
5115 switch (Chunk.Kind) {
5116 case DeclaratorChunk::Function:
5117 case DeclaratorChunk::Array:
5118 case DeclaratorChunk::Paren:
5119 case DeclaratorChunk::Pipe:
5120 llvm_unreachable("cannot be _Atomic qualified");
5121
5122 case DeclaratorChunk::Pointer:
5123 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5124 break;
5125
5126 case DeclaratorChunk::BlockPointer:
5127 case DeclaratorChunk::Reference:
5128 case DeclaratorChunk::MemberPointer:
5129 // FIXME: Provide a source location for the _Atomic keyword.
5130 break;
5131 }
5132
5133 ATL.setKWLoc(Loc);
5134 ATL.setParensRange(SourceRange());
5135 }
5136
5137 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5138 ///
5139 /// \param T QualType referring to the type as written in source code.
5140 ///
5141 /// \param ReturnTypeInfo For declarators whose return type does not show
5142 /// up in the normal place in the declaration specifiers (such as a C++
5143 /// conversion function), this pointer will refer to a type source information
5144 /// for that return type.
5145 TypeSourceInfo *
GetTypeSourceInfoForDeclarator(Declarator & D,QualType T,TypeSourceInfo * ReturnTypeInfo)5146 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5147 TypeSourceInfo *ReturnTypeInfo) {
5148 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5149 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5150 const AttributeList *DeclAttrs = D.getAttributes();
5151
5152 // Handle parameter packs whose type is a pack expansion.
5153 if (isa<PackExpansionType>(T)) {
5154 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5155 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5156 }
5157
5158 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5159 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5160 // declarator chunk.
5161 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5162 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5163 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5164 }
5165
5166 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5167 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5168 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5169 }
5170
5171 // FIXME: Ordering here?
5172 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5173 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5174
5175 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5176 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5177 }
5178
5179 // If we have different source information for the return type, use
5180 // that. This really only applies to C++ conversion functions.
5181 if (ReturnTypeInfo) {
5182 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5183 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5184 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5185 } else {
5186 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5187 }
5188
5189 return TInfo;
5190 }
5191
5192 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
CreateParsedType(QualType T,TypeSourceInfo * TInfo)5193 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5194 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5195 // and Sema during declaration parsing. Try deallocating/caching them when
5196 // it's appropriate, instead of allocating them and keeping them around.
5197 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5198 TypeAlignment);
5199 new (LocT) LocInfoType(T, TInfo);
5200 assert(LocT->getTypeClass() != T->getTypeClass() &&
5201 "LocInfoType's TypeClass conflicts with an existing Type class");
5202 return ParsedType::make(QualType(LocT, 0));
5203 }
5204
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const5205 void LocInfoType::getAsStringInternal(std::string &Str,
5206 const PrintingPolicy &Policy) const {
5207 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5208 " was used directly instead of getting the QualType through"
5209 " GetTypeFromParser");
5210 }
5211
ActOnTypeName(Scope * S,Declarator & D)5212 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5213 // C99 6.7.6: Type names have no identifier. This is already validated by
5214 // the parser.
5215 assert(D.getIdentifier() == nullptr &&
5216 "Type name should have no identifier!");
5217
5218 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5219 QualType T = TInfo->getType();
5220 if (D.isInvalidType())
5221 return true;
5222
5223 // Make sure there are no unused decl attributes on the declarator.
5224 // We don't want to do this for ObjC parameters because we're going
5225 // to apply them to the actual parameter declaration.
5226 // Likewise, we don't want to do this for alias declarations, because
5227 // we are actually going to build a declaration from this eventually.
5228 if (D.getContext() != Declarator::ObjCParameterContext &&
5229 D.getContext() != Declarator::AliasDeclContext &&
5230 D.getContext() != Declarator::AliasTemplateContext)
5231 checkUnusedDeclAttributes(D);
5232
5233 if (getLangOpts().CPlusPlus) {
5234 // Check that there are no default arguments (C++ only).
5235 CheckExtraCXXDefaultArguments(D);
5236 }
5237
5238 return CreateParsedType(T, TInfo);
5239 }
5240
ActOnObjCInstanceType(SourceLocation Loc)5241 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5242 QualType T = Context.getObjCInstanceType();
5243 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5244 return CreateParsedType(T, TInfo);
5245 }
5246
5247 //===----------------------------------------------------------------------===//
5248 // Type Attribute Processing
5249 //===----------------------------------------------------------------------===//
5250
5251 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5252 /// specified type. The attribute contains 1 argument, the id of the address
5253 /// space for the type.
HandleAddressSpaceTypeAttribute(QualType & Type,const AttributeList & Attr,Sema & S)5254 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5255 const AttributeList &Attr, Sema &S){
5256
5257 // If this type is already address space qualified, reject it.
5258 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5259 // qualifiers for two or more different address spaces."
5260 if (Type.getAddressSpace()) {
5261 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5262 Attr.setInvalid();
5263 return;
5264 }
5265
5266 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5267 // qualified by an address-space qualifier."
5268 if (Type->isFunctionType()) {
5269 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5270 Attr.setInvalid();
5271 return;
5272 }
5273
5274 unsigned ASIdx;
5275 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5276 // Check the attribute arguments.
5277 if (Attr.getNumArgs() != 1) {
5278 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5279 << Attr.getName() << 1;
5280 Attr.setInvalid();
5281 return;
5282 }
5283 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5284 llvm::APSInt addrSpace(32);
5285 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5286 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5287 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5288 << Attr.getName() << AANT_ArgumentIntegerConstant
5289 << ASArgExpr->getSourceRange();
5290 Attr.setInvalid();
5291 return;
5292 }
5293
5294 // Bounds checking.
5295 if (addrSpace.isSigned()) {
5296 if (addrSpace.isNegative()) {
5297 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5298 << ASArgExpr->getSourceRange();
5299 Attr.setInvalid();
5300 return;
5301 }
5302 addrSpace.setIsSigned(false);
5303 }
5304 llvm::APSInt max(addrSpace.getBitWidth());
5305 max = Qualifiers::MaxAddressSpace;
5306 if (addrSpace > max) {
5307 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5308 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5309 Attr.setInvalid();
5310 return;
5311 }
5312 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5313 } else {
5314 // The keyword-based type attributes imply which address space to use.
5315 switch (Attr.getKind()) {
5316 case AttributeList::AT_OpenCLGlobalAddressSpace:
5317 ASIdx = LangAS::opencl_global; break;
5318 case AttributeList::AT_OpenCLLocalAddressSpace:
5319 ASIdx = LangAS::opencl_local; break;
5320 case AttributeList::AT_OpenCLConstantAddressSpace:
5321 ASIdx = LangAS::opencl_constant; break;
5322 case AttributeList::AT_OpenCLGenericAddressSpace:
5323 ASIdx = LangAS::opencl_generic; break;
5324 default:
5325 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5326 ASIdx = 0; break;
5327 }
5328 }
5329
5330 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5331 }
5332
5333 /// Does this type have a "direct" ownership qualifier? That is,
5334 /// is it written like "__strong id", as opposed to something like
5335 /// "typeof(foo)", where that happens to be strong?
hasDirectOwnershipQualifier(QualType type)5336 static bool hasDirectOwnershipQualifier(QualType type) {
5337 // Fast path: no qualifier at all.
5338 assert(type.getQualifiers().hasObjCLifetime());
5339
5340 while (true) {
5341 // __strong id
5342 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5343 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5344 return true;
5345
5346 type = attr->getModifiedType();
5347
5348 // X *__strong (...)
5349 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5350 type = paren->getInnerType();
5351
5352 // That's it for things we want to complain about. In particular,
5353 // we do not want to look through typedefs, typeof(expr),
5354 // typeof(type), or any other way that the type is somehow
5355 // abstracted.
5356 } else {
5357
5358 return false;
5359 }
5360 }
5361 }
5362
5363 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5364 /// attribute on the specified type.
5365 ///
5366 /// Returns 'true' if the attribute was handled.
handleObjCOwnershipTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)5367 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5368 AttributeList &attr,
5369 QualType &type) {
5370 bool NonObjCPointer = false;
5371
5372 if (!type->isDependentType() && !type->isUndeducedType()) {
5373 if (const PointerType *ptr = type->getAs<PointerType>()) {
5374 QualType pointee = ptr->getPointeeType();
5375 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5376 return false;
5377 // It is important not to lose the source info that there was an attribute
5378 // applied to non-objc pointer. We will create an attributed type but
5379 // its type will be the same as the original type.
5380 NonObjCPointer = true;
5381 } else if (!type->isObjCRetainableType()) {
5382 return false;
5383 }
5384
5385 // Don't accept an ownership attribute in the declspec if it would
5386 // just be the return type of a block pointer.
5387 if (state.isProcessingDeclSpec()) {
5388 Declarator &D = state.getDeclarator();
5389 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5390 /*onlyBlockPointers=*/true))
5391 return false;
5392 }
5393 }
5394
5395 Sema &S = state.getSema();
5396 SourceLocation AttrLoc = attr.getLoc();
5397 if (AttrLoc.isMacroID())
5398 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5399
5400 if (!attr.isArgIdent(0)) {
5401 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5402 << attr.getName() << AANT_ArgumentString;
5403 attr.setInvalid();
5404 return true;
5405 }
5406
5407 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5408 Qualifiers::ObjCLifetime lifetime;
5409 if (II->isStr("none"))
5410 lifetime = Qualifiers::OCL_ExplicitNone;
5411 else if (II->isStr("strong"))
5412 lifetime = Qualifiers::OCL_Strong;
5413 else if (II->isStr("weak"))
5414 lifetime = Qualifiers::OCL_Weak;
5415 else if (II->isStr("autoreleasing"))
5416 lifetime = Qualifiers::OCL_Autoreleasing;
5417 else {
5418 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5419 << attr.getName() << II;
5420 attr.setInvalid();
5421 return true;
5422 }
5423
5424 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5425 // outside of ARC mode.
5426 if (!S.getLangOpts().ObjCAutoRefCount &&
5427 lifetime != Qualifiers::OCL_Weak &&
5428 lifetime != Qualifiers::OCL_ExplicitNone) {
5429 return true;
5430 }
5431
5432 SplitQualType underlyingType = type.split();
5433
5434 // Check for redundant/conflicting ownership qualifiers.
5435 if (Qualifiers::ObjCLifetime previousLifetime
5436 = type.getQualifiers().getObjCLifetime()) {
5437 // If it's written directly, that's an error.
5438 if (hasDirectOwnershipQualifier(type)) {
5439 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5440 << type;
5441 return true;
5442 }
5443
5444 // Otherwise, if the qualifiers actually conflict, pull sugar off
5445 // and remove the ObjCLifetime qualifiers.
5446 if (previousLifetime != lifetime) {
5447 // It's possible to have multiple local ObjCLifetime qualifiers. We
5448 // can't stop after we reach a type that is directly qualified.
5449 const Type *prevTy = nullptr;
5450 while (!prevTy || prevTy != underlyingType.Ty) {
5451 prevTy = underlyingType.Ty;
5452 underlyingType = underlyingType.getSingleStepDesugaredType();
5453 }
5454 underlyingType.Quals.removeObjCLifetime();
5455 }
5456 }
5457
5458 underlyingType.Quals.addObjCLifetime(lifetime);
5459
5460 if (NonObjCPointer) {
5461 StringRef name = attr.getName()->getName();
5462 switch (lifetime) {
5463 case Qualifiers::OCL_None:
5464 case Qualifiers::OCL_ExplicitNone:
5465 break;
5466 case Qualifiers::OCL_Strong: name = "__strong"; break;
5467 case Qualifiers::OCL_Weak: name = "__weak"; break;
5468 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5469 }
5470 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5471 << TDS_ObjCObjOrBlock << type;
5472 }
5473
5474 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5475 // because having both 'T' and '__unsafe_unretained T' exist in the type
5476 // system causes unfortunate widespread consistency problems. (For example,
5477 // they're not considered compatible types, and we mangle them identicially
5478 // as template arguments.) These problems are all individually fixable,
5479 // but it's easier to just not add the qualifier and instead sniff it out
5480 // in specific places using isObjCInertUnsafeUnretainedType().
5481 //
5482 // Doing this does means we miss some trivial consistency checks that
5483 // would've triggered in ARC, but that's better than trying to solve all
5484 // the coexistence problems with __unsafe_unretained.
5485 if (!S.getLangOpts().ObjCAutoRefCount &&
5486 lifetime == Qualifiers::OCL_ExplicitNone) {
5487 type = S.Context.getAttributedType(
5488 AttributedType::attr_objc_inert_unsafe_unretained,
5489 type, type);
5490 return true;
5491 }
5492
5493 QualType origType = type;
5494 if (!NonObjCPointer)
5495 type = S.Context.getQualifiedType(underlyingType);
5496
5497 // If we have a valid source location for the attribute, use an
5498 // AttributedType instead.
5499 if (AttrLoc.isValid())
5500 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5501 origType, type);
5502
5503 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5504 unsigned diagnostic, QualType type) {
5505 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5506 S.DelayedDiagnostics.add(
5507 sema::DelayedDiagnostic::makeForbiddenType(
5508 S.getSourceManager().getExpansionLoc(loc),
5509 diagnostic, type, /*ignored*/ 0));
5510 } else {
5511 S.Diag(loc, diagnostic);
5512 }
5513 };
5514
5515 // Sometimes, __weak isn't allowed.
5516 if (lifetime == Qualifiers::OCL_Weak &&
5517 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5518
5519 // Use a specialized diagnostic if the runtime just doesn't support them.
5520 unsigned diagnostic =
5521 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5522 : diag::err_arc_weak_no_runtime);
5523
5524 // In any case, delay the diagnostic until we know what we're parsing.
5525 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5526
5527 attr.setInvalid();
5528 return true;
5529 }
5530
5531 // Forbid __weak for class objects marked as
5532 // objc_arc_weak_reference_unavailable
5533 if (lifetime == Qualifiers::OCL_Weak) {
5534 if (const ObjCObjectPointerType *ObjT =
5535 type->getAs<ObjCObjectPointerType>()) {
5536 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5537 if (Class->isArcWeakrefUnavailable()) {
5538 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5539 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5540 diag::note_class_declared);
5541 }
5542 }
5543 }
5544 }
5545
5546 return true;
5547 }
5548
5549 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5550 /// attribute on the specified type. Returns true to indicate that
5551 /// the attribute was handled, false to indicate that the type does
5552 /// not permit the attribute.
handleObjCGCTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)5553 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5554 AttributeList &attr,
5555 QualType &type) {
5556 Sema &S = state.getSema();
5557
5558 // Delay if this isn't some kind of pointer.
5559 if (!type->isPointerType() &&
5560 !type->isObjCObjectPointerType() &&
5561 !type->isBlockPointerType())
5562 return false;
5563
5564 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5565 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5566 attr.setInvalid();
5567 return true;
5568 }
5569
5570 // Check the attribute arguments.
5571 if (!attr.isArgIdent(0)) {
5572 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5573 << attr.getName() << AANT_ArgumentString;
5574 attr.setInvalid();
5575 return true;
5576 }
5577 Qualifiers::GC GCAttr;
5578 if (attr.getNumArgs() > 1) {
5579 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5580 << attr.getName() << 1;
5581 attr.setInvalid();
5582 return true;
5583 }
5584
5585 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5586 if (II->isStr("weak"))
5587 GCAttr = Qualifiers::Weak;
5588 else if (II->isStr("strong"))
5589 GCAttr = Qualifiers::Strong;
5590 else {
5591 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5592 << attr.getName() << II;
5593 attr.setInvalid();
5594 return true;
5595 }
5596
5597 QualType origType = type;
5598 type = S.Context.getObjCGCQualType(origType, GCAttr);
5599
5600 // Make an attributed type to preserve the source information.
5601 if (attr.getLoc().isValid())
5602 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5603 origType, type);
5604
5605 return true;
5606 }
5607
5608 namespace {
5609 /// A helper class to unwrap a type down to a function for the
5610 /// purposes of applying attributes there.
5611 ///
5612 /// Use:
5613 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5614 /// if (unwrapped.isFunctionType()) {
5615 /// const FunctionType *fn = unwrapped.get();
5616 /// // change fn somehow
5617 /// T = unwrapped.wrap(fn);
5618 /// }
5619 struct FunctionTypeUnwrapper {
5620 enum WrapKind {
5621 Desugar,
5622 Attributed,
5623 Parens,
5624 Pointer,
5625 BlockPointer,
5626 Reference,
5627 MemberPointer
5628 };
5629
5630 QualType Original;
5631 const FunctionType *Fn;
5632 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5633
FunctionTypeUnwrapper__anon0c34bf780d11::FunctionTypeUnwrapper5634 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5635 while (true) {
5636 const Type *Ty = T.getTypePtr();
5637 if (isa<FunctionType>(Ty)) {
5638 Fn = cast<FunctionType>(Ty);
5639 return;
5640 } else if (isa<ParenType>(Ty)) {
5641 T = cast<ParenType>(Ty)->getInnerType();
5642 Stack.push_back(Parens);
5643 } else if (isa<PointerType>(Ty)) {
5644 T = cast<PointerType>(Ty)->getPointeeType();
5645 Stack.push_back(Pointer);
5646 } else if (isa<BlockPointerType>(Ty)) {
5647 T = cast<BlockPointerType>(Ty)->getPointeeType();
5648 Stack.push_back(BlockPointer);
5649 } else if (isa<MemberPointerType>(Ty)) {
5650 T = cast<MemberPointerType>(Ty)->getPointeeType();
5651 Stack.push_back(MemberPointer);
5652 } else if (isa<ReferenceType>(Ty)) {
5653 T = cast<ReferenceType>(Ty)->getPointeeType();
5654 Stack.push_back(Reference);
5655 } else if (isa<AttributedType>(Ty)) {
5656 T = cast<AttributedType>(Ty)->getEquivalentType();
5657 Stack.push_back(Attributed);
5658 } else {
5659 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5660 if (Ty == DTy) {
5661 Fn = nullptr;
5662 return;
5663 }
5664
5665 T = QualType(DTy, 0);
5666 Stack.push_back(Desugar);
5667 }
5668 }
5669 }
5670
isFunctionType__anon0c34bf780d11::FunctionTypeUnwrapper5671 bool isFunctionType() const { return (Fn != nullptr); }
get__anon0c34bf780d11::FunctionTypeUnwrapper5672 const FunctionType *get() const { return Fn; }
5673
wrap__anon0c34bf780d11::FunctionTypeUnwrapper5674 QualType wrap(Sema &S, const FunctionType *New) {
5675 // If T wasn't modified from the unwrapped type, do nothing.
5676 if (New == get()) return Original;
5677
5678 Fn = New;
5679 return wrap(S.Context, Original, 0);
5680 }
5681
5682 private:
wrap__anon0c34bf780d11::FunctionTypeUnwrapper5683 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5684 if (I == Stack.size())
5685 return C.getQualifiedType(Fn, Old.getQualifiers());
5686
5687 // Build up the inner type, applying the qualifiers from the old
5688 // type to the new type.
5689 SplitQualType SplitOld = Old.split();
5690
5691 // As a special case, tail-recurse if there are no qualifiers.
5692 if (SplitOld.Quals.empty())
5693 return wrap(C, SplitOld.Ty, I);
5694 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5695 }
5696
wrap__anon0c34bf780d11::FunctionTypeUnwrapper5697 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5698 if (I == Stack.size()) return QualType(Fn, 0);
5699
5700 switch (static_cast<WrapKind>(Stack[I++])) {
5701 case Desugar:
5702 // This is the point at which we potentially lose source
5703 // information.
5704 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5705
5706 case Attributed:
5707 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5708
5709 case Parens: {
5710 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5711 return C.getParenType(New);
5712 }
5713
5714 case Pointer: {
5715 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5716 return C.getPointerType(New);
5717 }
5718
5719 case BlockPointer: {
5720 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5721 return C.getBlockPointerType(New);
5722 }
5723
5724 case MemberPointer: {
5725 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5726 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5727 return C.getMemberPointerType(New, OldMPT->getClass());
5728 }
5729
5730 case Reference: {
5731 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5732 QualType New = wrap(C, OldRef->getPointeeType(), I);
5733 if (isa<LValueReferenceType>(OldRef))
5734 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5735 else
5736 return C.getRValueReferenceType(New);
5737 }
5738 }
5739
5740 llvm_unreachable("unknown wrapping kind");
5741 }
5742 };
5743 } // end anonymous namespace
5744
handleMSPointerTypeQualifierAttr(TypeProcessingState & State,AttributeList & Attr,QualType & Type)5745 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5746 AttributeList &Attr,
5747 QualType &Type) {
5748 Sema &S = State.getSema();
5749
5750 AttributeList::Kind Kind = Attr.getKind();
5751 QualType Desugared = Type;
5752 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5753 while (AT) {
5754 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5755
5756 // You cannot specify duplicate type attributes, so if the attribute has
5757 // already been applied, flag it.
5758 if (getAttrListKind(CurAttrKind) == Kind) {
5759 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5760 << Attr.getName();
5761 return true;
5762 }
5763
5764 // You cannot have both __sptr and __uptr on the same type, nor can you
5765 // have __ptr32 and __ptr64.
5766 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5767 Kind == AttributeList::AT_Ptr64) ||
5768 (CurAttrKind == AttributedType::attr_ptr64 &&
5769 Kind == AttributeList::AT_Ptr32)) {
5770 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5771 << "'__ptr32'" << "'__ptr64'";
5772 return true;
5773 } else if ((CurAttrKind == AttributedType::attr_sptr &&
5774 Kind == AttributeList::AT_UPtr) ||
5775 (CurAttrKind == AttributedType::attr_uptr &&
5776 Kind == AttributeList::AT_SPtr)) {
5777 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5778 << "'__sptr'" << "'__uptr'";
5779 return true;
5780 }
5781
5782 Desugared = AT->getEquivalentType();
5783 AT = dyn_cast<AttributedType>(Desugared);
5784 }
5785
5786 // Pointer type qualifiers can only operate on pointer types, but not
5787 // pointer-to-member types.
5788 if (!isa<PointerType>(Desugared)) {
5789 if (Type->isMemberPointerType())
5790 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
5791 << Attr.getName();
5792 else
5793 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5794 << Attr.getName() << 0;
5795 return true;
5796 }
5797
5798 AttributedType::Kind TAK;
5799 switch (Kind) {
5800 default: llvm_unreachable("Unknown attribute kind");
5801 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5802 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5803 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5804 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5805 }
5806
5807 Type = S.Context.getAttributedType(TAK, Type, Type);
5808 return false;
5809 }
5810
checkNullabilityTypeSpecifier(QualType & type,NullabilityKind nullability,SourceLocation nullabilityLoc,bool isContextSensitive)5811 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5812 NullabilityKind nullability,
5813 SourceLocation nullabilityLoc,
5814 bool isContextSensitive) {
5815 // We saw a nullability type specifier. If this is the first one for
5816 // this file, note that.
5817 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5818 if (!file.isInvalid()) {
5819 FileNullability &fileNullability = NullabilityMap[file];
5820 if (!fileNullability.SawTypeNullability) {
5821 // If we have already seen a pointer declarator without a nullability
5822 // annotation, complain about it.
5823 if (fileNullability.PointerLoc.isValid()) {
5824 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5825 << static_cast<unsigned>(fileNullability.PointerKind);
5826 }
5827
5828 fileNullability.SawTypeNullability = true;
5829 }
5830 }
5831
5832 // Check for existing nullability attributes on the type.
5833 QualType desugared = type;
5834 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5835 // Check whether there is already a null
5836 if (auto existingNullability = attributed->getImmediateNullability()) {
5837 // Duplicated nullability.
5838 if (nullability == *existingNullability) {
5839 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5840 << DiagNullabilityKind(nullability, isContextSensitive)
5841 << FixItHint::CreateRemoval(nullabilityLoc);
5842
5843 break;
5844 }
5845
5846 // Conflicting nullability.
5847 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5848 << DiagNullabilityKind(nullability, isContextSensitive)
5849 << DiagNullabilityKind(*existingNullability, false);
5850 return true;
5851 }
5852
5853 desugared = attributed->getModifiedType();
5854 }
5855
5856 // If there is already a different nullability specifier, complain.
5857 // This (unlike the code above) looks through typedefs that might
5858 // have nullability specifiers on them, which means we cannot
5859 // provide a useful Fix-It.
5860 if (auto existingNullability = desugared->getNullability(Context)) {
5861 if (nullability != *existingNullability) {
5862 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5863 << DiagNullabilityKind(nullability, isContextSensitive)
5864 << DiagNullabilityKind(*existingNullability, false);
5865
5866 // Try to find the typedef with the existing nullability specifier.
5867 if (auto typedefType = desugared->getAs<TypedefType>()) {
5868 TypedefNameDecl *typedefDecl = typedefType->getDecl();
5869 QualType underlyingType = typedefDecl->getUnderlyingType();
5870 if (auto typedefNullability
5871 = AttributedType::stripOuterNullability(underlyingType)) {
5872 if (*typedefNullability == *existingNullability) {
5873 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5874 << DiagNullabilityKind(*existingNullability, false);
5875 }
5876 }
5877 }
5878
5879 return true;
5880 }
5881 }
5882
5883 // If this definitely isn't a pointer type, reject the specifier.
5884 if (!desugared->canHaveNullability()) {
5885 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5886 << DiagNullabilityKind(nullability, isContextSensitive) << type;
5887 return true;
5888 }
5889
5890 // For the context-sensitive keywords/Objective-C property
5891 // attributes, require that the type be a single-level pointer.
5892 if (isContextSensitive) {
5893 // Make sure that the pointee isn't itself a pointer type.
5894 QualType pointeeType = desugared->getPointeeType();
5895 if (pointeeType->isAnyPointerType() ||
5896 pointeeType->isObjCObjectPointerType() ||
5897 pointeeType->isMemberPointerType()) {
5898 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5899 << DiagNullabilityKind(nullability, true)
5900 << type;
5901 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5902 << DiagNullabilityKind(nullability, false)
5903 << type
5904 << FixItHint::CreateReplacement(nullabilityLoc,
5905 getNullabilitySpelling(nullability));
5906 return true;
5907 }
5908 }
5909
5910 // Form the attributed type.
5911 type = Context.getAttributedType(
5912 AttributedType::getNullabilityAttrKind(nullability), type, type);
5913 return false;
5914 }
5915
checkObjCKindOfType(QualType & type,SourceLocation loc)5916 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5917 // Find out if it's an Objective-C object or object pointer type;
5918 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5919 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5920 : type->getAs<ObjCObjectType>();
5921
5922 // If not, we can't apply __kindof.
5923 if (!objType) {
5924 // FIXME: Handle dependent types that aren't yet object types.
5925 Diag(loc, diag::err_objc_kindof_nonobject)
5926 << type;
5927 return true;
5928 }
5929
5930 // Rebuild the "equivalent" type, which pushes __kindof down into
5931 // the object type.
5932 // There is no need to apply kindof on an unqualified id type.
5933 QualType equivType = Context.getObjCObjectType(
5934 objType->getBaseType(), objType->getTypeArgsAsWritten(),
5935 objType->getProtocols(),
5936 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
5937
5938 // If we started with an object pointer type, rebuild it.
5939 if (ptrType) {
5940 equivType = Context.getObjCObjectPointerType(equivType);
5941 if (auto nullability = type->getNullability(Context)) {
5942 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5943 equivType = Context.getAttributedType(attrKind, equivType, equivType);
5944 }
5945 }
5946
5947 // Build the attributed type to record where __kindof occurred.
5948 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5949 type,
5950 equivType);
5951
5952 return false;
5953 }
5954
5955 /// Map a nullability attribute kind to a nullability kind.
mapNullabilityAttrKind(AttributeList::Kind kind)5956 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5957 switch (kind) {
5958 case AttributeList::AT_TypeNonNull:
5959 return NullabilityKind::NonNull;
5960
5961 case AttributeList::AT_TypeNullable:
5962 return NullabilityKind::Nullable;
5963
5964 case AttributeList::AT_TypeNullUnspecified:
5965 return NullabilityKind::Unspecified;
5966
5967 default:
5968 llvm_unreachable("not a nullability attribute kind");
5969 }
5970 }
5971
5972 /// Distribute a nullability type attribute that cannot be applied to
5973 /// the type specifier to a pointer, block pointer, or member pointer
5974 /// declarator, complaining if necessary.
5975 ///
5976 /// \returns true if the nullability annotation was distributed, false
5977 /// otherwise.
distributeNullabilityTypeAttr(TypeProcessingState & state,QualType type,AttributeList & attr)5978 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5979 QualType type,
5980 AttributeList &attr) {
5981 Declarator &declarator = state.getDeclarator();
5982
5983 /// Attempt to move the attribute to the specified chunk.
5984 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5985 // If there is already a nullability attribute there, don't add
5986 // one.
5987 if (hasNullabilityAttr(chunk.getAttrListRef()))
5988 return false;
5989
5990 // Complain about the nullability qualifier being in the wrong
5991 // place.
5992 enum {
5993 PK_Pointer,
5994 PK_BlockPointer,
5995 PK_MemberPointer,
5996 PK_FunctionPointer,
5997 PK_MemberFunctionPointer,
5998 } pointerKind
5999 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6000 : PK_Pointer)
6001 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6002 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6003
6004 auto diag = state.getSema().Diag(attr.getLoc(),
6005 diag::warn_nullability_declspec)
6006 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6007 attr.isContextSensitiveKeywordAttribute())
6008 << type
6009 << static_cast<unsigned>(pointerKind);
6010
6011 // FIXME: MemberPointer chunks don't carry the location of the *.
6012 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6013 diag << FixItHint::CreateRemoval(attr.getLoc())
6014 << FixItHint::CreateInsertion(
6015 state.getSema().getPreprocessor()
6016 .getLocForEndOfToken(chunk.Loc),
6017 " " + attr.getName()->getName().str() + " ");
6018 }
6019
6020 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6021 chunk.getAttrListRef());
6022 return true;
6023 };
6024
6025 // Move it to the outermost pointer, member pointer, or block
6026 // pointer declarator.
6027 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6028 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6029 switch (chunk.Kind) {
6030 case DeclaratorChunk::Pointer:
6031 case DeclaratorChunk::BlockPointer:
6032 case DeclaratorChunk::MemberPointer:
6033 return moveToChunk(chunk, false);
6034
6035 case DeclaratorChunk::Paren:
6036 case DeclaratorChunk::Array:
6037 continue;
6038
6039 case DeclaratorChunk::Function:
6040 // Try to move past the return type to a function/block/member
6041 // function pointer.
6042 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6043 declarator, i,
6044 /*onlyBlockPointers=*/false)) {
6045 return moveToChunk(*dest, true);
6046 }
6047
6048 return false;
6049
6050 // Don't walk through these.
6051 case DeclaratorChunk::Reference:
6052 case DeclaratorChunk::Pipe:
6053 return false;
6054 }
6055 }
6056
6057 return false;
6058 }
6059
getCCTypeAttrKind(AttributeList & Attr)6060 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6061 assert(!Attr.isInvalid());
6062 switch (Attr.getKind()) {
6063 default:
6064 llvm_unreachable("not a calling convention attribute");
6065 case AttributeList::AT_CDecl:
6066 return AttributedType::attr_cdecl;
6067 case AttributeList::AT_FastCall:
6068 return AttributedType::attr_fastcall;
6069 case AttributeList::AT_StdCall:
6070 return AttributedType::attr_stdcall;
6071 case AttributeList::AT_ThisCall:
6072 return AttributedType::attr_thiscall;
6073 case AttributeList::AT_Pascal:
6074 return AttributedType::attr_pascal;
6075 case AttributeList::AT_SwiftCall:
6076 return AttributedType::attr_swiftcall;
6077 case AttributeList::AT_VectorCall:
6078 return AttributedType::attr_vectorcall;
6079 case AttributeList::AT_Pcs: {
6080 // The attribute may have had a fixit applied where we treated an
6081 // identifier as a string literal. The contents of the string are valid,
6082 // but the form may not be.
6083 StringRef Str;
6084 if (Attr.isArgExpr(0))
6085 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6086 else
6087 Str = Attr.getArgAsIdent(0)->Ident->getName();
6088 return llvm::StringSwitch<AttributedType::Kind>(Str)
6089 .Case("aapcs", AttributedType::attr_pcs)
6090 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6091 }
6092 case AttributeList::AT_IntelOclBicc:
6093 return AttributedType::attr_inteloclbicc;
6094 case AttributeList::AT_MSABI:
6095 return AttributedType::attr_ms_abi;
6096 case AttributeList::AT_SysVABI:
6097 return AttributedType::attr_sysv_abi;
6098 case AttributeList::AT_PreserveMost:
6099 return AttributedType::attr_preserve_most;
6100 case AttributeList::AT_PreserveAll:
6101 return AttributedType::attr_preserve_all;
6102 }
6103 llvm_unreachable("unexpected attribute kind!");
6104 }
6105
6106 /// Process an individual function attribute. Returns true to
6107 /// indicate that the attribute was handled, false if it wasn't.
handleFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)6108 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6109 AttributeList &attr,
6110 QualType &type) {
6111 Sema &S = state.getSema();
6112
6113 FunctionTypeUnwrapper unwrapped(S, type);
6114
6115 if (attr.getKind() == AttributeList::AT_NoReturn) {
6116 if (S.CheckNoReturnAttr(attr))
6117 return true;
6118
6119 // Delay if this is not a function type.
6120 if (!unwrapped.isFunctionType())
6121 return false;
6122
6123 // Otherwise we can process right away.
6124 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6125 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6126 return true;
6127 }
6128
6129 // ns_returns_retained is not always a type attribute, but if we got
6130 // here, we're treating it as one right now.
6131 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6132 assert(S.getLangOpts().ObjCAutoRefCount &&
6133 "ns_returns_retained treated as type attribute in non-ARC");
6134 if (attr.getNumArgs()) return true;
6135
6136 // Delay if this is not a function type.
6137 if (!unwrapped.isFunctionType())
6138 return false;
6139
6140 FunctionType::ExtInfo EI
6141 = unwrapped.get()->getExtInfo().withProducesResult(true);
6142 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6143 return true;
6144 }
6145
6146 if (attr.getKind() == AttributeList::AT_Regparm) {
6147 unsigned value;
6148 if (S.CheckRegparmAttr(attr, value))
6149 return true;
6150
6151 // Delay if this is not a function type.
6152 if (!unwrapped.isFunctionType())
6153 return false;
6154
6155 // Diagnose regparm with fastcall.
6156 const FunctionType *fn = unwrapped.get();
6157 CallingConv CC = fn->getCallConv();
6158 if (CC == CC_X86FastCall) {
6159 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6160 << FunctionType::getNameForCallConv(CC)
6161 << "regparm";
6162 attr.setInvalid();
6163 return true;
6164 }
6165
6166 FunctionType::ExtInfo EI =
6167 unwrapped.get()->getExtInfo().withRegParm(value);
6168 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6169 return true;
6170 }
6171
6172 // Delay if the type didn't work out to a function.
6173 if (!unwrapped.isFunctionType()) return false;
6174
6175 // Otherwise, a calling convention.
6176 CallingConv CC;
6177 if (S.CheckCallingConvAttr(attr, CC))
6178 return true;
6179
6180 const FunctionType *fn = unwrapped.get();
6181 CallingConv CCOld = fn->getCallConv();
6182 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6183
6184 if (CCOld != CC) {
6185 // Error out on when there's already an attribute on the type
6186 // and the CCs don't match.
6187 const AttributedType *AT = S.getCallingConvAttributedType(type);
6188 if (AT && AT->getAttrKind() != CCAttrKind) {
6189 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6190 << FunctionType::getNameForCallConv(CC)
6191 << FunctionType::getNameForCallConv(CCOld);
6192 attr.setInvalid();
6193 return true;
6194 }
6195 }
6196
6197 // Diagnose use of variadic functions with calling conventions that
6198 // don't support them (e.g. because they're callee-cleanup).
6199 // We delay warning about this on unprototyped function declarations
6200 // until after redeclaration checking, just in case we pick up a
6201 // prototype that way. And apparently we also "delay" warning about
6202 // unprototyped function types in general, despite not necessarily having
6203 // much ability to diagnose it later.
6204 if (!supportsVariadicCall(CC)) {
6205 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6206 if (FnP && FnP->isVariadic()) {
6207 unsigned DiagID = diag::err_cconv_varargs;
6208
6209 // stdcall and fastcall are ignored with a warning for GCC and MS
6210 // compatibility.
6211 bool IsInvalid = true;
6212 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6213 DiagID = diag::warn_cconv_varargs;
6214 IsInvalid = false;
6215 }
6216
6217 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6218 if (IsInvalid) attr.setInvalid();
6219 return true;
6220 }
6221 }
6222
6223 // Also diagnose fastcall with regparm.
6224 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6225 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6226 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6227 attr.setInvalid();
6228 return true;
6229 }
6230
6231 // Modify the CC from the wrapped function type, wrap it all back, and then
6232 // wrap the whole thing in an AttributedType as written. The modified type
6233 // might have a different CC if we ignored the attribute.
6234 QualType Equivalent;
6235 if (CCOld == CC) {
6236 Equivalent = type;
6237 } else {
6238 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6239 Equivalent =
6240 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6241 }
6242 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6243 return true;
6244 }
6245
hasExplicitCallingConv(QualType & T)6246 bool Sema::hasExplicitCallingConv(QualType &T) {
6247 QualType R = T.IgnoreParens();
6248 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6249 if (AT->isCallingConv())
6250 return true;
6251 R = AT->getModifiedType().IgnoreParens();
6252 }
6253 return false;
6254 }
6255
adjustMemberFunctionCC(QualType & T,bool IsStatic,bool IsCtorOrDtor,SourceLocation Loc)6256 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6257 SourceLocation Loc) {
6258 FunctionTypeUnwrapper Unwrapped(*this, T);
6259 const FunctionType *FT = Unwrapped.get();
6260 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6261 cast<FunctionProtoType>(FT)->isVariadic());
6262 CallingConv CurCC = FT->getCallConv();
6263 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6264
6265 if (CurCC == ToCC)
6266 return;
6267
6268 // MS compiler ignores explicit calling convention attributes on structors. We
6269 // should do the same.
6270 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6271 // Issue a warning on ignored calling convention -- except of __stdcall.
6272 // Again, this is what MS compiler does.
6273 if (CurCC != CC_X86StdCall)
6274 Diag(Loc, diag::warn_cconv_structors)
6275 << FunctionType::getNameForCallConv(CurCC);
6276 // Default adjustment.
6277 } else {
6278 // Only adjust types with the default convention. For example, on Windows
6279 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6280 // __thiscall type to __cdecl for static methods.
6281 CallingConv DefaultCC =
6282 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6283
6284 if (CurCC != DefaultCC || DefaultCC == ToCC)
6285 return;
6286
6287 if (hasExplicitCallingConv(T))
6288 return;
6289 }
6290
6291 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6292 QualType Wrapped = Unwrapped.wrap(*this, FT);
6293 T = Context.getAdjustedType(T, Wrapped);
6294 }
6295
6296 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6297 /// and float scalars, although arrays, pointers, and function return values are
6298 /// allowed in conjunction with this construct. Aggregates with this attribute
6299 /// are invalid, even if they are of the same size as a corresponding scalar.
6300 /// The raw attribute should contain precisely 1 argument, the vector size for
6301 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6302 /// this routine will return a new vector type.
HandleVectorSizeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)6303 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6304 Sema &S) {
6305 // Check the attribute arguments.
6306 if (Attr.getNumArgs() != 1) {
6307 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6308 << Attr.getName() << 1;
6309 Attr.setInvalid();
6310 return;
6311 }
6312 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6313 llvm::APSInt vecSize(32);
6314 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6315 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6316 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6317 << Attr.getName() << AANT_ArgumentIntegerConstant
6318 << sizeExpr->getSourceRange();
6319 Attr.setInvalid();
6320 return;
6321 }
6322 // The base type must be integer (not Boolean or enumeration) or float, and
6323 // can't already be a vector.
6324 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6325 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6326 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6327 Attr.setInvalid();
6328 return;
6329 }
6330 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6331 // vecSize is specified in bytes - convert to bits.
6332 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6333
6334 // the vector size needs to be an integral multiple of the type size.
6335 if (vectorSize % typeSize) {
6336 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6337 << sizeExpr->getSourceRange();
6338 Attr.setInvalid();
6339 return;
6340 }
6341 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6342 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6343 << sizeExpr->getSourceRange();
6344 Attr.setInvalid();
6345 return;
6346 }
6347 if (vectorSize == 0) {
6348 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6349 << sizeExpr->getSourceRange();
6350 Attr.setInvalid();
6351 return;
6352 }
6353
6354 // Success! Instantiate the vector type, the number of elements is > 0, and
6355 // not required to be a power of 2, unlike GCC.
6356 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6357 VectorType::GenericVector);
6358 }
6359
6360 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6361 /// a type.
HandleExtVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)6362 static void HandleExtVectorTypeAttr(QualType &CurType,
6363 const AttributeList &Attr,
6364 Sema &S) {
6365 // check the attribute arguments.
6366 if (Attr.getNumArgs() != 1) {
6367 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6368 << Attr.getName() << 1;
6369 return;
6370 }
6371
6372 Expr *sizeExpr;
6373
6374 // Special case where the argument is a template id.
6375 if (Attr.isArgIdent(0)) {
6376 CXXScopeSpec SS;
6377 SourceLocation TemplateKWLoc;
6378 UnqualifiedId id;
6379 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6380
6381 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6382 id, false, false);
6383 if (Size.isInvalid())
6384 return;
6385
6386 sizeExpr = Size.get();
6387 } else {
6388 sizeExpr = Attr.getArgAsExpr(0);
6389 }
6390
6391 // Create the vector type.
6392 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6393 if (!T.isNull())
6394 CurType = T;
6395 }
6396
isPermittedNeonBaseType(QualType & Ty,VectorType::VectorKind VecKind,Sema & S)6397 static bool isPermittedNeonBaseType(QualType &Ty,
6398 VectorType::VectorKind VecKind, Sema &S) {
6399 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6400 if (!BTy)
6401 return false;
6402
6403 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6404
6405 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6406 // now.
6407 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6408 Triple.getArch() == llvm::Triple::aarch64_be;
6409 if (VecKind == VectorType::NeonPolyVector) {
6410 if (IsPolyUnsigned) {
6411 // AArch64 polynomial vectors are unsigned and support poly64.
6412 return BTy->getKind() == BuiltinType::UChar ||
6413 BTy->getKind() == BuiltinType::UShort ||
6414 BTy->getKind() == BuiltinType::ULong ||
6415 BTy->getKind() == BuiltinType::ULongLong;
6416 } else {
6417 // AArch32 polynomial vector are signed.
6418 return BTy->getKind() == BuiltinType::SChar ||
6419 BTy->getKind() == BuiltinType::Short;
6420 }
6421 }
6422
6423 // Non-polynomial vector types: the usual suspects are allowed, as well as
6424 // float64_t on AArch64.
6425 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6426 Triple.getArch() == llvm::Triple::aarch64_be;
6427
6428 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6429 return true;
6430
6431 return BTy->getKind() == BuiltinType::SChar ||
6432 BTy->getKind() == BuiltinType::UChar ||
6433 BTy->getKind() == BuiltinType::Short ||
6434 BTy->getKind() == BuiltinType::UShort ||
6435 BTy->getKind() == BuiltinType::Int ||
6436 BTy->getKind() == BuiltinType::UInt ||
6437 BTy->getKind() == BuiltinType::Long ||
6438 BTy->getKind() == BuiltinType::ULong ||
6439 BTy->getKind() == BuiltinType::LongLong ||
6440 BTy->getKind() == BuiltinType::ULongLong ||
6441 BTy->getKind() == BuiltinType::Float ||
6442 BTy->getKind() == BuiltinType::Half;
6443 }
6444
6445 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6446 /// "neon_polyvector_type" attributes are used to create vector types that
6447 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6448 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6449 /// the argument to these Neon attributes is the number of vector elements,
6450 /// not the vector size in bytes. The vector width and element type must
6451 /// match one of the standard Neon vector types.
HandleNeonVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S,VectorType::VectorKind VecKind)6452 static void HandleNeonVectorTypeAttr(QualType& CurType,
6453 const AttributeList &Attr, Sema &S,
6454 VectorType::VectorKind VecKind) {
6455 // Target must have NEON
6456 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6457 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6458 Attr.setInvalid();
6459 return;
6460 }
6461 // Check the attribute arguments.
6462 if (Attr.getNumArgs() != 1) {
6463 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6464 << Attr.getName() << 1;
6465 Attr.setInvalid();
6466 return;
6467 }
6468 // The number of elements must be an ICE.
6469 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6470 llvm::APSInt numEltsInt(32);
6471 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6472 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6473 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6474 << Attr.getName() << AANT_ArgumentIntegerConstant
6475 << numEltsExpr->getSourceRange();
6476 Attr.setInvalid();
6477 return;
6478 }
6479 // Only certain element types are supported for Neon vectors.
6480 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6481 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6482 Attr.setInvalid();
6483 return;
6484 }
6485
6486 // The total size of the vector must be 64 or 128 bits.
6487 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6488 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6489 unsigned vecSize = typeSize * numElts;
6490 if (vecSize != 64 && vecSize != 128) {
6491 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6492 Attr.setInvalid();
6493 return;
6494 }
6495
6496 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6497 }
6498
6499 /// Handle OpenCL Access Qualifier Attribute.
HandleOpenCLAccessAttr(QualType & CurType,const AttributeList & Attr,Sema & S)6500 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6501 Sema &S) {
6502 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6503 if (!(CurType->isImageType() || CurType->isPipeType())) {
6504 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6505 Attr.setInvalid();
6506 return;
6507 }
6508
6509 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6510 QualType PointeeTy = TypedefTy->desugar();
6511 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6512
6513 std::string PrevAccessQual;
6514 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6515 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6516 case BuiltinType::Id: \
6517 PrevAccessQual = #Access; \
6518 break;
6519 #include "clang/Basic/OpenCLImageTypes.def"
6520 default:
6521 assert(0 && "Unable to find corresponding image type.");
6522 }
6523
6524 S.Diag(TypedefTy->getDecl()->getLocStart(),
6525 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6526 }
6527 }
6528
processTypeAttrs(TypeProcessingState & state,QualType & type,TypeAttrLocation TAL,AttributeList * attrs)6529 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6530 TypeAttrLocation TAL, AttributeList *attrs) {
6531 // Scan through and apply attributes to this type where it makes sense. Some
6532 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6533 // type, but others can be present in the type specifiers even though they
6534 // apply to the decl. Here we apply type attributes and ignore the rest.
6535
6536 bool hasOpenCLAddressSpace = false;
6537 while (attrs) {
6538 AttributeList &attr = *attrs;
6539 attrs = attr.getNext(); // reset to the next here due to early loop continue
6540 // stmts
6541
6542 // Skip attributes that were marked to be invalid.
6543 if (attr.isInvalid())
6544 continue;
6545
6546 if (attr.isCXX11Attribute()) {
6547 // [[gnu::...]] attributes are treated as declaration attributes, so may
6548 // not appertain to a DeclaratorChunk, even if we handle them as type
6549 // attributes.
6550 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6551 if (TAL == TAL_DeclChunk) {
6552 state.getSema().Diag(attr.getLoc(),
6553 diag::warn_cxx11_gnu_attribute_on_type)
6554 << attr.getName();
6555 continue;
6556 }
6557 } else if (TAL != TAL_DeclChunk) {
6558 // Otherwise, only consider type processing for a C++11 attribute if
6559 // it's actually been applied to a type.
6560 continue;
6561 }
6562 }
6563
6564 // If this is an attribute we can handle, do so now,
6565 // otherwise, add it to the FnAttrs list for rechaining.
6566 switch (attr.getKind()) {
6567 default:
6568 // A C++11 attribute on a declarator chunk must appertain to a type.
6569 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6570 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6571 << attr.getName();
6572 attr.setUsedAsTypeAttr();
6573 }
6574 break;
6575
6576 case AttributeList::UnknownAttribute:
6577 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6578 state.getSema().Diag(attr.getLoc(),
6579 diag::warn_unknown_attribute_ignored)
6580 << attr.getName();
6581 break;
6582
6583 case AttributeList::IgnoredAttribute:
6584 break;
6585
6586 case AttributeList::AT_MayAlias:
6587 // FIXME: This attribute needs to actually be handled, but if we ignore
6588 // it it breaks large amounts of Linux software.
6589 attr.setUsedAsTypeAttr();
6590 break;
6591 case AttributeList::AT_OpenCLPrivateAddressSpace:
6592 case AttributeList::AT_OpenCLGlobalAddressSpace:
6593 case AttributeList::AT_OpenCLLocalAddressSpace:
6594 case AttributeList::AT_OpenCLConstantAddressSpace:
6595 case AttributeList::AT_OpenCLGenericAddressSpace:
6596 case AttributeList::AT_AddressSpace:
6597 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6598 attr.setUsedAsTypeAttr();
6599 hasOpenCLAddressSpace = true;
6600 break;
6601 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6602 if (!handleObjCPointerTypeAttr(state, attr, type))
6603 distributeObjCPointerTypeAttr(state, attr, type);
6604 attr.setUsedAsTypeAttr();
6605 break;
6606 case AttributeList::AT_VectorSize:
6607 HandleVectorSizeAttr(type, attr, state.getSema());
6608 attr.setUsedAsTypeAttr();
6609 break;
6610 case AttributeList::AT_ExtVectorType:
6611 HandleExtVectorTypeAttr(type, attr, state.getSema());
6612 attr.setUsedAsTypeAttr();
6613 break;
6614 case AttributeList::AT_NeonVectorType:
6615 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6616 VectorType::NeonVector);
6617 attr.setUsedAsTypeAttr();
6618 break;
6619 case AttributeList::AT_NeonPolyVectorType:
6620 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6621 VectorType::NeonPolyVector);
6622 attr.setUsedAsTypeAttr();
6623 break;
6624 case AttributeList::AT_OpenCLAccess:
6625 HandleOpenCLAccessAttr(type, attr, state.getSema());
6626 attr.setUsedAsTypeAttr();
6627 break;
6628
6629 MS_TYPE_ATTRS_CASELIST:
6630 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6631 attr.setUsedAsTypeAttr();
6632 break;
6633
6634
6635 NULLABILITY_TYPE_ATTRS_CASELIST:
6636 // Either add nullability here or try to distribute it. We
6637 // don't want to distribute the nullability specifier past any
6638 // dependent type, because that complicates the user model.
6639 if (type->canHaveNullability() || type->isDependentType() ||
6640 !distributeNullabilityTypeAttr(state, type, attr)) {
6641 if (state.getSema().checkNullabilityTypeSpecifier(
6642 type,
6643 mapNullabilityAttrKind(attr.getKind()),
6644 attr.getLoc(),
6645 attr.isContextSensitiveKeywordAttribute())) {
6646 attr.setInvalid();
6647 }
6648
6649 attr.setUsedAsTypeAttr();
6650 }
6651 break;
6652
6653 case AttributeList::AT_ObjCKindOf:
6654 // '__kindof' must be part of the decl-specifiers.
6655 switch (TAL) {
6656 case TAL_DeclSpec:
6657 break;
6658
6659 case TAL_DeclChunk:
6660 case TAL_DeclName:
6661 state.getSema().Diag(attr.getLoc(),
6662 diag::err_objc_kindof_wrong_position)
6663 << FixItHint::CreateRemoval(attr.getLoc())
6664 << FixItHint::CreateInsertion(
6665 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6666 break;
6667 }
6668
6669 // Apply it regardless.
6670 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6671 attr.setInvalid();
6672 attr.setUsedAsTypeAttr();
6673 break;
6674
6675 case AttributeList::AT_NSReturnsRetained:
6676 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6677 break;
6678 // fallthrough into the function attrs
6679
6680 FUNCTION_TYPE_ATTRS_CASELIST:
6681 attr.setUsedAsTypeAttr();
6682
6683 // Never process function type attributes as part of the
6684 // declaration-specifiers.
6685 if (TAL == TAL_DeclSpec)
6686 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6687
6688 // Otherwise, handle the possible delays.
6689 else if (!handleFunctionTypeAttr(state, attr, type))
6690 distributeFunctionTypeAttr(state, attr, type);
6691 break;
6692 }
6693 }
6694
6695 // If address space is not set, OpenCL 2.0 defines non private default
6696 // address spaces for some cases:
6697 // OpenCL 2.0, section 6.5:
6698 // The address space for a variable at program scope or a static variable
6699 // inside a function can either be __global or __constant, but defaults to
6700 // __global if not specified.
6701 // (...)
6702 // Pointers that are declared without pointing to a named address space point
6703 // to the generic address space.
6704 if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6705 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6706 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6707 Declarator &D = state.getDeclarator();
6708 if (state.getCurrentChunkIndex() > 0 &&
6709 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6710 DeclaratorChunk::Pointer) {
6711 type = state.getSema().Context.getAddrSpaceQualType(
6712 type, LangAS::opencl_generic);
6713 } else if (state.getCurrentChunkIndex() == 0 &&
6714 D.getContext() == Declarator::FileContext &&
6715 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6716 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6717 !type->isSamplerT())
6718 type = state.getSema().Context.getAddrSpaceQualType(
6719 type, LangAS::opencl_global);
6720 else if (state.getCurrentChunkIndex() == 0 &&
6721 D.getContext() == Declarator::BlockContext &&
6722 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6723 type = state.getSema().Context.getAddrSpaceQualType(
6724 type, LangAS::opencl_global);
6725 }
6726 }
6727
completeExprArrayBound(Expr * E)6728 void Sema::completeExprArrayBound(Expr *E) {
6729 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6730 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6731 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6732 SourceLocation PointOfInstantiation = E->getExprLoc();
6733
6734 if (MemberSpecializationInfo *MSInfo =
6735 Var->getMemberSpecializationInfo()) {
6736 // If we don't already have a point of instantiation, this is it.
6737 if (MSInfo->getPointOfInstantiation().isInvalid()) {
6738 MSInfo->setPointOfInstantiation(PointOfInstantiation);
6739
6740 // This is a modification of an existing AST node. Notify
6741 // listeners.
6742 if (ASTMutationListener *L = getASTMutationListener())
6743 L->StaticDataMemberInstantiated(Var);
6744 }
6745 } else {
6746 VarTemplateSpecializationDecl *VarSpec =
6747 cast<VarTemplateSpecializationDecl>(Var);
6748 if (VarSpec->getPointOfInstantiation().isInvalid())
6749 VarSpec->setPointOfInstantiation(PointOfInstantiation);
6750 }
6751
6752 InstantiateVariableDefinition(PointOfInstantiation, Var);
6753
6754 // Update the type to the newly instantiated definition's type both
6755 // here and within the expression.
6756 if (VarDecl *Def = Var->getDefinition()) {
6757 DRE->setDecl(Def);
6758 QualType T = Def->getType();
6759 DRE->setType(T);
6760 // FIXME: Update the type on all intervening expressions.
6761 E->setType(T);
6762 }
6763
6764 // We still go on to try to complete the type independently, as it
6765 // may also require instantiations or diagnostics if it remains
6766 // incomplete.
6767 }
6768 }
6769 }
6770 }
6771
6772 /// \brief Ensure that the type of the given expression is complete.
6773 ///
6774 /// This routine checks whether the expression \p E has a complete type. If the
6775 /// expression refers to an instantiable construct, that instantiation is
6776 /// performed as needed to complete its type. Furthermore
6777 /// Sema::RequireCompleteType is called for the expression's type (or in the
6778 /// case of a reference type, the referred-to type).
6779 ///
6780 /// \param E The expression whose type is required to be complete.
6781 /// \param Diagnoser The object that will emit a diagnostic if the type is
6782 /// incomplete.
6783 ///
6784 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6785 /// otherwise.
RequireCompleteExprType(Expr * E,TypeDiagnoser & Diagnoser)6786 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6787 QualType T = E->getType();
6788
6789 // Incomplete array types may be completed by the initializer attached to
6790 // their definitions. For static data members of class templates and for
6791 // variable templates, we need to instantiate the definition to get this
6792 // initializer and complete the type.
6793 if (T->isIncompleteArrayType()) {
6794 completeExprArrayBound(E);
6795 T = E->getType();
6796 }
6797
6798 // FIXME: Are there other cases which require instantiating something other
6799 // than the type to complete the type of an expression?
6800
6801 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6802 }
6803
RequireCompleteExprType(Expr * E,unsigned DiagID)6804 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6805 BoundTypeDiagnoser<> Diagnoser(DiagID);
6806 return RequireCompleteExprType(E, Diagnoser);
6807 }
6808
6809 /// @brief Ensure that the type T is a complete type.
6810 ///
6811 /// This routine checks whether the type @p T is complete in any
6812 /// context where a complete type is required. If @p T is a complete
6813 /// type, returns false. If @p T is a class template specialization,
6814 /// this routine then attempts to perform class template
6815 /// instantiation. If instantiation fails, or if @p T is incomplete
6816 /// and cannot be completed, issues the diagnostic @p diag (giving it
6817 /// the type @p T) and returns true.
6818 ///
6819 /// @param Loc The location in the source that the incomplete type
6820 /// diagnostic should refer to.
6821 ///
6822 /// @param T The type that this routine is examining for completeness.
6823 ///
6824 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6825 /// @c false otherwise.
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)6826 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6827 TypeDiagnoser &Diagnoser) {
6828 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6829 return true;
6830 if (const TagType *Tag = T->getAs<TagType>()) {
6831 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6832 Tag->getDecl()->setCompleteDefinitionRequired();
6833 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6834 }
6835 }
6836 return false;
6837 }
6838
6839 /// \brief Determine whether there is any declaration of \p D that was ever a
6840 /// definition (perhaps before module merging) and is currently visible.
6841 /// \param D The definition of the entity.
6842 /// \param Suggested Filled in with the declaration that should be made visible
6843 /// in order to provide a definition of this entity.
6844 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6845 /// not defined. This only matters for enums with a fixed underlying
6846 /// type, since in all other cases, a type is complete if and only if it
6847 /// is defined.
hasVisibleDefinition(NamedDecl * D,NamedDecl ** Suggested,bool OnlyNeedComplete)6848 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6849 bool OnlyNeedComplete) {
6850 // Easy case: if we don't have modules, all declarations are visible.
6851 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6852 return true;
6853
6854 // If this definition was instantiated from a template, map back to the
6855 // pattern from which it was instantiated.
6856 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6857 // We're in the middle of defining it; this definition should be treated
6858 // as visible.
6859 return true;
6860 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6861 if (auto *Pattern = RD->getTemplateInstantiationPattern())
6862 RD = Pattern;
6863 D = RD->getDefinition();
6864 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6865 if (auto *Pattern = ED->getTemplateInstantiationPattern())
6866 ED = Pattern;
6867 if (OnlyNeedComplete && ED->isFixed()) {
6868 // If the enum has a fixed underlying type, and we're only looking for a
6869 // complete type (not a definition), any visible declaration of it will
6870 // do.
6871 *Suggested = nullptr;
6872 for (auto *Redecl : ED->redecls()) {
6873 if (isVisible(Redecl))
6874 return true;
6875 if (Redecl->isThisDeclarationADefinition() ||
6876 (Redecl->isCanonicalDecl() && !*Suggested))
6877 *Suggested = Redecl;
6878 }
6879 return false;
6880 }
6881 D = ED->getDefinition();
6882 }
6883 assert(D && "missing definition for pattern of instantiated definition");
6884
6885 *Suggested = D;
6886 if (isVisible(D))
6887 return true;
6888
6889 // The external source may have additional definitions of this type that are
6890 // visible, so complete the redeclaration chain now and ask again.
6891 if (auto *Source = Context.getExternalSource()) {
6892 Source->CompleteRedeclChain(D);
6893 return isVisible(D);
6894 }
6895
6896 return false;
6897 }
6898
6899 /// Locks in the inheritance model for the given class and all of its bases.
assignInheritanceModel(Sema & S,CXXRecordDecl * RD)6900 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6901 RD = RD->getMostRecentDecl();
6902 if (!RD->hasAttr<MSInheritanceAttr>()) {
6903 MSInheritanceAttr::Spelling IM;
6904
6905 switch (S.MSPointerToMemberRepresentationMethod) {
6906 case LangOptions::PPTMK_BestCase:
6907 IM = RD->calculateInheritanceModel();
6908 break;
6909 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6910 IM = MSInheritanceAttr::Keyword_single_inheritance;
6911 break;
6912 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6913 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6914 break;
6915 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6916 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6917 break;
6918 }
6919
6920 RD->addAttr(MSInheritanceAttr::CreateImplicit(
6921 S.getASTContext(), IM,
6922 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6923 LangOptions::PPTMK_BestCase,
6924 S.ImplicitMSInheritanceAttrLoc.isValid()
6925 ? S.ImplicitMSInheritanceAttrLoc
6926 : RD->getSourceRange()));
6927 S.Consumer.AssignInheritanceModel(RD);
6928 }
6929 }
6930
6931 /// \brief The implementation of RequireCompleteType
RequireCompleteTypeImpl(SourceLocation Loc,QualType T,TypeDiagnoser * Diagnoser)6932 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6933 TypeDiagnoser *Diagnoser) {
6934 // FIXME: Add this assertion to make sure we always get instantiation points.
6935 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6936 // FIXME: Add this assertion to help us flush out problems with
6937 // checking for dependent types and type-dependent expressions.
6938 //
6939 // assert(!T->isDependentType() &&
6940 // "Can't ask whether a dependent type is complete");
6941
6942 // We lock in the inheritance model once somebody has asked us to ensure
6943 // that a pointer-to-member type is complete.
6944 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6945 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6946 if (!MPTy->getClass()->isDependentType()) {
6947 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
6948 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6949 }
6950 }
6951 }
6952
6953 NamedDecl *Def = nullptr;
6954 bool Incomplete = T->isIncompleteType(&Def);
6955
6956 // Check that any necessary explicit specializations are visible. For an
6957 // enum, we just need the declaration, so don't check this.
6958 if (Def && !isa<EnumDecl>(Def))
6959 checkSpecializationVisibility(Loc, Def);
6960
6961 // If we have a complete type, we're done.
6962 if (!Incomplete) {
6963 // If we know about the definition but it is not visible, complain.
6964 NamedDecl *SuggestedDef = nullptr;
6965 if (Def &&
6966 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
6967 // If the user is going to see an error here, recover by making the
6968 // definition visible.
6969 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
6970 if (Diagnoser)
6971 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
6972 /*Recover*/TreatAsComplete);
6973 return !TreatAsComplete;
6974 }
6975
6976 return false;
6977 }
6978
6979 const TagType *Tag = T->getAs<TagType>();
6980 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6981
6982 // If there's an unimported definition of this type in a module (for
6983 // instance, because we forward declared it, then imported the definition),
6984 // import that definition now.
6985 //
6986 // FIXME: What about other cases where an import extends a redeclaration
6987 // chain for a declaration that can be accessed through a mechanism other
6988 // than name lookup (eg, referenced in a template, or a variable whose type
6989 // could be completed by the module)?
6990 //
6991 // FIXME: Should we map through to the base array element type before
6992 // checking for a tag type?
6993 if (Tag || IFace) {
6994 NamedDecl *D =
6995 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6996
6997 // Avoid diagnosing invalid decls as incomplete.
6998 if (D->isInvalidDecl())
6999 return true;
7000
7001 // Give the external AST source a chance to complete the type.
7002 if (auto *Source = Context.getExternalSource()) {
7003 if (Tag)
7004 Source->CompleteType(Tag->getDecl());
7005 else
7006 Source->CompleteType(IFace->getDecl());
7007
7008 // If the external source completed the type, go through the motions
7009 // again to ensure we're allowed to use the completed type.
7010 if (!T->isIncompleteType())
7011 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7012 }
7013 }
7014
7015 // If we have a class template specialization or a class member of a
7016 // class template specialization, or an array with known size of such,
7017 // try to instantiate it.
7018 QualType MaybeTemplate = T;
7019 while (const ConstantArrayType *Array
7020 = Context.getAsConstantArrayType(MaybeTemplate))
7021 MaybeTemplate = Array->getElementType();
7022 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7023 bool Instantiated = false;
7024 bool Diagnosed = false;
7025 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7026 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7027 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7028 Diagnosed = InstantiateClassTemplateSpecialization(
7029 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7030 /*Complain=*/Diagnoser);
7031 Instantiated = true;
7032 }
7033 } else if (CXXRecordDecl *Rec
7034 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7035 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7036 if (!Rec->isBeingDefined() && Pattern) {
7037 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7038 assert(MSI && "Missing member specialization information?");
7039 // This record was instantiated from a class within a template.
7040 if (MSI->getTemplateSpecializationKind() !=
7041 TSK_ExplicitSpecialization) {
7042 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7043 getTemplateInstantiationArgs(Rec),
7044 TSK_ImplicitInstantiation,
7045 /*Complain=*/Diagnoser);
7046 Instantiated = true;
7047 }
7048 }
7049 }
7050
7051 if (Instantiated) {
7052 // Instantiate* might have already complained that the template is not
7053 // defined, if we asked it to.
7054 if (Diagnoser && Diagnosed)
7055 return true;
7056 // If we instantiated a definition, check that it's usable, even if
7057 // instantiation produced an error, so that repeated calls to this
7058 // function give consistent answers.
7059 if (!T->isIncompleteType())
7060 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7061 }
7062 }
7063
7064 // FIXME: If we didn't instantiate a definition because of an explicit
7065 // specialization declaration, check that it's visible.
7066
7067 if (!Diagnoser)
7068 return true;
7069
7070 Diagnoser->diagnose(*this, Loc, T);
7071
7072 // If the type was a forward declaration of a class/struct/union
7073 // type, produce a note.
7074 if (Tag && !Tag->getDecl()->isInvalidDecl())
7075 Diag(Tag->getDecl()->getLocation(),
7076 Tag->isBeingDefined() ? diag::note_type_being_defined
7077 : diag::note_forward_declaration)
7078 << QualType(Tag, 0);
7079
7080 // If the Objective-C class was a forward declaration, produce a note.
7081 if (IFace && !IFace->getDecl()->isInvalidDecl())
7082 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7083
7084 // If we have external information that we can use to suggest a fix,
7085 // produce a note.
7086 if (ExternalSource)
7087 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7088
7089 return true;
7090 }
7091
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)7092 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7093 unsigned DiagID) {
7094 BoundTypeDiagnoser<> Diagnoser(DiagID);
7095 return RequireCompleteType(Loc, T, Diagnoser);
7096 }
7097
7098 /// \brief Get diagnostic %select index for tag kind for
7099 /// literal type diagnostic message.
7100 /// WARNING: Indexes apply to particular diagnostics only!
7101 ///
7102 /// \returns diagnostic %select index.
getLiteralDiagFromTagKind(TagTypeKind Tag)7103 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7104 switch (Tag) {
7105 case TTK_Struct: return 0;
7106 case TTK_Interface: return 1;
7107 case TTK_Class: return 2;
7108 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7109 }
7110 }
7111
7112 /// @brief Ensure that the type T is a literal type.
7113 ///
7114 /// This routine checks whether the type @p T is a literal type. If @p T is an
7115 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7116 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7117 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7118 /// it the type @p T), along with notes explaining why the type is not a
7119 /// literal type, and returns true.
7120 ///
7121 /// @param Loc The location in the source that the non-literal type
7122 /// diagnostic should refer to.
7123 ///
7124 /// @param T The type that this routine is examining for literalness.
7125 ///
7126 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7127 ///
7128 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7129 /// @c false otherwise.
RequireLiteralType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)7130 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7131 TypeDiagnoser &Diagnoser) {
7132 assert(!T->isDependentType() && "type should not be dependent");
7133
7134 QualType ElemType = Context.getBaseElementType(T);
7135 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7136 T->isLiteralType(Context))
7137 return false;
7138
7139 Diagnoser.diagnose(*this, Loc, T);
7140
7141 if (T->isVariableArrayType())
7142 return true;
7143
7144 const RecordType *RT = ElemType->getAs<RecordType>();
7145 if (!RT)
7146 return true;
7147
7148 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7149
7150 // A partially-defined class type can't be a literal type, because a literal
7151 // class type must have a trivial destructor (which can't be checked until
7152 // the class definition is complete).
7153 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7154 return true;
7155
7156 // If the class has virtual base classes, then it's not an aggregate, and
7157 // cannot have any constexpr constructors or a trivial default constructor,
7158 // so is non-literal. This is better to diagnose than the resulting absence
7159 // of constexpr constructors.
7160 if (RD->getNumVBases()) {
7161 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7162 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7163 for (const auto &I : RD->vbases())
7164 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7165 << I.getSourceRange();
7166 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7167 !RD->hasTrivialDefaultConstructor()) {
7168 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7169 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7170 for (const auto &I : RD->bases()) {
7171 if (!I.getType()->isLiteralType(Context)) {
7172 Diag(I.getLocStart(),
7173 diag::note_non_literal_base_class)
7174 << RD << I.getType() << I.getSourceRange();
7175 return true;
7176 }
7177 }
7178 for (const auto *I : RD->fields()) {
7179 if (!I->getType()->isLiteralType(Context) ||
7180 I->getType().isVolatileQualified()) {
7181 Diag(I->getLocation(), diag::note_non_literal_field)
7182 << RD << I << I->getType()
7183 << I->getType().isVolatileQualified();
7184 return true;
7185 }
7186 }
7187 } else if (!RD->hasTrivialDestructor()) {
7188 // All fields and bases are of literal types, so have trivial destructors.
7189 // If this class's destructor is non-trivial it must be user-declared.
7190 CXXDestructorDecl *Dtor = RD->getDestructor();
7191 assert(Dtor && "class has literal fields and bases but no dtor?");
7192 if (!Dtor)
7193 return true;
7194
7195 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7196 diag::note_non_literal_user_provided_dtor :
7197 diag::note_non_literal_nontrivial_dtor) << RD;
7198 if (!Dtor->isUserProvided())
7199 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7200 }
7201
7202 return true;
7203 }
7204
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID)7205 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7206 BoundTypeDiagnoser<> Diagnoser(DiagID);
7207 return RequireLiteralType(Loc, T, Diagnoser);
7208 }
7209
7210 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7211 /// and qualified by the nested-name-specifier contained in SS.
getElaboratedType(ElaboratedTypeKeyword Keyword,const CXXScopeSpec & SS,QualType T)7212 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7213 const CXXScopeSpec &SS, QualType T) {
7214 if (T.isNull())
7215 return T;
7216 NestedNameSpecifier *NNS;
7217 if (SS.isValid())
7218 NNS = SS.getScopeRep();
7219 else {
7220 if (Keyword == ETK_None)
7221 return T;
7222 NNS = nullptr;
7223 }
7224 return Context.getElaboratedType(Keyword, NNS, T);
7225 }
7226
BuildTypeofExprType(Expr * E,SourceLocation Loc)7227 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7228 ExprResult ER = CheckPlaceholderExpr(E);
7229 if (ER.isInvalid()) return QualType();
7230 E = ER.get();
7231
7232 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7233 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7234
7235 if (!E->isTypeDependent()) {
7236 QualType T = E->getType();
7237 if (const TagType *TT = T->getAs<TagType>())
7238 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7239 }
7240 return Context.getTypeOfExprType(E);
7241 }
7242
7243 /// getDecltypeForExpr - Given an expr, will return the decltype for
7244 /// that expression, according to the rules in C++11
7245 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
getDecltypeForExpr(Sema & S,Expr * E)7246 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7247 if (E->isTypeDependent())
7248 return S.Context.DependentTy;
7249
7250 // C++11 [dcl.type.simple]p4:
7251 // The type denoted by decltype(e) is defined as follows:
7252 //
7253 // - if e is an unparenthesized id-expression or an unparenthesized class
7254 // member access (5.2.5), decltype(e) is the type of the entity named
7255 // by e. If there is no such entity, or if e names a set of overloaded
7256 // functions, the program is ill-formed;
7257 //
7258 // We apply the same rules for Objective-C ivar and property references.
7259 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7260 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7261 return VD->getType();
7262 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7263 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7264 return FD->getType();
7265 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7266 return IR->getDecl()->getType();
7267 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7268 if (PR->isExplicitProperty())
7269 return PR->getExplicitProperty()->getType();
7270 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7271 return PE->getType();
7272 }
7273
7274 // C++11 [expr.lambda.prim]p18:
7275 // Every occurrence of decltype((x)) where x is a possibly
7276 // parenthesized id-expression that names an entity of automatic
7277 // storage duration is treated as if x were transformed into an
7278 // access to a corresponding data member of the closure type that
7279 // would have been declared if x were an odr-use of the denoted
7280 // entity.
7281 using namespace sema;
7282 if (S.getCurLambda()) {
7283 if (isa<ParenExpr>(E)) {
7284 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7285 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7286 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7287 if (!T.isNull())
7288 return S.Context.getLValueReferenceType(T);
7289 }
7290 }
7291 }
7292 }
7293
7294
7295 // C++11 [dcl.type.simple]p4:
7296 // [...]
7297 QualType T = E->getType();
7298 switch (E->getValueKind()) {
7299 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7300 // type of e;
7301 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7302 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7303 // type of e;
7304 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7305 // - otherwise, decltype(e) is the type of e.
7306 case VK_RValue: break;
7307 }
7308
7309 return T;
7310 }
7311
BuildDecltypeType(Expr * E,SourceLocation Loc,bool AsUnevaluated)7312 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7313 bool AsUnevaluated) {
7314 ExprResult ER = CheckPlaceholderExpr(E);
7315 if (ER.isInvalid()) return QualType();
7316 E = ER.get();
7317
7318 if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7319 E->HasSideEffects(Context, false)) {
7320 // The expression operand for decltype is in an unevaluated expression
7321 // context, so side effects could result in unintended consequences.
7322 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7323 }
7324
7325 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7326 }
7327
BuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)7328 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7329 UnaryTransformType::UTTKind UKind,
7330 SourceLocation Loc) {
7331 switch (UKind) {
7332 case UnaryTransformType::EnumUnderlyingType:
7333 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7334 Diag(Loc, diag::err_only_enums_have_underlying_types);
7335 return QualType();
7336 } else {
7337 QualType Underlying = BaseType;
7338 if (!BaseType->isDependentType()) {
7339 // The enum could be incomplete if we're parsing its definition or
7340 // recovering from an error.
7341 NamedDecl *FwdDecl = nullptr;
7342 if (BaseType->isIncompleteType(&FwdDecl)) {
7343 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7344 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7345 return QualType();
7346 }
7347
7348 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7349 assert(ED && "EnumType has no EnumDecl");
7350
7351 DiagnoseUseOfDecl(ED, Loc);
7352
7353 Underlying = ED->getIntegerType();
7354 assert(!Underlying.isNull());
7355 }
7356 return Context.getUnaryTransformType(BaseType, Underlying,
7357 UnaryTransformType::EnumUnderlyingType);
7358 }
7359 }
7360 llvm_unreachable("unknown unary transform type");
7361 }
7362
BuildAtomicType(QualType T,SourceLocation Loc)7363 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7364 if (!T->isDependentType()) {
7365 // FIXME: It isn't entirely clear whether incomplete atomic types
7366 // are allowed or not; for simplicity, ban them for the moment.
7367 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7368 return QualType();
7369
7370 int DisallowedKind = -1;
7371 if (T->isArrayType())
7372 DisallowedKind = 1;
7373 else if (T->isFunctionType())
7374 DisallowedKind = 2;
7375 else if (T->isReferenceType())
7376 DisallowedKind = 3;
7377 else if (T->isAtomicType())
7378 DisallowedKind = 4;
7379 else if (T.hasQualifiers())
7380 DisallowedKind = 5;
7381 else if (!T.isTriviallyCopyableType(Context))
7382 // Some other non-trivially-copyable type (probably a C++ class)
7383 DisallowedKind = 6;
7384
7385 if (DisallowedKind != -1) {
7386 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7387 return QualType();
7388 }
7389
7390 // FIXME: Do we need any handling for ARC here?
7391 }
7392
7393 // Build the pointer type.
7394 return Context.getAtomicType(T);
7395 }
7396