1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTStructuralEquivalence.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/Specifiers.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/DelayedDiagnostic.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/Template.h"
37#include "clang/Sema/TemplateInstCallback.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <bitset>
44#include <optional>
45
46using namespace clang;
47
48enum TypeDiagSelector {
49  TDS_Function,
50  TDS_Pointer,
51  TDS_ObjCObjOrBlock
52};
53
54/// isOmittedBlockReturnType - Return true if this declarator is missing a
55/// return type because this is a omitted return type on a block literal.
56static bool isOmittedBlockReturnType(const Declarator &D) {
57  if (D.getContext() != DeclaratorContext::BlockLiteral ||
58      D.getDeclSpec().hasTypeSpecifier())
59    return false;
60
61  if (D.getNumTypeObjects() == 0)
62    return true;   // ^{ ... }
63
64  if (D.getNumTypeObjects() == 1 &&
65      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
66    return true;   // ^(int X, float Y) { ... }
67
68  return false;
69}
70
71/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
72/// doesn't apply to the given type.
73static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
74                                     QualType type) {
75  TypeDiagSelector WhichType;
76  bool useExpansionLoc = true;
77  switch (attr.getKind()) {
78  case ParsedAttr::AT_ObjCGC:
79    WhichType = TDS_Pointer;
80    break;
81  case ParsedAttr::AT_ObjCOwnership:
82    WhichType = TDS_ObjCObjOrBlock;
83    break;
84  default:
85    // Assume everything else was a function attribute.
86    WhichType = TDS_Function;
87    useExpansionLoc = false;
88    break;
89  }
90
91  SourceLocation loc = attr.getLoc();
92  StringRef name = attr.getAttrName()->getName();
93
94  // The GC attributes are usually written with macros;  special-case them.
95  IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
96                                          : nullptr;
97  if (useExpansionLoc && loc.isMacroID() && II) {
98    if (II->isStr("strong")) {
99      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
100    } else if (II->isStr("weak")) {
101      if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
102    }
103  }
104
105  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
106    << type;
107}
108
109// objc_gc applies to Objective-C pointers or, otherwise, to the
110// smallest available pointer type (i.e. 'void*' in 'void**').
111#define OBJC_POINTER_TYPE_ATTRS_CASELIST                                       \
112  case ParsedAttr::AT_ObjCGC:                                                  \
113  case ParsedAttr::AT_ObjCOwnership
114
115// Calling convention attributes.
116#define CALLING_CONV_ATTRS_CASELIST                                            \
117  case ParsedAttr::AT_CDecl:                                                   \
118  case ParsedAttr::AT_FastCall:                                                \
119  case ParsedAttr::AT_StdCall:                                                 \
120  case ParsedAttr::AT_ThisCall:                                                \
121  case ParsedAttr::AT_RegCall:                                                 \
122  case ParsedAttr::AT_Pascal:                                                  \
123  case ParsedAttr::AT_SwiftCall:                                               \
124  case ParsedAttr::AT_SwiftAsyncCall:                                          \
125  case ParsedAttr::AT_VectorCall:                                              \
126  case ParsedAttr::AT_AArch64VectorPcs:                                        \
127  case ParsedAttr::AT_AArch64SVEPcs:                                           \
128  case ParsedAttr::AT_AMDGPUKernelCall:                                        \
129  case ParsedAttr::AT_MSABI:                                                   \
130  case ParsedAttr::AT_SysVABI:                                                 \
131  case ParsedAttr::AT_Pcs:                                                     \
132  case ParsedAttr::AT_IntelOclBicc:                                            \
133  case ParsedAttr::AT_PreserveMost:                                            \
134  case ParsedAttr::AT_PreserveAll
135
136// Function type attributes.
137#define FUNCTION_TYPE_ATTRS_CASELIST                                           \
138  case ParsedAttr::AT_NSReturnsRetained:                                       \
139  case ParsedAttr::AT_NoReturn:                                                \
140  case ParsedAttr::AT_Regparm:                                                 \
141  case ParsedAttr::AT_CmseNSCall:                                              \
142  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
143  case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
144    CALLING_CONV_ATTRS_CASELIST
145
146// Microsoft-specific type qualifiers.
147#define MS_TYPE_ATTRS_CASELIST                                                 \
148  case ParsedAttr::AT_Ptr32:                                                   \
149  case ParsedAttr::AT_Ptr64:                                                   \
150  case ParsedAttr::AT_SPtr:                                                    \
151  case ParsedAttr::AT_UPtr
152
153// Nullability qualifiers.
154#define NULLABILITY_TYPE_ATTRS_CASELIST                                        \
155  case ParsedAttr::AT_TypeNonNull:                                             \
156  case ParsedAttr::AT_TypeNullable:                                            \
157  case ParsedAttr::AT_TypeNullableResult:                                      \
158  case ParsedAttr::AT_TypeNullUnspecified
159
160namespace {
161  /// An object which stores processing state for the entire
162  /// GetTypeForDeclarator process.
163  class TypeProcessingState {
164    Sema &sema;
165
166    /// The declarator being processed.
167    Declarator &declarator;
168
169    /// The index of the declarator chunk we're currently processing.
170    /// May be the total number of valid chunks, indicating the
171    /// DeclSpec.
172    unsigned chunkIndex;
173
174    /// The original set of attributes on the DeclSpec.
175    SmallVector<ParsedAttr *, 2> savedAttrs;
176
177    /// A list of attributes to diagnose the uselessness of when the
178    /// processing is complete.
179    SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
180
181    /// Attributes corresponding to AttributedTypeLocs that we have not yet
182    /// populated.
183    // FIXME: The two-phase mechanism by which we construct Types and fill
184    // their TypeLocs makes it hard to correctly assign these. We keep the
185    // attributes in creation order as an attempt to make them line up
186    // properly.
187    using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
188    SmallVector<TypeAttrPair, 8> AttrsForTypes;
189    bool AttrsForTypesSorted = true;
190
191    /// MacroQualifiedTypes mapping to macro expansion locations that will be
192    /// stored in a MacroQualifiedTypeLoc.
193    llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
194
195    /// Flag to indicate we parsed a noderef attribute. This is used for
196    /// validating that noderef was used on a pointer or array.
197    bool parsedNoDeref;
198
199  public:
200    TypeProcessingState(Sema &sema, Declarator &declarator)
201        : sema(sema), declarator(declarator),
202          chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
203
204    Sema &getSema() const {
205      return sema;
206    }
207
208    Declarator &getDeclarator() const {
209      return declarator;
210    }
211
212    bool isProcessingDeclSpec() const {
213      return chunkIndex == declarator.getNumTypeObjects();
214    }
215
216    unsigned getCurrentChunkIndex() const {
217      return chunkIndex;
218    }
219
220    void setCurrentChunkIndex(unsigned idx) {
221      assert(idx <= declarator.getNumTypeObjects());
222      chunkIndex = idx;
223    }
224
225    ParsedAttributesView &getCurrentAttributes() const {
226      if (isProcessingDeclSpec())
227        return getMutableDeclSpec().getAttributes();
228      return declarator.getTypeObject(chunkIndex).getAttrs();
229    }
230
231    /// Save the current set of attributes on the DeclSpec.
232    void saveDeclSpecAttrs() {
233      // Don't try to save them multiple times.
234      if (!savedAttrs.empty())
235        return;
236
237      DeclSpec &spec = getMutableDeclSpec();
238      llvm::append_range(savedAttrs,
239                         llvm::make_pointer_range(spec.getAttributes()));
240    }
241
242    /// Record that we had nowhere to put the given type attribute.
243    /// We will diagnose such attributes later.
244    void addIgnoredTypeAttr(ParsedAttr &attr) {
245      ignoredTypeAttrs.push_back(&attr);
246    }
247
248    /// Diagnose all the ignored type attributes, given that the
249    /// declarator worked out to the given type.
250    void diagnoseIgnoredTypeAttrs(QualType type) const {
251      for (auto *Attr : ignoredTypeAttrs)
252        diagnoseBadTypeAttribute(getSema(), *Attr, type);
253    }
254
255    /// Get an attributed type for the given attribute, and remember the Attr
256    /// object so that we can attach it to the AttributedTypeLoc.
257    QualType getAttributedType(Attr *A, QualType ModifiedType,
258                               QualType EquivType) {
259      QualType T =
260          sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
261      AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
262      AttrsForTypesSorted = false;
263      return T;
264    }
265
266    /// Get a BTFTagAttributed type for the btf_type_tag attribute.
267    QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
268                                     QualType WrappedType) {
269      return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
270    }
271
272    /// Completely replace the \c auto in \p TypeWithAuto by
273    /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
274    /// necessary.
275    QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
276      QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
277      if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
278        // Attributed type still should be an attributed type after replacement.
279        auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
280        for (TypeAttrPair &A : AttrsForTypes) {
281          if (A.first == AttrTy)
282            A.first = NewAttrTy;
283        }
284        AttrsForTypesSorted = false;
285      }
286      return T;
287    }
288
289    /// Extract and remove the Attr* for a given attributed type.
290    const Attr *takeAttrForAttributedType(const AttributedType *AT) {
291      if (!AttrsForTypesSorted) {
292        llvm::stable_sort(AttrsForTypes, llvm::less_first());
293        AttrsForTypesSorted = true;
294      }
295
296      // FIXME: This is quadratic if we have lots of reuses of the same
297      // attributed type.
298      for (auto It = std::partition_point(
299               AttrsForTypes.begin(), AttrsForTypes.end(),
300               [=](const TypeAttrPair &A) { return A.first < AT; });
301           It != AttrsForTypes.end() && It->first == AT; ++It) {
302        if (It->second) {
303          const Attr *Result = It->second;
304          It->second = nullptr;
305          return Result;
306        }
307      }
308
309      llvm_unreachable("no Attr* for AttributedType*");
310    }
311
312    SourceLocation
313    getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
314      auto FoundLoc = LocsForMacros.find(MQT);
315      assert(FoundLoc != LocsForMacros.end() &&
316             "Unable to find macro expansion location for MacroQualifedType");
317      return FoundLoc->second;
318    }
319
320    void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
321                                              SourceLocation Loc) {
322      LocsForMacros[MQT] = Loc;
323    }
324
325    void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
326
327    bool didParseNoDeref() const { return parsedNoDeref; }
328
329    ~TypeProcessingState() {
330      if (savedAttrs.empty())
331        return;
332
333      getMutableDeclSpec().getAttributes().clearListOnly();
334      for (ParsedAttr *AL : savedAttrs)
335        getMutableDeclSpec().getAttributes().addAtEnd(AL);
336    }
337
338  private:
339    DeclSpec &getMutableDeclSpec() const {
340      return const_cast<DeclSpec&>(declarator.getDeclSpec());
341    }
342  };
343} // end anonymous namespace
344
345static void moveAttrFromListToList(ParsedAttr &attr,
346                                   ParsedAttributesView &fromList,
347                                   ParsedAttributesView &toList) {
348  fromList.remove(&attr);
349  toList.addAtEnd(&attr);
350}
351
352/// The location of a type attribute.
353enum TypeAttrLocation {
354  /// The attribute is in the decl-specifier-seq.
355  TAL_DeclSpec,
356  /// The attribute is part of a DeclaratorChunk.
357  TAL_DeclChunk,
358  /// The attribute is immediately after the declaration's name.
359  TAL_DeclName
360};
361
362static void processTypeAttrs(TypeProcessingState &state, QualType &type,
363                             TypeAttrLocation TAL,
364                             const ParsedAttributesView &attrs);
365
366static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
367                                   QualType &type);
368
369static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
370                                             ParsedAttr &attr, QualType &type);
371
372static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
373                                 QualType &type);
374
375static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
376                                        ParsedAttr &attr, QualType &type);
377
378static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
379                                      ParsedAttr &attr, QualType &type) {
380  if (attr.getKind() == ParsedAttr::AT_ObjCGC)
381    return handleObjCGCTypeAttr(state, attr, type);
382  assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
383  return handleObjCOwnershipTypeAttr(state, attr, type);
384}
385
386/// Given the index of a declarator chunk, check whether that chunk
387/// directly specifies the return type of a function and, if so, find
388/// an appropriate place for it.
389///
390/// \param i - a notional index which the search will start
391///   immediately inside
392///
393/// \param onlyBlockPointers Whether we should only look into block
394/// pointer types (vs. all pointer types).
395static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
396                                                unsigned i,
397                                                bool onlyBlockPointers) {
398  assert(i <= declarator.getNumTypeObjects());
399
400  DeclaratorChunk *result = nullptr;
401
402  // First, look inwards past parens for a function declarator.
403  for (; i != 0; --i) {
404    DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
405    switch (fnChunk.Kind) {
406    case DeclaratorChunk::Paren:
407      continue;
408
409    // If we find anything except a function, bail out.
410    case DeclaratorChunk::Pointer:
411    case DeclaratorChunk::BlockPointer:
412    case DeclaratorChunk::Array:
413    case DeclaratorChunk::Reference:
414    case DeclaratorChunk::MemberPointer:
415    case DeclaratorChunk::Pipe:
416      return result;
417
418    // If we do find a function declarator, scan inwards from that,
419    // looking for a (block-)pointer declarator.
420    case DeclaratorChunk::Function:
421      for (--i; i != 0; --i) {
422        DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
423        switch (ptrChunk.Kind) {
424        case DeclaratorChunk::Paren:
425        case DeclaratorChunk::Array:
426        case DeclaratorChunk::Function:
427        case DeclaratorChunk::Reference:
428        case DeclaratorChunk::Pipe:
429          continue;
430
431        case DeclaratorChunk::MemberPointer:
432        case DeclaratorChunk::Pointer:
433          if (onlyBlockPointers)
434            continue;
435
436          [[fallthrough]];
437
438        case DeclaratorChunk::BlockPointer:
439          result = &ptrChunk;
440          goto continue_outer;
441        }
442        llvm_unreachable("bad declarator chunk kind");
443      }
444
445      // If we run out of declarators doing that, we're done.
446      return result;
447    }
448    llvm_unreachable("bad declarator chunk kind");
449
450    // Okay, reconsider from our new point.
451  continue_outer: ;
452  }
453
454  // Ran out of chunks, bail out.
455  return result;
456}
457
458/// Given that an objc_gc attribute was written somewhere on a
459/// declaration *other* than on the declarator itself (for which, use
460/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
461/// didn't apply in whatever position it was written in, try to move
462/// it to a more appropriate position.
463static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
464                                          ParsedAttr &attr, QualType type) {
465  Declarator &declarator = state.getDeclarator();
466
467  // Move it to the outermost normal or block pointer declarator.
468  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
469    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
470    switch (chunk.Kind) {
471    case DeclaratorChunk::Pointer:
472    case DeclaratorChunk::BlockPointer: {
473      // But don't move an ARC ownership attribute to the return type
474      // of a block.
475      DeclaratorChunk *destChunk = nullptr;
476      if (state.isProcessingDeclSpec() &&
477          attr.getKind() == ParsedAttr::AT_ObjCOwnership)
478        destChunk = maybeMovePastReturnType(declarator, i - 1,
479                                            /*onlyBlockPointers=*/true);
480      if (!destChunk) destChunk = &chunk;
481
482      moveAttrFromListToList(attr, state.getCurrentAttributes(),
483                             destChunk->getAttrs());
484      return;
485    }
486
487    case DeclaratorChunk::Paren:
488    case DeclaratorChunk::Array:
489      continue;
490
491    // We may be starting at the return type of a block.
492    case DeclaratorChunk::Function:
493      if (state.isProcessingDeclSpec() &&
494          attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
495        if (DeclaratorChunk *dest = maybeMovePastReturnType(
496                                      declarator, i,
497                                      /*onlyBlockPointers=*/true)) {
498          moveAttrFromListToList(attr, state.getCurrentAttributes(),
499                                 dest->getAttrs());
500          return;
501        }
502      }
503      goto error;
504
505    // Don't walk through these.
506    case DeclaratorChunk::Reference:
507    case DeclaratorChunk::MemberPointer:
508    case DeclaratorChunk::Pipe:
509      goto error;
510    }
511  }
512 error:
513
514  diagnoseBadTypeAttribute(state.getSema(), attr, type);
515}
516
517/// Distribute an objc_gc type attribute that was written on the
518/// declarator.
519static void distributeObjCPointerTypeAttrFromDeclarator(
520    TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
521  Declarator &declarator = state.getDeclarator();
522
523  // objc_gc goes on the innermost pointer to something that's not a
524  // pointer.
525  unsigned innermost = -1U;
526  bool considerDeclSpec = true;
527  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
528    DeclaratorChunk &chunk = declarator.getTypeObject(i);
529    switch (chunk.Kind) {
530    case DeclaratorChunk::Pointer:
531    case DeclaratorChunk::BlockPointer:
532      innermost = i;
533      continue;
534
535    case DeclaratorChunk::Reference:
536    case DeclaratorChunk::MemberPointer:
537    case DeclaratorChunk::Paren:
538    case DeclaratorChunk::Array:
539    case DeclaratorChunk::Pipe:
540      continue;
541
542    case DeclaratorChunk::Function:
543      considerDeclSpec = false;
544      goto done;
545    }
546  }
547 done:
548
549  // That might actually be the decl spec if we weren't blocked by
550  // anything in the declarator.
551  if (considerDeclSpec) {
552    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
553      // Splice the attribute into the decl spec.  Prevents the
554      // attribute from being applied multiple times and gives
555      // the source-location-filler something to work with.
556      state.saveDeclSpecAttrs();
557      declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
558          declarator.getAttributes(), &attr);
559      return;
560    }
561  }
562
563  // Otherwise, if we found an appropriate chunk, splice the attribute
564  // into it.
565  if (innermost != -1U) {
566    moveAttrFromListToList(attr, declarator.getAttributes(),
567                           declarator.getTypeObject(innermost).getAttrs());
568    return;
569  }
570
571  // Otherwise, diagnose when we're done building the type.
572  declarator.getAttributes().remove(&attr);
573  state.addIgnoredTypeAttr(attr);
574}
575
576/// A function type attribute was written somewhere in a declaration
577/// *other* than on the declarator itself or in the decl spec.  Given
578/// that it didn't apply in whatever position it was written in, try
579/// to move it to a more appropriate position.
580static void distributeFunctionTypeAttr(TypeProcessingState &state,
581                                       ParsedAttr &attr, QualType type) {
582  Declarator &declarator = state.getDeclarator();
583
584  // Try to push the attribute from the return type of a function to
585  // the function itself.
586  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
587    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
588    switch (chunk.Kind) {
589    case DeclaratorChunk::Function:
590      moveAttrFromListToList(attr, state.getCurrentAttributes(),
591                             chunk.getAttrs());
592      return;
593
594    case DeclaratorChunk::Paren:
595    case DeclaratorChunk::Pointer:
596    case DeclaratorChunk::BlockPointer:
597    case DeclaratorChunk::Array:
598    case DeclaratorChunk::Reference:
599    case DeclaratorChunk::MemberPointer:
600    case DeclaratorChunk::Pipe:
601      continue;
602    }
603  }
604
605  diagnoseBadTypeAttribute(state.getSema(), attr, type);
606}
607
608/// Try to distribute a function type attribute to the innermost
609/// function chunk or type.  Returns true if the attribute was
610/// distributed, false if no location was found.
611static bool distributeFunctionTypeAttrToInnermost(
612    TypeProcessingState &state, ParsedAttr &attr,
613    ParsedAttributesView &attrList, QualType &declSpecType) {
614  Declarator &declarator = state.getDeclarator();
615
616  // Put it on the innermost function chunk, if there is one.
617  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
618    DeclaratorChunk &chunk = declarator.getTypeObject(i);
619    if (chunk.Kind != DeclaratorChunk::Function) continue;
620
621    moveAttrFromListToList(attr, attrList, chunk.getAttrs());
622    return true;
623  }
624
625  return handleFunctionTypeAttr(state, attr, declSpecType);
626}
627
628/// A function type attribute was written in the decl spec.  Try to
629/// apply it somewhere.
630static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
631                                                   ParsedAttr &attr,
632                                                   QualType &declSpecType) {
633  state.saveDeclSpecAttrs();
634
635  // Try to distribute to the innermost.
636  if (distributeFunctionTypeAttrToInnermost(
637          state, attr, state.getCurrentAttributes(), declSpecType))
638    return;
639
640  // If that failed, diagnose the bad attribute when the declarator is
641  // fully built.
642  state.addIgnoredTypeAttr(attr);
643}
644
645/// A function type attribute was written on the declarator or declaration.
646/// Try to apply it somewhere.
647/// `Attrs` is the attribute list containing the declaration (either of the
648/// declarator or the declaration).
649static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
650                                                     ParsedAttr &attr,
651                                                     QualType &declSpecType) {
652  Declarator &declarator = state.getDeclarator();
653
654  // Try to distribute to the innermost.
655  if (distributeFunctionTypeAttrToInnermost(
656          state, attr, declarator.getAttributes(), declSpecType))
657    return;
658
659  // If that failed, diagnose the bad attribute when the declarator is
660  // fully built.
661  declarator.getAttributes().remove(&attr);
662  state.addIgnoredTypeAttr(attr);
663}
664
665/// Given that there are attributes written on the declarator or declaration
666/// itself, try to distribute any type attributes to the appropriate
667/// declarator chunk.
668///
669/// These are attributes like the following:
670///   int f ATTR;
671///   int (f ATTR)();
672/// but not necessarily this:
673///   int f() ATTR;
674///
675/// `Attrs` is the attribute list containing the declaration (either of the
676/// declarator or the declaration).
677static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
678                                              QualType &declSpecType) {
679  // The called functions in this loop actually remove things from the current
680  // list, so iterating over the existing list isn't possible.  Instead, make a
681  // non-owning copy and iterate over that.
682  ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
683  for (ParsedAttr &attr : AttrsCopy) {
684    // Do not distribute [[]] attributes. They have strict rules for what
685    // they appertain to.
686    if (attr.isStandardAttributeSyntax())
687      continue;
688
689    switch (attr.getKind()) {
690    OBJC_POINTER_TYPE_ATTRS_CASELIST:
691      distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
692      break;
693
694    FUNCTION_TYPE_ATTRS_CASELIST:
695      distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
696      break;
697
698    MS_TYPE_ATTRS_CASELIST:
699      // Microsoft type attributes cannot go after the declarator-id.
700      continue;
701
702    NULLABILITY_TYPE_ATTRS_CASELIST:
703      // Nullability specifiers cannot go after the declarator-id.
704
705    // Objective-C __kindof does not get distributed.
706    case ParsedAttr::AT_ObjCKindOf:
707      continue;
708
709    default:
710      break;
711    }
712  }
713}
714
715/// Add a synthetic '()' to a block-literal declarator if it is
716/// required, given the return type.
717static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
718                                          QualType declSpecType) {
719  Declarator &declarator = state.getDeclarator();
720
721  // First, check whether the declarator would produce a function,
722  // i.e. whether the innermost semantic chunk is a function.
723  if (declarator.isFunctionDeclarator()) {
724    // If so, make that declarator a prototyped declarator.
725    declarator.getFunctionTypeInfo().hasPrototype = true;
726    return;
727  }
728
729  // If there are any type objects, the type as written won't name a
730  // function, regardless of the decl spec type.  This is because a
731  // block signature declarator is always an abstract-declarator, and
732  // abstract-declarators can't just be parentheses chunks.  Therefore
733  // we need to build a function chunk unless there are no type
734  // objects and the decl spec type is a function.
735  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
736    return;
737
738  // Note that there *are* cases with invalid declarators where
739  // declarators consist solely of parentheses.  In general, these
740  // occur only in failed efforts to make function declarators, so
741  // faking up the function chunk is still the right thing to do.
742
743  // Otherwise, we need to fake up a function declarator.
744  SourceLocation loc = declarator.getBeginLoc();
745
746  // ...and *prepend* it to the declarator.
747  SourceLocation NoLoc;
748  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
749      /*HasProto=*/true,
750      /*IsAmbiguous=*/false,
751      /*LParenLoc=*/NoLoc,
752      /*ArgInfo=*/nullptr,
753      /*NumParams=*/0,
754      /*EllipsisLoc=*/NoLoc,
755      /*RParenLoc=*/NoLoc,
756      /*RefQualifierIsLvalueRef=*/true,
757      /*RefQualifierLoc=*/NoLoc,
758      /*MutableLoc=*/NoLoc, EST_None,
759      /*ESpecRange=*/SourceRange(),
760      /*Exceptions=*/nullptr,
761      /*ExceptionRanges=*/nullptr,
762      /*NumExceptions=*/0,
763      /*NoexceptExpr=*/nullptr,
764      /*ExceptionSpecTokens=*/nullptr,
765      /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
766
767  // For consistency, make sure the state still has us as processing
768  // the decl spec.
769  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
770  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
771}
772
773static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
774                                            unsigned &TypeQuals,
775                                            QualType TypeSoFar,
776                                            unsigned RemoveTQs,
777                                            unsigned DiagID) {
778  // If this occurs outside a template instantiation, warn the user about
779  // it; they probably didn't mean to specify a redundant qualifier.
780  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
781  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
782                       QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
783                       QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
784                       QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
785    if (!(RemoveTQs & Qual.first))
786      continue;
787
788    if (!S.inTemplateInstantiation()) {
789      if (TypeQuals & Qual.first)
790        S.Diag(Qual.second, DiagID)
791          << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
792          << FixItHint::CreateRemoval(Qual.second);
793    }
794
795    TypeQuals &= ~Qual.first;
796  }
797}
798
799/// Return true if this is omitted block return type. Also check type
800/// attributes and type qualifiers when returning true.
801static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
802                                        QualType Result) {
803  if (!isOmittedBlockReturnType(declarator))
804    return false;
805
806  // Warn if we see type attributes for omitted return type on a block literal.
807  SmallVector<ParsedAttr *, 2> ToBeRemoved;
808  for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
809    if (AL.isInvalid() || !AL.isTypeAttr())
810      continue;
811    S.Diag(AL.getLoc(),
812           diag::warn_block_literal_attributes_on_omitted_return_type)
813        << AL;
814    ToBeRemoved.push_back(&AL);
815  }
816  // Remove bad attributes from the list.
817  for (ParsedAttr *AL : ToBeRemoved)
818    declarator.getMutableDeclSpec().getAttributes().remove(AL);
819
820  // Warn if we see type qualifiers for omitted return type on a block literal.
821  const DeclSpec &DS = declarator.getDeclSpec();
822  unsigned TypeQuals = DS.getTypeQualifiers();
823  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
824      diag::warn_block_literal_qualifiers_on_omitted_return_type);
825  declarator.getMutableDeclSpec().ClearTypeQualifiers();
826
827  return true;
828}
829
830/// Apply Objective-C type arguments to the given type.
831static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
832                                  ArrayRef<TypeSourceInfo *> typeArgs,
833                                  SourceRange typeArgsRange, bool failOnError,
834                                  bool rebuilding) {
835  // We can only apply type arguments to an Objective-C class type.
836  const auto *objcObjectType = type->getAs<ObjCObjectType>();
837  if (!objcObjectType || !objcObjectType->getInterface()) {
838    S.Diag(loc, diag::err_objc_type_args_non_class)
839      << type
840      << typeArgsRange;
841
842    if (failOnError)
843      return QualType();
844    return type;
845  }
846
847  // The class type must be parameterized.
848  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
849  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
850  if (!typeParams) {
851    S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
852      << objcClass->getDeclName()
853      << FixItHint::CreateRemoval(typeArgsRange);
854
855    if (failOnError)
856      return QualType();
857
858    return type;
859  }
860
861  // The type must not already be specialized.
862  if (objcObjectType->isSpecialized()) {
863    S.Diag(loc, diag::err_objc_type_args_specialized_class)
864      << type
865      << FixItHint::CreateRemoval(typeArgsRange);
866
867    if (failOnError)
868      return QualType();
869
870    return type;
871  }
872
873  // Check the type arguments.
874  SmallVector<QualType, 4> finalTypeArgs;
875  unsigned numTypeParams = typeParams->size();
876  bool anyPackExpansions = false;
877  for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
878    TypeSourceInfo *typeArgInfo = typeArgs[i];
879    QualType typeArg = typeArgInfo->getType();
880
881    // Type arguments cannot have explicit qualifiers or nullability.
882    // We ignore indirect sources of these, e.g. behind typedefs or
883    // template arguments.
884    if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
885      bool diagnosed = false;
886      SourceRange rangeToRemove;
887      if (auto attr = qual.getAs<AttributedTypeLoc>()) {
888        rangeToRemove = attr.getLocalSourceRange();
889        if (attr.getTypePtr()->getImmediateNullability()) {
890          typeArg = attr.getTypePtr()->getModifiedType();
891          S.Diag(attr.getBeginLoc(),
892                 diag::err_objc_type_arg_explicit_nullability)
893              << typeArg << FixItHint::CreateRemoval(rangeToRemove);
894          diagnosed = true;
895        }
896      }
897
898      // When rebuilding, qualifiers might have gotten here through a
899      // final substitution.
900      if (!rebuilding && !diagnosed) {
901        S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
902            << typeArg << typeArg.getQualifiers().getAsString()
903            << FixItHint::CreateRemoval(rangeToRemove);
904      }
905    }
906
907    // Remove qualifiers even if they're non-local.
908    typeArg = typeArg.getUnqualifiedType();
909
910    finalTypeArgs.push_back(typeArg);
911
912    if (typeArg->getAs<PackExpansionType>())
913      anyPackExpansions = true;
914
915    // Find the corresponding type parameter, if there is one.
916    ObjCTypeParamDecl *typeParam = nullptr;
917    if (!anyPackExpansions) {
918      if (i < numTypeParams) {
919        typeParam = typeParams->begin()[i];
920      } else {
921        // Too many arguments.
922        S.Diag(loc, diag::err_objc_type_args_wrong_arity)
923          << false
924          << objcClass->getDeclName()
925          << (unsigned)typeArgs.size()
926          << numTypeParams;
927        S.Diag(objcClass->getLocation(), diag::note_previous_decl)
928          << objcClass;
929
930        if (failOnError)
931          return QualType();
932
933        return type;
934      }
935    }
936
937    // Objective-C object pointer types must be substitutable for the bounds.
938    if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
939      // If we don't have a type parameter to match against, assume
940      // everything is fine. There was a prior pack expansion that
941      // means we won't be able to match anything.
942      if (!typeParam) {
943        assert(anyPackExpansions && "Too many arguments?");
944        continue;
945      }
946
947      // Retrieve the bound.
948      QualType bound = typeParam->getUnderlyingType();
949      const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
950
951      // Determine whether the type argument is substitutable for the bound.
952      if (typeArgObjC->isObjCIdType()) {
953        // When the type argument is 'id', the only acceptable type
954        // parameter bound is 'id'.
955        if (boundObjC->isObjCIdType())
956          continue;
957      } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
958        // Otherwise, we follow the assignability rules.
959        continue;
960      }
961
962      // Diagnose the mismatch.
963      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
964             diag::err_objc_type_arg_does_not_match_bound)
965          << typeArg << bound << typeParam->getDeclName();
966      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
967        << typeParam->getDeclName();
968
969      if (failOnError)
970        return QualType();
971
972      return type;
973    }
974
975    // Block pointer types are permitted for unqualified 'id' bounds.
976    if (typeArg->isBlockPointerType()) {
977      // If we don't have a type parameter to match against, assume
978      // everything is fine. There was a prior pack expansion that
979      // means we won't be able to match anything.
980      if (!typeParam) {
981        assert(anyPackExpansions && "Too many arguments?");
982        continue;
983      }
984
985      // Retrieve the bound.
986      QualType bound = typeParam->getUnderlyingType();
987      if (bound->isBlockCompatibleObjCPointerType(S.Context))
988        continue;
989
990      // Diagnose the mismatch.
991      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
992             diag::err_objc_type_arg_does_not_match_bound)
993          << typeArg << bound << typeParam->getDeclName();
994      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
995        << typeParam->getDeclName();
996
997      if (failOnError)
998        return QualType();
999
1000      return type;
1001    }
1002
1003    // Dependent types will be checked at instantiation time.
1004    if (typeArg->isDependentType()) {
1005      continue;
1006    }
1007
1008    // Diagnose non-id-compatible type arguments.
1009    S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1010           diag::err_objc_type_arg_not_id_compatible)
1011        << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1012
1013    if (failOnError)
1014      return QualType();
1015
1016    return type;
1017  }
1018
1019  // Make sure we didn't have the wrong number of arguments.
1020  if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1021    S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1022      << (typeArgs.size() < typeParams->size())
1023      << objcClass->getDeclName()
1024      << (unsigned)finalTypeArgs.size()
1025      << (unsigned)numTypeParams;
1026    S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1027      << objcClass;
1028
1029    if (failOnError)
1030      return QualType();
1031
1032    return type;
1033  }
1034
1035  // Success. Form the specialized type.
1036  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1037}
1038
1039QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1040                                      SourceLocation ProtocolLAngleLoc,
1041                                      ArrayRef<ObjCProtocolDecl *> Protocols,
1042                                      ArrayRef<SourceLocation> ProtocolLocs,
1043                                      SourceLocation ProtocolRAngleLoc,
1044                                      bool FailOnError) {
1045  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1046  if (!Protocols.empty()) {
1047    bool HasError;
1048    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1049                                                 HasError);
1050    if (HasError) {
1051      Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1052        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1053      if (FailOnError) Result = QualType();
1054    }
1055    if (FailOnError && Result.isNull())
1056      return QualType();
1057  }
1058
1059  return Result;
1060}
1061
1062QualType Sema::BuildObjCObjectType(
1063    QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1064    ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1065    SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1066    ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1067    bool FailOnError, bool Rebuilding) {
1068  QualType Result = BaseType;
1069  if (!TypeArgs.empty()) {
1070    Result =
1071        applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1072                          SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1073                          FailOnError, Rebuilding);
1074    if (FailOnError && Result.isNull())
1075      return QualType();
1076  }
1077
1078  if (!Protocols.empty()) {
1079    bool HasError;
1080    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1081                                                 HasError);
1082    if (HasError) {
1083      Diag(Loc, diag::err_invalid_protocol_qualifiers)
1084        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1085      if (FailOnError) Result = QualType();
1086    }
1087    if (FailOnError && Result.isNull())
1088      return QualType();
1089  }
1090
1091  return Result;
1092}
1093
1094TypeResult Sema::actOnObjCProtocolQualifierType(
1095             SourceLocation lAngleLoc,
1096             ArrayRef<Decl *> protocols,
1097             ArrayRef<SourceLocation> protocolLocs,
1098             SourceLocation rAngleLoc) {
1099  // Form id<protocol-list>.
1100  QualType Result = Context.getObjCObjectType(
1101      Context.ObjCBuiltinIdTy, {},
1102      llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1103                     protocols.size()),
1104      false);
1105  Result = Context.getObjCObjectPointerType(Result);
1106
1107  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1108  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1109
1110  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1111  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1112
1113  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1114                        .castAs<ObjCObjectTypeLoc>();
1115  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1116  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1117
1118  // No type arguments.
1119  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1120  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1121
1122  // Fill in protocol qualifiers.
1123  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1124  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1125  for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1126    ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1127
1128  // We're done. Return the completed type to the parser.
1129  return CreateParsedType(Result, ResultTInfo);
1130}
1131
1132TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1133             Scope *S,
1134             SourceLocation Loc,
1135             ParsedType BaseType,
1136             SourceLocation TypeArgsLAngleLoc,
1137             ArrayRef<ParsedType> TypeArgs,
1138             SourceLocation TypeArgsRAngleLoc,
1139             SourceLocation ProtocolLAngleLoc,
1140             ArrayRef<Decl *> Protocols,
1141             ArrayRef<SourceLocation> ProtocolLocs,
1142             SourceLocation ProtocolRAngleLoc) {
1143  TypeSourceInfo *BaseTypeInfo = nullptr;
1144  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1145  if (T.isNull())
1146    return true;
1147
1148  // Handle missing type-source info.
1149  if (!BaseTypeInfo)
1150    BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1151
1152  // Extract type arguments.
1153  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1154  for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1155    TypeSourceInfo *TypeArgInfo = nullptr;
1156    QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1157    if (TypeArg.isNull()) {
1158      ActualTypeArgInfos.clear();
1159      break;
1160    }
1161
1162    assert(TypeArgInfo && "No type source info?");
1163    ActualTypeArgInfos.push_back(TypeArgInfo);
1164  }
1165
1166  // Build the object type.
1167  QualType Result = BuildObjCObjectType(
1168      T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1169      TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1170      ProtocolLAngleLoc,
1171      llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1172                     Protocols.size()),
1173      ProtocolLocs, ProtocolRAngleLoc,
1174      /*FailOnError=*/false,
1175      /*Rebuilding=*/false);
1176
1177  if (Result == T)
1178    return BaseType;
1179
1180  // Create source information for this type.
1181  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1182  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1183
1184  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1185  // object pointer type. Fill in source information for it.
1186  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1187    // The '*' is implicit.
1188    ObjCObjectPointerTL.setStarLoc(SourceLocation());
1189    ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1190  }
1191
1192  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1193    // Protocol qualifier information.
1194    if (OTPTL.getNumProtocols() > 0) {
1195      assert(OTPTL.getNumProtocols() == Protocols.size());
1196      OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1197      OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1198      for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1199        OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1200    }
1201
1202    // We're done. Return the completed type to the parser.
1203    return CreateParsedType(Result, ResultTInfo);
1204  }
1205
1206  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1207
1208  // Type argument information.
1209  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1210    assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1211    ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1212    ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1213    for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1214      ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1215  } else {
1216    ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1217    ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1218  }
1219
1220  // Protocol qualifier information.
1221  if (ObjCObjectTL.getNumProtocols() > 0) {
1222    assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1223    ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1224    ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1225    for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1226      ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1227  } else {
1228    ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1229    ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1230  }
1231
1232  // Base type.
1233  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1234  if (ObjCObjectTL.getType() == T)
1235    ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1236  else
1237    ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1238
1239  // We're done. Return the completed type to the parser.
1240  return CreateParsedType(Result, ResultTInfo);
1241}
1242
1243static OpenCLAccessAttr::Spelling
1244getImageAccess(const ParsedAttributesView &Attrs) {
1245  for (const ParsedAttr &AL : Attrs)
1246    if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1247      return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1248  return OpenCLAccessAttr::Keyword_read_only;
1249}
1250
1251static UnaryTransformType::UTTKind
1252TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1253  switch (SwitchTST) {
1254#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \
1255  case TST_##Trait:                                                            \
1256    return UnaryTransformType::Enum;
1257#include "clang/Basic/TransformTypeTraits.def"
1258  default:
1259    llvm_unreachable("attempted to parse a non-unary transform builtin");
1260  }
1261}
1262
1263/// Convert the specified declspec to the appropriate type
1264/// object.
1265/// \param state Specifies the declarator containing the declaration specifier
1266/// to be converted, along with other associated processing state.
1267/// \returns The type described by the declaration specifiers.  This function
1268/// never returns null.
1269static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1270  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1271  // checking.
1272
1273  Sema &S = state.getSema();
1274  Declarator &declarator = state.getDeclarator();
1275  DeclSpec &DS = declarator.getMutableDeclSpec();
1276  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1277  if (DeclLoc.isInvalid())
1278    DeclLoc = DS.getBeginLoc();
1279
1280  ASTContext &Context = S.Context;
1281
1282  QualType Result;
1283  switch (DS.getTypeSpecType()) {
1284  case DeclSpec::TST_void:
1285    Result = Context.VoidTy;
1286    break;
1287  case DeclSpec::TST_char:
1288    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1289      Result = Context.CharTy;
1290    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1291      Result = Context.SignedCharTy;
1292    else {
1293      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1294             "Unknown TSS value");
1295      Result = Context.UnsignedCharTy;
1296    }
1297    break;
1298  case DeclSpec::TST_wchar:
1299    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1300      Result = Context.WCharTy;
1301    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1302      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1303        << DS.getSpecifierName(DS.getTypeSpecType(),
1304                               Context.getPrintingPolicy());
1305      Result = Context.getSignedWCharType();
1306    } else {
1307      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1308             "Unknown TSS value");
1309      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1310        << DS.getSpecifierName(DS.getTypeSpecType(),
1311                               Context.getPrintingPolicy());
1312      Result = Context.getUnsignedWCharType();
1313    }
1314    break;
1315  case DeclSpec::TST_char8:
1316    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1317           "Unknown TSS value");
1318    Result = Context.Char8Ty;
1319    break;
1320  case DeclSpec::TST_char16:
1321    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1322           "Unknown TSS value");
1323    Result = Context.Char16Ty;
1324    break;
1325  case DeclSpec::TST_char32:
1326    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1327           "Unknown TSS value");
1328    Result = Context.Char32Ty;
1329    break;
1330  case DeclSpec::TST_unspecified:
1331    // If this is a missing declspec in a block literal return context, then it
1332    // is inferred from the return statements inside the block.
1333    // The declspec is always missing in a lambda expr context; it is either
1334    // specified with a trailing return type or inferred.
1335    if (S.getLangOpts().CPlusPlus14 &&
1336        declarator.getContext() == DeclaratorContext::LambdaExpr) {
1337      // In C++1y, a lambda's implicit return type is 'auto'.
1338      Result = Context.getAutoDeductType();
1339      break;
1340    } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1341               checkOmittedBlockReturnType(S, declarator,
1342                                           Context.DependentTy)) {
1343      Result = Context.DependentTy;
1344      break;
1345    }
1346
1347    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1348    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1349    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1350    // Note that the one exception to this is function definitions, which are
1351    // allowed to be completely missing a declspec.  This is handled in the
1352    // parser already though by it pretending to have seen an 'int' in this
1353    // case.
1354    if (S.getLangOpts().isImplicitIntRequired()) {
1355      S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1356          << DS.getSourceRange()
1357          << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1358    } else if (!DS.hasTypeSpecifier()) {
1359      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1360      // "At least one type specifier shall be given in the declaration
1361      // specifiers in each declaration, and in the specifier-qualifier list in
1362      // each struct declaration and type name."
1363      if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1364        S.Diag(DeclLoc, diag::err_missing_type_specifier)
1365            << DS.getSourceRange();
1366
1367        // When this occurs, often something is very broken with the value
1368        // being declared, poison it as invalid so we don't get chains of
1369        // errors.
1370        declarator.setInvalidType(true);
1371      } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1372                 DS.isTypeSpecPipe()) {
1373        S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1374            << DS.getSourceRange();
1375        declarator.setInvalidType(true);
1376      } else {
1377        assert(S.getLangOpts().isImplicitIntAllowed() &&
1378               "implicit int is disabled?");
1379        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1380            << DS.getSourceRange()
1381            << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1382      }
1383    }
1384
1385    [[fallthrough]];
1386  case DeclSpec::TST_int: {
1387    if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1388      switch (DS.getTypeSpecWidth()) {
1389      case TypeSpecifierWidth::Unspecified:
1390        Result = Context.IntTy;
1391        break;
1392      case TypeSpecifierWidth::Short:
1393        Result = Context.ShortTy;
1394        break;
1395      case TypeSpecifierWidth::Long:
1396        Result = Context.LongTy;
1397        break;
1398      case TypeSpecifierWidth::LongLong:
1399        Result = Context.LongLongTy;
1400
1401        // 'long long' is a C99 or C++11 feature.
1402        if (!S.getLangOpts().C99) {
1403          if (S.getLangOpts().CPlusPlus)
1404            S.Diag(DS.getTypeSpecWidthLoc(),
1405                   S.getLangOpts().CPlusPlus11 ?
1406                   diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1407          else
1408            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1409        }
1410        break;
1411      }
1412    } else {
1413      switch (DS.getTypeSpecWidth()) {
1414      case TypeSpecifierWidth::Unspecified:
1415        Result = Context.UnsignedIntTy;
1416        break;
1417      case TypeSpecifierWidth::Short:
1418        Result = Context.UnsignedShortTy;
1419        break;
1420      case TypeSpecifierWidth::Long:
1421        Result = Context.UnsignedLongTy;
1422        break;
1423      case TypeSpecifierWidth::LongLong:
1424        Result = Context.UnsignedLongLongTy;
1425
1426        // 'long long' is a C99 or C++11 feature.
1427        if (!S.getLangOpts().C99) {
1428          if (S.getLangOpts().CPlusPlus)
1429            S.Diag(DS.getTypeSpecWidthLoc(),
1430                   S.getLangOpts().CPlusPlus11 ?
1431                   diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1432          else
1433            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1434        }
1435        break;
1436      }
1437    }
1438    break;
1439  }
1440  case DeclSpec::TST_bitint: {
1441    if (!S.Context.getTargetInfo().hasBitIntType())
1442      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1443    Result =
1444        S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1445                          DS.getRepAsExpr(), DS.getBeginLoc());
1446    if (Result.isNull()) {
1447      Result = Context.IntTy;
1448      declarator.setInvalidType(true);
1449    }
1450    break;
1451  }
1452  case DeclSpec::TST_accum: {
1453    switch (DS.getTypeSpecWidth()) {
1454    case TypeSpecifierWidth::Short:
1455      Result = Context.ShortAccumTy;
1456      break;
1457    case TypeSpecifierWidth::Unspecified:
1458      Result = Context.AccumTy;
1459      break;
1460    case TypeSpecifierWidth::Long:
1461      Result = Context.LongAccumTy;
1462      break;
1463    case TypeSpecifierWidth::LongLong:
1464      llvm_unreachable("Unable to specify long long as _Accum width");
1465    }
1466
1467    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1468      Result = Context.getCorrespondingUnsignedType(Result);
1469
1470    if (DS.isTypeSpecSat())
1471      Result = Context.getCorrespondingSaturatedType(Result);
1472
1473    break;
1474  }
1475  case DeclSpec::TST_fract: {
1476    switch (DS.getTypeSpecWidth()) {
1477    case TypeSpecifierWidth::Short:
1478      Result = Context.ShortFractTy;
1479      break;
1480    case TypeSpecifierWidth::Unspecified:
1481      Result = Context.FractTy;
1482      break;
1483    case TypeSpecifierWidth::Long:
1484      Result = Context.LongFractTy;
1485      break;
1486    case TypeSpecifierWidth::LongLong:
1487      llvm_unreachable("Unable to specify long long as _Fract width");
1488    }
1489
1490    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1491      Result = Context.getCorrespondingUnsignedType(Result);
1492
1493    if (DS.isTypeSpecSat())
1494      Result = Context.getCorrespondingSaturatedType(Result);
1495
1496    break;
1497  }
1498  case DeclSpec::TST_int128:
1499    if (!S.Context.getTargetInfo().hasInt128Type() &&
1500        !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1501          (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
1502      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1503        << "__int128";
1504    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1505      Result = Context.UnsignedInt128Ty;
1506    else
1507      Result = Context.Int128Ty;
1508    break;
1509  case DeclSpec::TST_float16:
1510    // CUDA host and device may have different _Float16 support, therefore
1511    // do not diagnose _Float16 usage to avoid false alarm.
1512    // ToDo: more precise diagnostics for CUDA.
1513    if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1514        !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1515      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1516        << "_Float16";
1517    Result = Context.Float16Ty;
1518    break;
1519  case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1520  case DeclSpec::TST_BFloat16:
1521    if (!S.Context.getTargetInfo().hasBFloat16Type())
1522      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1523        << "__bf16";
1524    Result = Context.BFloat16Ty;
1525    break;
1526  case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1527  case DeclSpec::TST_double:
1528    if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1529      Result = Context.LongDoubleTy;
1530    else
1531      Result = Context.DoubleTy;
1532    if (S.getLangOpts().OpenCL) {
1533      if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1534        S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1535            << 0 << Result
1536            << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1537                    ? "cl_khr_fp64 and __opencl_c_fp64"
1538                    : "cl_khr_fp64");
1539      else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1540        S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1541    }
1542    break;
1543  case DeclSpec::TST_float128:
1544    if (!S.Context.getTargetInfo().hasFloat128Type() &&
1545        !S.getLangOpts().SYCLIsDevice &&
1546        !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1547      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1548        << "__float128";
1549    Result = Context.Float128Ty;
1550    break;
1551  case DeclSpec::TST_ibm128:
1552    if (!S.Context.getTargetInfo().hasIbm128Type() &&
1553        !S.getLangOpts().SYCLIsDevice &&
1554        !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1555      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1556    Result = Context.Ibm128Ty;
1557    break;
1558  case DeclSpec::TST_bool:
1559    Result = Context.BoolTy; // _Bool or bool
1560    break;
1561  case DeclSpec::TST_decimal32:    // _Decimal32
1562  case DeclSpec::TST_decimal64:    // _Decimal64
1563  case DeclSpec::TST_decimal128:   // _Decimal128
1564    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1565    Result = Context.IntTy;
1566    declarator.setInvalidType(true);
1567    break;
1568  case DeclSpec::TST_class:
1569  case DeclSpec::TST_enum:
1570  case DeclSpec::TST_union:
1571  case DeclSpec::TST_struct:
1572  case DeclSpec::TST_interface: {
1573    TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1574    if (!D) {
1575      // This can happen in C++ with ambiguous lookups.
1576      Result = Context.IntTy;
1577      declarator.setInvalidType(true);
1578      break;
1579    }
1580
1581    // If the type is deprecated or unavailable, diagnose it.
1582    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1583
1584    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1585           DS.getTypeSpecComplex() == 0 &&
1586           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1587           "No qualifiers on tag names!");
1588
1589    // TypeQuals handled by caller.
1590    Result = Context.getTypeDeclType(D);
1591
1592    // In both C and C++, make an ElaboratedType.
1593    ElaboratedTypeKeyword Keyword
1594      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1595    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1596                                 DS.isTypeSpecOwned() ? D : nullptr);
1597    break;
1598  }
1599  case DeclSpec::TST_typename: {
1600    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1601           DS.getTypeSpecComplex() == 0 &&
1602           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1603           "Can't handle qualifiers on typedef names yet!");
1604    Result = S.GetTypeFromParser(DS.getRepAsType());
1605    if (Result.isNull()) {
1606      declarator.setInvalidType(true);
1607    }
1608
1609    // TypeQuals handled by caller.
1610    break;
1611  }
1612  case DeclSpec::TST_typeof_unqualType:
1613  case DeclSpec::TST_typeofType:
1614    // FIXME: Preserve type source info.
1615    Result = S.GetTypeFromParser(DS.getRepAsType());
1616    assert(!Result.isNull() && "Didn't get a type for typeof?");
1617    if (!Result->isDependentType())
1618      if (const TagType *TT = Result->getAs<TagType>())
1619        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1620    // TypeQuals handled by caller.
1621    Result = Context.getTypeOfType(
1622        Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1623                    ? TypeOfKind::Unqualified
1624                    : TypeOfKind::Qualified);
1625    break;
1626  case DeclSpec::TST_typeof_unqualExpr:
1627  case DeclSpec::TST_typeofExpr: {
1628    Expr *E = DS.getRepAsExpr();
1629    assert(E && "Didn't get an expression for typeof?");
1630    // TypeQuals handled by caller.
1631    Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1632                                              DeclSpec::TST_typeof_unqualExpr
1633                                          ? TypeOfKind::Unqualified
1634                                          : TypeOfKind::Qualified);
1635    if (Result.isNull()) {
1636      Result = Context.IntTy;
1637      declarator.setInvalidType(true);
1638    }
1639    break;
1640  }
1641  case DeclSpec::TST_decltype: {
1642    Expr *E = DS.getRepAsExpr();
1643    assert(E && "Didn't get an expression for decltype?");
1644    // TypeQuals handled by caller.
1645    Result = S.BuildDecltypeType(E);
1646    if (Result.isNull()) {
1647      Result = Context.IntTy;
1648      declarator.setInvalidType(true);
1649    }
1650    break;
1651  }
1652#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1653#include "clang/Basic/TransformTypeTraits.def"
1654    Result = S.GetTypeFromParser(DS.getRepAsType());
1655    assert(!Result.isNull() && "Didn't get a type for the transformation?");
1656    Result = S.BuildUnaryTransformType(
1657        Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1658        DS.getTypeSpecTypeLoc());
1659    if (Result.isNull()) {
1660      Result = Context.IntTy;
1661      declarator.setInvalidType(true);
1662    }
1663    break;
1664
1665  case DeclSpec::TST_auto:
1666  case DeclSpec::TST_decltype_auto: {
1667    auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1668                      ? AutoTypeKeyword::DecltypeAuto
1669                      : AutoTypeKeyword::Auto;
1670
1671    ConceptDecl *TypeConstraintConcept = nullptr;
1672    llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1673    if (DS.isConstrainedAuto()) {
1674      if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1675        TypeConstraintConcept =
1676            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1677        TemplateArgumentListInfo TemplateArgsInfo;
1678        TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1679        TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1680        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1681                                           TemplateId->NumArgs);
1682        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1683        for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1684          TemplateArgs.push_back(ArgLoc.getArgument());
1685      } else {
1686        declarator.setInvalidType(true);
1687      }
1688    }
1689    Result = S.Context.getAutoType(QualType(), AutoKW,
1690                                   /*IsDependent*/ false, /*IsPack=*/false,
1691                                   TypeConstraintConcept, TemplateArgs);
1692    break;
1693  }
1694
1695  case DeclSpec::TST_auto_type:
1696    Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1697    break;
1698
1699  case DeclSpec::TST_unknown_anytype:
1700    Result = Context.UnknownAnyTy;
1701    break;
1702
1703  case DeclSpec::TST_atomic:
1704    Result = S.GetTypeFromParser(DS.getRepAsType());
1705    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1706    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1707    if (Result.isNull()) {
1708      Result = Context.IntTy;
1709      declarator.setInvalidType(true);
1710    }
1711    break;
1712
1713#define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
1714  case DeclSpec::TST_##ImgType##_t:                                            \
1715    switch (getImageAccess(DS.getAttributes())) {                              \
1716    case OpenCLAccessAttr::Keyword_write_only:                                 \
1717      Result = Context.Id##WOTy;                                               \
1718      break;                                                                   \
1719    case OpenCLAccessAttr::Keyword_read_write:                                 \
1720      Result = Context.Id##RWTy;                                               \
1721      break;                                                                   \
1722    case OpenCLAccessAttr::Keyword_read_only:                                  \
1723      Result = Context.Id##ROTy;                                               \
1724      break;                                                                   \
1725    case OpenCLAccessAttr::SpellingNotCalculated:                              \
1726      llvm_unreachable("Spelling not yet calculated");                         \
1727    }                                                                          \
1728    break;
1729#include "clang/Basic/OpenCLImageTypes.def"
1730
1731  case DeclSpec::TST_error:
1732    Result = Context.IntTy;
1733    declarator.setInvalidType(true);
1734    break;
1735  }
1736
1737  // FIXME: we want resulting declarations to be marked invalid, but claiming
1738  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1739  // a null type.
1740  if (Result->containsErrors())
1741    declarator.setInvalidType();
1742
1743  if (S.getLangOpts().OpenCL) {
1744    const auto &OpenCLOptions = S.getOpenCLOptions();
1745    bool IsOpenCLC30Compatible =
1746        S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1747    // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1748    // support.
1749    // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1750    // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1751    // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1752    // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1753    // only when the optional feature is supported
1754    if ((Result->isImageType() || Result->isSamplerT()) &&
1755        (IsOpenCLC30Compatible &&
1756         !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1757      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1758          << 0 << Result << "__opencl_c_images";
1759      declarator.setInvalidType();
1760    } else if (Result->isOCLImage3dWOType() &&
1761               !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1762                                          S.getLangOpts())) {
1763      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1764          << 0 << Result
1765          << (IsOpenCLC30Compatible
1766                  ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1767                  : "cl_khr_3d_image_writes");
1768      declarator.setInvalidType();
1769    }
1770  }
1771
1772  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1773                          DS.getTypeSpecType() == DeclSpec::TST_fract;
1774
1775  // Only fixed point types can be saturated
1776  if (DS.isTypeSpecSat() && !IsFixedPointType)
1777    S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1778        << DS.getSpecifierName(DS.getTypeSpecType(),
1779                               Context.getPrintingPolicy());
1780
1781  // Handle complex types.
1782  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1783    if (S.getLangOpts().Freestanding)
1784      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1785    Result = Context.getComplexType(Result);
1786  } else if (DS.isTypeAltiVecVector()) {
1787    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1788    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1789    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1790    if (DS.isTypeAltiVecPixel())
1791      VecKind = VectorType::AltiVecPixel;
1792    else if (DS.isTypeAltiVecBool())
1793      VecKind = VectorType::AltiVecBool;
1794    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1795  }
1796
1797  // FIXME: Imaginary.
1798  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1799    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1800
1801  // Before we process any type attributes, synthesize a block literal
1802  // function declarator if necessary.
1803  if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1804    maybeSynthesizeBlockSignature(state, Result);
1805
1806  // Apply any type attributes from the decl spec.  This may cause the
1807  // list of type attributes to be temporarily saved while the type
1808  // attributes are pushed around.
1809  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1810  if (!DS.isTypeSpecPipe()) {
1811    // We also apply declaration attributes that "slide" to the decl spec.
1812    // Ordering can be important for attributes. The decalaration attributes
1813    // come syntactically before the decl spec attributes, so we process them
1814    // in that order.
1815    ParsedAttributesView SlidingAttrs;
1816    for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1817      if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1818        SlidingAttrs.addAtEnd(&AL);
1819
1820        // For standard syntax attributes, which would normally appertain to the
1821        // declaration here, suggest moving them to the type instead. But only
1822        // do this for our own vendor attributes; moving other vendors'
1823        // attributes might hurt portability.
1824        // There's one special case that we need to deal with here: The
1825        // `MatrixType` attribute may only be used in a typedef declaration. If
1826        // it's being used anywhere else, don't output the warning as
1827        // ProcessDeclAttributes() will output an error anyway.
1828        if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1829            !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1830              DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1831          S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1832              << AL;
1833        }
1834      }
1835    }
1836    // During this call to processTypeAttrs(),
1837    // TypeProcessingState::getCurrentAttributes() will erroneously return a
1838    // reference to the DeclSpec attributes, rather than the declaration
1839    // attributes. However, this doesn't matter, as getCurrentAttributes()
1840    // is only called when distributing attributes from one attribute list
1841    // to another. Declaration attributes are always C++11 attributes, and these
1842    // are never distributed.
1843    processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1844    processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1845  }
1846
1847  // Apply const/volatile/restrict qualifiers to T.
1848  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1849    // Warn about CV qualifiers on function types.
1850    // C99 6.7.3p8:
1851    //   If the specification of a function type includes any type qualifiers,
1852    //   the behavior is undefined.
1853    // C++11 [dcl.fct]p7:
1854    //   The effect of a cv-qualifier-seq in a function declarator is not the
1855    //   same as adding cv-qualification on top of the function type. In the
1856    //   latter case, the cv-qualifiers are ignored.
1857    if (Result->isFunctionType()) {
1858      diagnoseAndRemoveTypeQualifiers(
1859          S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1860          S.getLangOpts().CPlusPlus
1861              ? diag::warn_typecheck_function_qualifiers_ignored
1862              : diag::warn_typecheck_function_qualifiers_unspecified);
1863      // No diagnostic for 'restrict' or '_Atomic' applied to a
1864      // function type; we'll diagnose those later, in BuildQualifiedType.
1865    }
1866
1867    // C++11 [dcl.ref]p1:
1868    //   Cv-qualified references are ill-formed except when the
1869    //   cv-qualifiers are introduced through the use of a typedef-name
1870    //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1871    //
1872    // There don't appear to be any other contexts in which a cv-qualified
1873    // reference type could be formed, so the 'ill-formed' clause here appears
1874    // to never happen.
1875    if (TypeQuals && Result->isReferenceType()) {
1876      diagnoseAndRemoveTypeQualifiers(
1877          S, DS, TypeQuals, Result,
1878          DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1879          diag::warn_typecheck_reference_qualifiers);
1880    }
1881
1882    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1883    // than once in the same specifier-list or qualifier-list, either directly
1884    // or via one or more typedefs."
1885    if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1886        && TypeQuals & Result.getCVRQualifiers()) {
1887      if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1888        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1889          << "const";
1890      }
1891
1892      if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1893        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1894          << "volatile";
1895      }
1896
1897      // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1898      // produce a warning in this case.
1899    }
1900
1901    QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1902
1903    // If adding qualifiers fails, just use the unqualified type.
1904    if (Qualified.isNull())
1905      declarator.setInvalidType(true);
1906    else
1907      Result = Qualified;
1908  }
1909
1910  assert(!Result.isNull() && "This function should not return a null type");
1911  return Result;
1912}
1913
1914static std::string getPrintableNameForEntity(DeclarationName Entity) {
1915  if (Entity)
1916    return Entity.getAsString();
1917
1918  return "type name";
1919}
1920
1921static bool isDependentOrGNUAutoType(QualType T) {
1922  if (T->isDependentType())
1923    return true;
1924
1925  const auto *AT = dyn_cast<AutoType>(T);
1926  return AT && AT->isGNUAutoType();
1927}
1928
1929QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1930                                  Qualifiers Qs, const DeclSpec *DS) {
1931  if (T.isNull())
1932    return QualType();
1933
1934  // Ignore any attempt to form a cv-qualified reference.
1935  if (T->isReferenceType()) {
1936    Qs.removeConst();
1937    Qs.removeVolatile();
1938  }
1939
1940  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1941  // object or incomplete types shall not be restrict-qualified."
1942  if (Qs.hasRestrict()) {
1943    unsigned DiagID = 0;
1944    QualType ProblemTy;
1945
1946    if (T->isAnyPointerType() || T->isReferenceType() ||
1947        T->isMemberPointerType()) {
1948      QualType EltTy;
1949      if (T->isObjCObjectPointerType())
1950        EltTy = T;
1951      else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1952        EltTy = PTy->getPointeeType();
1953      else
1954        EltTy = T->getPointeeType();
1955
1956      // If we have a pointer or reference, the pointee must have an object
1957      // incomplete type.
1958      if (!EltTy->isIncompleteOrObjectType()) {
1959        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1960        ProblemTy = EltTy;
1961      }
1962    } else if (!isDependentOrGNUAutoType(T)) {
1963      // For an __auto_type variable, we may not have seen the initializer yet
1964      // and so have no idea whether the underlying type is a pointer type or
1965      // not.
1966      DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1967      ProblemTy = T;
1968    }
1969
1970    if (DiagID) {
1971      Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1972      Qs.removeRestrict();
1973    }
1974  }
1975
1976  return Context.getQualifiedType(T, Qs);
1977}
1978
1979QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1980                                  unsigned CVRAU, const DeclSpec *DS) {
1981  if (T.isNull())
1982    return QualType();
1983
1984  // Ignore any attempt to form a cv-qualified reference.
1985  if (T->isReferenceType())
1986    CVRAU &=
1987        ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1988
1989  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1990  // TQ_unaligned;
1991  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1992
1993  // C11 6.7.3/5:
1994  //   If the same qualifier appears more than once in the same
1995  //   specifier-qualifier-list, either directly or via one or more typedefs,
1996  //   the behavior is the same as if it appeared only once.
1997  //
1998  // It's not specified what happens when the _Atomic qualifier is applied to
1999  // a type specified with the _Atomic specifier, but we assume that this
2000  // should be treated as if the _Atomic qualifier appeared multiple times.
2001  if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2002    // C11 6.7.3/5:
2003    //   If other qualifiers appear along with the _Atomic qualifier in a
2004    //   specifier-qualifier-list, the resulting type is the so-qualified
2005    //   atomic type.
2006    //
2007    // Don't need to worry about array types here, since _Atomic can't be
2008    // applied to such types.
2009    SplitQualType Split = T.getSplitUnqualifiedType();
2010    T = BuildAtomicType(QualType(Split.Ty, 0),
2011                        DS ? DS->getAtomicSpecLoc() : Loc);
2012    if (T.isNull())
2013      return T;
2014    Split.Quals.addCVRQualifiers(CVR);
2015    return BuildQualifiedType(T, Loc, Split.Quals);
2016  }
2017
2018  Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2019  Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2020  return BuildQualifiedType(T, Loc, Q, DS);
2021}
2022
2023/// Build a paren type including \p T.
2024QualType Sema::BuildParenType(QualType T) {
2025  return Context.getParenType(T);
2026}
2027
2028/// Given that we're building a pointer or reference to the given
2029static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2030                                           SourceLocation loc,
2031                                           bool isReference) {
2032  // Bail out if retention is unrequired or already specified.
2033  if (!type->isObjCLifetimeType() ||
2034      type.getObjCLifetime() != Qualifiers::OCL_None)
2035    return type;
2036
2037  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2038
2039  // If the object type is const-qualified, we can safely use
2040  // __unsafe_unretained.  This is safe (because there are no read
2041  // barriers), and it'll be safe to coerce anything but __weak* to
2042  // the resulting type.
2043  if (type.isConstQualified()) {
2044    implicitLifetime = Qualifiers::OCL_ExplicitNone;
2045
2046  // Otherwise, check whether the static type does not require
2047  // retaining.  This currently only triggers for Class (possibly
2048  // protocol-qualifed, and arrays thereof).
2049  } else if (type->isObjCARCImplicitlyUnretainedType()) {
2050    implicitLifetime = Qualifiers::OCL_ExplicitNone;
2051
2052  // If we are in an unevaluated context, like sizeof, skip adding a
2053  // qualification.
2054  } else if (S.isUnevaluatedContext()) {
2055    return type;
2056
2057  // If that failed, give an error and recover using __strong.  __strong
2058  // is the option most likely to prevent spurious second-order diagnostics,
2059  // like when binding a reference to a field.
2060  } else {
2061    // These types can show up in private ivars in system headers, so
2062    // we need this to not be an error in those cases.  Instead we
2063    // want to delay.
2064    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2065      S.DelayedDiagnostics.add(
2066          sema::DelayedDiagnostic::makeForbiddenType(loc,
2067              diag::err_arc_indirect_no_ownership, type, isReference));
2068    } else {
2069      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2070    }
2071    implicitLifetime = Qualifiers::OCL_Strong;
2072  }
2073  assert(implicitLifetime && "didn't infer any lifetime!");
2074
2075  Qualifiers qs;
2076  qs.addObjCLifetime(implicitLifetime);
2077  return S.Context.getQualifiedType(type, qs);
2078}
2079
2080static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2081  std::string Quals = FnTy->getMethodQuals().getAsString();
2082
2083  switch (FnTy->getRefQualifier()) {
2084  case RQ_None:
2085    break;
2086
2087  case RQ_LValue:
2088    if (!Quals.empty())
2089      Quals += ' ';
2090    Quals += '&';
2091    break;
2092
2093  case RQ_RValue:
2094    if (!Quals.empty())
2095      Quals += ' ';
2096    Quals += "&&";
2097    break;
2098  }
2099
2100  return Quals;
2101}
2102
2103namespace {
2104/// Kinds of declarator that cannot contain a qualified function type.
2105///
2106/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2107///     a function type with a cv-qualifier or a ref-qualifier can only appear
2108///     at the topmost level of a type.
2109///
2110/// Parens and member pointers are permitted. We don't diagnose array and
2111/// function declarators, because they don't allow function types at all.
2112///
2113/// The values of this enum are used in diagnostics.
2114enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2115} // end anonymous namespace
2116
2117/// Check whether the type T is a qualified function type, and if it is,
2118/// diagnose that it cannot be contained within the given kind of declarator.
2119static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2120                                   QualifiedFunctionKind QFK) {
2121  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2122  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2123  if (!FPT ||
2124      (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2125    return false;
2126
2127  S.Diag(Loc, diag::err_compound_qualified_function_type)
2128    << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2129    << getFunctionQualifiersAsString(FPT);
2130  return true;
2131}
2132
2133bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2134  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2135  if (!FPT ||
2136      (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2137    return false;
2138
2139  Diag(Loc, diag::err_qualified_function_typeid)
2140      << T << getFunctionQualifiersAsString(FPT);
2141  return true;
2142}
2143
2144// Helper to deduce addr space of a pointee type in OpenCL mode.
2145static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2146  if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2147      !PointeeType->isSamplerT() &&
2148      !PointeeType.hasAddressSpace())
2149    PointeeType = S.getASTContext().getAddrSpaceQualType(
2150        PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2151  return PointeeType;
2152}
2153
2154/// Build a pointer type.
2155///
2156/// \param T The type to which we'll be building a pointer.
2157///
2158/// \param Loc The location of the entity whose type involves this
2159/// pointer type or, if there is no such entity, the location of the
2160/// type that will have pointer type.
2161///
2162/// \param Entity The name of the entity that involves the pointer
2163/// type, if known.
2164///
2165/// \returns A suitable pointer type, if there are no
2166/// errors. Otherwise, returns a NULL type.
2167QualType Sema::BuildPointerType(QualType T,
2168                                SourceLocation Loc, DeclarationName Entity) {
2169  if (T->isReferenceType()) {
2170    // C++ 8.3.2p4: There shall be no ... pointers to references ...
2171    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2172      << getPrintableNameForEntity(Entity) << T;
2173    return QualType();
2174  }
2175
2176  if (T->isFunctionType() && getLangOpts().OpenCL &&
2177      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2178                                            getLangOpts())) {
2179    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2180    return QualType();
2181  }
2182
2183  if (getLangOpts().HLSL && Loc.isValid()) {
2184    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2185    return QualType();
2186  }
2187
2188  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2189    return QualType();
2190
2191  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2192
2193  // In ARC, it is forbidden to build pointers to unqualified pointers.
2194  if (getLangOpts().ObjCAutoRefCount)
2195    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2196
2197  if (getLangOpts().OpenCL)
2198    T = deduceOpenCLPointeeAddrSpace(*this, T);
2199
2200  // Build the pointer type.
2201  return Context.getPointerType(T);
2202}
2203
2204/// Build a reference type.
2205///
2206/// \param T The type to which we'll be building a reference.
2207///
2208/// \param Loc The location of the entity whose type involves this
2209/// reference type or, if there is no such entity, the location of the
2210/// type that will have reference type.
2211///
2212/// \param Entity The name of the entity that involves the reference
2213/// type, if known.
2214///
2215/// \returns A suitable reference type, if there are no
2216/// errors. Otherwise, returns a NULL type.
2217QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2218                                  SourceLocation Loc,
2219                                  DeclarationName Entity) {
2220  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2221         "Unresolved overloaded function type");
2222
2223  // C++0x [dcl.ref]p6:
2224  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2225  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2226  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2227  //   the type "lvalue reference to T", while an attempt to create the type
2228  //   "rvalue reference to cv TR" creates the type TR.
2229  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2230
2231  // C++ [dcl.ref]p4: There shall be no references to references.
2232  //
2233  // According to C++ DR 106, references to references are only
2234  // diagnosed when they are written directly (e.g., "int & &"),
2235  // but not when they happen via a typedef:
2236  //
2237  //   typedef int& intref;
2238  //   typedef intref& intref2;
2239  //
2240  // Parser::ParseDeclaratorInternal diagnoses the case where
2241  // references are written directly; here, we handle the
2242  // collapsing of references-to-references as described in C++0x.
2243  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2244
2245  // C++ [dcl.ref]p1:
2246  //   A declarator that specifies the type "reference to cv void"
2247  //   is ill-formed.
2248  if (T->isVoidType()) {
2249    Diag(Loc, diag::err_reference_to_void);
2250    return QualType();
2251  }
2252
2253  if (getLangOpts().HLSL && Loc.isValid()) {
2254    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2255    return QualType();
2256  }
2257
2258  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2259    return QualType();
2260
2261  if (T->isFunctionType() && getLangOpts().OpenCL &&
2262      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2263                                            getLangOpts())) {
2264    Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2265    return QualType();
2266  }
2267
2268  // In ARC, it is forbidden to build references to unqualified pointers.
2269  if (getLangOpts().ObjCAutoRefCount)
2270    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2271
2272  if (getLangOpts().OpenCL)
2273    T = deduceOpenCLPointeeAddrSpace(*this, T);
2274
2275  // Handle restrict on references.
2276  if (LValueRef)
2277    return Context.getLValueReferenceType(T, SpelledAsLValue);
2278  return Context.getRValueReferenceType(T);
2279}
2280
2281/// Build a Read-only Pipe type.
2282///
2283/// \param T The type to which we'll be building a Pipe.
2284///
2285/// \param Loc We do not use it for now.
2286///
2287/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2288/// NULL type.
2289QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2290  return Context.getReadPipeType(T);
2291}
2292
2293/// Build a Write-only Pipe type.
2294///
2295/// \param T The type to which we'll be building a Pipe.
2296///
2297/// \param Loc We do not use it for now.
2298///
2299/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2300/// NULL type.
2301QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2302  return Context.getWritePipeType(T);
2303}
2304
2305/// Build a bit-precise integer type.
2306///
2307/// \param IsUnsigned Boolean representing the signedness of the type.
2308///
2309/// \param BitWidth Size of this int type in bits, or an expression representing
2310/// that.
2311///
2312/// \param Loc Location of the keyword.
2313QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2314                               SourceLocation Loc) {
2315  if (BitWidth->isInstantiationDependent())
2316    return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2317
2318  llvm::APSInt Bits(32);
2319  ExprResult ICE =
2320      VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2321
2322  if (ICE.isInvalid())
2323    return QualType();
2324
2325  size_t NumBits = Bits.getZExtValue();
2326  if (!IsUnsigned && NumBits < 2) {
2327    Diag(Loc, diag::err_bit_int_bad_size) << 0;
2328    return QualType();
2329  }
2330
2331  if (IsUnsigned && NumBits < 1) {
2332    Diag(Loc, diag::err_bit_int_bad_size) << 1;
2333    return QualType();
2334  }
2335
2336  const TargetInfo &TI = getASTContext().getTargetInfo();
2337  if (NumBits > TI.getMaxBitIntWidth()) {
2338    Diag(Loc, diag::err_bit_int_max_size)
2339        << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2340    return QualType();
2341  }
2342
2343  return Context.getBitIntType(IsUnsigned, NumBits);
2344}
2345
2346/// Check whether the specified array bound can be evaluated using the relevant
2347/// language rules. If so, returns the possibly-converted expression and sets
2348/// SizeVal to the size. If not, but the expression might be a VLA bound,
2349/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2350/// ExprError().
2351static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2352                                 llvm::APSInt &SizeVal, unsigned VLADiag,
2353                                 bool VLAIsError) {
2354  if (S.getLangOpts().CPlusPlus14 &&
2355      (VLAIsError ||
2356       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2357    // C++14 [dcl.array]p1:
2358    //   The constant-expression shall be a converted constant expression of
2359    //   type std::size_t.
2360    //
2361    // Don't apply this rule if we might be forming a VLA: in that case, we
2362    // allow non-constant expressions and constant-folding. We only need to use
2363    // the converted constant expression rules (to properly convert the source)
2364    // when the source expression is of class type.
2365    return S.CheckConvertedConstantExpression(
2366        ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2367  }
2368
2369  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2370  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2371  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2372  public:
2373    unsigned VLADiag;
2374    bool VLAIsError;
2375    bool IsVLA = false;
2376
2377    VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2378        : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2379
2380    Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2381                                                   QualType T) override {
2382      return S.Diag(Loc, diag::err_array_size_non_int) << T;
2383    }
2384
2385    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2386                                               SourceLocation Loc) override {
2387      IsVLA = !VLAIsError;
2388      return S.Diag(Loc, VLADiag);
2389    }
2390
2391    Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2392                                             SourceLocation Loc) override {
2393      return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2394    }
2395  } Diagnoser(VLADiag, VLAIsError);
2396
2397  ExprResult R =
2398      S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2399  if (Diagnoser.IsVLA)
2400    return ExprResult();
2401  return R;
2402}
2403
2404bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2405  EltTy = Context.getBaseElementType(EltTy);
2406  if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2407      EltTy->isUndeducedType())
2408    return true;
2409
2410  CharUnits Size = Context.getTypeSizeInChars(EltTy);
2411  CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2412
2413  if (Size.isMultipleOf(Alignment))
2414    return true;
2415
2416  Diag(Loc, diag::err_array_element_alignment)
2417      << EltTy << Size.getQuantity() << Alignment.getQuantity();
2418  return false;
2419}
2420
2421/// Build an array type.
2422///
2423/// \param T The type of each element in the array.
2424///
2425/// \param ASM C99 array size modifier (e.g., '*', 'static').
2426///
2427/// \param ArraySize Expression describing the size of the array.
2428///
2429/// \param Brackets The range from the opening '[' to the closing ']'.
2430///
2431/// \param Entity The name of the entity that involves the array
2432/// type, if known.
2433///
2434/// \returns A suitable array type, if there are no errors. Otherwise,
2435/// returns a NULL type.
2436QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2437                              Expr *ArraySize, unsigned Quals,
2438                              SourceRange Brackets, DeclarationName Entity) {
2439
2440  SourceLocation Loc = Brackets.getBegin();
2441  if (getLangOpts().CPlusPlus) {
2442    // C++ [dcl.array]p1:
2443    //   T is called the array element type; this type shall not be a reference
2444    //   type, the (possibly cv-qualified) type void, a function type or an
2445    //   abstract class type.
2446    //
2447    // C++ [dcl.array]p3:
2448    //   When several "array of" specifications are adjacent, [...] only the
2449    //   first of the constant expressions that specify the bounds of the arrays
2450    //   may be omitted.
2451    //
2452    // Note: function types are handled in the common path with C.
2453    if (T->isReferenceType()) {
2454      Diag(Loc, diag::err_illegal_decl_array_of_references)
2455      << getPrintableNameForEntity(Entity) << T;
2456      return QualType();
2457    }
2458
2459    if (T->isVoidType() || T->isIncompleteArrayType()) {
2460      Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2461      return QualType();
2462    }
2463
2464    if (RequireNonAbstractType(Brackets.getBegin(), T,
2465                               diag::err_array_of_abstract_type))
2466      return QualType();
2467
2468    // Mentioning a member pointer type for an array type causes us to lock in
2469    // an inheritance model, even if it's inside an unused typedef.
2470    if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2471      if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2472        if (!MPTy->getClass()->isDependentType())
2473          (void)isCompleteType(Loc, T);
2474
2475  } else {
2476    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2477    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2478    if (RequireCompleteSizedType(Loc, T,
2479                                 diag::err_array_incomplete_or_sizeless_type))
2480      return QualType();
2481  }
2482
2483  if (T->isSizelessType()) {
2484    Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2485    return QualType();
2486  }
2487
2488  if (T->isFunctionType()) {
2489    Diag(Loc, diag::err_illegal_decl_array_of_functions)
2490      << getPrintableNameForEntity(Entity) << T;
2491    return QualType();
2492  }
2493
2494  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2495    // If the element type is a struct or union that contains a variadic
2496    // array, accept it as a GNU extension: C99 6.7.2.1p2.
2497    if (EltTy->getDecl()->hasFlexibleArrayMember())
2498      Diag(Loc, diag::ext_flexible_array_in_array) << T;
2499  } else if (T->isObjCObjectType()) {
2500    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2501    return QualType();
2502  }
2503
2504  if (!checkArrayElementAlignment(T, Loc))
2505    return QualType();
2506
2507  // Do placeholder conversions on the array size expression.
2508  if (ArraySize && ArraySize->hasPlaceholderType()) {
2509    ExprResult Result = CheckPlaceholderExpr(ArraySize);
2510    if (Result.isInvalid()) return QualType();
2511    ArraySize = Result.get();
2512  }
2513
2514  // Do lvalue-to-rvalue conversions on the array size expression.
2515  if (ArraySize && !ArraySize->isPRValue()) {
2516    ExprResult Result = DefaultLvalueConversion(ArraySize);
2517    if (Result.isInvalid())
2518      return QualType();
2519
2520    ArraySize = Result.get();
2521  }
2522
2523  // C99 6.7.5.2p1: The size expression shall have integer type.
2524  // C++11 allows contextual conversions to such types.
2525  if (!getLangOpts().CPlusPlus11 &&
2526      ArraySize && !ArraySize->isTypeDependent() &&
2527      !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2528    Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2529        << ArraySize->getType() << ArraySize->getSourceRange();
2530    return QualType();
2531  }
2532
2533  // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2534  unsigned VLADiag;
2535  bool VLAIsError;
2536  if (getLangOpts().OpenCL) {
2537    // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2538    VLADiag = diag::err_opencl_vla;
2539    VLAIsError = true;
2540  } else if (getLangOpts().C99) {
2541    VLADiag = diag::warn_vla_used;
2542    VLAIsError = false;
2543  } else if (isSFINAEContext()) {
2544    VLADiag = diag::err_vla_in_sfinae;
2545    VLAIsError = true;
2546  } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2547    VLADiag = diag::err_openmp_vla_in_task_untied;
2548    VLAIsError = true;
2549  } else {
2550    VLADiag = diag::ext_vla;
2551    VLAIsError = false;
2552  }
2553
2554  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2555  if (!ArraySize) {
2556    if (ASM == ArrayType::Star) {
2557      Diag(Loc, VLADiag);
2558      if (VLAIsError)
2559        return QualType();
2560
2561      T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2562    } else {
2563      T = Context.getIncompleteArrayType(T, ASM, Quals);
2564    }
2565  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2566    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2567  } else {
2568    ExprResult R =
2569        checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2570    if (R.isInvalid())
2571      return QualType();
2572
2573    if (!R.isUsable()) {
2574      // C99: an array with a non-ICE size is a VLA. We accept any expression
2575      // that we can fold to a non-zero positive value as a non-VLA as an
2576      // extension.
2577      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2578    } else if (!T->isDependentType() && !T->isIncompleteType() &&
2579               !T->isConstantSizeType()) {
2580      // C99: an array with an element type that has a non-constant-size is a
2581      // VLA.
2582      // FIXME: Add a note to explain why this isn't a VLA.
2583      Diag(Loc, VLADiag);
2584      if (VLAIsError)
2585        return QualType();
2586      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2587    } else {
2588      // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2589      // have a value greater than zero.
2590      // In C++, this follows from narrowing conversions being disallowed.
2591      if (ConstVal.isSigned() && ConstVal.isNegative()) {
2592        if (Entity)
2593          Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2594              << getPrintableNameForEntity(Entity)
2595              << ArraySize->getSourceRange();
2596        else
2597          Diag(ArraySize->getBeginLoc(),
2598               diag::err_typecheck_negative_array_size)
2599              << ArraySize->getSourceRange();
2600        return QualType();
2601      }
2602      if (ConstVal == 0) {
2603        // GCC accepts zero sized static arrays. We allow them when
2604        // we're not in a SFINAE context.
2605        Diag(ArraySize->getBeginLoc(),
2606             isSFINAEContext() ? diag::err_typecheck_zero_array_size
2607                               : diag::ext_typecheck_zero_array_size)
2608            << 0 << ArraySize->getSourceRange();
2609      }
2610
2611      // Is the array too large?
2612      unsigned ActiveSizeBits =
2613          (!T->isDependentType() && !T->isVariablyModifiedType() &&
2614           !T->isIncompleteType() && !T->isUndeducedType())
2615              ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2616              : ConstVal.getActiveBits();
2617      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2618        Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2619            << toString(ConstVal, 10) << ArraySize->getSourceRange();
2620        return QualType();
2621      }
2622
2623      T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2624    }
2625  }
2626
2627  if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2628    // CUDA device code and some other targets don't support VLAs.
2629    bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2630    targetDiag(Loc,
2631               IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2632        << (IsCUDADevice ? CurrentCUDATarget() : 0);
2633  }
2634
2635  // If this is not C99, diagnose array size modifiers on non-VLAs.
2636  if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2637      (ASM != ArrayType::Normal || Quals != 0)) {
2638    Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2639                                      : diag::ext_c99_array_usage)
2640        << ASM;
2641  }
2642
2643  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2644  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2645  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2646  if (getLangOpts().OpenCL) {
2647    const QualType ArrType = Context.getBaseElementType(T);
2648    if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2649        ArrType->isSamplerT() || ArrType->isImageType()) {
2650      Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2651      return QualType();
2652    }
2653  }
2654
2655  return T;
2656}
2657
2658QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2659                               SourceLocation AttrLoc) {
2660  // The base type must be integer (not Boolean or enumeration) or float, and
2661  // can't already be a vector.
2662  if ((!CurType->isDependentType() &&
2663       (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2664        (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2665       !CurType->isBitIntType()) ||
2666      CurType->isArrayType()) {
2667    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2668    return QualType();
2669  }
2670  // Only support _BitInt elements with byte-sized power of 2 NumBits.
2671  if (CurType->isBitIntType()) {
2672    unsigned NumBits = CurType->getAs<BitIntType>()->getNumBits();
2673    if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2674      Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2675          << (NumBits < 8);
2676      return QualType();
2677    }
2678  }
2679
2680  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2681    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2682                                               VectorType::GenericVector);
2683
2684  std::optional<llvm::APSInt> VecSize =
2685      SizeExpr->getIntegerConstantExpr(Context);
2686  if (!VecSize) {
2687    Diag(AttrLoc, diag::err_attribute_argument_type)
2688        << "vector_size" << AANT_ArgumentIntegerConstant
2689        << SizeExpr->getSourceRange();
2690    return QualType();
2691  }
2692
2693  if (CurType->isDependentType())
2694    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2695                                               VectorType::GenericVector);
2696
2697  // vecSize is specified in bytes - convert to bits.
2698  if (!VecSize->isIntN(61)) {
2699    // Bit size will overflow uint64.
2700    Diag(AttrLoc, diag::err_attribute_size_too_large)
2701        << SizeExpr->getSourceRange() << "vector";
2702    return QualType();
2703  }
2704  uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2705  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2706
2707  if (VectorSizeBits == 0) {
2708    Diag(AttrLoc, diag::err_attribute_zero_size)
2709        << SizeExpr->getSourceRange() << "vector";
2710    return QualType();
2711  }
2712
2713  if (!TypeSize || VectorSizeBits % TypeSize) {
2714    Diag(AttrLoc, diag::err_attribute_invalid_size)
2715        << SizeExpr->getSourceRange();
2716    return QualType();
2717  }
2718
2719  if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2720    Diag(AttrLoc, diag::err_attribute_size_too_large)
2721        << SizeExpr->getSourceRange() << "vector";
2722    return QualType();
2723  }
2724
2725  return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2726                               VectorType::GenericVector);
2727}
2728
2729/// Build an ext-vector type.
2730///
2731/// Run the required checks for the extended vector type.
2732QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2733                                  SourceLocation AttrLoc) {
2734  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2735  // in conjunction with complex types (pointers, arrays, functions, etc.).
2736  //
2737  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2738  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2739  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2740  // of bool aren't allowed.
2741  //
2742  // We explictly allow bool elements in ext_vector_type for C/C++.
2743  bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2744  if ((!T->isDependentType() && !T->isIntegerType() &&
2745       !T->isRealFloatingType()) ||
2746      (IsNoBoolVecLang && T->isBooleanType())) {
2747    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2748    return QualType();
2749  }
2750
2751  // Only support _BitInt elements with byte-sized power of 2 NumBits.
2752  if (T->isBitIntType()) {
2753    unsigned NumBits = T->getAs<BitIntType>()->getNumBits();
2754    if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2755      Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2756          << (NumBits < 8);
2757      return QualType();
2758    }
2759  }
2760
2761  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2762    std::optional<llvm::APSInt> vecSize =
2763        ArraySize->getIntegerConstantExpr(Context);
2764    if (!vecSize) {
2765      Diag(AttrLoc, diag::err_attribute_argument_type)
2766        << "ext_vector_type" << AANT_ArgumentIntegerConstant
2767        << ArraySize->getSourceRange();
2768      return QualType();
2769    }
2770
2771    if (!vecSize->isIntN(32)) {
2772      Diag(AttrLoc, diag::err_attribute_size_too_large)
2773          << ArraySize->getSourceRange() << "vector";
2774      return QualType();
2775    }
2776    // Unlike gcc's vector_size attribute, the size is specified as the
2777    // number of elements, not the number of bytes.
2778    unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2779
2780    if (vectorSize == 0) {
2781      Diag(AttrLoc, diag::err_attribute_zero_size)
2782          << ArraySize->getSourceRange() << "vector";
2783      return QualType();
2784    }
2785
2786    return Context.getExtVectorType(T, vectorSize);
2787  }
2788
2789  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2790}
2791
2792QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2793                               SourceLocation AttrLoc) {
2794  assert(Context.getLangOpts().MatrixTypes &&
2795         "Should never build a matrix type when it is disabled");
2796
2797  // Check element type, if it is not dependent.
2798  if (!ElementTy->isDependentType() &&
2799      !MatrixType::isValidElementType(ElementTy)) {
2800    Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2801    return QualType();
2802  }
2803
2804  if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2805      NumRows->isValueDependent() || NumCols->isValueDependent())
2806    return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2807                                               AttrLoc);
2808
2809  std::optional<llvm::APSInt> ValueRows =
2810      NumRows->getIntegerConstantExpr(Context);
2811  std::optional<llvm::APSInt> ValueColumns =
2812      NumCols->getIntegerConstantExpr(Context);
2813
2814  auto const RowRange = NumRows->getSourceRange();
2815  auto const ColRange = NumCols->getSourceRange();
2816
2817  // Both are row and column expressions are invalid.
2818  if (!ValueRows && !ValueColumns) {
2819    Diag(AttrLoc, diag::err_attribute_argument_type)
2820        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2821        << ColRange;
2822    return QualType();
2823  }
2824
2825  // Only the row expression is invalid.
2826  if (!ValueRows) {
2827    Diag(AttrLoc, diag::err_attribute_argument_type)
2828        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2829    return QualType();
2830  }
2831
2832  // Only the column expression is invalid.
2833  if (!ValueColumns) {
2834    Diag(AttrLoc, diag::err_attribute_argument_type)
2835        << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2836    return QualType();
2837  }
2838
2839  // Check the matrix dimensions.
2840  unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2841  unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2842  if (MatrixRows == 0 && MatrixColumns == 0) {
2843    Diag(AttrLoc, diag::err_attribute_zero_size)
2844        << "matrix" << RowRange << ColRange;
2845    return QualType();
2846  }
2847  if (MatrixRows == 0) {
2848    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2849    return QualType();
2850  }
2851  if (MatrixColumns == 0) {
2852    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2853    return QualType();
2854  }
2855  if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2856    Diag(AttrLoc, diag::err_attribute_size_too_large)
2857        << RowRange << "matrix row";
2858    return QualType();
2859  }
2860  if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2861    Diag(AttrLoc, diag::err_attribute_size_too_large)
2862        << ColRange << "matrix column";
2863    return QualType();
2864  }
2865  return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2866}
2867
2868bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2869  if (T->isArrayType() || T->isFunctionType()) {
2870    Diag(Loc, diag::err_func_returning_array_function)
2871      << T->isFunctionType() << T;
2872    return true;
2873  }
2874
2875  // Functions cannot return half FP.
2876  if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2877      !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2878    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2879      FixItHint::CreateInsertion(Loc, "*");
2880    return true;
2881  }
2882
2883  // Methods cannot return interface types. All ObjC objects are
2884  // passed by reference.
2885  if (T->isObjCObjectType()) {
2886    Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2887        << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2888    return true;
2889  }
2890
2891  if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2892      T.hasNonTrivialToPrimitiveCopyCUnion())
2893    checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2894                          NTCUK_Destruct|NTCUK_Copy);
2895
2896  // C++2a [dcl.fct]p12:
2897  //   A volatile-qualified return type is deprecated
2898  if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2899    Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2900
2901  if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2902    return true;
2903  return false;
2904}
2905
2906/// Check the extended parameter information.  Most of the necessary
2907/// checking should occur when applying the parameter attribute; the
2908/// only other checks required are positional restrictions.
2909static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2910                    const FunctionProtoType::ExtProtoInfo &EPI,
2911                    llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2912  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2913
2914  bool emittedError = false;
2915  auto actualCC = EPI.ExtInfo.getCC();
2916  enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2917  auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2918    bool isCompatible =
2919        (required == RequiredCC::OnlySwift)
2920            ? (actualCC == CC_Swift)
2921            : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2922    if (isCompatible || emittedError)
2923      return;
2924    S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2925        << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2926        << (required == RequiredCC::OnlySwift);
2927    emittedError = true;
2928  };
2929  for (size_t paramIndex = 0, numParams = paramTypes.size();
2930          paramIndex != numParams; ++paramIndex) {
2931    switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2932    // Nothing interesting to check for orindary-ABI parameters.
2933    case ParameterABI::Ordinary:
2934      continue;
2935
2936    // swift_indirect_result parameters must be a prefix of the function
2937    // arguments.
2938    case ParameterABI::SwiftIndirectResult:
2939      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2940      if (paramIndex != 0 &&
2941          EPI.ExtParameterInfos[paramIndex - 1].getABI()
2942            != ParameterABI::SwiftIndirectResult) {
2943        S.Diag(getParamLoc(paramIndex),
2944               diag::err_swift_indirect_result_not_first);
2945      }
2946      continue;
2947
2948    case ParameterABI::SwiftContext:
2949      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2950      continue;
2951
2952    // SwiftAsyncContext is not limited to swiftasynccall functions.
2953    case ParameterABI::SwiftAsyncContext:
2954      continue;
2955
2956    // swift_error parameters must be preceded by a swift_context parameter.
2957    case ParameterABI::SwiftErrorResult:
2958      checkCompatible(paramIndex, RequiredCC::OnlySwift);
2959      if (paramIndex == 0 ||
2960          EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2961              ParameterABI::SwiftContext) {
2962        S.Diag(getParamLoc(paramIndex),
2963               diag::err_swift_error_result_not_after_swift_context);
2964      }
2965      continue;
2966    }
2967    llvm_unreachable("bad ABI kind");
2968  }
2969}
2970
2971QualType Sema::BuildFunctionType(QualType T,
2972                                 MutableArrayRef<QualType> ParamTypes,
2973                                 SourceLocation Loc, DeclarationName Entity,
2974                                 const FunctionProtoType::ExtProtoInfo &EPI) {
2975  bool Invalid = false;
2976
2977  Invalid |= CheckFunctionReturnType(T, Loc);
2978
2979  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2980    // FIXME: Loc is too inprecise here, should use proper locations for args.
2981    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2982    if (ParamType->isVoidType()) {
2983      Diag(Loc, diag::err_param_with_void_type);
2984      Invalid = true;
2985    } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2986               !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2987      // Disallow half FP arguments.
2988      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2989        FixItHint::CreateInsertion(Loc, "*");
2990      Invalid = true;
2991    }
2992
2993    // C++2a [dcl.fct]p4:
2994    //   A parameter with volatile-qualified type is deprecated
2995    if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2996      Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2997
2998    ParamTypes[Idx] = ParamType;
2999  }
3000
3001  if (EPI.ExtParameterInfos) {
3002    checkExtParameterInfos(*this, ParamTypes, EPI,
3003                           [=](unsigned i) { return Loc; });
3004  }
3005
3006  if (EPI.ExtInfo.getProducesResult()) {
3007    // This is just a warning, so we can't fail to build if we see it.
3008    checkNSReturnsRetainedReturnType(Loc, T);
3009  }
3010
3011  if (Invalid)
3012    return QualType();
3013
3014  return Context.getFunctionType(T, ParamTypes, EPI);
3015}
3016
3017/// Build a member pointer type \c T Class::*.
3018///
3019/// \param T the type to which the member pointer refers.
3020/// \param Class the class type into which the member pointer points.
3021/// \param Loc the location where this type begins
3022/// \param Entity the name of the entity that will have this member pointer type
3023///
3024/// \returns a member pointer type, if successful, or a NULL type if there was
3025/// an error.
3026QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3027                                      SourceLocation Loc,
3028                                      DeclarationName Entity) {
3029  // Verify that we're not building a pointer to pointer to function with
3030  // exception specification.
3031  if (CheckDistantExceptionSpec(T)) {
3032    Diag(Loc, diag::err_distant_exception_spec);
3033    return QualType();
3034  }
3035
3036  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3037  //   with reference type, or "cv void."
3038  if (T->isReferenceType()) {
3039    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3040      << getPrintableNameForEntity(Entity) << T;
3041    return QualType();
3042  }
3043
3044  if (T->isVoidType()) {
3045    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3046      << getPrintableNameForEntity(Entity);
3047    return QualType();
3048  }
3049
3050  if (!Class->isDependentType() && !Class->isRecordType()) {
3051    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3052    return QualType();
3053  }
3054
3055  if (T->isFunctionType() && getLangOpts().OpenCL &&
3056      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3057                                            getLangOpts())) {
3058    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3059    return QualType();
3060  }
3061
3062  if (getLangOpts().HLSL && Loc.isValid()) {
3063    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3064    return QualType();
3065  }
3066
3067  // Adjust the default free function calling convention to the default method
3068  // calling convention.
3069  bool IsCtorOrDtor =
3070      (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3071      (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3072  if (T->isFunctionType())
3073    adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
3074
3075  return Context.getMemberPointerType(T, Class.getTypePtr());
3076}
3077
3078/// Build a block pointer type.
3079///
3080/// \param T The type to which we'll be building a block pointer.
3081///
3082/// \param Loc The source location, used for diagnostics.
3083///
3084/// \param Entity The name of the entity that involves the block pointer
3085/// type, if known.
3086///
3087/// \returns A suitable block pointer type, if there are no
3088/// errors. Otherwise, returns a NULL type.
3089QualType Sema::BuildBlockPointerType(QualType T,
3090                                     SourceLocation Loc,
3091                                     DeclarationName Entity) {
3092  if (!T->isFunctionType()) {
3093    Diag(Loc, diag::err_nonfunction_block_type);
3094    return QualType();
3095  }
3096
3097  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3098    return QualType();
3099
3100  if (getLangOpts().OpenCL)
3101    T = deduceOpenCLPointeeAddrSpace(*this, T);
3102
3103  return Context.getBlockPointerType(T);
3104}
3105
3106QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3107  QualType QT = Ty.get();
3108  if (QT.isNull()) {
3109    if (TInfo) *TInfo = nullptr;
3110    return QualType();
3111  }
3112
3113  TypeSourceInfo *DI = nullptr;
3114  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3115    QT = LIT->getType();
3116    DI = LIT->getTypeSourceInfo();
3117  }
3118
3119  if (TInfo) *TInfo = DI;
3120  return QT;
3121}
3122
3123static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3124                                            Qualifiers::ObjCLifetime ownership,
3125                                            unsigned chunkIndex);
3126
3127/// Given that this is the declaration of a parameter under ARC,
3128/// attempt to infer attributes and such for pointer-to-whatever
3129/// types.
3130static void inferARCWriteback(TypeProcessingState &state,
3131                              QualType &declSpecType) {
3132  Sema &S = state.getSema();
3133  Declarator &declarator = state.getDeclarator();
3134
3135  // TODO: should we care about decl qualifiers?
3136
3137  // Check whether the declarator has the expected form.  We walk
3138  // from the inside out in order to make the block logic work.
3139  unsigned outermostPointerIndex = 0;
3140  bool isBlockPointer = false;
3141  unsigned numPointers = 0;
3142  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3143    unsigned chunkIndex = i;
3144    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3145    switch (chunk.Kind) {
3146    case DeclaratorChunk::Paren:
3147      // Ignore parens.
3148      break;
3149
3150    case DeclaratorChunk::Reference:
3151    case DeclaratorChunk::Pointer:
3152      // Count the number of pointers.  Treat references
3153      // interchangeably as pointers; if they're mis-ordered, normal
3154      // type building will discover that.
3155      outermostPointerIndex = chunkIndex;
3156      numPointers++;
3157      break;
3158
3159    case DeclaratorChunk::BlockPointer:
3160      // If we have a pointer to block pointer, that's an acceptable
3161      // indirect reference; anything else is not an application of
3162      // the rules.
3163      if (numPointers != 1) return;
3164      numPointers++;
3165      outermostPointerIndex = chunkIndex;
3166      isBlockPointer = true;
3167
3168      // We don't care about pointer structure in return values here.
3169      goto done;
3170
3171    case DeclaratorChunk::Array: // suppress if written (id[])?
3172    case DeclaratorChunk::Function:
3173    case DeclaratorChunk::MemberPointer:
3174    case DeclaratorChunk::Pipe:
3175      return;
3176    }
3177  }
3178 done:
3179
3180  // If we have *one* pointer, then we want to throw the qualifier on
3181  // the declaration-specifiers, which means that it needs to be a
3182  // retainable object type.
3183  if (numPointers == 1) {
3184    // If it's not a retainable object type, the rule doesn't apply.
3185    if (!declSpecType->isObjCRetainableType()) return;
3186
3187    // If it already has lifetime, don't do anything.
3188    if (declSpecType.getObjCLifetime()) return;
3189
3190    // Otherwise, modify the type in-place.
3191    Qualifiers qs;
3192
3193    if (declSpecType->isObjCARCImplicitlyUnretainedType())
3194      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3195    else
3196      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3197    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3198
3199  // If we have *two* pointers, then we want to throw the qualifier on
3200  // the outermost pointer.
3201  } else if (numPointers == 2) {
3202    // If we don't have a block pointer, we need to check whether the
3203    // declaration-specifiers gave us something that will turn into a
3204    // retainable object pointer after we slap the first pointer on it.
3205    if (!isBlockPointer && !declSpecType->isObjCObjectType())
3206      return;
3207
3208    // Look for an explicit lifetime attribute there.
3209    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3210    if (chunk.Kind != DeclaratorChunk::Pointer &&
3211        chunk.Kind != DeclaratorChunk::BlockPointer)
3212      return;
3213    for (const ParsedAttr &AL : chunk.getAttrs())
3214      if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3215        return;
3216
3217    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3218                                          outermostPointerIndex);
3219
3220  // Any other number of pointers/references does not trigger the rule.
3221  } else return;
3222
3223  // TODO: mark whether we did this inference?
3224}
3225
3226void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3227                                     SourceLocation FallbackLoc,
3228                                     SourceLocation ConstQualLoc,
3229                                     SourceLocation VolatileQualLoc,
3230                                     SourceLocation RestrictQualLoc,
3231                                     SourceLocation AtomicQualLoc,
3232                                     SourceLocation UnalignedQualLoc) {
3233  if (!Quals)
3234    return;
3235
3236  struct Qual {
3237    const char *Name;
3238    unsigned Mask;
3239    SourceLocation Loc;
3240  } const QualKinds[5] = {
3241    { "const", DeclSpec::TQ_const, ConstQualLoc },
3242    { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3243    { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3244    { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3245    { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3246  };
3247
3248  SmallString<32> QualStr;
3249  unsigned NumQuals = 0;
3250  SourceLocation Loc;
3251  FixItHint FixIts[5];
3252
3253  // Build a string naming the redundant qualifiers.
3254  for (auto &E : QualKinds) {
3255    if (Quals & E.Mask) {
3256      if (!QualStr.empty()) QualStr += ' ';
3257      QualStr += E.Name;
3258
3259      // If we have a location for the qualifier, offer a fixit.
3260      SourceLocation QualLoc = E.Loc;
3261      if (QualLoc.isValid()) {
3262        FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3263        if (Loc.isInvalid() ||
3264            getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3265          Loc = QualLoc;
3266      }
3267
3268      ++NumQuals;
3269    }
3270  }
3271
3272  Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3273    << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3274}
3275
3276// Diagnose pointless type qualifiers on the return type of a function.
3277static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3278                                                  Declarator &D,
3279                                                  unsigned FunctionChunkIndex) {
3280  const DeclaratorChunk::FunctionTypeInfo &FTI =
3281      D.getTypeObject(FunctionChunkIndex).Fun;
3282  if (FTI.hasTrailingReturnType()) {
3283    S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3284                                RetTy.getLocalCVRQualifiers(),
3285                                FTI.getTrailingReturnTypeLoc());
3286    return;
3287  }
3288
3289  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3290                End = D.getNumTypeObjects();
3291       OuterChunkIndex != End; ++OuterChunkIndex) {
3292    DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3293    switch (OuterChunk.Kind) {
3294    case DeclaratorChunk::Paren:
3295      continue;
3296
3297    case DeclaratorChunk::Pointer: {
3298      DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3299      S.diagnoseIgnoredQualifiers(
3300          diag::warn_qual_return_type,
3301          PTI.TypeQuals,
3302          SourceLocation(),
3303          PTI.ConstQualLoc,
3304          PTI.VolatileQualLoc,
3305          PTI.RestrictQualLoc,
3306          PTI.AtomicQualLoc,
3307          PTI.UnalignedQualLoc);
3308      return;
3309    }
3310
3311    case DeclaratorChunk::Function:
3312    case DeclaratorChunk::BlockPointer:
3313    case DeclaratorChunk::Reference:
3314    case DeclaratorChunk::Array:
3315    case DeclaratorChunk::MemberPointer:
3316    case DeclaratorChunk::Pipe:
3317      // FIXME: We can't currently provide an accurate source location and a
3318      // fix-it hint for these.
3319      unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3320      S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3321                                  RetTy.getCVRQualifiers() | AtomicQual,
3322                                  D.getIdentifierLoc());
3323      return;
3324    }
3325
3326    llvm_unreachable("unknown declarator chunk kind");
3327  }
3328
3329  // If the qualifiers come from a conversion function type, don't diagnose
3330  // them -- they're not necessarily redundant, since such a conversion
3331  // operator can be explicitly called as "x.operator const int()".
3332  if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3333    return;
3334
3335  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3336  // which are present there.
3337  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3338                              D.getDeclSpec().getTypeQualifiers(),
3339                              D.getIdentifierLoc(),
3340                              D.getDeclSpec().getConstSpecLoc(),
3341                              D.getDeclSpec().getVolatileSpecLoc(),
3342                              D.getDeclSpec().getRestrictSpecLoc(),
3343                              D.getDeclSpec().getAtomicSpecLoc(),
3344                              D.getDeclSpec().getUnalignedSpecLoc());
3345}
3346
3347static std::pair<QualType, TypeSourceInfo *>
3348InventTemplateParameter(TypeProcessingState &state, QualType T,
3349                        TypeSourceInfo *TrailingTSI, AutoType *Auto,
3350                        InventedTemplateParameterInfo &Info) {
3351  Sema &S = state.getSema();
3352  Declarator &D = state.getDeclarator();
3353
3354  const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3355  const unsigned AutoParameterPosition = Info.TemplateParams.size();
3356  const bool IsParameterPack = D.hasEllipsis();
3357
3358  // If auto is mentioned in a lambda parameter or abbreviated function
3359  // template context, convert it to a template parameter type.
3360
3361  // Create the TemplateTypeParmDecl here to retrieve the corresponding
3362  // template parameter type. Template parameters are temporarily added
3363  // to the TU until the associated TemplateDecl is created.
3364  TemplateTypeParmDecl *InventedTemplateParam =
3365      TemplateTypeParmDecl::Create(
3366          S.Context, S.Context.getTranslationUnitDecl(),
3367          /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3368          /*NameLoc=*/D.getIdentifierLoc(),
3369          TemplateParameterDepth, AutoParameterPosition,
3370          S.InventAbbreviatedTemplateParameterTypeName(
3371              D.getIdentifier(), AutoParameterPosition), false,
3372          IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3373  InventedTemplateParam->setImplicit();
3374  Info.TemplateParams.push_back(InventedTemplateParam);
3375
3376  // Attach type constraints to the new parameter.
3377  if (Auto->isConstrained()) {
3378    if (TrailingTSI) {
3379      // The 'auto' appears in a trailing return type we've already built;
3380      // extract its type constraints to attach to the template parameter.
3381      AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3382      TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3383      bool Invalid = false;
3384      for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3385        if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3386            S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3387                                              Sema::UPPC_TypeConstraint))
3388          Invalid = true;
3389        TAL.addArgument(AutoLoc.getArgLoc(Idx));
3390      }
3391
3392      if (!Invalid) {
3393        S.AttachTypeConstraint(
3394            AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3395            AutoLoc.getNamedConcept(),
3396            AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3397            InventedTemplateParam, D.getEllipsisLoc());
3398      }
3399    } else {
3400      // The 'auto' appears in the decl-specifiers; we've not finished forming
3401      // TypeSourceInfo for it yet.
3402      TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3403      TemplateArgumentListInfo TemplateArgsInfo;
3404      bool Invalid = false;
3405      if (TemplateId->LAngleLoc.isValid()) {
3406        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3407                                           TemplateId->NumArgs);
3408        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3409
3410        if (D.getEllipsisLoc().isInvalid()) {
3411          for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3412            if (S.DiagnoseUnexpandedParameterPack(Arg,
3413                                                  Sema::UPPC_TypeConstraint)) {
3414              Invalid = true;
3415              break;
3416            }
3417          }
3418        }
3419      }
3420      if (!Invalid) {
3421        S.AttachTypeConstraint(
3422            D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3423            DeclarationNameInfo(DeclarationName(TemplateId->Name),
3424                                TemplateId->TemplateNameLoc),
3425            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3426            TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3427            InventedTemplateParam, D.getEllipsisLoc());
3428      }
3429    }
3430  }
3431
3432  // Replace the 'auto' in the function parameter with this invented
3433  // template type parameter.
3434  // FIXME: Retain some type sugar to indicate that this was written
3435  //  as 'auto'?
3436  QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3437  QualType NewT = state.ReplaceAutoType(T, Replacement);
3438  TypeSourceInfo *NewTSI =
3439      TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3440                  : nullptr;
3441  return {NewT, NewTSI};
3442}
3443
3444static TypeSourceInfo *
3445GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3446                               QualType T, TypeSourceInfo *ReturnTypeInfo);
3447
3448static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3449                                             TypeSourceInfo *&ReturnTypeInfo) {
3450  Sema &SemaRef = state.getSema();
3451  Declarator &D = state.getDeclarator();
3452  QualType T;
3453  ReturnTypeInfo = nullptr;
3454
3455  // The TagDecl owned by the DeclSpec.
3456  TagDecl *OwnedTagDecl = nullptr;
3457
3458  switch (D.getName().getKind()) {
3459  case UnqualifiedIdKind::IK_ImplicitSelfParam:
3460  case UnqualifiedIdKind::IK_OperatorFunctionId:
3461  case UnqualifiedIdKind::IK_Identifier:
3462  case UnqualifiedIdKind::IK_LiteralOperatorId:
3463  case UnqualifiedIdKind::IK_TemplateId:
3464    T = ConvertDeclSpecToType(state);
3465
3466    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3467      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3468      // Owned declaration is embedded in declarator.
3469      OwnedTagDecl->setEmbeddedInDeclarator(true);
3470    }
3471    break;
3472
3473  case UnqualifiedIdKind::IK_ConstructorName:
3474  case UnqualifiedIdKind::IK_ConstructorTemplateId:
3475  case UnqualifiedIdKind::IK_DestructorName:
3476    // Constructors and destructors don't have return types. Use
3477    // "void" instead.
3478    T = SemaRef.Context.VoidTy;
3479    processTypeAttrs(state, T, TAL_DeclSpec,
3480                     D.getMutableDeclSpec().getAttributes());
3481    break;
3482
3483  case UnqualifiedIdKind::IK_DeductionGuideName:
3484    // Deduction guides have a trailing return type and no type in their
3485    // decl-specifier sequence. Use a placeholder return type for now.
3486    T = SemaRef.Context.DependentTy;
3487    break;
3488
3489  case UnqualifiedIdKind::IK_ConversionFunctionId:
3490    // The result type of a conversion function is the type that it
3491    // converts to.
3492    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3493                                  &ReturnTypeInfo);
3494    break;
3495  }
3496
3497  // Note: We don't need to distribute declaration attributes (i.e.
3498  // D.getDeclarationAttributes()) because those are always C++11 attributes,
3499  // and those don't get distributed.
3500  distributeTypeAttrsFromDeclarator(state, T);
3501
3502  // Find the deduced type in this type. Look in the trailing return type if we
3503  // have one, otherwise in the DeclSpec type.
3504  // FIXME: The standard wording doesn't currently describe this.
3505  DeducedType *Deduced = T->getContainedDeducedType();
3506  bool DeducedIsTrailingReturnType = false;
3507  if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3508    QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3509    Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3510    DeducedIsTrailingReturnType = true;
3511  }
3512
3513  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3514  if (Deduced) {
3515    AutoType *Auto = dyn_cast<AutoType>(Deduced);
3516    int Error = -1;
3517
3518    // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3519    // class template argument deduction)?
3520    bool IsCXXAutoType =
3521        (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3522    bool IsDeducedReturnType = false;
3523
3524    switch (D.getContext()) {
3525    case DeclaratorContext::LambdaExpr:
3526      // Declared return type of a lambda-declarator is implicit and is always
3527      // 'auto'.
3528      break;
3529    case DeclaratorContext::ObjCParameter:
3530    case DeclaratorContext::ObjCResult:
3531      Error = 0;
3532      break;
3533    case DeclaratorContext::RequiresExpr:
3534      Error = 22;
3535      break;
3536    case DeclaratorContext::Prototype:
3537    case DeclaratorContext::LambdaExprParameter: {
3538      InventedTemplateParameterInfo *Info = nullptr;
3539      if (D.getContext() == DeclaratorContext::Prototype) {
3540        // With concepts we allow 'auto' in function parameters.
3541        if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3542            Auto->getKeyword() != AutoTypeKeyword::Auto) {
3543          Error = 0;
3544          break;
3545        } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3546          Error = 21;
3547          break;
3548        }
3549
3550        Info = &SemaRef.InventedParameterInfos.back();
3551      } else {
3552        // In C++14, generic lambdas allow 'auto' in their parameters.
3553        if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3554            Auto->getKeyword() != AutoTypeKeyword::Auto) {
3555          Error = 16;
3556          break;
3557        }
3558        Info = SemaRef.getCurLambda();
3559        assert(Info && "No LambdaScopeInfo on the stack!");
3560      }
3561
3562      // We'll deal with inventing template parameters for 'auto' in trailing
3563      // return types when we pick up the trailing return type when processing
3564      // the function chunk.
3565      if (!DeducedIsTrailingReturnType)
3566        T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3567      break;
3568    }
3569    case DeclaratorContext::Member: {
3570      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3571          D.isFunctionDeclarator())
3572        break;
3573      bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3574      if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3575        Error = 6; // Interface member.
3576      } else {
3577        switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3578        case TTK_Enum: llvm_unreachable("unhandled tag kind");
3579        case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3580        case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
3581        case TTK_Class:  Error = 5; /* Class member */ break;
3582        case TTK_Interface: Error = 6; /* Interface member */ break;
3583        }
3584      }
3585      if (D.getDeclSpec().isFriendSpecified())
3586        Error = 20; // Friend type
3587      break;
3588    }
3589    case DeclaratorContext::CXXCatch:
3590    case DeclaratorContext::ObjCCatch:
3591      Error = 7; // Exception declaration
3592      break;
3593    case DeclaratorContext::TemplateParam:
3594      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3595          !SemaRef.getLangOpts().CPlusPlus20)
3596        Error = 19; // Template parameter (until C++20)
3597      else if (!SemaRef.getLangOpts().CPlusPlus17)
3598        Error = 8; // Template parameter (until C++17)
3599      break;
3600    case DeclaratorContext::BlockLiteral:
3601      Error = 9; // Block literal
3602      break;
3603    case DeclaratorContext::TemplateArg:
3604      // Within a template argument list, a deduced template specialization
3605      // type will be reinterpreted as a template template argument.
3606      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3607          !D.getNumTypeObjects() &&
3608          D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3609        break;
3610      [[fallthrough]];
3611    case DeclaratorContext::TemplateTypeArg:
3612      Error = 10; // Template type argument
3613      break;
3614    case DeclaratorContext::AliasDecl:
3615    case DeclaratorContext::AliasTemplate:
3616      Error = 12; // Type alias
3617      break;
3618    case DeclaratorContext::TrailingReturn:
3619    case DeclaratorContext::TrailingReturnVar:
3620      if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3621        Error = 13; // Function return type
3622      IsDeducedReturnType = true;
3623      break;
3624    case DeclaratorContext::ConversionId:
3625      if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3626        Error = 14; // conversion-type-id
3627      IsDeducedReturnType = true;
3628      break;
3629    case DeclaratorContext::FunctionalCast:
3630      if (isa<DeducedTemplateSpecializationType>(Deduced))
3631        break;
3632      if (SemaRef.getLangOpts().CPlusPlus2b && IsCXXAutoType &&
3633          !Auto->isDecltypeAuto())
3634        break; // auto(x)
3635      [[fallthrough]];
3636    case DeclaratorContext::TypeName:
3637    case DeclaratorContext::Association:
3638      Error = 15; // Generic
3639      break;
3640    case DeclaratorContext::File:
3641    case DeclaratorContext::Block:
3642    case DeclaratorContext::ForInit:
3643    case DeclaratorContext::SelectionInit:
3644    case DeclaratorContext::Condition:
3645      // FIXME: P0091R3 (erroneously) does not permit class template argument
3646      // deduction in conditions, for-init-statements, and other declarations
3647      // that are not simple-declarations.
3648      break;
3649    case DeclaratorContext::CXXNew:
3650      // FIXME: P0091R3 does not permit class template argument deduction here,
3651      // but we follow GCC and allow it anyway.
3652      if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3653        Error = 17; // 'new' type
3654      break;
3655    case DeclaratorContext::KNRTypeList:
3656      Error = 18; // K&R function parameter
3657      break;
3658    }
3659
3660    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3661      Error = 11;
3662
3663    // In Objective-C it is an error to use 'auto' on a function declarator
3664    // (and everywhere for '__auto_type').
3665    if (D.isFunctionDeclarator() &&
3666        (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3667      Error = 13;
3668
3669    SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3670    if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3671      AutoRange = D.getName().getSourceRange();
3672
3673    if (Error != -1) {
3674      unsigned Kind;
3675      if (Auto) {
3676        switch (Auto->getKeyword()) {
3677        case AutoTypeKeyword::Auto: Kind = 0; break;
3678        case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3679        case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3680        }
3681      } else {
3682        assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3683               "unknown auto type");
3684        Kind = 3;
3685      }
3686
3687      auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3688      TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3689
3690      SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3691        << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3692        << QualType(Deduced, 0) << AutoRange;
3693      if (auto *TD = TN.getAsTemplateDecl())
3694        SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3695
3696      T = SemaRef.Context.IntTy;
3697      D.setInvalidType(true);
3698    } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3699      // If there was a trailing return type, we already got
3700      // warn_cxx98_compat_trailing_return_type in the parser.
3701      SemaRef.Diag(AutoRange.getBegin(),
3702                   D.getContext() == DeclaratorContext::LambdaExprParameter
3703                       ? diag::warn_cxx11_compat_generic_lambda
3704                   : IsDeducedReturnType
3705                       ? diag::warn_cxx11_compat_deduced_return_type
3706                       : diag::warn_cxx98_compat_auto_type_specifier)
3707          << AutoRange;
3708    }
3709  }
3710
3711  if (SemaRef.getLangOpts().CPlusPlus &&
3712      OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3713    // Check the contexts where C++ forbids the declaration of a new class
3714    // or enumeration in a type-specifier-seq.
3715    unsigned DiagID = 0;
3716    switch (D.getContext()) {
3717    case DeclaratorContext::TrailingReturn:
3718    case DeclaratorContext::TrailingReturnVar:
3719      // Class and enumeration definitions are syntactically not allowed in
3720      // trailing return types.
3721      llvm_unreachable("parser should not have allowed this");
3722      break;
3723    case DeclaratorContext::File:
3724    case DeclaratorContext::Member:
3725    case DeclaratorContext::Block:
3726    case DeclaratorContext::ForInit:
3727    case DeclaratorContext::SelectionInit:
3728    case DeclaratorContext::BlockLiteral:
3729    case DeclaratorContext::LambdaExpr:
3730      // C++11 [dcl.type]p3:
3731      //   A type-specifier-seq shall not define a class or enumeration unless
3732      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3733      //   the declaration of a template-declaration.
3734    case DeclaratorContext::AliasDecl:
3735      break;
3736    case DeclaratorContext::AliasTemplate:
3737      DiagID = diag::err_type_defined_in_alias_template;
3738      break;
3739    case DeclaratorContext::TypeName:
3740    case DeclaratorContext::FunctionalCast:
3741    case DeclaratorContext::ConversionId:
3742    case DeclaratorContext::TemplateParam:
3743    case DeclaratorContext::CXXNew:
3744    case DeclaratorContext::CXXCatch:
3745    case DeclaratorContext::ObjCCatch:
3746    case DeclaratorContext::TemplateArg:
3747    case DeclaratorContext::TemplateTypeArg:
3748    case DeclaratorContext::Association:
3749      DiagID = diag::err_type_defined_in_type_specifier;
3750      break;
3751    case DeclaratorContext::Prototype:
3752    case DeclaratorContext::LambdaExprParameter:
3753    case DeclaratorContext::ObjCParameter:
3754    case DeclaratorContext::ObjCResult:
3755    case DeclaratorContext::KNRTypeList:
3756    case DeclaratorContext::RequiresExpr:
3757      // C++ [dcl.fct]p6:
3758      //   Types shall not be defined in return or parameter types.
3759      DiagID = diag::err_type_defined_in_param_type;
3760      break;
3761    case DeclaratorContext::Condition:
3762      // C++ 6.4p2:
3763      // The type-specifier-seq shall not contain typedef and shall not declare
3764      // a new class or enumeration.
3765      DiagID = diag::err_type_defined_in_condition;
3766      break;
3767    }
3768
3769    if (DiagID != 0) {
3770      SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3771          << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3772      D.setInvalidType(true);
3773    }
3774  }
3775
3776  assert(!T.isNull() && "This function should not return a null type");
3777  return T;
3778}
3779
3780/// Produce an appropriate diagnostic for an ambiguity between a function
3781/// declarator and a C++ direct-initializer.
3782static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3783                                       DeclaratorChunk &DeclType, QualType RT) {
3784  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3785  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3786
3787  // If the return type is void there is no ambiguity.
3788  if (RT->isVoidType())
3789    return;
3790
3791  // An initializer for a non-class type can have at most one argument.
3792  if (!RT->isRecordType() && FTI.NumParams > 1)
3793    return;
3794
3795  // An initializer for a reference must have exactly one argument.
3796  if (RT->isReferenceType() && FTI.NumParams != 1)
3797    return;
3798
3799  // Only warn if this declarator is declaring a function at block scope, and
3800  // doesn't have a storage class (such as 'extern') specified.
3801  if (!D.isFunctionDeclarator() ||
3802      D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3803      !S.CurContext->isFunctionOrMethod() ||
3804      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3805    return;
3806
3807  // Inside a condition, a direct initializer is not permitted. We allow one to
3808  // be parsed in order to give better diagnostics in condition parsing.
3809  if (D.getContext() == DeclaratorContext::Condition)
3810    return;
3811
3812  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3813
3814  S.Diag(DeclType.Loc,
3815         FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3816                       : diag::warn_empty_parens_are_function_decl)
3817      << ParenRange;
3818
3819  // If the declaration looks like:
3820  //   T var1,
3821  //   f();
3822  // and name lookup finds a function named 'f', then the ',' was
3823  // probably intended to be a ';'.
3824  if (!D.isFirstDeclarator() && D.getIdentifier()) {
3825    FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3826    FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3827    if (Comma.getFileID() != Name.getFileID() ||
3828        Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3829      LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3830                          Sema::LookupOrdinaryName);
3831      if (S.LookupName(Result, S.getCurScope()))
3832        S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3833          << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3834          << D.getIdentifier();
3835      Result.suppressDiagnostics();
3836    }
3837  }
3838
3839  if (FTI.NumParams > 0) {
3840    // For a declaration with parameters, eg. "T var(T());", suggest adding
3841    // parens around the first parameter to turn the declaration into a
3842    // variable declaration.
3843    SourceRange Range = FTI.Params[0].Param->getSourceRange();
3844    SourceLocation B = Range.getBegin();
3845    SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3846    // FIXME: Maybe we should suggest adding braces instead of parens
3847    // in C++11 for classes that don't have an initializer_list constructor.
3848    S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3849      << FixItHint::CreateInsertion(B, "(")
3850      << FixItHint::CreateInsertion(E, ")");
3851  } else {
3852    // For a declaration without parameters, eg. "T var();", suggest replacing
3853    // the parens with an initializer to turn the declaration into a variable
3854    // declaration.
3855    const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3856
3857    // Empty parens mean value-initialization, and no parens mean
3858    // default initialization. These are equivalent if the default
3859    // constructor is user-provided or if zero-initialization is a
3860    // no-op.
3861    if (RD && RD->hasDefinition() &&
3862        (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3863      S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3864        << FixItHint::CreateRemoval(ParenRange);
3865    else {
3866      std::string Init =
3867          S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3868      if (Init.empty() && S.LangOpts.CPlusPlus11)
3869        Init = "{}";
3870      if (!Init.empty())
3871        S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3872          << FixItHint::CreateReplacement(ParenRange, Init);
3873    }
3874  }
3875}
3876
3877/// Produce an appropriate diagnostic for a declarator with top-level
3878/// parentheses.
3879static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3880  DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3881  assert(Paren.Kind == DeclaratorChunk::Paren &&
3882         "do not have redundant top-level parentheses");
3883
3884  // This is a syntactic check; we're not interested in cases that arise
3885  // during template instantiation.
3886  if (S.inTemplateInstantiation())
3887    return;
3888
3889  // Check whether this could be intended to be a construction of a temporary
3890  // object in C++ via a function-style cast.
3891  bool CouldBeTemporaryObject =
3892      S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3893      !D.isInvalidType() && D.getIdentifier() &&
3894      D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3895      (T->isRecordType() || T->isDependentType()) &&
3896      D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3897
3898  bool StartsWithDeclaratorId = true;
3899  for (auto &C : D.type_objects()) {
3900    switch (C.Kind) {
3901    case DeclaratorChunk::Paren:
3902      if (&C == &Paren)
3903        continue;
3904      [[fallthrough]];
3905    case DeclaratorChunk::Pointer:
3906      StartsWithDeclaratorId = false;
3907      continue;
3908
3909    case DeclaratorChunk::Array:
3910      if (!C.Arr.NumElts)
3911        CouldBeTemporaryObject = false;
3912      continue;
3913
3914    case DeclaratorChunk::Reference:
3915      // FIXME: Suppress the warning here if there is no initializer; we're
3916      // going to give an error anyway.
3917      // We assume that something like 'T (&x) = y;' is highly likely to not
3918      // be intended to be a temporary object.
3919      CouldBeTemporaryObject = false;
3920      StartsWithDeclaratorId = false;
3921      continue;
3922
3923    case DeclaratorChunk::Function:
3924      // In a new-type-id, function chunks require parentheses.
3925      if (D.getContext() == DeclaratorContext::CXXNew)
3926        return;
3927      // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3928      // redundant-parens warning, but we don't know whether the function
3929      // chunk was syntactically valid as an expression here.
3930      CouldBeTemporaryObject = false;
3931      continue;
3932
3933    case DeclaratorChunk::BlockPointer:
3934    case DeclaratorChunk::MemberPointer:
3935    case DeclaratorChunk::Pipe:
3936      // These cannot appear in expressions.
3937      CouldBeTemporaryObject = false;
3938      StartsWithDeclaratorId = false;
3939      continue;
3940    }
3941  }
3942
3943  // FIXME: If there is an initializer, assume that this is not intended to be
3944  // a construction of a temporary object.
3945
3946  // Check whether the name has already been declared; if not, this is not a
3947  // function-style cast.
3948  if (CouldBeTemporaryObject) {
3949    LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3950                        Sema::LookupOrdinaryName);
3951    if (!S.LookupName(Result, S.getCurScope()))
3952      CouldBeTemporaryObject = false;
3953    Result.suppressDiagnostics();
3954  }
3955
3956  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3957
3958  if (!CouldBeTemporaryObject) {
3959    // If we have A (::B), the parentheses affect the meaning of the program.
3960    // Suppress the warning in that case. Don't bother looking at the DeclSpec
3961    // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3962    // formally unambiguous.
3963    if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3964      for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3965           NNS = NNS->getPrefix()) {
3966        if (NNS->getKind() == NestedNameSpecifier::Global)
3967          return;
3968      }
3969    }
3970
3971    S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3972        << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3973        << FixItHint::CreateRemoval(Paren.EndLoc);
3974    return;
3975  }
3976
3977  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3978      << ParenRange << D.getIdentifier();
3979  auto *RD = T->getAsCXXRecordDecl();
3980  if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3981    S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3982        << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3983        << D.getIdentifier();
3984  // FIXME: A cast to void is probably a better suggestion in cases where it's
3985  // valid (when there is no initializer and we're not in a condition).
3986  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3987      << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3988      << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3989  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3990      << FixItHint::CreateRemoval(Paren.Loc)
3991      << FixItHint::CreateRemoval(Paren.EndLoc);
3992}
3993
3994/// Helper for figuring out the default CC for a function declarator type.  If
3995/// this is the outermost chunk, then we can determine the CC from the
3996/// declarator context.  If not, then this could be either a member function
3997/// type or normal function type.
3998static CallingConv getCCForDeclaratorChunk(
3999    Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4000    const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4001  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4002
4003  // Check for an explicit CC attribute.
4004  for (const ParsedAttr &AL : AttrList) {
4005    switch (AL.getKind()) {
4006    CALLING_CONV_ATTRS_CASELIST : {
4007      // Ignore attributes that don't validate or can't apply to the
4008      // function type.  We'll diagnose the failure to apply them in
4009      // handleFunctionTypeAttr.
4010      CallingConv CC;
4011      if (!S.CheckCallingConvAttr(AL, CC) &&
4012          (!FTI.isVariadic || supportsVariadicCall(CC))) {
4013        return CC;
4014      }
4015      break;
4016    }
4017
4018    default:
4019      break;
4020    }
4021  }
4022
4023  bool IsCXXInstanceMethod = false;
4024
4025  if (S.getLangOpts().CPlusPlus) {
4026    // Look inwards through parentheses to see if this chunk will form a
4027    // member pointer type or if we're the declarator.  Any type attributes
4028    // between here and there will override the CC we choose here.
4029    unsigned I = ChunkIndex;
4030    bool FoundNonParen = false;
4031    while (I && !FoundNonParen) {
4032      --I;
4033      if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4034        FoundNonParen = true;
4035    }
4036
4037    if (FoundNonParen) {
4038      // If we're not the declarator, we're a regular function type unless we're
4039      // in a member pointer.
4040      IsCXXInstanceMethod =
4041          D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4042    } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4043      // This can only be a call operator for a lambda, which is an instance
4044      // method.
4045      IsCXXInstanceMethod = true;
4046    } else {
4047      // We're the innermost decl chunk, so must be a function declarator.
4048      assert(D.isFunctionDeclarator());
4049
4050      // If we're inside a record, we're declaring a method, but it could be
4051      // explicitly or implicitly static.
4052      IsCXXInstanceMethod =
4053          D.isFirstDeclarationOfMember() &&
4054          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4055          !D.isStaticMember();
4056    }
4057  }
4058
4059  CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4060                                                         IsCXXInstanceMethod);
4061
4062  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4063  // and AMDGPU targets, hence it cannot be treated as a calling
4064  // convention attribute. This is the simplest place to infer
4065  // calling convention for OpenCL kernels.
4066  if (S.getLangOpts().OpenCL) {
4067    for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4068      if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4069        CC = CC_OpenCLKernel;
4070        break;
4071      }
4072    }
4073  } else if (S.getLangOpts().CUDA) {
4074    // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4075    // sure the kernels will be marked with the right calling convention so that
4076    // they will be visible by the APIs that ingest SPIR-V.
4077    llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4078    if (Triple.getArch() == llvm::Triple::spirv32 ||
4079        Triple.getArch() == llvm::Triple::spirv64) {
4080      for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4081        if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4082          CC = CC_OpenCLKernel;
4083          break;
4084        }
4085      }
4086    }
4087  }
4088
4089  return CC;
4090}
4091
4092namespace {
4093  /// A simple notion of pointer kinds, which matches up with the various
4094  /// pointer declarators.
4095  enum class SimplePointerKind {
4096    Pointer,
4097    BlockPointer,
4098    MemberPointer,
4099    Array,
4100  };
4101} // end anonymous namespace
4102
4103IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4104  switch (nullability) {
4105  case NullabilityKind::NonNull:
4106    if (!Ident__Nonnull)
4107      Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4108    return Ident__Nonnull;
4109
4110  case NullabilityKind::Nullable:
4111    if (!Ident__Nullable)
4112      Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4113    return Ident__Nullable;
4114
4115  case NullabilityKind::NullableResult:
4116    if (!Ident__Nullable_result)
4117      Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4118    return Ident__Nullable_result;
4119
4120  case NullabilityKind::Unspecified:
4121    if (!Ident__Null_unspecified)
4122      Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4123    return Ident__Null_unspecified;
4124  }
4125  llvm_unreachable("Unknown nullability kind.");
4126}
4127
4128/// Retrieve the identifier "NSError".
4129IdentifierInfo *Sema::getNSErrorIdent() {
4130  if (!Ident_NSError)
4131    Ident_NSError = PP.getIdentifierInfo("NSError");
4132
4133  return Ident_NSError;
4134}
4135
4136/// Check whether there is a nullability attribute of any kind in the given
4137/// attribute list.
4138static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4139  for (const ParsedAttr &AL : attrs) {
4140    if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4141        AL.getKind() == ParsedAttr::AT_TypeNullable ||
4142        AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4143        AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4144      return true;
4145  }
4146
4147  return false;
4148}
4149
4150namespace {
4151  /// Describes the kind of a pointer a declarator describes.
4152  enum class PointerDeclaratorKind {
4153    // Not a pointer.
4154    NonPointer,
4155    // Single-level pointer.
4156    SingleLevelPointer,
4157    // Multi-level pointer (of any pointer kind).
4158    MultiLevelPointer,
4159    // CFFooRef*
4160    MaybePointerToCFRef,
4161    // CFErrorRef*
4162    CFErrorRefPointer,
4163    // NSError**
4164    NSErrorPointerPointer,
4165  };
4166
4167  /// Describes a declarator chunk wrapping a pointer that marks inference as
4168  /// unexpected.
4169  // These values must be kept in sync with diagnostics.
4170  enum class PointerWrappingDeclaratorKind {
4171    /// Pointer is top-level.
4172    None = -1,
4173    /// Pointer is an array element.
4174    Array = 0,
4175    /// Pointer is the referent type of a C++ reference.
4176    Reference = 1
4177  };
4178} // end anonymous namespace
4179
4180/// Classify the given declarator, whose type-specified is \c type, based on
4181/// what kind of pointer it refers to.
4182///
4183/// This is used to determine the default nullability.
4184static PointerDeclaratorKind
4185classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4186                          PointerWrappingDeclaratorKind &wrappingKind) {
4187  unsigned numNormalPointers = 0;
4188
4189  // For any dependent type, we consider it a non-pointer.
4190  if (type->isDependentType())
4191    return PointerDeclaratorKind::NonPointer;
4192
4193  // Look through the declarator chunks to identify pointers.
4194  for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4195    DeclaratorChunk &chunk = declarator.getTypeObject(i);
4196    switch (chunk.Kind) {
4197    case DeclaratorChunk::Array:
4198      if (numNormalPointers == 0)
4199        wrappingKind = PointerWrappingDeclaratorKind::Array;
4200      break;
4201
4202    case DeclaratorChunk::Function:
4203    case DeclaratorChunk::Pipe:
4204      break;
4205
4206    case DeclaratorChunk::BlockPointer:
4207    case DeclaratorChunk::MemberPointer:
4208      return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4209                                   : PointerDeclaratorKind::SingleLevelPointer;
4210
4211    case DeclaratorChunk::Paren:
4212      break;
4213
4214    case DeclaratorChunk::Reference:
4215      if (numNormalPointers == 0)
4216        wrappingKind = PointerWrappingDeclaratorKind::Reference;
4217      break;
4218
4219    case DeclaratorChunk::Pointer:
4220      ++numNormalPointers;
4221      if (numNormalPointers > 2)
4222        return PointerDeclaratorKind::MultiLevelPointer;
4223      break;
4224    }
4225  }
4226
4227  // Then, dig into the type specifier itself.
4228  unsigned numTypeSpecifierPointers = 0;
4229  do {
4230    // Decompose normal pointers.
4231    if (auto ptrType = type->getAs<PointerType>()) {
4232      ++numNormalPointers;
4233
4234      if (numNormalPointers > 2)
4235        return PointerDeclaratorKind::MultiLevelPointer;
4236
4237      type = ptrType->getPointeeType();
4238      ++numTypeSpecifierPointers;
4239      continue;
4240    }
4241
4242    // Decompose block pointers.
4243    if (type->getAs<BlockPointerType>()) {
4244      return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4245                                   : PointerDeclaratorKind::SingleLevelPointer;
4246    }
4247
4248    // Decompose member pointers.
4249    if (type->getAs<MemberPointerType>()) {
4250      return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4251                                   : PointerDeclaratorKind::SingleLevelPointer;
4252    }
4253
4254    // Look at Objective-C object pointers.
4255    if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4256      ++numNormalPointers;
4257      ++numTypeSpecifierPointers;
4258
4259      // If this is NSError**, report that.
4260      if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4261        if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4262            numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4263          return PointerDeclaratorKind::NSErrorPointerPointer;
4264        }
4265      }
4266
4267      break;
4268    }
4269
4270    // Look at Objective-C class types.
4271    if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4272      if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4273        if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4274          return PointerDeclaratorKind::NSErrorPointerPointer;
4275      }
4276
4277      break;
4278    }
4279
4280    // If at this point we haven't seen a pointer, we won't see one.
4281    if (numNormalPointers == 0)
4282      return PointerDeclaratorKind::NonPointer;
4283
4284    if (auto recordType = type->getAs<RecordType>()) {
4285      RecordDecl *recordDecl = recordType->getDecl();
4286
4287      // If this is CFErrorRef*, report it as such.
4288      if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4289          S.isCFError(recordDecl)) {
4290        return PointerDeclaratorKind::CFErrorRefPointer;
4291      }
4292      break;
4293    }
4294
4295    break;
4296  } while (true);
4297
4298  switch (numNormalPointers) {
4299  case 0:
4300    return PointerDeclaratorKind::NonPointer;
4301
4302  case 1:
4303    return PointerDeclaratorKind::SingleLevelPointer;
4304
4305  case 2:
4306    return PointerDeclaratorKind::MaybePointerToCFRef;
4307
4308  default:
4309    return PointerDeclaratorKind::MultiLevelPointer;
4310  }
4311}
4312
4313bool Sema::isCFError(RecordDecl *RD) {
4314  // If we already know about CFError, test it directly.
4315  if (CFError)
4316    return CFError == RD;
4317
4318  // Check whether this is CFError, which we identify based on its bridge to
4319  // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4320  // declared with "objc_bridge_mutable", so look for either one of the two
4321  // attributes.
4322  if (RD->getTagKind() == TTK_Struct) {
4323    IdentifierInfo *bridgedType = nullptr;
4324    if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4325      bridgedType = bridgeAttr->getBridgedType();
4326    else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4327      bridgedType = bridgeAttr->getBridgedType();
4328
4329    if (bridgedType == getNSErrorIdent()) {
4330      CFError = RD;
4331      return true;
4332    }
4333  }
4334
4335  return false;
4336}
4337
4338static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4339                                                    SourceLocation loc) {
4340  // If we're anywhere in a function, method, or closure context, don't perform
4341  // completeness checks.
4342  for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4343    if (ctx->isFunctionOrMethod())
4344      return FileID();
4345
4346    if (ctx->isFileContext())
4347      break;
4348  }
4349
4350  // We only care about the expansion location.
4351  loc = S.SourceMgr.getExpansionLoc(loc);
4352  FileID file = S.SourceMgr.getFileID(loc);
4353  if (file.isInvalid())
4354    return FileID();
4355
4356  // Retrieve file information.
4357  bool invalid = false;
4358  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4359  if (invalid || !sloc.isFile())
4360    return FileID();
4361
4362  // We don't want to perform completeness checks on the main file or in
4363  // system headers.
4364  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4365  if (fileInfo.getIncludeLoc().isInvalid())
4366    return FileID();
4367  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4368      S.Diags.getSuppressSystemWarnings()) {
4369    return FileID();
4370  }
4371
4372  return file;
4373}
4374
4375/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4376/// taking into account whitespace before and after.
4377template <typename DiagBuilderT>
4378static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4379                             SourceLocation PointerLoc,
4380                             NullabilityKind Nullability) {
4381  assert(PointerLoc.isValid());
4382  if (PointerLoc.isMacroID())
4383    return;
4384
4385  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4386  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4387    return;
4388
4389  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4390  if (!NextChar)
4391    return;
4392
4393  SmallString<32> InsertionTextBuf{" "};
4394  InsertionTextBuf += getNullabilitySpelling(Nullability);
4395  InsertionTextBuf += " ";
4396  StringRef InsertionText = InsertionTextBuf.str();
4397
4398  if (isWhitespace(*NextChar)) {
4399    InsertionText = InsertionText.drop_back();
4400  } else if (NextChar[-1] == '[') {
4401    if (NextChar[0] == ']')
4402      InsertionText = InsertionText.drop_back().drop_front();
4403    else
4404      InsertionText = InsertionText.drop_front();
4405  } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4406             !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4407    InsertionText = InsertionText.drop_back().drop_front();
4408  }
4409
4410  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4411}
4412
4413static void emitNullabilityConsistencyWarning(Sema &S,
4414                                              SimplePointerKind PointerKind,
4415                                              SourceLocation PointerLoc,
4416                                              SourceLocation PointerEndLoc) {
4417  assert(PointerLoc.isValid());
4418
4419  if (PointerKind == SimplePointerKind::Array) {
4420    S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4421  } else {
4422    S.Diag(PointerLoc, diag::warn_nullability_missing)
4423      << static_cast<unsigned>(PointerKind);
4424  }
4425
4426  auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4427  if (FixItLoc.isMacroID())
4428    return;
4429
4430  auto addFixIt = [&](NullabilityKind Nullability) {
4431    auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4432    Diag << static_cast<unsigned>(Nullability);
4433    Diag << static_cast<unsigned>(PointerKind);
4434    fixItNullability(S, Diag, FixItLoc, Nullability);
4435  };
4436  addFixIt(NullabilityKind::Nullable);
4437  addFixIt(NullabilityKind::NonNull);
4438}
4439
4440/// Complains about missing nullability if the file containing \p pointerLoc
4441/// has other uses of nullability (either the keywords or the \c assume_nonnull
4442/// pragma).
4443///
4444/// If the file has \e not seen other uses of nullability, this particular
4445/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4446static void
4447checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4448                            SourceLocation pointerLoc,
4449                            SourceLocation pointerEndLoc = SourceLocation()) {
4450  // Determine which file we're performing consistency checking for.
4451  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4452  if (file.isInvalid())
4453    return;
4454
4455  // If we haven't seen any type nullability in this file, we won't warn now
4456  // about anything.
4457  FileNullability &fileNullability = S.NullabilityMap[file];
4458  if (!fileNullability.SawTypeNullability) {
4459    // If this is the first pointer declarator in the file, and the appropriate
4460    // warning is on, record it in case we need to diagnose it retroactively.
4461    diag::kind diagKind;
4462    if (pointerKind == SimplePointerKind::Array)
4463      diagKind = diag::warn_nullability_missing_array;
4464    else
4465      diagKind = diag::warn_nullability_missing;
4466
4467    if (fileNullability.PointerLoc.isInvalid() &&
4468        !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4469      fileNullability.PointerLoc = pointerLoc;
4470      fileNullability.PointerEndLoc = pointerEndLoc;
4471      fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4472    }
4473
4474    return;
4475  }
4476
4477  // Complain about missing nullability.
4478  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4479}
4480
4481/// Marks that a nullability feature has been used in the file containing
4482/// \p loc.
4483///
4484/// If this file already had pointer types in it that were missing nullability,
4485/// the first such instance is retroactively diagnosed.
4486///
4487/// \sa checkNullabilityConsistency
4488static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4489  FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4490  if (file.isInvalid())
4491    return;
4492
4493  FileNullability &fileNullability = S.NullabilityMap[file];
4494  if (fileNullability.SawTypeNullability)
4495    return;
4496  fileNullability.SawTypeNullability = true;
4497
4498  // If we haven't seen any type nullability before, now we have. Retroactively
4499  // diagnose the first unannotated pointer, if there was one.
4500  if (fileNullability.PointerLoc.isInvalid())
4501    return;
4502
4503  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4504  emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4505                                    fileNullability.PointerEndLoc);
4506}
4507
4508/// Returns true if any of the declarator chunks before \p endIndex include a
4509/// level of indirection: array, pointer, reference, or pointer-to-member.
4510///
4511/// Because declarator chunks are stored in outer-to-inner order, testing
4512/// every chunk before \p endIndex is testing all chunks that embed the current
4513/// chunk as part of their type.
4514///
4515/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4516/// end index, in which case all chunks are tested.
4517static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4518  unsigned i = endIndex;
4519  while (i != 0) {
4520    // Walk outwards along the declarator chunks.
4521    --i;
4522    const DeclaratorChunk &DC = D.getTypeObject(i);
4523    switch (DC.Kind) {
4524    case DeclaratorChunk::Paren:
4525      break;
4526    case DeclaratorChunk::Array:
4527    case DeclaratorChunk::Pointer:
4528    case DeclaratorChunk::Reference:
4529    case DeclaratorChunk::MemberPointer:
4530      return true;
4531    case DeclaratorChunk::Function:
4532    case DeclaratorChunk::BlockPointer:
4533    case DeclaratorChunk::Pipe:
4534      // These are invalid anyway, so just ignore.
4535      break;
4536    }
4537  }
4538  return false;
4539}
4540
4541static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4542  return (Chunk.Kind == DeclaratorChunk::Pointer ||
4543          Chunk.Kind == DeclaratorChunk::Array);
4544}
4545
4546template<typename AttrT>
4547static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4548  AL.setUsedAsTypeAttr();
4549  return ::new (Ctx) AttrT(Ctx, AL);
4550}
4551
4552static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4553                                   NullabilityKind NK) {
4554  switch (NK) {
4555  case NullabilityKind::NonNull:
4556    return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4557
4558  case NullabilityKind::Nullable:
4559    return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4560
4561  case NullabilityKind::NullableResult:
4562    return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4563
4564  case NullabilityKind::Unspecified:
4565    return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4566  }
4567  llvm_unreachable("unknown NullabilityKind");
4568}
4569
4570// Diagnose whether this is a case with the multiple addr spaces.
4571// Returns true if this is an invalid case.
4572// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4573// by qualifiers for two or more different address spaces."
4574static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4575                                                LangAS ASNew,
4576                                                SourceLocation AttrLoc) {
4577  if (ASOld != LangAS::Default) {
4578    if (ASOld != ASNew) {
4579      S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4580      return true;
4581    }
4582    // Emit a warning if they are identical; it's likely unintended.
4583    S.Diag(AttrLoc,
4584           diag::warn_attribute_address_multiple_identical_qualifiers);
4585  }
4586  return false;
4587}
4588
4589static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4590                                                QualType declSpecType,
4591                                                TypeSourceInfo *TInfo) {
4592  // The TypeSourceInfo that this function returns will not be a null type.
4593  // If there is an error, this function will fill in a dummy type as fallback.
4594  QualType T = declSpecType;
4595  Declarator &D = state.getDeclarator();
4596  Sema &S = state.getSema();
4597  ASTContext &Context = S.Context;
4598  const LangOptions &LangOpts = S.getLangOpts();
4599
4600  // The name we're declaring, if any.
4601  DeclarationName Name;
4602  if (D.getIdentifier())
4603    Name = D.getIdentifier();
4604
4605  // Does this declaration declare a typedef-name?
4606  bool IsTypedefName =
4607      D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4608      D.getContext() == DeclaratorContext::AliasDecl ||
4609      D.getContext() == DeclaratorContext::AliasTemplate;
4610
4611  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4612  bool IsQualifiedFunction = T->isFunctionProtoType() &&
4613      (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4614       T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4615
4616  // If T is 'decltype(auto)', the only declarators we can have are parens
4617  // and at most one function declarator if this is a function declaration.
4618  // If T is a deduced class template specialization type, we can have no
4619  // declarator chunks at all.
4620  if (auto *DT = T->getAs<DeducedType>()) {
4621    const AutoType *AT = T->getAs<AutoType>();
4622    bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4623    if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4624      for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4625        unsigned Index = E - I - 1;
4626        DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4627        unsigned DiagId = IsClassTemplateDeduction
4628                              ? diag::err_deduced_class_template_compound_type
4629                              : diag::err_decltype_auto_compound_type;
4630        unsigned DiagKind = 0;
4631        switch (DeclChunk.Kind) {
4632        case DeclaratorChunk::Paren:
4633          // FIXME: Rejecting this is a little silly.
4634          if (IsClassTemplateDeduction) {
4635            DiagKind = 4;
4636            break;
4637          }
4638          continue;
4639        case DeclaratorChunk::Function: {
4640          if (IsClassTemplateDeduction) {
4641            DiagKind = 3;
4642            break;
4643          }
4644          unsigned FnIndex;
4645          if (D.isFunctionDeclarationContext() &&
4646              D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4647            continue;
4648          DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4649          break;
4650        }
4651        case DeclaratorChunk::Pointer:
4652        case DeclaratorChunk::BlockPointer:
4653        case DeclaratorChunk::MemberPointer:
4654          DiagKind = 0;
4655          break;
4656        case DeclaratorChunk::Reference:
4657          DiagKind = 1;
4658          break;
4659        case DeclaratorChunk::Array:
4660          DiagKind = 2;
4661          break;
4662        case DeclaratorChunk::Pipe:
4663          break;
4664        }
4665
4666        S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4667        D.setInvalidType(true);
4668        break;
4669      }
4670    }
4671  }
4672
4673  // Determine whether we should infer _Nonnull on pointer types.
4674  std::optional<NullabilityKind> inferNullability;
4675  bool inferNullabilityCS = false;
4676  bool inferNullabilityInnerOnly = false;
4677  bool inferNullabilityInnerOnlyComplete = false;
4678
4679  // Are we in an assume-nonnull region?
4680  bool inAssumeNonNullRegion = false;
4681  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4682  if (assumeNonNullLoc.isValid()) {
4683    inAssumeNonNullRegion = true;
4684    recordNullabilitySeen(S, assumeNonNullLoc);
4685  }
4686
4687  // Whether to complain about missing nullability specifiers or not.
4688  enum {
4689    /// Never complain.
4690    CAMN_No,
4691    /// Complain on the inner pointers (but not the outermost
4692    /// pointer).
4693    CAMN_InnerPointers,
4694    /// Complain about any pointers that don't have nullability
4695    /// specified or inferred.
4696    CAMN_Yes
4697  } complainAboutMissingNullability = CAMN_No;
4698  unsigned NumPointersRemaining = 0;
4699  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4700
4701  if (IsTypedefName) {
4702    // For typedefs, we do not infer any nullability (the default),
4703    // and we only complain about missing nullability specifiers on
4704    // inner pointers.
4705    complainAboutMissingNullability = CAMN_InnerPointers;
4706
4707    if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4708        !T->getNullability()) {
4709      // Note that we allow but don't require nullability on dependent types.
4710      ++NumPointersRemaining;
4711    }
4712
4713    for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4714      DeclaratorChunk &chunk = D.getTypeObject(i);
4715      switch (chunk.Kind) {
4716      case DeclaratorChunk::Array:
4717      case DeclaratorChunk::Function:
4718      case DeclaratorChunk::Pipe:
4719        break;
4720
4721      case DeclaratorChunk::BlockPointer:
4722      case DeclaratorChunk::MemberPointer:
4723        ++NumPointersRemaining;
4724        break;
4725
4726      case DeclaratorChunk::Paren:
4727      case DeclaratorChunk::Reference:
4728        continue;
4729
4730      case DeclaratorChunk::Pointer:
4731        ++NumPointersRemaining;
4732        continue;
4733      }
4734    }
4735  } else {
4736    bool isFunctionOrMethod = false;
4737    switch (auto context = state.getDeclarator().getContext()) {
4738    case DeclaratorContext::ObjCParameter:
4739    case DeclaratorContext::ObjCResult:
4740    case DeclaratorContext::Prototype:
4741    case DeclaratorContext::TrailingReturn:
4742    case DeclaratorContext::TrailingReturnVar:
4743      isFunctionOrMethod = true;
4744      [[fallthrough]];
4745
4746    case DeclaratorContext::Member:
4747      if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4748        complainAboutMissingNullability = CAMN_No;
4749        break;
4750      }
4751
4752      // Weak properties are inferred to be nullable.
4753      if (state.getDeclarator().isObjCWeakProperty()) {
4754        // Weak properties cannot be nonnull, and should not complain about
4755        // missing nullable attributes during completeness checks.
4756        complainAboutMissingNullability = CAMN_No;
4757        if (inAssumeNonNullRegion) {
4758          inferNullability = NullabilityKind::Nullable;
4759        }
4760        break;
4761      }
4762
4763      [[fallthrough]];
4764
4765    case DeclaratorContext::File:
4766    case DeclaratorContext::KNRTypeList: {
4767      complainAboutMissingNullability = CAMN_Yes;
4768
4769      // Nullability inference depends on the type and declarator.
4770      auto wrappingKind = PointerWrappingDeclaratorKind::None;
4771      switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4772      case PointerDeclaratorKind::NonPointer:
4773      case PointerDeclaratorKind::MultiLevelPointer:
4774        // Cannot infer nullability.
4775        break;
4776
4777      case PointerDeclaratorKind::SingleLevelPointer:
4778        // Infer _Nonnull if we are in an assumes-nonnull region.
4779        if (inAssumeNonNullRegion) {
4780          complainAboutInferringWithinChunk = wrappingKind;
4781          inferNullability = NullabilityKind::NonNull;
4782          inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4783                                context == DeclaratorContext::ObjCResult);
4784        }
4785        break;
4786
4787      case PointerDeclaratorKind::CFErrorRefPointer:
4788      case PointerDeclaratorKind::NSErrorPointerPointer:
4789        // Within a function or method signature, infer _Nullable at both
4790        // levels.
4791        if (isFunctionOrMethod && inAssumeNonNullRegion)
4792          inferNullability = NullabilityKind::Nullable;
4793        break;
4794
4795      case PointerDeclaratorKind::MaybePointerToCFRef:
4796        if (isFunctionOrMethod) {
4797          // On pointer-to-pointer parameters marked cf_returns_retained or
4798          // cf_returns_not_retained, if the outer pointer is explicit then
4799          // infer the inner pointer as _Nullable.
4800          auto hasCFReturnsAttr =
4801              [](const ParsedAttributesView &AttrList) -> bool {
4802            return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4803                   AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4804          };
4805          if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4806            if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4807                hasCFReturnsAttr(D.getAttributes()) ||
4808                hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4809                hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4810              inferNullability = NullabilityKind::Nullable;
4811              inferNullabilityInnerOnly = true;
4812            }
4813          }
4814        }
4815        break;
4816      }
4817      break;
4818    }
4819
4820    case DeclaratorContext::ConversionId:
4821      complainAboutMissingNullability = CAMN_Yes;
4822      break;
4823
4824    case DeclaratorContext::AliasDecl:
4825    case DeclaratorContext::AliasTemplate:
4826    case DeclaratorContext::Block:
4827    case DeclaratorContext::BlockLiteral:
4828    case DeclaratorContext::Condition:
4829    case DeclaratorContext::CXXCatch:
4830    case DeclaratorContext::CXXNew:
4831    case DeclaratorContext::ForInit:
4832    case DeclaratorContext::SelectionInit:
4833    case DeclaratorContext::LambdaExpr:
4834    case DeclaratorContext::LambdaExprParameter:
4835    case DeclaratorContext::ObjCCatch:
4836    case DeclaratorContext::TemplateParam:
4837    case DeclaratorContext::TemplateArg:
4838    case DeclaratorContext::TemplateTypeArg:
4839    case DeclaratorContext::TypeName:
4840    case DeclaratorContext::FunctionalCast:
4841    case DeclaratorContext::RequiresExpr:
4842    case DeclaratorContext::Association:
4843      // Don't infer in these contexts.
4844      break;
4845    }
4846  }
4847
4848  // Local function that returns true if its argument looks like a va_list.
4849  auto isVaList = [&S](QualType T) -> bool {
4850    auto *typedefTy = T->getAs<TypedefType>();
4851    if (!typedefTy)
4852      return false;
4853    TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4854    do {
4855      if (typedefTy->getDecl() == vaListTypedef)
4856        return true;
4857      if (auto *name = typedefTy->getDecl()->getIdentifier())
4858        if (name->isStr("va_list"))
4859          return true;
4860      typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4861    } while (typedefTy);
4862    return false;
4863  };
4864
4865  // Local function that checks the nullability for a given pointer declarator.
4866  // Returns true if _Nonnull was inferred.
4867  auto inferPointerNullability =
4868      [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4869          SourceLocation pointerEndLoc,
4870          ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4871    // We've seen a pointer.
4872    if (NumPointersRemaining > 0)
4873      --NumPointersRemaining;
4874
4875    // If a nullability attribute is present, there's nothing to do.
4876    if (hasNullabilityAttr(attrs))
4877      return nullptr;
4878
4879    // If we're supposed to infer nullability, do so now.
4880    if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4881      ParsedAttr::Syntax syntax = inferNullabilityCS
4882                                      ? ParsedAttr::AS_ContextSensitiveKeyword
4883                                      : ParsedAttr::AS_Keyword;
4884      ParsedAttr *nullabilityAttr = Pool.create(
4885          S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4886          nullptr, SourceLocation(), nullptr, 0, syntax);
4887
4888      attrs.addAtEnd(nullabilityAttr);
4889
4890      if (inferNullabilityCS) {
4891        state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4892          ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4893      }
4894
4895      if (pointerLoc.isValid() &&
4896          complainAboutInferringWithinChunk !=
4897            PointerWrappingDeclaratorKind::None) {
4898        auto Diag =
4899            S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4900        Diag << static_cast<int>(complainAboutInferringWithinChunk);
4901        fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4902      }
4903
4904      if (inferNullabilityInnerOnly)
4905        inferNullabilityInnerOnlyComplete = true;
4906      return nullabilityAttr;
4907    }
4908
4909    // If we're supposed to complain about missing nullability, do so
4910    // now if it's truly missing.
4911    switch (complainAboutMissingNullability) {
4912    case CAMN_No:
4913      break;
4914
4915    case CAMN_InnerPointers:
4916      if (NumPointersRemaining == 0)
4917        break;
4918      [[fallthrough]];
4919
4920    case CAMN_Yes:
4921      checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4922    }
4923    return nullptr;
4924  };
4925
4926  // If the type itself could have nullability but does not, infer pointer
4927  // nullability and perform consistency checking.
4928  if (S.CodeSynthesisContexts.empty()) {
4929    if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4930        !T->getNullability()) {
4931      if (isVaList(T)) {
4932        // Record that we've seen a pointer, but do nothing else.
4933        if (NumPointersRemaining > 0)
4934          --NumPointersRemaining;
4935      } else {
4936        SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4937        if (T->isBlockPointerType())
4938          pointerKind = SimplePointerKind::BlockPointer;
4939        else if (T->isMemberPointerType())
4940          pointerKind = SimplePointerKind::MemberPointer;
4941
4942        if (auto *attr = inferPointerNullability(
4943                pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4944                D.getDeclSpec().getEndLoc(),
4945                D.getMutableDeclSpec().getAttributes(),
4946                D.getMutableDeclSpec().getAttributePool())) {
4947          T = state.getAttributedType(
4948              createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4949        }
4950      }
4951    }
4952
4953    if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4954        !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4955        !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4956      checkNullabilityConsistency(S, SimplePointerKind::Array,
4957                                  D.getDeclSpec().getTypeSpecTypeLoc());
4958    }
4959  }
4960
4961  bool ExpectNoDerefChunk =
4962      state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4963
4964  // Walk the DeclTypeInfo, building the recursive type as we go.
4965  // DeclTypeInfos are ordered from the identifier out, which is
4966  // opposite of what we want :).
4967  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4968    unsigned chunkIndex = e - i - 1;
4969    state.setCurrentChunkIndex(chunkIndex);
4970    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4971    IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4972    switch (DeclType.Kind) {
4973    case DeclaratorChunk::Paren:
4974      if (i == 0)
4975        warnAboutRedundantParens(S, D, T);
4976      T = S.BuildParenType(T);
4977      break;
4978    case DeclaratorChunk::BlockPointer:
4979      // If blocks are disabled, emit an error.
4980      if (!LangOpts.Blocks)
4981        S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4982
4983      // Handle pointer nullability.
4984      inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4985                              DeclType.EndLoc, DeclType.getAttrs(),
4986                              state.getDeclarator().getAttributePool());
4987
4988      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4989      if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4990        // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4991        // qualified with const.
4992        if (LangOpts.OpenCL)
4993          DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4994        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4995      }
4996      break;
4997    case DeclaratorChunk::Pointer:
4998      // Verify that we're not building a pointer to pointer to function with
4999      // exception specification.
5000      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5001        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5002        D.setInvalidType(true);
5003        // Build the type anyway.
5004      }
5005
5006      // Handle pointer nullability
5007      inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5008                              DeclType.EndLoc, DeclType.getAttrs(),
5009                              state.getDeclarator().getAttributePool());
5010
5011      if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
5012        T = Context.getObjCObjectPointerType(T);
5013        if (DeclType.Ptr.TypeQuals)
5014          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5015        break;
5016      }
5017
5018      // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5019      // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5020      // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5021      if (LangOpts.OpenCL) {
5022        if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
5023            T->isBlockPointerType()) {
5024          S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5025          D.setInvalidType(true);
5026        }
5027      }
5028
5029      T = S.BuildPointerType(T, DeclType.Loc, Name);
5030      if (DeclType.Ptr.TypeQuals)
5031        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5032      break;
5033    case DeclaratorChunk::Reference: {
5034      // Verify that we're not building a reference to pointer to function with
5035      // exception specification.
5036      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5037        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5038        D.setInvalidType(true);
5039        // Build the type anyway.
5040      }
5041      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5042
5043      if (DeclType.Ref.HasRestrict)
5044        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5045      break;
5046    }
5047    case DeclaratorChunk::Array: {
5048      // Verify that we're not building an array of pointers to function with
5049      // exception specification.
5050      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5051        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5052        D.setInvalidType(true);
5053        // Build the type anyway.
5054      }
5055      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5056      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5057      ArrayType::ArraySizeModifier ASM;
5058      if (ATI.isStar)
5059        ASM = ArrayType::Star;
5060      else if (ATI.hasStatic)
5061        ASM = ArrayType::Static;
5062      else
5063        ASM = ArrayType::Normal;
5064      if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
5065        // FIXME: This check isn't quite right: it allows star in prototypes
5066        // for function definitions, and disallows some edge cases detailed
5067        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5068        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5069        ASM = ArrayType::Normal;
5070        D.setInvalidType(true);
5071      }
5072
5073      // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5074      // shall appear only in a declaration of a function parameter with an
5075      // array type, ...
5076      if (ASM == ArrayType::Static || ATI.TypeQuals) {
5077        if (!(D.isPrototypeContext() ||
5078              D.getContext() == DeclaratorContext::KNRTypeList)) {
5079          S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
5080              (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5081          // Remove the 'static' and the type qualifiers.
5082          if (ASM == ArrayType::Static)
5083            ASM = ArrayType::Normal;
5084          ATI.TypeQuals = 0;
5085          D.setInvalidType(true);
5086        }
5087
5088        // C99 6.7.5.2p1: ... and then only in the outermost array type
5089        // derivation.
5090        if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5091          S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
5092            (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5093          if (ASM == ArrayType::Static)
5094            ASM = ArrayType::Normal;
5095          ATI.TypeQuals = 0;
5096          D.setInvalidType(true);
5097        }
5098      }
5099      const AutoType *AT = T->getContainedAutoType();
5100      // Allow arrays of auto if we are a generic lambda parameter.
5101      // i.e. [](auto (&array)[5]) { return array[0]; }; OK
5102      if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) {
5103        // We've already diagnosed this for decltype(auto).
5104        if (!AT->isDecltypeAuto())
5105          S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
5106              << getPrintableNameForEntity(Name) << T;
5107        T = QualType();
5108        break;
5109      }
5110
5111      // Array parameters can be marked nullable as well, although it's not
5112      // necessary if they're marked 'static'.
5113      if (complainAboutMissingNullability == CAMN_Yes &&
5114          !hasNullabilityAttr(DeclType.getAttrs()) &&
5115          ASM != ArrayType::Static &&
5116          D.isPrototypeContext() &&
5117          !hasOuterPointerLikeChunk(D, chunkIndex)) {
5118        checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5119      }
5120
5121      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5122                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5123      break;
5124    }
5125    case DeclaratorChunk::Function: {
5126      // If the function declarator has a prototype (i.e. it is not () and
5127      // does not have a K&R-style identifier list), then the arguments are part
5128      // of the type, otherwise the argument list is ().
5129      DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5130      IsQualifiedFunction =
5131          FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5132
5133      // Check for auto functions and trailing return type and adjust the
5134      // return type accordingly.
5135      if (!D.isInvalidType()) {
5136        // trailing-return-type is only required if we're declaring a function,
5137        // and not, for instance, a pointer to a function.
5138        if (D.getDeclSpec().hasAutoTypeSpec() &&
5139            !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5140          if (!S.getLangOpts().CPlusPlus14) {
5141            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5142                   D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5143                       ? diag::err_auto_missing_trailing_return
5144                       : diag::err_deduced_return_type);
5145            T = Context.IntTy;
5146            D.setInvalidType(true);
5147          } else {
5148            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5149                   diag::warn_cxx11_compat_deduced_return_type);
5150          }
5151        } else if (FTI.hasTrailingReturnType()) {
5152          // T must be exactly 'auto' at this point. See CWG issue 681.
5153          if (isa<ParenType>(T)) {
5154            S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5155                << T << D.getSourceRange();
5156            D.setInvalidType(true);
5157          } else if (D.getName().getKind() ==
5158                     UnqualifiedIdKind::IK_DeductionGuideName) {
5159            if (T != Context.DependentTy) {
5160              S.Diag(D.getDeclSpec().getBeginLoc(),
5161                     diag::err_deduction_guide_with_complex_decl)
5162                  << D.getSourceRange();
5163              D.setInvalidType(true);
5164            }
5165          } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5166                     (T.hasQualifiers() || !isa<AutoType>(T) ||
5167                      cast<AutoType>(T)->getKeyword() !=
5168                          AutoTypeKeyword::Auto ||
5169                      cast<AutoType>(T)->isConstrained())) {
5170            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5171                   diag::err_trailing_return_without_auto)
5172                << T << D.getDeclSpec().getSourceRange();
5173            D.setInvalidType(true);
5174          }
5175          T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5176          if (T.isNull()) {
5177            // An error occurred parsing the trailing return type.
5178            T = Context.IntTy;
5179            D.setInvalidType(true);
5180          } else if (AutoType *Auto = T->getContainedAutoType()) {
5181            // If the trailing return type contains an `auto`, we may need to
5182            // invent a template parameter for it, for cases like
5183            // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5184            InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5185            if (D.getContext() == DeclaratorContext::Prototype)
5186              InventedParamInfo = &S.InventedParameterInfos.back();
5187            else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5188              InventedParamInfo = S.getCurLambda();
5189            if (InventedParamInfo) {
5190              std::tie(T, TInfo) = InventTemplateParameter(
5191                  state, T, TInfo, Auto, *InventedParamInfo);
5192            }
5193          }
5194        } else {
5195          // This function type is not the type of the entity being declared,
5196          // so checking the 'auto' is not the responsibility of this chunk.
5197        }
5198      }
5199
5200      // C99 6.7.5.3p1: The return type may not be a function or array type.
5201      // For conversion functions, we'll diagnose this particular error later.
5202      if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5203          (D.getName().getKind() !=
5204           UnqualifiedIdKind::IK_ConversionFunctionId)) {
5205        unsigned diagID = diag::err_func_returning_array_function;
5206        // Last processing chunk in block context means this function chunk
5207        // represents the block.
5208        if (chunkIndex == 0 &&
5209            D.getContext() == DeclaratorContext::BlockLiteral)
5210          diagID = diag::err_block_returning_array_function;
5211        S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5212        T = Context.IntTy;
5213        D.setInvalidType(true);
5214      }
5215
5216      // Do not allow returning half FP value.
5217      // FIXME: This really should be in BuildFunctionType.
5218      if (T->isHalfType()) {
5219        if (S.getLangOpts().OpenCL) {
5220          if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5221                                                      S.getLangOpts())) {
5222            S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5223                << T << 0 /*pointer hint*/;
5224            D.setInvalidType(true);
5225          }
5226        } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5227                   !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5228          S.Diag(D.getIdentifierLoc(),
5229            diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5230          D.setInvalidType(true);
5231        }
5232      }
5233
5234      if (LangOpts.OpenCL) {
5235        // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5236        // function.
5237        if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5238            T->isPipeType()) {
5239          S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5240              << T << 1 /*hint off*/;
5241          D.setInvalidType(true);
5242        }
5243        // OpenCL doesn't support variadic functions and blocks
5244        // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5245        // We also allow here any toolchain reserved identifiers.
5246        if (FTI.isVariadic &&
5247            !S.getOpenCLOptions().isAvailableOption(
5248                "__cl_clang_variadic_functions", S.getLangOpts()) &&
5249            !(D.getIdentifier() &&
5250              ((D.getIdentifier()->getName() == "printf" &&
5251                LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5252               D.getIdentifier()->getName().startswith("__")))) {
5253          S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5254          D.setInvalidType(true);
5255        }
5256      }
5257
5258      // Methods cannot return interface types. All ObjC objects are
5259      // passed by reference.
5260      if (T->isObjCObjectType()) {
5261        SourceLocation DiagLoc, FixitLoc;
5262        if (TInfo) {
5263          DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5264          FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5265        } else {
5266          DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5267          FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5268        }
5269        S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5270          << 0 << T
5271          << FixItHint::CreateInsertion(FixitLoc, "*");
5272
5273        T = Context.getObjCObjectPointerType(T);
5274        if (TInfo) {
5275          TypeLocBuilder TLB;
5276          TLB.pushFullCopy(TInfo->getTypeLoc());
5277          ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5278          TLoc.setStarLoc(FixitLoc);
5279          TInfo = TLB.getTypeSourceInfo(Context, T);
5280        }
5281
5282        D.setInvalidType(true);
5283      }
5284
5285      // cv-qualifiers on return types are pointless except when the type is a
5286      // class type in C++.
5287      if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5288          !(S.getLangOpts().CPlusPlus &&
5289            (T->isDependentType() || T->isRecordType()))) {
5290        if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5291            D.getFunctionDefinitionKind() ==
5292                FunctionDefinitionKind::Definition) {
5293          // [6.9.1/3] qualified void return is invalid on a C
5294          // function definition.  Apparently ok on declarations and
5295          // in C++ though (!)
5296          S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5297        } else
5298          diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5299
5300        // C++2a [dcl.fct]p12:
5301        //   A volatile-qualified return type is deprecated
5302        if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5303          S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5304      }
5305
5306      // Objective-C ARC ownership qualifiers are ignored on the function
5307      // return type (by type canonicalization). Complain if this attribute
5308      // was written here.
5309      if (T.getQualifiers().hasObjCLifetime()) {
5310        SourceLocation AttrLoc;
5311        if (chunkIndex + 1 < D.getNumTypeObjects()) {
5312          DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5313          for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5314            if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5315              AttrLoc = AL.getLoc();
5316              break;
5317            }
5318          }
5319        }
5320        if (AttrLoc.isInvalid()) {
5321          for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5322            if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5323              AttrLoc = AL.getLoc();
5324              break;
5325            }
5326          }
5327        }
5328
5329        if (AttrLoc.isValid()) {
5330          // The ownership attributes are almost always written via
5331          // the predefined
5332          // __strong/__weak/__autoreleasing/__unsafe_unretained.
5333          if (AttrLoc.isMacroID())
5334            AttrLoc =
5335                S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5336
5337          S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5338            << T.getQualifiers().getObjCLifetime();
5339        }
5340      }
5341
5342      if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5343        // C++ [dcl.fct]p6:
5344        //   Types shall not be defined in return or parameter types.
5345        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5346        S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5347          << Context.getTypeDeclType(Tag);
5348      }
5349
5350      // Exception specs are not allowed in typedefs. Complain, but add it
5351      // anyway.
5352      if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5353        S.Diag(FTI.getExceptionSpecLocBeg(),
5354               diag::err_exception_spec_in_typedef)
5355            << (D.getContext() == DeclaratorContext::AliasDecl ||
5356                D.getContext() == DeclaratorContext::AliasTemplate);
5357
5358      // If we see "T var();" or "T var(T());" at block scope, it is probably
5359      // an attempt to initialize a variable, not a function declaration.
5360      if (FTI.isAmbiguous)
5361        warnAboutAmbiguousFunction(S, D, DeclType, T);
5362
5363      FunctionType::ExtInfo EI(
5364          getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5365
5366      // OpenCL disallows functions without a prototype, but it doesn't enforce
5367      // strict prototypes as in C2x because it allows a function definition to
5368      // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5369      if (!FTI.NumParams && !FTI.isVariadic &&
5370          !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5371        // Simple void foo(), where the incoming T is the result type.
5372        T = Context.getFunctionNoProtoType(T, EI);
5373      } else {
5374        // We allow a zero-parameter variadic function in C if the
5375        // function is marked with the "overloadable" attribute. Scan
5376        // for this attribute now. We also allow it in C2x per WG14 N2975.
5377        if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5378          if (LangOpts.C2x)
5379            S.Diag(FTI.getEllipsisLoc(),
5380                   diag::warn_c17_compat_ellipsis_only_parameter);
5381          else if (!D.getDeclarationAttributes().hasAttribute(
5382                       ParsedAttr::AT_Overloadable) &&
5383                   !D.getAttributes().hasAttribute(
5384                       ParsedAttr::AT_Overloadable) &&
5385                   !D.getDeclSpec().getAttributes().hasAttribute(
5386                       ParsedAttr::AT_Overloadable))
5387            S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5388        }
5389
5390        if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5391          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5392          // definition.
5393          S.Diag(FTI.Params[0].IdentLoc,
5394                 diag::err_ident_list_in_fn_declaration);
5395          D.setInvalidType(true);
5396          // Recover by creating a K&R-style function type, if possible.
5397          T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5398                  ? Context.getFunctionNoProtoType(T, EI)
5399                  : Context.IntTy;
5400          break;
5401        }
5402
5403        FunctionProtoType::ExtProtoInfo EPI;
5404        EPI.ExtInfo = EI;
5405        EPI.Variadic = FTI.isVariadic;
5406        EPI.EllipsisLoc = FTI.getEllipsisLoc();
5407        EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5408        EPI.TypeQuals.addCVRUQualifiers(
5409            FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5410                                 : 0);
5411        EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5412                    : FTI.RefQualifierIsLValueRef? RQ_LValue
5413                    : RQ_RValue;
5414
5415        // Otherwise, we have a function with a parameter list that is
5416        // potentially variadic.
5417        SmallVector<QualType, 16> ParamTys;
5418        ParamTys.reserve(FTI.NumParams);
5419
5420        SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5421          ExtParameterInfos(FTI.NumParams);
5422        bool HasAnyInterestingExtParameterInfos = false;
5423
5424        for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5425          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5426          QualType ParamTy = Param->getType();
5427          assert(!ParamTy.isNull() && "Couldn't parse type?");
5428
5429          // Look for 'void'.  void is allowed only as a single parameter to a
5430          // function with no other parameters (C99 6.7.5.3p10).  We record
5431          // int(void) as a FunctionProtoType with an empty parameter list.
5432          if (ParamTy->isVoidType()) {
5433            // If this is something like 'float(int, void)', reject it.  'void'
5434            // is an incomplete type (C99 6.2.5p19) and function decls cannot
5435            // have parameters of incomplete type.
5436            if (FTI.NumParams != 1 || FTI.isVariadic) {
5437              S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5438              ParamTy = Context.IntTy;
5439              Param->setType(ParamTy);
5440            } else if (FTI.Params[i].Ident) {
5441              // Reject, but continue to parse 'int(void abc)'.
5442              S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5443              ParamTy = Context.IntTy;
5444              Param->setType(ParamTy);
5445            } else {
5446              // Reject, but continue to parse 'float(const void)'.
5447              if (ParamTy.hasQualifiers())
5448                S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5449
5450              // Do not add 'void' to the list.
5451              break;
5452            }
5453          } else if (ParamTy->isHalfType()) {
5454            // Disallow half FP parameters.
5455            // FIXME: This really should be in BuildFunctionType.
5456            if (S.getLangOpts().OpenCL) {
5457              if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5458                                                          S.getLangOpts())) {
5459                S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5460                    << ParamTy << 0;
5461                D.setInvalidType();
5462                Param->setInvalidDecl();
5463              }
5464            } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5465                       !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5466              S.Diag(Param->getLocation(),
5467                diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5468              D.setInvalidType();
5469            }
5470          } else if (!FTI.hasPrototype) {
5471            if (Context.isPromotableIntegerType(ParamTy)) {
5472              ParamTy = Context.getPromotedIntegerType(ParamTy);
5473              Param->setKNRPromoted(true);
5474            } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5475              if (BTy->getKind() == BuiltinType::Float) {
5476                ParamTy = Context.DoubleTy;
5477                Param->setKNRPromoted(true);
5478              }
5479            }
5480          } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5481            // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5482            S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5483                << ParamTy << 1 /*hint off*/;
5484            D.setInvalidType();
5485          }
5486
5487          if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5488            ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5489            HasAnyInterestingExtParameterInfos = true;
5490          }
5491
5492          if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5493            ExtParameterInfos[i] =
5494              ExtParameterInfos[i].withABI(attr->getABI());
5495            HasAnyInterestingExtParameterInfos = true;
5496          }
5497
5498          if (Param->hasAttr<PassObjectSizeAttr>()) {
5499            ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5500            HasAnyInterestingExtParameterInfos = true;
5501          }
5502
5503          if (Param->hasAttr<NoEscapeAttr>()) {
5504            ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5505            HasAnyInterestingExtParameterInfos = true;
5506          }
5507
5508          ParamTys.push_back(ParamTy);
5509        }
5510
5511        if (HasAnyInterestingExtParameterInfos) {
5512          EPI.ExtParameterInfos = ExtParameterInfos.data();
5513          checkExtParameterInfos(S, ParamTys, EPI,
5514              [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5515        }
5516
5517        SmallVector<QualType, 4> Exceptions;
5518        SmallVector<ParsedType, 2> DynamicExceptions;
5519        SmallVector<SourceRange, 2> DynamicExceptionRanges;
5520        Expr *NoexceptExpr = nullptr;
5521
5522        if (FTI.getExceptionSpecType() == EST_Dynamic) {
5523          // FIXME: It's rather inefficient to have to split into two vectors
5524          // here.
5525          unsigned N = FTI.getNumExceptions();
5526          DynamicExceptions.reserve(N);
5527          DynamicExceptionRanges.reserve(N);
5528          for (unsigned I = 0; I != N; ++I) {
5529            DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5530            DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5531          }
5532        } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5533          NoexceptExpr = FTI.NoexceptExpr;
5534        }
5535
5536        S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5537                                      FTI.getExceptionSpecType(),
5538                                      DynamicExceptions,
5539                                      DynamicExceptionRanges,
5540                                      NoexceptExpr,
5541                                      Exceptions,
5542                                      EPI.ExceptionSpec);
5543
5544        // FIXME: Set address space from attrs for C++ mode here.
5545        // OpenCLCPlusPlus: A class member function has an address space.
5546        auto IsClassMember = [&]() {
5547          return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5548                  state.getDeclarator()
5549                          .getCXXScopeSpec()
5550                          .getScopeRep()
5551                          ->getKind() == NestedNameSpecifier::TypeSpec) ||
5552                 state.getDeclarator().getContext() ==
5553                     DeclaratorContext::Member ||
5554                 state.getDeclarator().getContext() ==
5555                     DeclaratorContext::LambdaExpr;
5556        };
5557
5558        if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5559          LangAS ASIdx = LangAS::Default;
5560          // Take address space attr if any and mark as invalid to avoid adding
5561          // them later while creating QualType.
5562          if (FTI.MethodQualifiers)
5563            for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5564              LangAS ASIdxNew = attr.asOpenCLLangAS();
5565              if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5566                                                      attr.getLoc()))
5567                D.setInvalidType(true);
5568              else
5569                ASIdx = ASIdxNew;
5570            }
5571          // If a class member function's address space is not set, set it to
5572          // __generic.
5573          LangAS AS =
5574              (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5575                                        : ASIdx);
5576          EPI.TypeQuals.addAddressSpace(AS);
5577        }
5578        T = Context.getFunctionType(T, ParamTys, EPI);
5579      }
5580      break;
5581    }
5582    case DeclaratorChunk::MemberPointer: {
5583      // The scope spec must refer to a class, or be dependent.
5584      CXXScopeSpec &SS = DeclType.Mem.Scope();
5585      QualType ClsType;
5586
5587      // Handle pointer nullability.
5588      inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5589                              DeclType.EndLoc, DeclType.getAttrs(),
5590                              state.getDeclarator().getAttributePool());
5591
5592      if (SS.isInvalid()) {
5593        // Avoid emitting extra errors if we already errored on the scope.
5594        D.setInvalidType(true);
5595      } else if (S.isDependentScopeSpecifier(SS) ||
5596                 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5597        NestedNameSpecifier *NNS = SS.getScopeRep();
5598        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5599        switch (NNS->getKind()) {
5600        case NestedNameSpecifier::Identifier:
5601          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5602                                                 NNS->getAsIdentifier());
5603          break;
5604
5605        case NestedNameSpecifier::Namespace:
5606        case NestedNameSpecifier::NamespaceAlias:
5607        case NestedNameSpecifier::Global:
5608        case NestedNameSpecifier::Super:
5609          llvm_unreachable("Nested-name-specifier must name a type");
5610
5611        case NestedNameSpecifier::TypeSpec:
5612        case NestedNameSpecifier::TypeSpecWithTemplate:
5613          ClsType = QualType(NNS->getAsType(), 0);
5614          // Note: if the NNS has a prefix and ClsType is a nondependent
5615          // TemplateSpecializationType, then the NNS prefix is NOT included
5616          // in ClsType; hence we wrap ClsType into an ElaboratedType.
5617          // NOTE: in particular, no wrap occurs if ClsType already is an
5618          // Elaborated, DependentName, or DependentTemplateSpecialization.
5619          if (isa<TemplateSpecializationType>(NNS->getAsType()))
5620            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5621          break;
5622        }
5623      } else {
5624        S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5625             diag::err_illegal_decl_mempointer_in_nonclass)
5626          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5627          << DeclType.Mem.Scope().getRange();
5628        D.setInvalidType(true);
5629      }
5630
5631      if (!ClsType.isNull())
5632        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5633                                     D.getIdentifier());
5634      if (T.isNull()) {
5635        T = Context.IntTy;
5636        D.setInvalidType(true);
5637      } else if (DeclType.Mem.TypeQuals) {
5638        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5639      }
5640      break;
5641    }
5642
5643    case DeclaratorChunk::Pipe: {
5644      T = S.BuildReadPipeType(T, DeclType.Loc);
5645      processTypeAttrs(state, T, TAL_DeclSpec,
5646                       D.getMutableDeclSpec().getAttributes());
5647      break;
5648    }
5649    }
5650
5651    if (T.isNull()) {
5652      D.setInvalidType(true);
5653      T = Context.IntTy;
5654    }
5655
5656    // See if there are any attributes on this declarator chunk.
5657    processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5658
5659    if (DeclType.Kind != DeclaratorChunk::Paren) {
5660      if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5661        S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5662
5663      ExpectNoDerefChunk = state.didParseNoDeref();
5664    }
5665  }
5666
5667  if (ExpectNoDerefChunk)
5668    S.Diag(state.getDeclarator().getBeginLoc(),
5669           diag::warn_noderef_on_non_pointer_or_array);
5670
5671  // GNU warning -Wstrict-prototypes
5672  //   Warn if a function declaration or definition is without a prototype.
5673  //   This warning is issued for all kinds of unprototyped function
5674  //   declarations (i.e. function type typedef, function pointer etc.)
5675  //   C99 6.7.5.3p14:
5676  //   The empty list in a function declarator that is not part of a definition
5677  //   of that function specifies that no information about the number or types
5678  //   of the parameters is supplied.
5679  // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5680  // function declarations whose behavior changes in C2x.
5681  if (!LangOpts.requiresStrictPrototypes()) {
5682    bool IsBlock = false;
5683    for (const DeclaratorChunk &DeclType : D.type_objects()) {
5684      switch (DeclType.Kind) {
5685      case DeclaratorChunk::BlockPointer:
5686        IsBlock = true;
5687        break;
5688      case DeclaratorChunk::Function: {
5689        const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5690        // We suppress the warning when there's no LParen location, as this
5691        // indicates the declaration was an implicit declaration, which gets
5692        // warned about separately via -Wimplicit-function-declaration. We also
5693        // suppress the warning when we know the function has a prototype.
5694        if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5695            FTI.getLParenLoc().isValid())
5696          S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5697              << IsBlock
5698              << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5699        IsBlock = false;
5700        break;
5701      }
5702      default:
5703        break;
5704      }
5705    }
5706  }
5707
5708  assert(!T.isNull() && "T must not be null after this point");
5709
5710  if (LangOpts.CPlusPlus && T->isFunctionType()) {
5711    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5712    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5713
5714    // C++ 8.3.5p4:
5715    //   A cv-qualifier-seq shall only be part of the function type
5716    //   for a nonstatic member function, the function type to which a pointer
5717    //   to member refers, or the top-level function type of a function typedef
5718    //   declaration.
5719    //
5720    // Core issue 547 also allows cv-qualifiers on function types that are
5721    // top-level template type arguments.
5722    enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5723    if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5724      Kind = DeductionGuide;
5725    else if (!D.getCXXScopeSpec().isSet()) {
5726      if ((D.getContext() == DeclaratorContext::Member ||
5727           D.getContext() == DeclaratorContext::LambdaExpr) &&
5728          !D.getDeclSpec().isFriendSpecified())
5729        Kind = Member;
5730    } else {
5731      DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5732      if (!DC || DC->isRecord())
5733        Kind = Member;
5734    }
5735
5736    // C++11 [dcl.fct]p6 (w/DR1417):
5737    // An attempt to specify a function type with a cv-qualifier-seq or a
5738    // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5739    //  - the function type for a non-static member function,
5740    //  - the function type to which a pointer to member refers,
5741    //  - the top-level function type of a function typedef declaration or
5742    //    alias-declaration,
5743    //  - the type-id in the default argument of a type-parameter, or
5744    //  - the type-id of a template-argument for a type-parameter
5745    //
5746    // FIXME: Checking this here is insufficient. We accept-invalid on:
5747    //
5748    //   template<typename T> struct S { void f(T); };
5749    //   S<int() const> s;
5750    //
5751    // ... for instance.
5752    if (IsQualifiedFunction &&
5753        !(Kind == Member &&
5754          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5755        !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5756        D.getContext() != DeclaratorContext::TemplateTypeArg) {
5757      SourceLocation Loc = D.getBeginLoc();
5758      SourceRange RemovalRange;
5759      unsigned I;
5760      if (D.isFunctionDeclarator(I)) {
5761        SmallVector<SourceLocation, 4> RemovalLocs;
5762        const DeclaratorChunk &Chunk = D.getTypeObject(I);
5763        assert(Chunk.Kind == DeclaratorChunk::Function);
5764
5765        if (Chunk.Fun.hasRefQualifier())
5766          RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5767
5768        if (Chunk.Fun.hasMethodTypeQualifiers())
5769          Chunk.Fun.MethodQualifiers->forEachQualifier(
5770              [&](DeclSpec::TQ TypeQual, StringRef QualName,
5771                  SourceLocation SL) { RemovalLocs.push_back(SL); });
5772
5773        if (!RemovalLocs.empty()) {
5774          llvm::sort(RemovalLocs,
5775                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5776          RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5777          Loc = RemovalLocs.front();
5778        }
5779      }
5780
5781      S.Diag(Loc, diag::err_invalid_qualified_function_type)
5782        << Kind << D.isFunctionDeclarator() << T
5783        << getFunctionQualifiersAsString(FnTy)
5784        << FixItHint::CreateRemoval(RemovalRange);
5785
5786      // Strip the cv-qualifiers and ref-qualifiers from the type.
5787      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5788      EPI.TypeQuals.removeCVRQualifiers();
5789      EPI.RefQualifier = RQ_None;
5790
5791      T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5792                                  EPI);
5793      // Rebuild any parens around the identifier in the function type.
5794      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5795        if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5796          break;
5797        T = S.BuildParenType(T);
5798      }
5799    }
5800  }
5801
5802  // Apply any undistributed attributes from the declaration or declarator.
5803  ParsedAttributesView NonSlidingAttrs;
5804  for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5805    if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5806      NonSlidingAttrs.addAtEnd(&AL);
5807    }
5808  }
5809  processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5810  processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5811
5812  // Diagnose any ignored type attributes.
5813  state.diagnoseIgnoredTypeAttrs(T);
5814
5815  // C++0x [dcl.constexpr]p9:
5816  //  A constexpr specifier used in an object declaration declares the object
5817  //  as const.
5818  if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5819      T->isObjectType())
5820    T.addConst();
5821
5822  // C++2a [dcl.fct]p4:
5823  //   A parameter with volatile-qualified type is deprecated
5824  if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5825      (D.getContext() == DeclaratorContext::Prototype ||
5826       D.getContext() == DeclaratorContext::LambdaExprParameter))
5827    S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5828
5829  // If there was an ellipsis in the declarator, the declaration declares a
5830  // parameter pack whose type may be a pack expansion type.
5831  if (D.hasEllipsis()) {
5832    // C++0x [dcl.fct]p13:
5833    //   A declarator-id or abstract-declarator containing an ellipsis shall
5834    //   only be used in a parameter-declaration. Such a parameter-declaration
5835    //   is a parameter pack (14.5.3). [...]
5836    switch (D.getContext()) {
5837    case DeclaratorContext::Prototype:
5838    case DeclaratorContext::LambdaExprParameter:
5839    case DeclaratorContext::RequiresExpr:
5840      // C++0x [dcl.fct]p13:
5841      //   [...] When it is part of a parameter-declaration-clause, the
5842      //   parameter pack is a function parameter pack (14.5.3). The type T
5843      //   of the declarator-id of the function parameter pack shall contain
5844      //   a template parameter pack; each template parameter pack in T is
5845      //   expanded by the function parameter pack.
5846      //
5847      // We represent function parameter packs as function parameters whose
5848      // type is a pack expansion.
5849      if (!T->containsUnexpandedParameterPack() &&
5850          (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5851        S.Diag(D.getEllipsisLoc(),
5852             diag::err_function_parameter_pack_without_parameter_packs)
5853          << T <<  D.getSourceRange();
5854        D.setEllipsisLoc(SourceLocation());
5855      } else {
5856        T = Context.getPackExpansionType(T, std::nullopt,
5857                                         /*ExpectPackInType=*/false);
5858      }
5859      break;
5860    case DeclaratorContext::TemplateParam:
5861      // C++0x [temp.param]p15:
5862      //   If a template-parameter is a [...] is a parameter-declaration that
5863      //   declares a parameter pack (8.3.5), then the template-parameter is a
5864      //   template parameter pack (14.5.3).
5865      //
5866      // Note: core issue 778 clarifies that, if there are any unexpanded
5867      // parameter packs in the type of the non-type template parameter, then
5868      // it expands those parameter packs.
5869      if (T->containsUnexpandedParameterPack())
5870        T = Context.getPackExpansionType(T, std::nullopt);
5871      else
5872        S.Diag(D.getEllipsisLoc(),
5873               LangOpts.CPlusPlus11
5874                 ? diag::warn_cxx98_compat_variadic_templates
5875                 : diag::ext_variadic_templates);
5876      break;
5877
5878    case DeclaratorContext::File:
5879    case DeclaratorContext::KNRTypeList:
5880    case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5881    case DeclaratorContext::ObjCResult:    // FIXME: special diagnostic here?
5882    case DeclaratorContext::TypeName:
5883    case DeclaratorContext::FunctionalCast:
5884    case DeclaratorContext::CXXNew:
5885    case DeclaratorContext::AliasDecl:
5886    case DeclaratorContext::AliasTemplate:
5887    case DeclaratorContext::Member:
5888    case DeclaratorContext::Block:
5889    case DeclaratorContext::ForInit:
5890    case DeclaratorContext::SelectionInit:
5891    case DeclaratorContext::Condition:
5892    case DeclaratorContext::CXXCatch:
5893    case DeclaratorContext::ObjCCatch:
5894    case DeclaratorContext::BlockLiteral:
5895    case DeclaratorContext::LambdaExpr:
5896    case DeclaratorContext::ConversionId:
5897    case DeclaratorContext::TrailingReturn:
5898    case DeclaratorContext::TrailingReturnVar:
5899    case DeclaratorContext::TemplateArg:
5900    case DeclaratorContext::TemplateTypeArg:
5901    case DeclaratorContext::Association:
5902      // FIXME: We may want to allow parameter packs in block-literal contexts
5903      // in the future.
5904      S.Diag(D.getEllipsisLoc(),
5905             diag::err_ellipsis_in_declarator_not_parameter);
5906      D.setEllipsisLoc(SourceLocation());
5907      break;
5908    }
5909  }
5910
5911  assert(!T.isNull() && "T must not be null at the end of this function");
5912  if (D.isInvalidType())
5913    return Context.getTrivialTypeSourceInfo(T);
5914
5915  return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5916}
5917
5918/// GetTypeForDeclarator - Convert the type for the specified
5919/// declarator to Type instances.
5920///
5921/// The result of this call will never be null, but the associated
5922/// type may be a null type if there's an unrecoverable error.
5923TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5924  // Determine the type of the declarator. Not all forms of declarator
5925  // have a type.
5926
5927  TypeProcessingState state(*this, D);
5928
5929  TypeSourceInfo *ReturnTypeInfo = nullptr;
5930  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5931  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5932    inferARCWriteback(state, T);
5933
5934  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5935}
5936
5937static void transferARCOwnershipToDeclSpec(Sema &S,
5938                                           QualType &declSpecTy,
5939                                           Qualifiers::ObjCLifetime ownership) {
5940  if (declSpecTy->isObjCRetainableType() &&
5941      declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5942    Qualifiers qs;
5943    qs.addObjCLifetime(ownership);
5944    declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5945  }
5946}
5947
5948static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5949                                            Qualifiers::ObjCLifetime ownership,
5950                                            unsigned chunkIndex) {
5951  Sema &S = state.getSema();
5952  Declarator &D = state.getDeclarator();
5953
5954  // Look for an explicit lifetime attribute.
5955  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5956  if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5957    return;
5958
5959  const char *attrStr = nullptr;
5960  switch (ownership) {
5961  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5962  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5963  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5964  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5965  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5966  }
5967
5968  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5969  Arg->Ident = &S.Context.Idents.get(attrStr);
5970  Arg->Loc = SourceLocation();
5971
5972  ArgsUnion Args(Arg);
5973
5974  // If there wasn't one, add one (with an invalid source location
5975  // so that we don't make an AttributedType for it).
5976  ParsedAttr *attr = D.getAttributePool().create(
5977      &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5978      /*scope*/ nullptr, SourceLocation(),
5979      /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5980  chunk.getAttrs().addAtEnd(attr);
5981  // TODO: mark whether we did this inference?
5982}
5983
5984/// Used for transferring ownership in casts resulting in l-values.
5985static void transferARCOwnership(TypeProcessingState &state,
5986                                 QualType &declSpecTy,
5987                                 Qualifiers::ObjCLifetime ownership) {
5988  Sema &S = state.getSema();
5989  Declarator &D = state.getDeclarator();
5990
5991  int inner = -1;
5992  bool hasIndirection = false;
5993  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5994    DeclaratorChunk &chunk = D.getTypeObject(i);
5995    switch (chunk.Kind) {
5996    case DeclaratorChunk::Paren:
5997      // Ignore parens.
5998      break;
5999
6000    case DeclaratorChunk::Array:
6001    case DeclaratorChunk::Reference:
6002    case DeclaratorChunk::Pointer:
6003      if (inner != -1)
6004        hasIndirection = true;
6005      inner = i;
6006      break;
6007
6008    case DeclaratorChunk::BlockPointer:
6009      if (inner != -1)
6010        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
6011      return;
6012
6013    case DeclaratorChunk::Function:
6014    case DeclaratorChunk::MemberPointer:
6015    case DeclaratorChunk::Pipe:
6016      return;
6017    }
6018  }
6019
6020  if (inner == -1)
6021    return;
6022
6023  DeclaratorChunk &chunk = D.getTypeObject(inner);
6024  if (chunk.Kind == DeclaratorChunk::Pointer) {
6025    if (declSpecTy->isObjCRetainableType())
6026      return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6027    if (declSpecTy->isObjCObjectType() && hasIndirection)
6028      return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
6029  } else {
6030    assert(chunk.Kind == DeclaratorChunk::Array ||
6031           chunk.Kind == DeclaratorChunk::Reference);
6032    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6033  }
6034}
6035
6036TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
6037  TypeProcessingState state(*this, D);
6038
6039  TypeSourceInfo *ReturnTypeInfo = nullptr;
6040  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6041
6042  if (getLangOpts().ObjC) {
6043    Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6044    if (ownership != Qualifiers::OCL_None)
6045      transferARCOwnership(state, declSpecTy, ownership);
6046  }
6047
6048  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6049}
6050
6051static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6052                                  TypeProcessingState &State) {
6053  TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6054}
6055
6056static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6057                              const ParsedAttributesView &Attrs) {
6058  for (const ParsedAttr &AL : Attrs) {
6059    if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6060      MTL.setAttrNameLoc(AL.getLoc());
6061      MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6062      MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6063      MTL.setAttrOperandParensRange(SourceRange());
6064      return;
6065    }
6066  }
6067
6068  llvm_unreachable("no matrix_type attribute found at the expected location!");
6069}
6070
6071namespace {
6072  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6073    Sema &SemaRef;
6074    ASTContext &Context;
6075    TypeProcessingState &State;
6076    const DeclSpec &DS;
6077
6078  public:
6079    TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6080                      const DeclSpec &DS)
6081        : SemaRef(S), Context(Context), State(State), DS(DS) {}
6082
6083    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6084      Visit(TL.getModifiedLoc());
6085      fillAttributedTypeLoc(TL, State);
6086    }
6087    void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6088      Visit(TL.getWrappedLoc());
6089    }
6090    void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6091      Visit(TL.getInnerLoc());
6092      TL.setExpansionLoc(
6093          State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6094    }
6095    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6096      Visit(TL.getUnqualifiedLoc());
6097    }
6098    // Allow to fill pointee's type locations, e.g.,
6099    //   int __attr * __attr * __attr *p;
6100    void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6101    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6102      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6103    }
6104    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6105      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6106      // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6107      // addition field. What we have is good enough for display of location
6108      // of 'fixit' on interface name.
6109      TL.setNameEndLoc(DS.getEndLoc());
6110    }
6111    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6112      TypeSourceInfo *RepTInfo = nullptr;
6113      Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6114      TL.copy(RepTInfo->getTypeLoc());
6115    }
6116    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6117      TypeSourceInfo *RepTInfo = nullptr;
6118      Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6119      TL.copy(RepTInfo->getTypeLoc());
6120    }
6121    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6122      TypeSourceInfo *TInfo = nullptr;
6123      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6124
6125      // If we got no declarator info from previous Sema routines,
6126      // just fill with the typespec loc.
6127      if (!TInfo) {
6128        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6129        return;
6130      }
6131
6132      TypeLoc OldTL = TInfo->getTypeLoc();
6133      if (TInfo->getType()->getAs<ElaboratedType>()) {
6134        ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6135        TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6136            .castAs<TemplateSpecializationTypeLoc>();
6137        TL.copy(NamedTL);
6138      } else {
6139        TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6140        assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6141      }
6142
6143    }
6144    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6145      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6146             DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6147      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6148      TL.setParensRange(DS.getTypeofParensRange());
6149    }
6150    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6151      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6152             DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6153      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6154      TL.setParensRange(DS.getTypeofParensRange());
6155      assert(DS.getRepAsType());
6156      TypeSourceInfo *TInfo = nullptr;
6157      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6158      TL.setUnmodifiedTInfo(TInfo);
6159    }
6160    void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6161      assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6162      TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6163      TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6164    }
6165    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6166      assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6167      TL.setKWLoc(DS.getTypeSpecTypeLoc());
6168      TL.setParensRange(DS.getTypeofParensRange());
6169      assert(DS.getRepAsType());
6170      TypeSourceInfo *TInfo = nullptr;
6171      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6172      TL.setUnderlyingTInfo(TInfo);
6173    }
6174    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6175      // By default, use the source location of the type specifier.
6176      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6177      if (TL.needsExtraLocalData()) {
6178        // Set info for the written builtin specifiers.
6179        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6180        // Try to have a meaningful source location.
6181        if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6182          TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6183        if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6184          TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6185      }
6186    }
6187    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6188      if (DS.getTypeSpecType() == TST_typename) {
6189        TypeSourceInfo *TInfo = nullptr;
6190        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6191        if (TInfo)
6192          if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6193            TL.copy(ETL);
6194            return;
6195          }
6196      }
6197      const ElaboratedType *T = TL.getTypePtr();
6198      TL.setElaboratedKeywordLoc(T->getKeyword() != ETK_None
6199                                     ? DS.getTypeSpecTypeLoc()
6200                                     : SourceLocation());
6201      const CXXScopeSpec& SS = DS.getTypeSpecScope();
6202      TL.setQualifierLoc(SS.getWithLocInContext(Context));
6203      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6204    }
6205    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6206      assert(DS.getTypeSpecType() == TST_typename);
6207      TypeSourceInfo *TInfo = nullptr;
6208      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6209      assert(TInfo);
6210      TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6211    }
6212    void VisitDependentTemplateSpecializationTypeLoc(
6213                                 DependentTemplateSpecializationTypeLoc TL) {
6214      assert(DS.getTypeSpecType() == TST_typename);
6215      TypeSourceInfo *TInfo = nullptr;
6216      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6217      assert(TInfo);
6218      TL.copy(
6219          TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6220    }
6221    void VisitAutoTypeLoc(AutoTypeLoc TL) {
6222      assert(DS.getTypeSpecType() == TST_auto ||
6223             DS.getTypeSpecType() == TST_decltype_auto ||
6224             DS.getTypeSpecType() == TST_auto_type ||
6225             DS.getTypeSpecType() == TST_unspecified);
6226      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6227      if (DS.getTypeSpecType() == TST_decltype_auto)
6228        TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6229      if (!DS.isConstrainedAuto())
6230        return;
6231      TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6232      if (!TemplateId)
6233        return;
6234      if (DS.getTypeSpecScope().isNotEmpty())
6235        TL.setNestedNameSpecifierLoc(
6236            DS.getTypeSpecScope().getWithLocInContext(Context));
6237      else
6238        TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
6239      TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
6240      TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
6241      TL.setFoundDecl(nullptr);
6242      TL.setLAngleLoc(TemplateId->LAngleLoc);
6243      TL.setRAngleLoc(TemplateId->RAngleLoc);
6244      if (TemplateId->NumArgs == 0)
6245        return;
6246      TemplateArgumentListInfo TemplateArgsInfo;
6247      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6248                                         TemplateId->NumArgs);
6249      SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6250      for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
6251        TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
6252    }
6253    void VisitTagTypeLoc(TagTypeLoc TL) {
6254      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6255    }
6256    void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6257      // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6258      // or an _Atomic qualifier.
6259      if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6260        TL.setKWLoc(DS.getTypeSpecTypeLoc());
6261        TL.setParensRange(DS.getTypeofParensRange());
6262
6263        TypeSourceInfo *TInfo = nullptr;
6264        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6265        assert(TInfo);
6266        TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6267      } else {
6268        TL.setKWLoc(DS.getAtomicSpecLoc());
6269        // No parens, to indicate this was spelled as an _Atomic qualifier.
6270        TL.setParensRange(SourceRange());
6271        Visit(TL.getValueLoc());
6272      }
6273    }
6274
6275    void VisitPipeTypeLoc(PipeTypeLoc TL) {
6276      TL.setKWLoc(DS.getTypeSpecTypeLoc());
6277
6278      TypeSourceInfo *TInfo = nullptr;
6279      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6280      TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6281    }
6282
6283    void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6284      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6285    }
6286
6287    void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6288      TL.setNameLoc(DS.getTypeSpecTypeLoc());
6289    }
6290
6291    void VisitTypeLoc(TypeLoc TL) {
6292      // FIXME: add other typespec types and change this to an assert.
6293      TL.initialize(Context, DS.getTypeSpecTypeLoc());
6294    }
6295  };
6296
6297  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6298    ASTContext &Context;
6299    TypeProcessingState &State;
6300    const DeclaratorChunk &Chunk;
6301
6302  public:
6303    DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6304                        const DeclaratorChunk &Chunk)
6305        : Context(Context), State(State), Chunk(Chunk) {}
6306
6307    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6308      llvm_unreachable("qualified type locs not expected here!");
6309    }
6310    void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6311      llvm_unreachable("decayed type locs not expected here!");
6312    }
6313
6314    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6315      fillAttributedTypeLoc(TL, State);
6316    }
6317    void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6318      // nothing
6319    }
6320    void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6321      // nothing
6322    }
6323    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6324      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6325      TL.setCaretLoc(Chunk.Loc);
6326    }
6327    void VisitPointerTypeLoc(PointerTypeLoc TL) {
6328      assert(Chunk.Kind == DeclaratorChunk::Pointer);
6329      TL.setStarLoc(Chunk.Loc);
6330    }
6331    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6332      assert(Chunk.Kind == DeclaratorChunk::Pointer);
6333      TL.setStarLoc(Chunk.Loc);
6334    }
6335    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6336      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6337      const CXXScopeSpec& SS = Chunk.Mem.Scope();
6338      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6339
6340      const Type* ClsTy = TL.getClass();
6341      QualType ClsQT = QualType(ClsTy, 0);
6342      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6343      // Now copy source location info into the type loc component.
6344      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6345      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6346      case NestedNameSpecifier::Identifier:
6347        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6348        {
6349          DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6350          DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6351          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6352          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6353        }
6354        break;
6355
6356      case NestedNameSpecifier::TypeSpec:
6357      case NestedNameSpecifier::TypeSpecWithTemplate:
6358        if (isa<ElaboratedType>(ClsTy)) {
6359          ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6360          ETLoc.setElaboratedKeywordLoc(SourceLocation());
6361          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6362          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6363          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6364        } else {
6365          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6366        }
6367        break;
6368
6369      case NestedNameSpecifier::Namespace:
6370      case NestedNameSpecifier::NamespaceAlias:
6371      case NestedNameSpecifier::Global:
6372      case NestedNameSpecifier::Super:
6373        llvm_unreachable("Nested-name-specifier must name a type");
6374      }
6375
6376      // Finally fill in MemberPointerLocInfo fields.
6377      TL.setStarLoc(Chunk.Mem.StarLoc);
6378      TL.setClassTInfo(ClsTInfo);
6379    }
6380    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6381      assert(Chunk.Kind == DeclaratorChunk::Reference);
6382      // 'Amp' is misleading: this might have been originally
6383      /// spelled with AmpAmp.
6384      TL.setAmpLoc(Chunk.Loc);
6385    }
6386    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6387      assert(Chunk.Kind == DeclaratorChunk::Reference);
6388      assert(!Chunk.Ref.LValueRef);
6389      TL.setAmpAmpLoc(Chunk.Loc);
6390    }
6391    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6392      assert(Chunk.Kind == DeclaratorChunk::Array);
6393      TL.setLBracketLoc(Chunk.Loc);
6394      TL.setRBracketLoc(Chunk.EndLoc);
6395      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6396    }
6397    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6398      assert(Chunk.Kind == DeclaratorChunk::Function);
6399      TL.setLocalRangeBegin(Chunk.Loc);
6400      TL.setLocalRangeEnd(Chunk.EndLoc);
6401
6402      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6403      TL.setLParenLoc(FTI.getLParenLoc());
6404      TL.setRParenLoc(FTI.getRParenLoc());
6405      for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6406        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6407        TL.setParam(tpi++, Param);
6408      }
6409      TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6410    }
6411    void VisitParenTypeLoc(ParenTypeLoc TL) {
6412      assert(Chunk.Kind == DeclaratorChunk::Paren);
6413      TL.setLParenLoc(Chunk.Loc);
6414      TL.setRParenLoc(Chunk.EndLoc);
6415    }
6416    void VisitPipeTypeLoc(PipeTypeLoc TL) {
6417      assert(Chunk.Kind == DeclaratorChunk::Pipe);
6418      TL.setKWLoc(Chunk.Loc);
6419    }
6420    void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6421      TL.setNameLoc(Chunk.Loc);
6422    }
6423    void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6424      TL.setExpansionLoc(Chunk.Loc);
6425    }
6426    void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6427    void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6428      TL.setNameLoc(Chunk.Loc);
6429    }
6430    void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6431      TL.setNameLoc(Chunk.Loc);
6432    }
6433    void
6434    VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6435      TL.setNameLoc(Chunk.Loc);
6436    }
6437    void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6438      fillMatrixTypeLoc(TL, Chunk.getAttrs());
6439    }
6440
6441    void VisitTypeLoc(TypeLoc TL) {
6442      llvm_unreachable("unsupported TypeLoc kind in declarator!");
6443    }
6444  };
6445} // end anonymous namespace
6446
6447static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6448  SourceLocation Loc;
6449  switch (Chunk.Kind) {
6450  case DeclaratorChunk::Function:
6451  case DeclaratorChunk::Array:
6452  case DeclaratorChunk::Paren:
6453  case DeclaratorChunk::Pipe:
6454    llvm_unreachable("cannot be _Atomic qualified");
6455
6456  case DeclaratorChunk::Pointer:
6457    Loc = Chunk.Ptr.AtomicQualLoc;
6458    break;
6459
6460  case DeclaratorChunk::BlockPointer:
6461  case DeclaratorChunk::Reference:
6462  case DeclaratorChunk::MemberPointer:
6463    // FIXME: Provide a source location for the _Atomic keyword.
6464    break;
6465  }
6466
6467  ATL.setKWLoc(Loc);
6468  ATL.setParensRange(SourceRange());
6469}
6470
6471static void
6472fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6473                                 const ParsedAttributesView &Attrs) {
6474  for (const ParsedAttr &AL : Attrs) {
6475    if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6476      DASTL.setAttrNameLoc(AL.getLoc());
6477      DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6478      DASTL.setAttrOperandParensRange(SourceRange());
6479      return;
6480    }
6481  }
6482
6483  llvm_unreachable(
6484      "no address_space attribute found at the expected location!");
6485}
6486
6487/// Create and instantiate a TypeSourceInfo with type source information.
6488///
6489/// \param T QualType referring to the type as written in source code.
6490///
6491/// \param ReturnTypeInfo For declarators whose return type does not show
6492/// up in the normal place in the declaration specifiers (such as a C++
6493/// conversion function), this pointer will refer to a type source information
6494/// for that return type.
6495static TypeSourceInfo *
6496GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6497                               QualType T, TypeSourceInfo *ReturnTypeInfo) {
6498  Sema &S = State.getSema();
6499  Declarator &D = State.getDeclarator();
6500
6501  TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6502  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6503
6504  // Handle parameter packs whose type is a pack expansion.
6505  if (isa<PackExpansionType>(T)) {
6506    CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6507    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6508  }
6509
6510  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6511    // An AtomicTypeLoc might be produced by an atomic qualifier in this
6512    // declarator chunk.
6513    if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6514      fillAtomicQualLoc(ATL, D.getTypeObject(i));
6515      CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6516    }
6517
6518    bool HasDesugaredTypeLoc = true;
6519    while (HasDesugaredTypeLoc) {
6520      switch (CurrTL.getTypeLocClass()) {
6521      case TypeLoc::MacroQualified: {
6522        auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6523        TL.setExpansionLoc(
6524            State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6525        CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6526        break;
6527      }
6528
6529      case TypeLoc::Attributed: {
6530        auto TL = CurrTL.castAs<AttributedTypeLoc>();
6531        fillAttributedTypeLoc(TL, State);
6532        CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6533        break;
6534      }
6535
6536      case TypeLoc::Adjusted:
6537      case TypeLoc::BTFTagAttributed: {
6538        CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6539        break;
6540      }
6541
6542      case TypeLoc::DependentAddressSpace: {
6543        auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6544        fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6545        CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6546        break;
6547      }
6548
6549      default:
6550        HasDesugaredTypeLoc = false;
6551        break;
6552      }
6553    }
6554
6555    DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6556    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6557  }
6558
6559  // If we have different source information for the return type, use
6560  // that.  This really only applies to C++ conversion functions.
6561  if (ReturnTypeInfo) {
6562    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6563    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6564    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6565  } else {
6566    TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6567  }
6568
6569  return TInfo;
6570}
6571
6572/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6573ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6574  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6575  // and Sema during declaration parsing. Try deallocating/caching them when
6576  // it's appropriate, instead of allocating them and keeping them around.
6577  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6578                                                       TypeAlignment);
6579  new (LocT) LocInfoType(T, TInfo);
6580  assert(LocT->getTypeClass() != T->getTypeClass() &&
6581         "LocInfoType's TypeClass conflicts with an existing Type class");
6582  return ParsedType::make(QualType(LocT, 0));
6583}
6584
6585void LocInfoType::getAsStringInternal(std::string &Str,
6586                                      const PrintingPolicy &Policy) const {
6587  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6588         " was used directly instead of getting the QualType through"
6589         " GetTypeFromParser");
6590}
6591
6592TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6593  // C99 6.7.6: Type names have no identifier.  This is already validated by
6594  // the parser.
6595  assert(D.getIdentifier() == nullptr &&
6596         "Type name should have no identifier!");
6597
6598  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6599  QualType T = TInfo->getType();
6600  if (D.isInvalidType())
6601    return true;
6602
6603  // Make sure there are no unused decl attributes on the declarator.
6604  // We don't want to do this for ObjC parameters because we're going
6605  // to apply them to the actual parameter declaration.
6606  // Likewise, we don't want to do this for alias declarations, because
6607  // we are actually going to build a declaration from this eventually.
6608  if (D.getContext() != DeclaratorContext::ObjCParameter &&
6609      D.getContext() != DeclaratorContext::AliasDecl &&
6610      D.getContext() != DeclaratorContext::AliasTemplate)
6611    checkUnusedDeclAttributes(D);
6612
6613  if (getLangOpts().CPlusPlus) {
6614    // Check that there are no default arguments (C++ only).
6615    CheckExtraCXXDefaultArguments(D);
6616  }
6617
6618  return CreateParsedType(T, TInfo);
6619}
6620
6621ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6622  QualType T = Context.getObjCInstanceType();
6623  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6624  return CreateParsedType(T, TInfo);
6625}
6626
6627//===----------------------------------------------------------------------===//
6628// Type Attribute Processing
6629//===----------------------------------------------------------------------===//
6630
6631/// Build an AddressSpace index from a constant expression and diagnose any
6632/// errors related to invalid address_spaces. Returns true on successfully
6633/// building an AddressSpace index.
6634static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6635                                   const Expr *AddrSpace,
6636                                   SourceLocation AttrLoc) {
6637  if (!AddrSpace->isValueDependent()) {
6638    std::optional<llvm::APSInt> OptAddrSpace =
6639        AddrSpace->getIntegerConstantExpr(S.Context);
6640    if (!OptAddrSpace) {
6641      S.Diag(AttrLoc, diag::err_attribute_argument_type)
6642          << "'address_space'" << AANT_ArgumentIntegerConstant
6643          << AddrSpace->getSourceRange();
6644      return false;
6645    }
6646    llvm::APSInt &addrSpace = *OptAddrSpace;
6647
6648    // Bounds checking.
6649    if (addrSpace.isSigned()) {
6650      if (addrSpace.isNegative()) {
6651        S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6652            << AddrSpace->getSourceRange();
6653        return false;
6654      }
6655      addrSpace.setIsSigned(false);
6656    }
6657
6658    llvm::APSInt max(addrSpace.getBitWidth());
6659    max =
6660        Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6661
6662    if (addrSpace > max) {
6663      S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6664          << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6665      return false;
6666    }
6667
6668    ASIdx =
6669        getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6670    return true;
6671  }
6672
6673  // Default value for DependentAddressSpaceTypes
6674  ASIdx = LangAS::Default;
6675  return true;
6676}
6677
6678/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6679/// is uninstantiated. If instantiated it will apply the appropriate address
6680/// space to the type. This function allows dependent template variables to be
6681/// used in conjunction with the address_space attribute
6682QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6683                                     SourceLocation AttrLoc) {
6684  if (!AddrSpace->isValueDependent()) {
6685    if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6686                                            AttrLoc))
6687      return QualType();
6688
6689    return Context.getAddrSpaceQualType(T, ASIdx);
6690  }
6691
6692  // A check with similar intentions as checking if a type already has an
6693  // address space except for on a dependent types, basically if the
6694  // current type is already a DependentAddressSpaceType then its already
6695  // lined up to have another address space on it and we can't have
6696  // multiple address spaces on the one pointer indirection
6697  if (T->getAs<DependentAddressSpaceType>()) {
6698    Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6699    return QualType();
6700  }
6701
6702  return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6703}
6704
6705QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6706                                     SourceLocation AttrLoc) {
6707  LangAS ASIdx;
6708  if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6709    return QualType();
6710  return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6711}
6712
6713static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6714                                      TypeProcessingState &State) {
6715  Sema &S = State.getSema();
6716
6717  // Check the number of attribute arguments.
6718  if (Attr.getNumArgs() != 1) {
6719    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6720        << Attr << 1;
6721    Attr.setInvalid();
6722    return;
6723  }
6724
6725  // Ensure the argument is a string.
6726  auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6727  if (!StrLiteral) {
6728    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6729        << Attr << AANT_ArgumentString;
6730    Attr.setInvalid();
6731    return;
6732  }
6733
6734  ASTContext &Ctx = S.Context;
6735  StringRef BTFTypeTag = StrLiteral->getString();
6736  Type = State.getBTFTagAttributedType(
6737      ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6738}
6739
6740/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6741/// specified type.  The attribute contains 1 argument, the id of the address
6742/// space for the type.
6743static void HandleAddressSpaceTypeAttribute(QualType &Type,
6744                                            const ParsedAttr &Attr,
6745                                            TypeProcessingState &State) {
6746  Sema &S = State.getSema();
6747
6748  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6749  // qualified by an address-space qualifier."
6750  if (Type->isFunctionType()) {
6751    S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6752    Attr.setInvalid();
6753    return;
6754  }
6755
6756  LangAS ASIdx;
6757  if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6758
6759    // Check the attribute arguments.
6760    if (Attr.getNumArgs() != 1) {
6761      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6762                                                                        << 1;
6763      Attr.setInvalid();
6764      return;
6765    }
6766
6767    Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6768    LangAS ASIdx;
6769    if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6770      Attr.setInvalid();
6771      return;
6772    }
6773
6774    ASTContext &Ctx = S.Context;
6775    auto *ASAttr =
6776        ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6777
6778    // If the expression is not value dependent (not templated), then we can
6779    // apply the address space qualifiers just to the equivalent type.
6780    // Otherwise, we make an AttributedType with the modified and equivalent
6781    // type the same, and wrap it in a DependentAddressSpaceType. When this
6782    // dependent type is resolved, the qualifier is added to the equivalent type
6783    // later.
6784    QualType T;
6785    if (!ASArgExpr->isValueDependent()) {
6786      QualType EquivType =
6787          S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6788      if (EquivType.isNull()) {
6789        Attr.setInvalid();
6790        return;
6791      }
6792      T = State.getAttributedType(ASAttr, Type, EquivType);
6793    } else {
6794      T = State.getAttributedType(ASAttr, Type, Type);
6795      T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6796    }
6797
6798    if (!T.isNull())
6799      Type = T;
6800    else
6801      Attr.setInvalid();
6802  } else {
6803    // The keyword-based type attributes imply which address space to use.
6804    ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6805                                         : Attr.asOpenCLLangAS();
6806    if (S.getLangOpts().HLSL)
6807      ASIdx = Attr.asHLSLLangAS();
6808
6809    if (ASIdx == LangAS::Default)
6810      llvm_unreachable("Invalid address space");
6811
6812    if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6813                                            Attr.getLoc())) {
6814      Attr.setInvalid();
6815      return;
6816    }
6817
6818    Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6819  }
6820}
6821
6822/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6823/// attribute on the specified type.
6824///
6825/// Returns 'true' if the attribute was handled.
6826static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6827                                        ParsedAttr &attr, QualType &type) {
6828  bool NonObjCPointer = false;
6829
6830  if (!type->isDependentType() && !type->isUndeducedType()) {
6831    if (const PointerType *ptr = type->getAs<PointerType>()) {
6832      QualType pointee = ptr->getPointeeType();
6833      if (pointee->isObjCRetainableType() || pointee->isPointerType())
6834        return false;
6835      // It is important not to lose the source info that there was an attribute
6836      // applied to non-objc pointer. We will create an attributed type but
6837      // its type will be the same as the original type.
6838      NonObjCPointer = true;
6839    } else if (!type->isObjCRetainableType()) {
6840      return false;
6841    }
6842
6843    // Don't accept an ownership attribute in the declspec if it would
6844    // just be the return type of a block pointer.
6845    if (state.isProcessingDeclSpec()) {
6846      Declarator &D = state.getDeclarator();
6847      if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6848                                  /*onlyBlockPointers=*/true))
6849        return false;
6850    }
6851  }
6852
6853  Sema &S = state.getSema();
6854  SourceLocation AttrLoc = attr.getLoc();
6855  if (AttrLoc.isMacroID())
6856    AttrLoc =
6857        S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6858
6859  if (!attr.isArgIdent(0)) {
6860    S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6861                                                       << AANT_ArgumentString;
6862    attr.setInvalid();
6863    return true;
6864  }
6865
6866  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6867  Qualifiers::ObjCLifetime lifetime;
6868  if (II->isStr("none"))
6869    lifetime = Qualifiers::OCL_ExplicitNone;
6870  else if (II->isStr("strong"))
6871    lifetime = Qualifiers::OCL_Strong;
6872  else if (II->isStr("weak"))
6873    lifetime = Qualifiers::OCL_Weak;
6874  else if (II->isStr("autoreleasing"))
6875    lifetime = Qualifiers::OCL_Autoreleasing;
6876  else {
6877    S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6878    attr.setInvalid();
6879    return true;
6880  }
6881
6882  // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6883  // outside of ARC mode.
6884  if (!S.getLangOpts().ObjCAutoRefCount &&
6885      lifetime != Qualifiers::OCL_Weak &&
6886      lifetime != Qualifiers::OCL_ExplicitNone) {
6887    return true;
6888  }
6889
6890  SplitQualType underlyingType = type.split();
6891
6892  // Check for redundant/conflicting ownership qualifiers.
6893  if (Qualifiers::ObjCLifetime previousLifetime
6894        = type.getQualifiers().getObjCLifetime()) {
6895    // If it's written directly, that's an error.
6896    if (S.Context.hasDirectOwnershipQualifier(type)) {
6897      S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6898        << type;
6899      return true;
6900    }
6901
6902    // Otherwise, if the qualifiers actually conflict, pull sugar off
6903    // and remove the ObjCLifetime qualifiers.
6904    if (previousLifetime != lifetime) {
6905      // It's possible to have multiple local ObjCLifetime qualifiers. We
6906      // can't stop after we reach a type that is directly qualified.
6907      const Type *prevTy = nullptr;
6908      while (!prevTy || prevTy != underlyingType.Ty) {
6909        prevTy = underlyingType.Ty;
6910        underlyingType = underlyingType.getSingleStepDesugaredType();
6911      }
6912      underlyingType.Quals.removeObjCLifetime();
6913    }
6914  }
6915
6916  underlyingType.Quals.addObjCLifetime(lifetime);
6917
6918  if (NonObjCPointer) {
6919    StringRef name = attr.getAttrName()->getName();
6920    switch (lifetime) {
6921    case Qualifiers::OCL_None:
6922    case Qualifiers::OCL_ExplicitNone:
6923      break;
6924    case Qualifiers::OCL_Strong: name = "__strong"; break;
6925    case Qualifiers::OCL_Weak: name = "__weak"; break;
6926    case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6927    }
6928    S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6929      << TDS_ObjCObjOrBlock << type;
6930  }
6931
6932  // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6933  // because having both 'T' and '__unsafe_unretained T' exist in the type
6934  // system causes unfortunate widespread consistency problems.  (For example,
6935  // they're not considered compatible types, and we mangle them identicially
6936  // as template arguments.)  These problems are all individually fixable,
6937  // but it's easier to just not add the qualifier and instead sniff it out
6938  // in specific places using isObjCInertUnsafeUnretainedType().
6939  //
6940  // Doing this does means we miss some trivial consistency checks that
6941  // would've triggered in ARC, but that's better than trying to solve all
6942  // the coexistence problems with __unsafe_unretained.
6943  if (!S.getLangOpts().ObjCAutoRefCount &&
6944      lifetime == Qualifiers::OCL_ExplicitNone) {
6945    type = state.getAttributedType(
6946        createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6947        type, type);
6948    return true;
6949  }
6950
6951  QualType origType = type;
6952  if (!NonObjCPointer)
6953    type = S.Context.getQualifiedType(underlyingType);
6954
6955  // If we have a valid source location for the attribute, use an
6956  // AttributedType instead.
6957  if (AttrLoc.isValid()) {
6958    type = state.getAttributedType(::new (S.Context)
6959                                       ObjCOwnershipAttr(S.Context, attr, II),
6960                                   origType, type);
6961  }
6962
6963  auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6964                            unsigned diagnostic, QualType type) {
6965    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6966      S.DelayedDiagnostics.add(
6967          sema::DelayedDiagnostic::makeForbiddenType(
6968              S.getSourceManager().getExpansionLoc(loc),
6969              diagnostic, type, /*ignored*/ 0));
6970    } else {
6971      S.Diag(loc, diagnostic);
6972    }
6973  };
6974
6975  // Sometimes, __weak isn't allowed.
6976  if (lifetime == Qualifiers::OCL_Weak &&
6977      !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6978
6979    // Use a specialized diagnostic if the runtime just doesn't support them.
6980    unsigned diagnostic =
6981      (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6982                                       : diag::err_arc_weak_no_runtime);
6983
6984    // In any case, delay the diagnostic until we know what we're parsing.
6985    diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6986
6987    attr.setInvalid();
6988    return true;
6989  }
6990
6991  // Forbid __weak for class objects marked as
6992  // objc_arc_weak_reference_unavailable
6993  if (lifetime == Qualifiers::OCL_Weak) {
6994    if (const ObjCObjectPointerType *ObjT =
6995          type->getAs<ObjCObjectPointerType>()) {
6996      if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6997        if (Class->isArcWeakrefUnavailable()) {
6998          S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6999          S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7000                 diag::note_class_declared);
7001        }
7002      }
7003    }
7004  }
7005
7006  return true;
7007}
7008
7009/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7010/// attribute on the specified type.  Returns true to indicate that
7011/// the attribute was handled, false to indicate that the type does
7012/// not permit the attribute.
7013static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7014                                 QualType &type) {
7015  Sema &S = state.getSema();
7016
7017  // Delay if this isn't some kind of pointer.
7018  if (!type->isPointerType() &&
7019      !type->isObjCObjectPointerType() &&
7020      !type->isBlockPointerType())
7021    return false;
7022
7023  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7024    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7025    attr.setInvalid();
7026    return true;
7027  }
7028
7029  // Check the attribute arguments.
7030  if (!attr.isArgIdent(0)) {
7031    S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7032        << attr << AANT_ArgumentString;
7033    attr.setInvalid();
7034    return true;
7035  }
7036  Qualifiers::GC GCAttr;
7037  if (attr.getNumArgs() > 1) {
7038    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7039                                                                      << 1;
7040    attr.setInvalid();
7041    return true;
7042  }
7043
7044  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7045  if (II->isStr("weak"))
7046    GCAttr = Qualifiers::Weak;
7047  else if (II->isStr("strong"))
7048    GCAttr = Qualifiers::Strong;
7049  else {
7050    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7051        << attr << II;
7052    attr.setInvalid();
7053    return true;
7054  }
7055
7056  QualType origType = type;
7057  type = S.Context.getObjCGCQualType(origType, GCAttr);
7058
7059  // Make an attributed type to preserve the source information.
7060  if (attr.getLoc().isValid())
7061    type = state.getAttributedType(
7062        ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7063
7064  return true;
7065}
7066
7067namespace {
7068  /// A helper class to unwrap a type down to a function for the
7069  /// purposes of applying attributes there.
7070  ///
7071  /// Use:
7072  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
7073  ///   if (unwrapped.isFunctionType()) {
7074  ///     const FunctionType *fn = unwrapped.get();
7075  ///     // change fn somehow
7076  ///     T = unwrapped.wrap(fn);
7077  ///   }
7078  struct FunctionTypeUnwrapper {
7079    enum WrapKind {
7080      Desugar,
7081      Attributed,
7082      Parens,
7083      Array,
7084      Pointer,
7085      BlockPointer,
7086      Reference,
7087      MemberPointer,
7088      MacroQualified,
7089    };
7090
7091    QualType Original;
7092    const FunctionType *Fn;
7093    SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7094
7095    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7096      while (true) {
7097        const Type *Ty = T.getTypePtr();
7098        if (isa<FunctionType>(Ty)) {
7099          Fn = cast<FunctionType>(Ty);
7100          return;
7101        } else if (isa<ParenType>(Ty)) {
7102          T = cast<ParenType>(Ty)->getInnerType();
7103          Stack.push_back(Parens);
7104        } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7105                   isa<IncompleteArrayType>(Ty)) {
7106          T = cast<ArrayType>(Ty)->getElementType();
7107          Stack.push_back(Array);
7108        } else if (isa<PointerType>(Ty)) {
7109          T = cast<PointerType>(Ty)->getPointeeType();
7110          Stack.push_back(Pointer);
7111        } else if (isa<BlockPointerType>(Ty)) {
7112          T = cast<BlockPointerType>(Ty)->getPointeeType();
7113          Stack.push_back(BlockPointer);
7114        } else if (isa<MemberPointerType>(Ty)) {
7115          T = cast<MemberPointerType>(Ty)->getPointeeType();
7116          Stack.push_back(MemberPointer);
7117        } else if (isa<ReferenceType>(Ty)) {
7118          T = cast<ReferenceType>(Ty)->getPointeeType();
7119          Stack.push_back(Reference);
7120        } else if (isa<AttributedType>(Ty)) {
7121          T = cast<AttributedType>(Ty)->getEquivalentType();
7122          Stack.push_back(Attributed);
7123        } else if (isa<MacroQualifiedType>(Ty)) {
7124          T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7125          Stack.push_back(MacroQualified);
7126        } else {
7127          const Type *DTy = Ty->getUnqualifiedDesugaredType();
7128          if (Ty == DTy) {
7129            Fn = nullptr;
7130            return;
7131          }
7132
7133          T = QualType(DTy, 0);
7134          Stack.push_back(Desugar);
7135        }
7136      }
7137    }
7138
7139    bool isFunctionType() const { return (Fn != nullptr); }
7140    const FunctionType *get() const { return Fn; }
7141
7142    QualType wrap(Sema &S, const FunctionType *New) {
7143      // If T wasn't modified from the unwrapped type, do nothing.
7144      if (New == get()) return Original;
7145
7146      Fn = New;
7147      return wrap(S.Context, Original, 0);
7148    }
7149
7150  private:
7151    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7152      if (I == Stack.size())
7153        return C.getQualifiedType(Fn, Old.getQualifiers());
7154
7155      // Build up the inner type, applying the qualifiers from the old
7156      // type to the new type.
7157      SplitQualType SplitOld = Old.split();
7158
7159      // As a special case, tail-recurse if there are no qualifiers.
7160      if (SplitOld.Quals.empty())
7161        return wrap(C, SplitOld.Ty, I);
7162      return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7163    }
7164
7165    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7166      if (I == Stack.size()) return QualType(Fn, 0);
7167
7168      switch (static_cast<WrapKind>(Stack[I++])) {
7169      case Desugar:
7170        // This is the point at which we potentially lose source
7171        // information.
7172        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7173
7174      case Attributed:
7175        return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7176
7177      case Parens: {
7178        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7179        return C.getParenType(New);
7180      }
7181
7182      case MacroQualified:
7183        return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7184
7185      case Array: {
7186        if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7187          QualType New = wrap(C, CAT->getElementType(), I);
7188          return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7189                                        CAT->getSizeModifier(),
7190                                        CAT->getIndexTypeCVRQualifiers());
7191        }
7192
7193        if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7194          QualType New = wrap(C, VAT->getElementType(), I);
7195          return C.getVariableArrayType(
7196              New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7197              VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7198        }
7199
7200        const auto *IAT = cast<IncompleteArrayType>(Old);
7201        QualType New = wrap(C, IAT->getElementType(), I);
7202        return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7203                                        IAT->getIndexTypeCVRQualifiers());
7204      }
7205
7206      case Pointer: {
7207        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7208        return C.getPointerType(New);
7209      }
7210
7211      case BlockPointer: {
7212        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7213        return C.getBlockPointerType(New);
7214      }
7215
7216      case MemberPointer: {
7217        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7218        QualType New = wrap(C, OldMPT->getPointeeType(), I);
7219        return C.getMemberPointerType(New, OldMPT->getClass());
7220      }
7221
7222      case Reference: {
7223        const ReferenceType *OldRef = cast<ReferenceType>(Old);
7224        QualType New = wrap(C, OldRef->getPointeeType(), I);
7225        if (isa<LValueReferenceType>(OldRef))
7226          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7227        else
7228          return C.getRValueReferenceType(New);
7229      }
7230      }
7231
7232      llvm_unreachable("unknown wrapping kind");
7233    }
7234  };
7235} // end anonymous namespace
7236
7237static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7238                                             ParsedAttr &PAttr, QualType &Type) {
7239  Sema &S = State.getSema();
7240
7241  Attr *A;
7242  switch (PAttr.getKind()) {
7243  default: llvm_unreachable("Unknown attribute kind");
7244  case ParsedAttr::AT_Ptr32:
7245    A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7246    break;
7247  case ParsedAttr::AT_Ptr64:
7248    A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7249    break;
7250  case ParsedAttr::AT_SPtr:
7251    A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7252    break;
7253  case ParsedAttr::AT_UPtr:
7254    A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7255    break;
7256  }
7257
7258  std::bitset<attr::LastAttr> Attrs;
7259  QualType Desugared = Type;
7260  for (;;) {
7261    if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7262      Desugared = TT->desugar();
7263      continue;
7264    } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7265      Desugared = ET->desugar();
7266      continue;
7267    }
7268    const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7269    if (!AT)
7270      break;
7271    Attrs[AT->getAttrKind()] = true;
7272    Desugared = AT->getModifiedType();
7273  }
7274
7275  // You cannot specify duplicate type attributes, so if the attribute has
7276  // already been applied, flag it.
7277  attr::Kind NewAttrKind = A->getKind();
7278  if (Attrs[NewAttrKind]) {
7279    S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7280    return true;
7281  }
7282  Attrs[NewAttrKind] = true;
7283
7284  // You cannot have both __sptr and __uptr on the same type, nor can you
7285  // have __ptr32 and __ptr64.
7286  if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7287    S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7288        << "'__ptr32'"
7289        << "'__ptr64'";
7290    return true;
7291  } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7292    S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7293        << "'__sptr'"
7294        << "'__uptr'";
7295    return true;
7296  }
7297
7298  // Check the raw (i.e., desugared) Canonical type to see if it
7299  // is a pointer type.
7300  if (!isa<PointerType>(Desugared)) {
7301    // Pointer type qualifiers can only operate on pointer types, but not
7302    // pointer-to-member types.
7303    if (Type->isMemberPointerType())
7304      S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7305    else
7306      S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7307    return true;
7308  }
7309
7310  // Add address space to type based on its attributes.
7311  LangAS ASIdx = LangAS::Default;
7312  uint64_t PtrWidth =
7313      S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
7314  if (PtrWidth == 32) {
7315    if (Attrs[attr::Ptr64])
7316      ASIdx = LangAS::ptr64;
7317    else if (Attrs[attr::UPtr])
7318      ASIdx = LangAS::ptr32_uptr;
7319  } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7320    if (Attrs[attr::UPtr])
7321      ASIdx = LangAS::ptr32_uptr;
7322    else
7323      ASIdx = LangAS::ptr32_sptr;
7324  }
7325
7326  QualType Pointee = Type->getPointeeType();
7327  if (ASIdx != LangAS::Default)
7328    Pointee = S.Context.getAddrSpaceQualType(
7329        S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7330  Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7331  return false;
7332}
7333
7334/// Map a nullability attribute kind to a nullability kind.
7335static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7336  switch (kind) {
7337  case ParsedAttr::AT_TypeNonNull:
7338    return NullabilityKind::NonNull;
7339
7340  case ParsedAttr::AT_TypeNullable:
7341    return NullabilityKind::Nullable;
7342
7343  case ParsedAttr::AT_TypeNullableResult:
7344    return NullabilityKind::NullableResult;
7345
7346  case ParsedAttr::AT_TypeNullUnspecified:
7347    return NullabilityKind::Unspecified;
7348
7349  default:
7350    llvm_unreachable("not a nullability attribute kind");
7351  }
7352}
7353
7354/// Applies a nullability type specifier to the given type, if possible.
7355///
7356/// \param state The type processing state.
7357///
7358/// \param type The type to which the nullability specifier will be
7359/// added. On success, this type will be updated appropriately.
7360///
7361/// \param attr The attribute as written on the type.
7362///
7363/// \param allowOnArrayType Whether to accept nullability specifiers on an
7364/// array type (e.g., because it will decay to a pointer).
7365///
7366/// \returns true if a problem has been diagnosed, false on success.
7367static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7368                                          QualType &type,
7369                                          ParsedAttr &attr,
7370                                          bool allowOnArrayType) {
7371  Sema &S = state.getSema();
7372
7373  NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7374  SourceLocation nullabilityLoc = attr.getLoc();
7375  bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7376
7377  recordNullabilitySeen(S, nullabilityLoc);
7378
7379  // Check for existing nullability attributes on the type.
7380  QualType desugared = type;
7381  while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7382    // Check whether there is already a null
7383    if (auto existingNullability = attributed->getImmediateNullability()) {
7384      // Duplicated nullability.
7385      if (nullability == *existingNullability) {
7386        S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7387          << DiagNullabilityKind(nullability, isContextSensitive)
7388          << FixItHint::CreateRemoval(nullabilityLoc);
7389
7390        break;
7391      }
7392
7393      // Conflicting nullability.
7394      S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7395        << DiagNullabilityKind(nullability, isContextSensitive)
7396        << DiagNullabilityKind(*existingNullability, false);
7397      return true;
7398    }
7399
7400    desugared = attributed->getModifiedType();
7401  }
7402
7403  // If there is already a different nullability specifier, complain.
7404  // This (unlike the code above) looks through typedefs that might
7405  // have nullability specifiers on them, which means we cannot
7406  // provide a useful Fix-It.
7407  if (auto existingNullability = desugared->getNullability()) {
7408    if (nullability != *existingNullability) {
7409      S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7410        << DiagNullabilityKind(nullability, isContextSensitive)
7411        << DiagNullabilityKind(*existingNullability, false);
7412
7413      // Try to find the typedef with the existing nullability specifier.
7414      if (auto typedefType = desugared->getAs<TypedefType>()) {
7415        TypedefNameDecl *typedefDecl = typedefType->getDecl();
7416        QualType underlyingType = typedefDecl->getUnderlyingType();
7417        if (auto typedefNullability
7418              = AttributedType::stripOuterNullability(underlyingType)) {
7419          if (*typedefNullability == *existingNullability) {
7420            S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7421              << DiagNullabilityKind(*existingNullability, false);
7422          }
7423        }
7424      }
7425
7426      return true;
7427    }
7428  }
7429
7430  // If this definitely isn't a pointer type, reject the specifier.
7431  if (!desugared->canHaveNullability() &&
7432      !(allowOnArrayType && desugared->isArrayType())) {
7433    S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7434      << DiagNullabilityKind(nullability, isContextSensitive) << type;
7435    return true;
7436  }
7437
7438  // For the context-sensitive keywords/Objective-C property
7439  // attributes, require that the type be a single-level pointer.
7440  if (isContextSensitive) {
7441    // Make sure that the pointee isn't itself a pointer type.
7442    const Type *pointeeType = nullptr;
7443    if (desugared->isArrayType())
7444      pointeeType = desugared->getArrayElementTypeNoTypeQual();
7445    else if (desugared->isAnyPointerType())
7446      pointeeType = desugared->getPointeeType().getTypePtr();
7447
7448    if (pointeeType && (pointeeType->isAnyPointerType() ||
7449                        pointeeType->isObjCObjectPointerType() ||
7450                        pointeeType->isMemberPointerType())) {
7451      S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7452        << DiagNullabilityKind(nullability, true)
7453        << type;
7454      S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7455        << DiagNullabilityKind(nullability, false)
7456        << type
7457        << FixItHint::CreateReplacement(nullabilityLoc,
7458                                        getNullabilitySpelling(nullability));
7459      return true;
7460    }
7461  }
7462
7463  // Form the attributed type.
7464  type = state.getAttributedType(
7465      createNullabilityAttr(S.Context, attr, nullability), type, type);
7466  return false;
7467}
7468
7469/// Check the application of the Objective-C '__kindof' qualifier to
7470/// the given type.
7471static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7472                                ParsedAttr &attr) {
7473  Sema &S = state.getSema();
7474
7475  if (isa<ObjCTypeParamType>(type)) {
7476    // Build the attributed type to record where __kindof occurred.
7477    type = state.getAttributedType(
7478        createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7479    return false;
7480  }
7481
7482  // Find out if it's an Objective-C object or object pointer type;
7483  const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7484  const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7485                                          : type->getAs<ObjCObjectType>();
7486
7487  // If not, we can't apply __kindof.
7488  if (!objType) {
7489    // FIXME: Handle dependent types that aren't yet object types.
7490    S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7491      << type;
7492    return true;
7493  }
7494
7495  // Rebuild the "equivalent" type, which pushes __kindof down into
7496  // the object type.
7497  // There is no need to apply kindof on an unqualified id type.
7498  QualType equivType = S.Context.getObjCObjectType(
7499      objType->getBaseType(), objType->getTypeArgsAsWritten(),
7500      objType->getProtocols(),
7501      /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7502
7503  // If we started with an object pointer type, rebuild it.
7504  if (ptrType) {
7505    equivType = S.Context.getObjCObjectPointerType(equivType);
7506    if (auto nullability = type->getNullability()) {
7507      // We create a nullability attribute from the __kindof attribute.
7508      // Make sure that will make sense.
7509      assert(attr.getAttributeSpellingListIndex() == 0 &&
7510             "multiple spellings for __kindof?");
7511      Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7512      A->setImplicit(true);
7513      equivType = state.getAttributedType(A, equivType, equivType);
7514    }
7515  }
7516
7517  // Build the attributed type to record where __kindof occurred.
7518  type = state.getAttributedType(
7519      createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7520  return false;
7521}
7522
7523/// Distribute a nullability type attribute that cannot be applied to
7524/// the type specifier to a pointer, block pointer, or member pointer
7525/// declarator, complaining if necessary.
7526///
7527/// \returns true if the nullability annotation was distributed, false
7528/// otherwise.
7529static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7530                                          QualType type, ParsedAttr &attr) {
7531  Declarator &declarator = state.getDeclarator();
7532
7533  /// Attempt to move the attribute to the specified chunk.
7534  auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7535    // If there is already a nullability attribute there, don't add
7536    // one.
7537    if (hasNullabilityAttr(chunk.getAttrs()))
7538      return false;
7539
7540    // Complain about the nullability qualifier being in the wrong
7541    // place.
7542    enum {
7543      PK_Pointer,
7544      PK_BlockPointer,
7545      PK_MemberPointer,
7546      PK_FunctionPointer,
7547      PK_MemberFunctionPointer,
7548    } pointerKind
7549      = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7550                                                             : PK_Pointer)
7551        : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7552        : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7553
7554    auto diag = state.getSema().Diag(attr.getLoc(),
7555                                     diag::warn_nullability_declspec)
7556      << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7557                             attr.isContextSensitiveKeywordAttribute())
7558      << type
7559      << static_cast<unsigned>(pointerKind);
7560
7561    // FIXME: MemberPointer chunks don't carry the location of the *.
7562    if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7563      diag << FixItHint::CreateRemoval(attr.getLoc())
7564           << FixItHint::CreateInsertion(
7565                  state.getSema().getPreprocessor().getLocForEndOfToken(
7566                      chunk.Loc),
7567                  " " + attr.getAttrName()->getName().str() + " ");
7568    }
7569
7570    moveAttrFromListToList(attr, state.getCurrentAttributes(),
7571                           chunk.getAttrs());
7572    return true;
7573  };
7574
7575  // Move it to the outermost pointer, member pointer, or block
7576  // pointer declarator.
7577  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7578    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7579    switch (chunk.Kind) {
7580    case DeclaratorChunk::Pointer:
7581    case DeclaratorChunk::BlockPointer:
7582    case DeclaratorChunk::MemberPointer:
7583      return moveToChunk(chunk, false);
7584
7585    case DeclaratorChunk::Paren:
7586    case DeclaratorChunk::Array:
7587      continue;
7588
7589    case DeclaratorChunk::Function:
7590      // Try to move past the return type to a function/block/member
7591      // function pointer.
7592      if (DeclaratorChunk *dest = maybeMovePastReturnType(
7593                                    declarator, i,
7594                                    /*onlyBlockPointers=*/false)) {
7595        return moveToChunk(*dest, true);
7596      }
7597
7598      return false;
7599
7600    // Don't walk through these.
7601    case DeclaratorChunk::Reference:
7602    case DeclaratorChunk::Pipe:
7603      return false;
7604    }
7605  }
7606
7607  return false;
7608}
7609
7610static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7611  assert(!Attr.isInvalid());
7612  switch (Attr.getKind()) {
7613  default:
7614    llvm_unreachable("not a calling convention attribute");
7615  case ParsedAttr::AT_CDecl:
7616    return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7617  case ParsedAttr::AT_FastCall:
7618    return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7619  case ParsedAttr::AT_StdCall:
7620    return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7621  case ParsedAttr::AT_ThisCall:
7622    return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7623  case ParsedAttr::AT_RegCall:
7624    return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7625  case ParsedAttr::AT_Pascal:
7626    return createSimpleAttr<PascalAttr>(Ctx, Attr);
7627  case ParsedAttr::AT_SwiftCall:
7628    return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7629  case ParsedAttr::AT_SwiftAsyncCall:
7630    return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7631  case ParsedAttr::AT_VectorCall:
7632    return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7633  case ParsedAttr::AT_AArch64VectorPcs:
7634    return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7635  case ParsedAttr::AT_AArch64SVEPcs:
7636    return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7637  case ParsedAttr::AT_AMDGPUKernelCall:
7638    return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7639  case ParsedAttr::AT_Pcs: {
7640    // The attribute may have had a fixit applied where we treated an
7641    // identifier as a string literal.  The contents of the string are valid,
7642    // but the form may not be.
7643    StringRef Str;
7644    if (Attr.isArgExpr(0))
7645      Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7646    else
7647      Str = Attr.getArgAsIdent(0)->Ident->getName();
7648    PcsAttr::PCSType Type;
7649    if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7650      llvm_unreachable("already validated the attribute");
7651    return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7652  }
7653  case ParsedAttr::AT_IntelOclBicc:
7654    return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7655  case ParsedAttr::AT_MSABI:
7656    return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7657  case ParsedAttr::AT_SysVABI:
7658    return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7659  case ParsedAttr::AT_PreserveMost:
7660    return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7661  case ParsedAttr::AT_PreserveAll:
7662    return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7663  }
7664  llvm_unreachable("unexpected attribute kind!");
7665}
7666
7667/// Process an individual function attribute.  Returns true to
7668/// indicate that the attribute was handled, false if it wasn't.
7669static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7670                                   QualType &type) {
7671  Sema &S = state.getSema();
7672
7673  FunctionTypeUnwrapper unwrapped(S, type);
7674
7675  if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7676    if (S.CheckAttrNoArgs(attr))
7677      return true;
7678
7679    // Delay if this is not a function type.
7680    if (!unwrapped.isFunctionType())
7681      return false;
7682
7683    // Otherwise we can process right away.
7684    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7685    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7686    return true;
7687  }
7688
7689  if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7690    // Delay if this is not a function type.
7691    if (!unwrapped.isFunctionType())
7692      return false;
7693
7694    // Ignore if we don't have CMSE enabled.
7695    if (!S.getLangOpts().Cmse) {
7696      S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7697      attr.setInvalid();
7698      return true;
7699    }
7700
7701    // Otherwise we can process right away.
7702    FunctionType::ExtInfo EI =
7703        unwrapped.get()->getExtInfo().withCmseNSCall(true);
7704    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7705    return true;
7706  }
7707
7708  // ns_returns_retained is not always a type attribute, but if we got
7709  // here, we're treating it as one right now.
7710  if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7711    if (attr.getNumArgs()) return true;
7712
7713    // Delay if this is not a function type.
7714    if (!unwrapped.isFunctionType())
7715      return false;
7716
7717    // Check whether the return type is reasonable.
7718    if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7719                                           unwrapped.get()->getReturnType()))
7720      return true;
7721
7722    // Only actually change the underlying type in ARC builds.
7723    QualType origType = type;
7724    if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7725      FunctionType::ExtInfo EI
7726        = unwrapped.get()->getExtInfo().withProducesResult(true);
7727      type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7728    }
7729    type = state.getAttributedType(
7730        createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7731        origType, type);
7732    return true;
7733  }
7734
7735  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7736    if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7737      return true;
7738
7739    // Delay if this is not a function type.
7740    if (!unwrapped.isFunctionType())
7741      return false;
7742
7743    FunctionType::ExtInfo EI =
7744        unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7745    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7746    return true;
7747  }
7748
7749  if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7750    if (!S.getLangOpts().CFProtectionBranch) {
7751      S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7752      attr.setInvalid();
7753      return true;
7754    }
7755
7756    if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7757      return true;
7758
7759    // If this is not a function type, warning will be asserted by subject
7760    // check.
7761    if (!unwrapped.isFunctionType())
7762      return true;
7763
7764    FunctionType::ExtInfo EI =
7765      unwrapped.get()->getExtInfo().withNoCfCheck(true);
7766    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7767    return true;
7768  }
7769
7770  if (attr.getKind() == ParsedAttr::AT_Regparm) {
7771    unsigned value;
7772    if (S.CheckRegparmAttr(attr, value))
7773      return true;
7774
7775    // Delay if this is not a function type.
7776    if (!unwrapped.isFunctionType())
7777      return false;
7778
7779    // Diagnose regparm with fastcall.
7780    const FunctionType *fn = unwrapped.get();
7781    CallingConv CC = fn->getCallConv();
7782    if (CC == CC_X86FastCall) {
7783      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7784        << FunctionType::getNameForCallConv(CC)
7785        << "regparm";
7786      attr.setInvalid();
7787      return true;
7788    }
7789
7790    FunctionType::ExtInfo EI =
7791      unwrapped.get()->getExtInfo().withRegParm(value);
7792    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7793    return true;
7794  }
7795
7796  if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7797    // Delay if this is not a function type.
7798    if (!unwrapped.isFunctionType())
7799      return false;
7800
7801    if (S.CheckAttrNoArgs(attr)) {
7802      attr.setInvalid();
7803      return true;
7804    }
7805
7806    // Otherwise we can process right away.
7807    auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7808
7809    // MSVC ignores nothrow if it is in conflict with an explicit exception
7810    // specification.
7811    if (Proto->hasExceptionSpec()) {
7812      switch (Proto->getExceptionSpecType()) {
7813      case EST_None:
7814        llvm_unreachable("This doesn't have an exception spec!");
7815
7816      case EST_DynamicNone:
7817      case EST_BasicNoexcept:
7818      case EST_NoexceptTrue:
7819      case EST_NoThrow:
7820        // Exception spec doesn't conflict with nothrow, so don't warn.
7821        [[fallthrough]];
7822      case EST_Unparsed:
7823      case EST_Uninstantiated:
7824      case EST_DependentNoexcept:
7825      case EST_Unevaluated:
7826        // We don't have enough information to properly determine if there is a
7827        // conflict, so suppress the warning.
7828        break;
7829      case EST_Dynamic:
7830      case EST_MSAny:
7831      case EST_NoexceptFalse:
7832        S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
7833        break;
7834      }
7835      return true;
7836    }
7837
7838    type = unwrapped.wrap(
7839        S, S.Context
7840               .getFunctionTypeWithExceptionSpec(
7841                   QualType{Proto, 0},
7842                   FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
7843               ->getAs<FunctionType>());
7844    return true;
7845  }
7846
7847  // Delay if the type didn't work out to a function.
7848  if (!unwrapped.isFunctionType()) return false;
7849
7850  // Otherwise, a calling convention.
7851  CallingConv CC;
7852  if (S.CheckCallingConvAttr(attr, CC))
7853    return true;
7854
7855  const FunctionType *fn = unwrapped.get();
7856  CallingConv CCOld = fn->getCallConv();
7857  Attr *CCAttr = getCCTypeAttr(S.Context, attr);
7858
7859  if (CCOld != CC) {
7860    // Error out on when there's already an attribute on the type
7861    // and the CCs don't match.
7862    if (S.getCallingConvAttributedType(type)) {
7863      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7864        << FunctionType::getNameForCallConv(CC)
7865        << FunctionType::getNameForCallConv(CCOld);
7866      attr.setInvalid();
7867      return true;
7868    }
7869  }
7870
7871  // Diagnose use of variadic functions with calling conventions that
7872  // don't support them (e.g. because they're callee-cleanup).
7873  // We delay warning about this on unprototyped function declarations
7874  // until after redeclaration checking, just in case we pick up a
7875  // prototype that way.  And apparently we also "delay" warning about
7876  // unprototyped function types in general, despite not necessarily having
7877  // much ability to diagnose it later.
7878  if (!supportsVariadicCall(CC)) {
7879    const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
7880    if (FnP && FnP->isVariadic()) {
7881      // stdcall and fastcall are ignored with a warning for GCC and MS
7882      // compatibility.
7883      if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7884        return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7885               << FunctionType::getNameForCallConv(CC)
7886               << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7887
7888      attr.setInvalid();
7889      return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7890             << FunctionType::getNameForCallConv(CC);
7891    }
7892  }
7893
7894  // Also diagnose fastcall with regparm.
7895  if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7896    S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7897        << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7898    attr.setInvalid();
7899    return true;
7900  }
7901
7902  // Modify the CC from the wrapped function type, wrap it all back, and then
7903  // wrap the whole thing in an AttributedType as written.  The modified type
7904  // might have a different CC if we ignored the attribute.
7905  QualType Equivalent;
7906  if (CCOld == CC) {
7907    Equivalent = type;
7908  } else {
7909    auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7910    Equivalent =
7911      unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7912  }
7913  type = state.getAttributedType(CCAttr, type, Equivalent);
7914  return true;
7915}
7916
7917bool Sema::hasExplicitCallingConv(QualType T) {
7918  const AttributedType *AT;
7919
7920  // Stop if we'd be stripping off a typedef sugar node to reach the
7921  // AttributedType.
7922  while ((AT = T->getAs<AttributedType>()) &&
7923         AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7924    if (AT->isCallingConv())
7925      return true;
7926    T = AT->getModifiedType();
7927  }
7928  return false;
7929}
7930
7931void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7932                                  SourceLocation Loc) {
7933  FunctionTypeUnwrapper Unwrapped(*this, T);
7934  const FunctionType *FT = Unwrapped.get();
7935  bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7936                     cast<FunctionProtoType>(FT)->isVariadic());
7937  CallingConv CurCC = FT->getCallConv();
7938  CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7939
7940  if (CurCC == ToCC)
7941    return;
7942
7943  // MS compiler ignores explicit calling convention attributes on structors. We
7944  // should do the same.
7945  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7946    // Issue a warning on ignored calling convention -- except of __stdcall.
7947    // Again, this is what MS compiler does.
7948    if (CurCC != CC_X86StdCall)
7949      Diag(Loc, diag::warn_cconv_unsupported)
7950          << FunctionType::getNameForCallConv(CurCC)
7951          << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7952  // Default adjustment.
7953  } else {
7954    // Only adjust types with the default convention.  For example, on Windows
7955    // we should adjust a __cdecl type to __thiscall for instance methods, and a
7956    // __thiscall type to __cdecl for static methods.
7957    CallingConv DefaultCC =
7958        Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7959
7960    if (CurCC != DefaultCC)
7961      return;
7962
7963    if (hasExplicitCallingConv(T))
7964      return;
7965  }
7966
7967  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7968  QualType Wrapped = Unwrapped.wrap(*this, FT);
7969  T = Context.getAdjustedType(T, Wrapped);
7970}
7971
7972/// HandleVectorSizeAttribute - this attribute is only applicable to integral
7973/// and float scalars, although arrays, pointers, and function return values are
7974/// allowed in conjunction with this construct. Aggregates with this attribute
7975/// are invalid, even if they are of the same size as a corresponding scalar.
7976/// The raw attribute should contain precisely 1 argument, the vector size for
7977/// the variable, measured in bytes. If curType and rawAttr are well formed,
7978/// this routine will return a new vector type.
7979static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7980                                 Sema &S) {
7981  // Check the attribute arguments.
7982  if (Attr.getNumArgs() != 1) {
7983    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7984                                                                      << 1;
7985    Attr.setInvalid();
7986    return;
7987  }
7988
7989  Expr *SizeExpr = Attr.getArgAsExpr(0);
7990  QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7991  if (!T.isNull())
7992    CurType = T;
7993  else
7994    Attr.setInvalid();
7995}
7996
7997/// Process the OpenCL-like ext_vector_type attribute when it occurs on
7998/// a type.
7999static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8000                                    Sema &S) {
8001  // check the attribute arguments.
8002  if (Attr.getNumArgs() != 1) {
8003    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8004                                                                      << 1;
8005    return;
8006  }
8007
8008  Expr *SizeExpr = Attr.getArgAsExpr(0);
8009  QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8010  if (!T.isNull())
8011    CurType = T;
8012}
8013
8014static bool isPermittedNeonBaseType(QualType &Ty,
8015                                    VectorType::VectorKind VecKind, Sema &S) {
8016  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8017  if (!BTy)
8018    return false;
8019
8020  llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8021
8022  // Signed poly is mathematically wrong, but has been baked into some ABIs by
8023  // now.
8024  bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8025                        Triple.getArch() == llvm::Triple::aarch64_32 ||
8026                        Triple.getArch() == llvm::Triple::aarch64_be;
8027  if (VecKind == VectorType::NeonPolyVector) {
8028    if (IsPolyUnsigned) {
8029      // AArch64 polynomial vectors are unsigned.
8030      return BTy->getKind() == BuiltinType::UChar ||
8031             BTy->getKind() == BuiltinType::UShort ||
8032             BTy->getKind() == BuiltinType::ULong ||
8033             BTy->getKind() == BuiltinType::ULongLong;
8034    } else {
8035      // AArch32 polynomial vectors are signed.
8036      return BTy->getKind() == BuiltinType::SChar ||
8037             BTy->getKind() == BuiltinType::Short ||
8038             BTy->getKind() == BuiltinType::LongLong;
8039    }
8040  }
8041
8042  // Non-polynomial vector types: the usual suspects are allowed, as well as
8043  // float64_t on AArch64.
8044  if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8045      BTy->getKind() == BuiltinType::Double)
8046    return true;
8047
8048  return BTy->getKind() == BuiltinType::SChar ||
8049         BTy->getKind() == BuiltinType::UChar ||
8050         BTy->getKind() == BuiltinType::Short ||
8051         BTy->getKind() == BuiltinType::UShort ||
8052         BTy->getKind() == BuiltinType::Int ||
8053         BTy->getKind() == BuiltinType::UInt ||
8054         BTy->getKind() == BuiltinType::Long ||
8055         BTy->getKind() == BuiltinType::ULong ||
8056         BTy->getKind() == BuiltinType::LongLong ||
8057         BTy->getKind() == BuiltinType::ULongLong ||
8058         BTy->getKind() == BuiltinType::Float ||
8059         BTy->getKind() == BuiltinType::Half ||
8060         BTy->getKind() == BuiltinType::BFloat16;
8061}
8062
8063static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8064                                           llvm::APSInt &Result) {
8065  const auto *AttrExpr = Attr.getArgAsExpr(0);
8066  if (!AttrExpr->isTypeDependent()) {
8067    if (std::optional<llvm::APSInt> Res =
8068            AttrExpr->getIntegerConstantExpr(S.Context)) {
8069      Result = *Res;
8070      return true;
8071    }
8072  }
8073  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8074      << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8075  Attr.setInvalid();
8076  return false;
8077}
8078
8079/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8080/// "neon_polyvector_type" attributes are used to create vector types that
8081/// are mangled according to ARM's ABI.  Otherwise, these types are identical
8082/// to those created with the "vector_size" attribute.  Unlike "vector_size"
8083/// the argument to these Neon attributes is the number of vector elements,
8084/// not the vector size in bytes.  The vector width and element type must
8085/// match one of the standard Neon vector types.
8086static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8087                                     Sema &S, VectorType::VectorKind VecKind) {
8088  // Target must have NEON (or MVE, whose vectors are similar enough
8089  // not to need a separate attribute)
8090  if (!S.Context.getTargetInfo().hasFeature("neon") &&
8091      !S.Context.getTargetInfo().hasFeature("mve")) {
8092    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8093        << Attr << "'neon' or 'mve'";
8094    Attr.setInvalid();
8095    return;
8096  }
8097  // Check the attribute arguments.
8098  if (Attr.getNumArgs() != 1) {
8099    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8100                                                                      << 1;
8101    Attr.setInvalid();
8102    return;
8103  }
8104  // The number of elements must be an ICE.
8105  llvm::APSInt numEltsInt(32);
8106  if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8107    return;
8108
8109  // Only certain element types are supported for Neon vectors.
8110  if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
8111    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8112    Attr.setInvalid();
8113    return;
8114  }
8115
8116  // The total size of the vector must be 64 or 128 bits.
8117  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8118  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8119  unsigned vecSize = typeSize * numElts;
8120  if (vecSize != 64 && vecSize != 128) {
8121    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8122    Attr.setInvalid();
8123    return;
8124  }
8125
8126  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8127}
8128
8129/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8130/// used to create fixed-length versions of sizeless SVE types defined by
8131/// the ACLE, such as svint32_t and svbool_t.
8132static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8133                                           Sema &S) {
8134  // Target must have SVE.
8135  if (!S.Context.getTargetInfo().hasFeature("sve")) {
8136    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8137    Attr.setInvalid();
8138    return;
8139  }
8140
8141  // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8142  // if <bits>+ syntax is used.
8143  if (!S.getLangOpts().VScaleMin ||
8144      S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8145    S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8146        << Attr;
8147    Attr.setInvalid();
8148    return;
8149  }
8150
8151  // Check the attribute arguments.
8152  if (Attr.getNumArgs() != 1) {
8153    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8154        << Attr << 1;
8155    Attr.setInvalid();
8156    return;
8157  }
8158
8159  // The vector size must be an integer constant expression.
8160  llvm::APSInt SveVectorSizeInBits(32);
8161  if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8162    return;
8163
8164  unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8165
8166  // The attribute vector size must match -msve-vector-bits.
8167  if (VecSize != S.getLangOpts().VScaleMin * 128) {
8168    S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8169        << VecSize << S.getLangOpts().VScaleMin * 128;
8170    Attr.setInvalid();
8171    return;
8172  }
8173
8174  // Attribute can only be attached to a single SVE vector or predicate type.
8175  if (!CurType->isVLSTBuiltinType()) {
8176    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8177        << Attr << CurType;
8178    Attr.setInvalid();
8179    return;
8180  }
8181
8182  const auto *BT = CurType->castAs<BuiltinType>();
8183
8184  QualType EltType = CurType->getSveEltType(S.Context);
8185  unsigned TypeSize = S.Context.getTypeSize(EltType);
8186  VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector;
8187  if (BT->getKind() == BuiltinType::SveBool) {
8188    // Predicates are represented as i8.
8189    VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8190    VecKind = VectorType::SveFixedLengthPredicateVector;
8191  } else
8192    VecSize /= TypeSize;
8193  CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8194}
8195
8196static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8197                                               QualType &CurType,
8198                                               ParsedAttr &Attr) {
8199  const VectorType *VT = dyn_cast<VectorType>(CurType);
8200  if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
8201    State.getSema().Diag(Attr.getLoc(),
8202                         diag::err_attribute_arm_mve_polymorphism);
8203    Attr.setInvalid();
8204    return;
8205  }
8206
8207  CurType =
8208      State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8209                                  State.getSema().Context, Attr),
8210                              CurType, CurType);
8211}
8212
8213/// Handle OpenCL Access Qualifier Attribute.
8214static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8215                                   Sema &S) {
8216  // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8217  if (!(CurType->isImageType() || CurType->isPipeType())) {
8218    S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8219    Attr.setInvalid();
8220    return;
8221  }
8222
8223  if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8224    QualType BaseTy = TypedefTy->desugar();
8225
8226    std::string PrevAccessQual;
8227    if (BaseTy->isPipeType()) {
8228      if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8229        OpenCLAccessAttr *Attr =
8230            TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8231        PrevAccessQual = Attr->getSpelling();
8232      } else {
8233        PrevAccessQual = "read_only";
8234      }
8235    } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8236
8237      switch (ImgType->getKind()) {
8238        #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8239      case BuiltinType::Id:                                          \
8240        PrevAccessQual = #Access;                                    \
8241        break;
8242        #include "clang/Basic/OpenCLImageTypes.def"
8243      default:
8244        llvm_unreachable("Unable to find corresponding image type.");
8245      }
8246    } else {
8247      llvm_unreachable("unexpected type");
8248    }
8249    StringRef AttrName = Attr.getAttrName()->getName();
8250    if (PrevAccessQual == AttrName.ltrim("_")) {
8251      // Duplicated qualifiers
8252      S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8253         << AttrName << Attr.getRange();
8254    } else {
8255      // Contradicting qualifiers
8256      S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8257    }
8258
8259    S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8260           diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8261  } else if (CurType->isPipeType()) {
8262    if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8263      QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8264      CurType = S.Context.getWritePipeType(ElemType);
8265    }
8266  }
8267}
8268
8269/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8270static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8271                                 Sema &S) {
8272  if (!S.getLangOpts().MatrixTypes) {
8273    S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8274    return;
8275  }
8276
8277  if (Attr.getNumArgs() != 2) {
8278    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8279        << Attr << 2;
8280    return;
8281  }
8282
8283  Expr *RowsExpr = Attr.getArgAsExpr(0);
8284  Expr *ColsExpr = Attr.getArgAsExpr(1);
8285  QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8286  if (!T.isNull())
8287    CurType = T;
8288}
8289
8290static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8291                                   QualType &CurType, const ParsedAttr &PA) {
8292  Sema &S = State.getSema();
8293
8294  if (PA.getNumArgs() < 1) {
8295    S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8296    return;
8297  }
8298
8299  // Make sure that there is a string literal as the annotation's first
8300  // argument.
8301  StringRef Str;
8302  if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8303    return;
8304
8305  llvm::SmallVector<Expr *, 4> Args;
8306  Args.reserve(PA.getNumArgs() - 1);
8307  for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8308    assert(!PA.isArgIdent(Idx));
8309    Args.push_back(PA.getArgAsExpr(Idx));
8310  }
8311  if (!S.ConstantFoldAttrArgs(PA, Args))
8312    return;
8313  auto *AnnotateTypeAttr =
8314      AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8315  CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8316}
8317
8318static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8319                                    QualType &CurType,
8320                                    ParsedAttr &Attr) {
8321  if (State.getDeclarator().isDeclarationOfFunction()) {
8322    CurType = State.getAttributedType(
8323        createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8324        CurType, CurType);
8325  }
8326}
8327
8328static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8329                             TypeAttrLocation TAL,
8330                             const ParsedAttributesView &attrs) {
8331
8332  state.setParsedNoDeref(false);
8333  if (attrs.empty())
8334    return;
8335
8336  // Scan through and apply attributes to this type where it makes sense.  Some
8337  // attributes (such as __address_space__, __vector_size__, etc) apply to the
8338  // type, but others can be present in the type specifiers even though they
8339  // apply to the decl.  Here we apply type attributes and ignore the rest.
8340
8341  // This loop modifies the list pretty frequently, but we still need to make
8342  // sure we visit every element once. Copy the attributes list, and iterate
8343  // over that.
8344  ParsedAttributesView AttrsCopy{attrs};
8345  for (ParsedAttr &attr : AttrsCopy) {
8346
8347    // Skip attributes that were marked to be invalid.
8348    if (attr.isInvalid())
8349      continue;
8350
8351    if (attr.isStandardAttributeSyntax()) {
8352      // [[gnu::...]] attributes are treated as declaration attributes, so may
8353      // not appertain to a DeclaratorChunk. If we handle them as type
8354      // attributes, accept them in that position and diagnose the GCC
8355      // incompatibility.
8356      if (attr.isGNUScope()) {
8357        bool IsTypeAttr = attr.isTypeAttr();
8358        if (TAL == TAL_DeclChunk) {
8359          state.getSema().Diag(attr.getLoc(),
8360                               IsTypeAttr
8361                                   ? diag::warn_gcc_ignores_type_attr
8362                                   : diag::warn_cxx11_gnu_attribute_on_type)
8363              << attr;
8364          if (!IsTypeAttr)
8365            continue;
8366        }
8367      } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8368                 !attr.isTypeAttr()) {
8369        // Otherwise, only consider type processing for a C++11 attribute if
8370        // - it has actually been applied to a type (decl-specifier-seq or
8371        //   declarator chunk), or
8372        // - it is a type attribute, irrespective of where it was applied (so
8373        //   that we can support the legacy behavior of some type attributes
8374        //   that can be applied to the declaration name).
8375        continue;
8376      }
8377    }
8378
8379    // If this is an attribute we can handle, do so now,
8380    // otherwise, add it to the FnAttrs list for rechaining.
8381    switch (attr.getKind()) {
8382    default:
8383      // A [[]] attribute on a declarator chunk must appertain to a type.
8384      if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
8385        state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8386            << attr;
8387        attr.setUsedAsTypeAttr();
8388      }
8389      break;
8390
8391    case ParsedAttr::UnknownAttribute:
8392      if (attr.isStandardAttributeSyntax()) {
8393        state.getSema().Diag(attr.getLoc(),
8394                             diag::warn_unknown_attribute_ignored)
8395            << attr << attr.getRange();
8396        // Mark the attribute as invalid so we don't emit the same diagnostic
8397        // multiple times.
8398        attr.setInvalid();
8399      }
8400      break;
8401
8402    case ParsedAttr::IgnoredAttribute:
8403      break;
8404
8405    case ParsedAttr::AT_BTFTypeTag:
8406      HandleBTFTypeTagAttribute(type, attr, state);
8407      attr.setUsedAsTypeAttr();
8408      break;
8409
8410    case ParsedAttr::AT_MayAlias:
8411      // FIXME: This attribute needs to actually be handled, but if we ignore
8412      // it it breaks large amounts of Linux software.
8413      attr.setUsedAsTypeAttr();
8414      break;
8415    case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8416    case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8417    case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8418    case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8419    case ParsedAttr::AT_OpenCLLocalAddressSpace:
8420    case ParsedAttr::AT_OpenCLConstantAddressSpace:
8421    case ParsedAttr::AT_OpenCLGenericAddressSpace:
8422    case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8423    case ParsedAttr::AT_AddressSpace:
8424      HandleAddressSpaceTypeAttribute(type, attr, state);
8425      attr.setUsedAsTypeAttr();
8426      break;
8427    OBJC_POINTER_TYPE_ATTRS_CASELIST:
8428      if (!handleObjCPointerTypeAttr(state, attr, type))
8429        distributeObjCPointerTypeAttr(state, attr, type);
8430      attr.setUsedAsTypeAttr();
8431      break;
8432    case ParsedAttr::AT_VectorSize:
8433      HandleVectorSizeAttr(type, attr, state.getSema());
8434      attr.setUsedAsTypeAttr();
8435      break;
8436    case ParsedAttr::AT_ExtVectorType:
8437      HandleExtVectorTypeAttr(type, attr, state.getSema());
8438      attr.setUsedAsTypeAttr();
8439      break;
8440    case ParsedAttr::AT_NeonVectorType:
8441      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8442                               VectorType::NeonVector);
8443      attr.setUsedAsTypeAttr();
8444      break;
8445    case ParsedAttr::AT_NeonPolyVectorType:
8446      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8447                               VectorType::NeonPolyVector);
8448      attr.setUsedAsTypeAttr();
8449      break;
8450    case ParsedAttr::AT_ArmSveVectorBits:
8451      HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8452      attr.setUsedAsTypeAttr();
8453      break;
8454    case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8455      HandleArmMveStrictPolymorphismAttr(state, type, attr);
8456      attr.setUsedAsTypeAttr();
8457      break;
8458    }
8459    case ParsedAttr::AT_OpenCLAccess:
8460      HandleOpenCLAccessAttr(type, attr, state.getSema());
8461      attr.setUsedAsTypeAttr();
8462      break;
8463    case ParsedAttr::AT_LifetimeBound:
8464      if (TAL == TAL_DeclChunk)
8465        HandleLifetimeBoundAttr(state, type, attr);
8466      break;
8467
8468    case ParsedAttr::AT_NoDeref: {
8469      // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8470      // See https://github.com/llvm/llvm-project/issues/55790 for details.
8471      // For the time being, we simply emit a warning that the attribute is
8472      // ignored.
8473      if (attr.isStandardAttributeSyntax()) {
8474        state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8475            << attr;
8476        break;
8477      }
8478      ASTContext &Ctx = state.getSema().Context;
8479      type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8480                                     type, type);
8481      attr.setUsedAsTypeAttr();
8482      state.setParsedNoDeref(true);
8483      break;
8484    }
8485
8486    case ParsedAttr::AT_MatrixType:
8487      HandleMatrixTypeAttr(type, attr, state.getSema());
8488      attr.setUsedAsTypeAttr();
8489      break;
8490
8491    MS_TYPE_ATTRS_CASELIST:
8492      if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8493        attr.setUsedAsTypeAttr();
8494      break;
8495
8496
8497    NULLABILITY_TYPE_ATTRS_CASELIST:
8498      // Either add nullability here or try to distribute it.  We
8499      // don't want to distribute the nullability specifier past any
8500      // dependent type, because that complicates the user model.
8501      if (type->canHaveNullability() || type->isDependentType() ||
8502          type->isArrayType() ||
8503          !distributeNullabilityTypeAttr(state, type, attr)) {
8504        unsigned endIndex;
8505        if (TAL == TAL_DeclChunk)
8506          endIndex = state.getCurrentChunkIndex();
8507        else
8508          endIndex = state.getDeclarator().getNumTypeObjects();
8509        bool allowOnArrayType =
8510            state.getDeclarator().isPrototypeContext() &&
8511            !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8512        if (checkNullabilityTypeSpecifier(
8513              state,
8514              type,
8515              attr,
8516              allowOnArrayType)) {
8517          attr.setInvalid();
8518        }
8519
8520        attr.setUsedAsTypeAttr();
8521      }
8522      break;
8523
8524    case ParsedAttr::AT_ObjCKindOf:
8525      // '__kindof' must be part of the decl-specifiers.
8526      switch (TAL) {
8527      case TAL_DeclSpec:
8528        break;
8529
8530      case TAL_DeclChunk:
8531      case TAL_DeclName:
8532        state.getSema().Diag(attr.getLoc(),
8533                             diag::err_objc_kindof_wrong_position)
8534            << FixItHint::CreateRemoval(attr.getLoc())
8535            << FixItHint::CreateInsertion(
8536                   state.getDeclarator().getDeclSpec().getBeginLoc(),
8537                   "__kindof ");
8538        break;
8539      }
8540
8541      // Apply it regardless.
8542      if (checkObjCKindOfType(state, type, attr))
8543        attr.setInvalid();
8544      break;
8545
8546    case ParsedAttr::AT_NoThrow:
8547    // Exception Specifications aren't generally supported in C mode throughout
8548    // clang, so revert to attribute-based handling for C.
8549      if (!state.getSema().getLangOpts().CPlusPlus)
8550        break;
8551      [[fallthrough]];
8552    FUNCTION_TYPE_ATTRS_CASELIST:
8553      attr.setUsedAsTypeAttr();
8554
8555      // Attributes with standard syntax have strict rules for what they
8556      // appertain to and hence should not use the "distribution" logic below.
8557      if (attr.isStandardAttributeSyntax()) {
8558        if (!handleFunctionTypeAttr(state, attr, type)) {
8559          diagnoseBadTypeAttribute(state.getSema(), attr, type);
8560          attr.setInvalid();
8561        }
8562        break;
8563      }
8564
8565      // Never process function type attributes as part of the
8566      // declaration-specifiers.
8567      if (TAL == TAL_DeclSpec)
8568        distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8569
8570      // Otherwise, handle the possible delays.
8571      else if (!handleFunctionTypeAttr(state, attr, type))
8572        distributeFunctionTypeAttr(state, attr, type);
8573      break;
8574    case ParsedAttr::AT_AcquireHandle: {
8575      if (!type->isFunctionType())
8576        return;
8577
8578      if (attr.getNumArgs() != 1) {
8579        state.getSema().Diag(attr.getLoc(),
8580                             diag::err_attribute_wrong_number_arguments)
8581            << attr << 1;
8582        attr.setInvalid();
8583        return;
8584      }
8585
8586      StringRef HandleType;
8587      if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8588        return;
8589      type = state.getAttributedType(
8590          AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8591          type, type);
8592      attr.setUsedAsTypeAttr();
8593      break;
8594    }
8595    case ParsedAttr::AT_AnnotateType: {
8596      HandleAnnotateTypeAttr(state, type, attr);
8597      attr.setUsedAsTypeAttr();
8598      break;
8599    }
8600    }
8601
8602    // Handle attributes that are defined in a macro. We do not want this to be
8603    // applied to ObjC builtin attributes.
8604    if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8605        !type.getQualifiers().hasObjCLifetime() &&
8606        !type.getQualifiers().hasObjCGCAttr() &&
8607        attr.getKind() != ParsedAttr::AT_ObjCGC &&
8608        attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8609      const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8610      type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8611      state.setExpansionLocForMacroQualifiedType(
8612          cast<MacroQualifiedType>(type.getTypePtr()),
8613          attr.getMacroExpansionLoc());
8614    }
8615  }
8616}
8617
8618void Sema::completeExprArrayBound(Expr *E) {
8619  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8620    if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8621      if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8622        auto *Def = Var->getDefinition();
8623        if (!Def) {
8624          SourceLocation PointOfInstantiation = E->getExprLoc();
8625          runWithSufficientStackSpace(PointOfInstantiation, [&] {
8626            InstantiateVariableDefinition(PointOfInstantiation, Var);
8627          });
8628          Def = Var->getDefinition();
8629
8630          // If we don't already have a point of instantiation, and we managed
8631          // to instantiate a definition, this is the point of instantiation.
8632          // Otherwise, we don't request an end-of-TU instantiation, so this is
8633          // not a point of instantiation.
8634          // FIXME: Is this really the right behavior?
8635          if (Var->getPointOfInstantiation().isInvalid() && Def) {
8636            assert(Var->getTemplateSpecializationKind() ==
8637                       TSK_ImplicitInstantiation &&
8638                   "explicit instantiation with no point of instantiation");
8639            Var->setTemplateSpecializationKind(
8640                Var->getTemplateSpecializationKind(), PointOfInstantiation);
8641          }
8642        }
8643
8644        // Update the type to the definition's type both here and within the
8645        // expression.
8646        if (Def) {
8647          DRE->setDecl(Def);
8648          QualType T = Def->getType();
8649          DRE->setType(T);
8650          // FIXME: Update the type on all intervening expressions.
8651          E->setType(T);
8652        }
8653
8654        // We still go on to try to complete the type independently, as it
8655        // may also require instantiations or diagnostics if it remains
8656        // incomplete.
8657      }
8658    }
8659  }
8660}
8661
8662QualType Sema::getCompletedType(Expr *E) {
8663  // Incomplete array types may be completed by the initializer attached to
8664  // their definitions. For static data members of class templates and for
8665  // variable templates, we need to instantiate the definition to get this
8666  // initializer and complete the type.
8667  if (E->getType()->isIncompleteArrayType())
8668    completeExprArrayBound(E);
8669
8670  // FIXME: Are there other cases which require instantiating something other
8671  // than the type to complete the type of an expression?
8672
8673  return E->getType();
8674}
8675
8676/// Ensure that the type of the given expression is complete.
8677///
8678/// This routine checks whether the expression \p E has a complete type. If the
8679/// expression refers to an instantiable construct, that instantiation is
8680/// performed as needed to complete its type. Furthermore
8681/// Sema::RequireCompleteType is called for the expression's type (or in the
8682/// case of a reference type, the referred-to type).
8683///
8684/// \param E The expression whose type is required to be complete.
8685/// \param Kind Selects which completeness rules should be applied.
8686/// \param Diagnoser The object that will emit a diagnostic if the type is
8687/// incomplete.
8688///
8689/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8690/// otherwise.
8691bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8692                                   TypeDiagnoser &Diagnoser) {
8693  return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
8694                             Diagnoser);
8695}
8696
8697bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8698  BoundTypeDiagnoser<> Diagnoser(DiagID);
8699  return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8700}
8701
8702/// Ensure that the type T is a complete type.
8703///
8704/// This routine checks whether the type @p T is complete in any
8705/// context where a complete type is required. If @p T is a complete
8706/// type, returns false. If @p T is a class template specialization,
8707/// this routine then attempts to perform class template
8708/// instantiation. If instantiation fails, or if @p T is incomplete
8709/// and cannot be completed, issues the diagnostic @p diag (giving it
8710/// the type @p T) and returns true.
8711///
8712/// @param Loc  The location in the source that the incomplete type
8713/// diagnostic should refer to.
8714///
8715/// @param T  The type that this routine is examining for completeness.
8716///
8717/// @param Kind Selects which completeness rules should be applied.
8718///
8719/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8720/// @c false otherwise.
8721bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8722                               CompleteTypeKind Kind,
8723                               TypeDiagnoser &Diagnoser) {
8724  if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8725    return true;
8726  if (const TagType *Tag = T->getAs<TagType>()) {
8727    if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8728      Tag->getDecl()->setCompleteDefinitionRequired();
8729      Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
8730    }
8731  }
8732  return false;
8733}
8734
8735bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
8736  llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
8737  if (!Suggested)
8738    return false;
8739
8740  // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
8741  // and isolate from other C++ specific checks.
8742  StructuralEquivalenceContext Ctx(
8743      D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
8744      StructuralEquivalenceKind::Default,
8745      false /*StrictTypeSpelling*/, true /*Complain*/,
8746      true /*ErrorOnTagTypeMismatch*/);
8747  return Ctx.IsEquivalent(D, Suggested);
8748}
8749
8750bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
8751                                   AcceptableKind Kind, bool OnlyNeedComplete) {
8752  // Easy case: if we don't have modules, all declarations are visible.
8753  if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
8754    return true;
8755
8756  // If this definition was instantiated from a template, map back to the
8757  // pattern from which it was instantiated.
8758  if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
8759    // We're in the middle of defining it; this definition should be treated
8760    // as visible.
8761    return true;
8762  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
8763    if (auto *Pattern = RD->getTemplateInstantiationPattern())
8764      RD = Pattern;
8765    D = RD->getDefinition();
8766  } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
8767    if (auto *Pattern = ED->getTemplateInstantiationPattern())
8768      ED = Pattern;
8769    if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
8770      // If the enum has a fixed underlying type, it may have been forward
8771      // declared. In -fms-compatibility, `enum Foo;` will also forward declare
8772      // the enum and assign it the underlying type of `int`. Since we're only
8773      // looking for a complete type (not a definition), any visible declaration
8774      // of it will do.
8775      *Suggested = nullptr;
8776      for (auto *Redecl : ED->redecls()) {
8777        if (isAcceptable(Redecl, Kind))
8778          return true;
8779        if (Redecl->isThisDeclarationADefinition() ||
8780            (Redecl->isCanonicalDecl() && !*Suggested))
8781          *Suggested = Redecl;
8782      }
8783
8784      return false;
8785    }
8786    D = ED->getDefinition();
8787  } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8788    if (auto *Pattern = FD->getTemplateInstantiationPattern())
8789      FD = Pattern;
8790    D = FD->getDefinition();
8791  } else if (auto *VD = dyn_cast<VarDecl>(D)) {
8792    if (auto *Pattern = VD->getTemplateInstantiationPattern())
8793      VD = Pattern;
8794    D = VD->getDefinition();
8795  }
8796
8797  assert(D && "missing definition for pattern of instantiated definition");
8798
8799  *Suggested = D;
8800
8801  auto DefinitionIsAcceptable = [&] {
8802    // The (primary) definition might be in a visible module.
8803    if (isAcceptable(D, Kind))
8804      return true;
8805
8806    // A visible module might have a merged definition instead.
8807    if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
8808                             : hasVisibleMergedDefinition(D)) {
8809      if (CodeSynthesisContexts.empty() &&
8810          !getLangOpts().ModulesLocalVisibility) {
8811        // Cache the fact that this definition is implicitly visible because
8812        // there is a visible merged definition.
8813        D->setVisibleDespiteOwningModule();
8814      }
8815      return true;
8816    }
8817
8818    return false;
8819  };
8820
8821  if (DefinitionIsAcceptable())
8822    return true;
8823
8824  // The external source may have additional definitions of this entity that are
8825  // visible, so complete the redeclaration chain now and ask again.
8826  if (auto *Source = Context.getExternalSource()) {
8827    Source->CompleteRedeclChain(D);
8828    return DefinitionIsAcceptable();
8829  }
8830
8831  return false;
8832}
8833
8834/// Determine whether there is any declaration of \p D that was ever a
8835///        definition (perhaps before module merging) and is currently visible.
8836/// \param D The definition of the entity.
8837/// \param Suggested Filled in with the declaration that should be made visible
8838///        in order to provide a definition of this entity.
8839/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8840///        not defined. This only matters for enums with a fixed underlying
8841///        type, since in all other cases, a type is complete if and only if it
8842///        is defined.
8843bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
8844                                bool OnlyNeedComplete) {
8845  return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
8846                                 OnlyNeedComplete);
8847}
8848
8849/// Determine whether there is any declaration of \p D that was ever a
8850///        definition (perhaps before module merging) and is currently
8851///        reachable.
8852/// \param D The definition of the entity.
8853/// \param Suggested Filled in with the declaration that should be made
8854/// reachable
8855///        in order to provide a definition of this entity.
8856/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8857///        not defined. This only matters for enums with a fixed underlying
8858///        type, since in all other cases, a type is complete if and only if it
8859///        is defined.
8860bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
8861                                  bool OnlyNeedComplete) {
8862  return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
8863                                 OnlyNeedComplete);
8864}
8865
8866/// Locks in the inheritance model for the given class and all of its bases.
8867static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
8868  RD = RD->getMostRecentNonInjectedDecl();
8869  if (!RD->hasAttr<MSInheritanceAttr>()) {
8870    MSInheritanceModel IM;
8871    bool BestCase = false;
8872    switch (S.MSPointerToMemberRepresentationMethod) {
8873    case LangOptions::PPTMK_BestCase:
8874      BestCase = true;
8875      IM = RD->calculateInheritanceModel();
8876      break;
8877    case LangOptions::PPTMK_FullGeneralitySingleInheritance:
8878      IM = MSInheritanceModel::Single;
8879      break;
8880    case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
8881      IM = MSInheritanceModel::Multiple;
8882      break;
8883    case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
8884      IM = MSInheritanceModel::Unspecified;
8885      break;
8886    }
8887
8888    SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
8889                          ? S.ImplicitMSInheritanceAttrLoc
8890                          : RD->getSourceRange();
8891    RD->addAttr(MSInheritanceAttr::CreateImplicit(
8892        S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
8893        MSInheritanceAttr::Spelling(IM)));
8894    S.Consumer.AssignInheritanceModel(RD);
8895  }
8896}
8897
8898/// The implementation of RequireCompleteType
8899bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
8900                                   CompleteTypeKind Kind,
8901                                   TypeDiagnoser *Diagnoser) {
8902  // FIXME: Add this assertion to make sure we always get instantiation points.
8903  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
8904  // FIXME: Add this assertion to help us flush out problems with
8905  // checking for dependent types and type-dependent expressions.
8906  //
8907  //  assert(!T->isDependentType() &&
8908  //         "Can't ask whether a dependent type is complete");
8909
8910  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
8911    if (!MPTy->getClass()->isDependentType()) {
8912      if (getLangOpts().CompleteMemberPointers &&
8913          !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
8914          RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
8915                              diag::err_memptr_incomplete))
8916        return true;
8917
8918      // We lock in the inheritance model once somebody has asked us to ensure
8919      // that a pointer-to-member type is complete.
8920      if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8921        (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
8922        assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
8923      }
8924    }
8925  }
8926
8927  NamedDecl *Def = nullptr;
8928  bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
8929  bool Incomplete = (T->isIncompleteType(&Def) ||
8930                     (!AcceptSizeless && T->isSizelessBuiltinType()));
8931
8932  // Check that any necessary explicit specializations are visible. For an
8933  // enum, we just need the declaration, so don't check this.
8934  if (Def && !isa<EnumDecl>(Def))
8935    checkSpecializationReachability(Loc, Def);
8936
8937  // If we have a complete type, we're done.
8938  if (!Incomplete) {
8939    NamedDecl *Suggested = nullptr;
8940    if (Def &&
8941        !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
8942      // If the user is going to see an error here, recover by making the
8943      // definition visible.
8944      bool TreatAsComplete = Diagnoser && !isSFINAEContext();
8945      if (Diagnoser && Suggested)
8946        diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
8947                              /*Recover*/ TreatAsComplete);
8948      return !TreatAsComplete;
8949    } else if (Def && !TemplateInstCallbacks.empty()) {
8950      CodeSynthesisContext TempInst;
8951      TempInst.Kind = CodeSynthesisContext::Memoization;
8952      TempInst.Template = Def;
8953      TempInst.Entity = Def;
8954      TempInst.PointOfInstantiation = Loc;
8955      atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
8956      atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
8957    }
8958
8959    return false;
8960  }
8961
8962  TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8963  ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8964
8965  // Give the external source a chance to provide a definition of the type.
8966  // This is kept separate from completing the redeclaration chain so that
8967  // external sources such as LLDB can avoid synthesizing a type definition
8968  // unless it's actually needed.
8969  if (Tag || IFace) {
8970    // Avoid diagnosing invalid decls as incomplete.
8971    if (Def->isInvalidDecl())
8972      return true;
8973
8974    // Give the external AST source a chance to complete the type.
8975    if (auto *Source = Context.getExternalSource()) {
8976      if (Tag && Tag->hasExternalLexicalStorage())
8977          Source->CompleteType(Tag);
8978      if (IFace && IFace->hasExternalLexicalStorage())
8979          Source->CompleteType(IFace);
8980      // If the external source completed the type, go through the motions
8981      // again to ensure we're allowed to use the completed type.
8982      if (!T->isIncompleteType())
8983        return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8984    }
8985  }
8986
8987  // If we have a class template specialization or a class member of a
8988  // class template specialization, or an array with known size of such,
8989  // try to instantiate it.
8990  if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8991    bool Instantiated = false;
8992    bool Diagnosed = false;
8993    if (RD->isDependentContext()) {
8994      // Don't try to instantiate a dependent class (eg, a member template of
8995      // an instantiated class template specialization).
8996      // FIXME: Can this ever happen?
8997    } else if (auto *ClassTemplateSpec =
8998            dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8999      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9000        runWithSufficientStackSpace(Loc, [&] {
9001          Diagnosed = InstantiateClassTemplateSpecialization(
9002              Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9003              /*Complain=*/Diagnoser);
9004        });
9005        Instantiated = true;
9006      }
9007    } else {
9008      CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9009      if (!RD->isBeingDefined() && Pattern) {
9010        MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9011        assert(MSI && "Missing member specialization information?");
9012        // This record was instantiated from a class within a template.
9013        if (MSI->getTemplateSpecializationKind() !=
9014            TSK_ExplicitSpecialization) {
9015          runWithSufficientStackSpace(Loc, [&] {
9016            Diagnosed = InstantiateClass(Loc, RD, Pattern,
9017                                         getTemplateInstantiationArgs(RD),
9018                                         TSK_ImplicitInstantiation,
9019                                         /*Complain=*/Diagnoser);
9020          });
9021          Instantiated = true;
9022        }
9023      }
9024    }
9025
9026    if (Instantiated) {
9027      // Instantiate* might have already complained that the template is not
9028      // defined, if we asked it to.
9029      if (Diagnoser && Diagnosed)
9030        return true;
9031      // If we instantiated a definition, check that it's usable, even if
9032      // instantiation produced an error, so that repeated calls to this
9033      // function give consistent answers.
9034      if (!T->isIncompleteType())
9035        return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9036    }
9037  }
9038
9039  // FIXME: If we didn't instantiate a definition because of an explicit
9040  // specialization declaration, check that it's visible.
9041
9042  if (!Diagnoser)
9043    return true;
9044
9045  Diagnoser->diagnose(*this, Loc, T);
9046
9047  // If the type was a forward declaration of a class/struct/union
9048  // type, produce a note.
9049  if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9050    Diag(Tag->getLocation(),
9051         Tag->isBeingDefined() ? diag::note_type_being_defined
9052                               : diag::note_forward_declaration)
9053      << Context.getTagDeclType(Tag);
9054
9055  // If the Objective-C class was a forward declaration, produce a note.
9056  if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9057    Diag(IFace->getLocation(), diag::note_forward_class);
9058
9059  // If we have external information that we can use to suggest a fix,
9060  // produce a note.
9061  if (ExternalSource)
9062    ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9063
9064  return true;
9065}
9066
9067bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9068                               CompleteTypeKind Kind, unsigned DiagID) {
9069  BoundTypeDiagnoser<> Diagnoser(DiagID);
9070  return RequireCompleteType(Loc, T, Kind, Diagnoser);
9071}
9072
9073/// Get diagnostic %select index for tag kind for
9074/// literal type diagnostic message.
9075/// WARNING: Indexes apply to particular diagnostics only!
9076///
9077/// \returns diagnostic %select index.
9078static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9079  switch (Tag) {
9080  case TTK_Struct: return 0;
9081  case TTK_Interface: return 1;
9082  case TTK_Class:  return 2;
9083  default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9084  }
9085}
9086
9087/// Ensure that the type T is a literal type.
9088///
9089/// This routine checks whether the type @p T is a literal type. If @p T is an
9090/// incomplete type, an attempt is made to complete it. If @p T is a literal
9091/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9092/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9093/// it the type @p T), along with notes explaining why the type is not a
9094/// literal type, and returns true.
9095///
9096/// @param Loc  The location in the source that the non-literal type
9097/// diagnostic should refer to.
9098///
9099/// @param T  The type that this routine is examining for literalness.
9100///
9101/// @param Diagnoser Emits a diagnostic if T is not a literal type.
9102///
9103/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9104/// @c false otherwise.
9105bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9106                              TypeDiagnoser &Diagnoser) {
9107  assert(!T->isDependentType() && "type should not be dependent");
9108
9109  QualType ElemType = Context.getBaseElementType(T);
9110  if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9111      T->isLiteralType(Context))
9112    return false;
9113
9114  Diagnoser.diagnose(*this, Loc, T);
9115
9116  if (T->isVariableArrayType())
9117    return true;
9118
9119  const RecordType *RT = ElemType->getAs<RecordType>();
9120  if (!RT)
9121    return true;
9122
9123  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9124
9125  // A partially-defined class type can't be a literal type, because a literal
9126  // class type must have a trivial destructor (which can't be checked until
9127  // the class definition is complete).
9128  if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9129    return true;
9130
9131  // [expr.prim.lambda]p3:
9132  //   This class type is [not] a literal type.
9133  if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9134    Diag(RD->getLocation(), diag::note_non_literal_lambda);
9135    return true;
9136  }
9137
9138  // If the class has virtual base classes, then it's not an aggregate, and
9139  // cannot have any constexpr constructors or a trivial default constructor,
9140  // so is non-literal. This is better to diagnose than the resulting absence
9141  // of constexpr constructors.
9142  if (RD->getNumVBases()) {
9143    Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9144      << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9145    for (const auto &I : RD->vbases())
9146      Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9147          << I.getSourceRange();
9148  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9149             !RD->hasTrivialDefaultConstructor()) {
9150    Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9151  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9152    for (const auto &I : RD->bases()) {
9153      if (!I.getType()->isLiteralType(Context)) {
9154        Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9155            << RD << I.getType() << I.getSourceRange();
9156        return true;
9157      }
9158    }
9159    for (const auto *I : RD->fields()) {
9160      if (!I->getType()->isLiteralType(Context) ||
9161          I->getType().isVolatileQualified()) {
9162        Diag(I->getLocation(), diag::note_non_literal_field)
9163          << RD << I << I->getType()
9164          << I->getType().isVolatileQualified();
9165        return true;
9166      }
9167    }
9168  } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9169                                       : !RD->hasTrivialDestructor()) {
9170    // All fields and bases are of literal types, so have trivial or constexpr
9171    // destructors. If this class's destructor is non-trivial / non-constexpr,
9172    // it must be user-declared.
9173    CXXDestructorDecl *Dtor = RD->getDestructor();
9174    assert(Dtor && "class has literal fields and bases but no dtor?");
9175    if (!Dtor)
9176      return true;
9177
9178    if (getLangOpts().CPlusPlus20) {
9179      Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9180          << RD;
9181    } else {
9182      Diag(Dtor->getLocation(), Dtor->isUserProvided()
9183                                    ? diag::note_non_literal_user_provided_dtor
9184                                    : diag::note_non_literal_nontrivial_dtor)
9185          << RD;
9186      if (!Dtor->isUserProvided())
9187        SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9188                               /*Diagnose*/ true);
9189    }
9190  }
9191
9192  return true;
9193}
9194
9195bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9196  BoundTypeDiagnoser<> Diagnoser(DiagID);
9197  return RequireLiteralType(Loc, T, Diagnoser);
9198}
9199
9200/// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9201/// by the nested-name-specifier contained in SS, and that is (re)declared by
9202/// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9203QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9204                                 const CXXScopeSpec &SS, QualType T,
9205                                 TagDecl *OwnedTagDecl) {
9206  if (T.isNull())
9207    return T;
9208  return Context.getElaboratedType(
9209      Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9210}
9211
9212QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9213  assert(!E->hasPlaceholderType() && "unexpected placeholder");
9214
9215  if (!getLangOpts().CPlusPlus && E->refersToBitField())
9216    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9217        << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9218
9219  if (!E->isTypeDependent()) {
9220    QualType T = E->getType();
9221    if (const TagType *TT = T->getAs<TagType>())
9222      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9223  }
9224  return Context.getTypeOfExprType(E, Kind);
9225}
9226
9227/// getDecltypeForExpr - Given an expr, will return the decltype for
9228/// that expression, according to the rules in C++11
9229/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9230QualType Sema::getDecltypeForExpr(Expr *E) {
9231  if (E->isTypeDependent())
9232    return Context.DependentTy;
9233
9234  Expr *IDExpr = E;
9235  if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9236    IDExpr = ImplCastExpr->getSubExpr();
9237
9238  // C++11 [dcl.type.simple]p4:
9239  //   The type denoted by decltype(e) is defined as follows:
9240
9241  // C++20:
9242  //     - if E is an unparenthesized id-expression naming a non-type
9243  //       template-parameter (13.2), decltype(E) is the type of the
9244  //       template-parameter after performing any necessary type deduction
9245  // Note that this does not pick up the implicit 'const' for a template
9246  // parameter object. This rule makes no difference before C++20 so we apply
9247  // it unconditionally.
9248  if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9249    return SNTTPE->getParameterType(Context);
9250
9251  //     - if e is an unparenthesized id-expression or an unparenthesized class
9252  //       member access (5.2.5), decltype(e) is the type of the entity named
9253  //       by e. If there is no such entity, or if e names a set of overloaded
9254  //       functions, the program is ill-formed;
9255  //
9256  // We apply the same rules for Objective-C ivar and property references.
9257  if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9258    const ValueDecl *VD = DRE->getDecl();
9259    QualType T = VD->getType();
9260    return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9261  }
9262  if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9263    if (const auto *VD = ME->getMemberDecl())
9264      if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9265        return VD->getType();
9266  } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9267    return IR->getDecl()->getType();
9268  } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9269    if (PR->isExplicitProperty())
9270      return PR->getExplicitProperty()->getType();
9271  } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9272    return PE->getType();
9273  }
9274
9275  // C++11 [expr.lambda.prim]p18:
9276  //   Every occurrence of decltype((x)) where x is a possibly
9277  //   parenthesized id-expression that names an entity of automatic
9278  //   storage duration is treated as if x were transformed into an
9279  //   access to a corresponding data member of the closure type that
9280  //   would have been declared if x were an odr-use of the denoted
9281  //   entity.
9282  if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9283    if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9284      if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9285        QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9286        if (!T.isNull())
9287          return Context.getLValueReferenceType(T);
9288      }
9289    }
9290  }
9291
9292  return Context.getReferenceQualifiedType(E);
9293}
9294
9295QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9296  assert(!E->hasPlaceholderType() && "unexpected placeholder");
9297
9298  if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9299      !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9300    // The expression operand for decltype is in an unevaluated expression
9301    // context, so side effects could result in unintended consequences.
9302    // Exclude instantiation-dependent expressions, because 'decltype' is often
9303    // used to build SFINAE gadgets.
9304    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9305  }
9306  return Context.getDecltypeType(E, getDecltypeForExpr(E));
9307}
9308
9309static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9310                                      SourceLocation Loc) {
9311  assert(BaseType->isEnumeralType());
9312  EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9313  assert(ED && "EnumType has no EnumDecl");
9314
9315  S.DiagnoseUseOfDecl(ED, Loc);
9316
9317  QualType Underlying = ED->getIntegerType();
9318  assert(!Underlying.isNull());
9319
9320  return Underlying;
9321}
9322
9323QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9324                                         SourceLocation Loc) {
9325  if (!BaseType->isEnumeralType()) {
9326    Diag(Loc, diag::err_only_enums_have_underlying_types);
9327    return QualType();
9328  }
9329
9330  // The enum could be incomplete if we're parsing its definition or
9331  // recovering from an error.
9332  NamedDecl *FwdDecl = nullptr;
9333  if (BaseType->isIncompleteType(&FwdDecl)) {
9334    Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9335    Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9336    return QualType();
9337  }
9338
9339  return GetEnumUnderlyingType(*this, BaseType, Loc);
9340}
9341
9342QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9343  QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9344                         ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9345                                            DeclarationName())
9346                         : BaseType;
9347
9348  return Pointer.isNull() ? QualType() : Pointer;
9349}
9350
9351QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9352  // We don't want block pointers or ObjectiveC's id type.
9353  if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9354    return BaseType;
9355
9356  return BaseType->getPointeeType();
9357}
9358
9359QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9360  QualType Underlying = BaseType.getNonReferenceType();
9361  if (Underlying->isArrayType())
9362    return Context.getDecayedType(Underlying);
9363
9364  if (Underlying->isFunctionType())
9365    return BuiltinAddPointer(BaseType, Loc);
9366
9367  SplitQualType Split = Underlying.getSplitUnqualifiedType();
9368  // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9369  // in the same group of qualifiers as 'const' and 'volatile', we're extending
9370  // '__decay(T)' so that it removes all qualifiers.
9371  Split.Quals.removeCVRQualifiers();
9372  return Context.getQualifiedType(Split);
9373}
9374
9375QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9376                                   SourceLocation Loc) {
9377  assert(LangOpts.CPlusPlus);
9378  QualType Reference =
9379      BaseType.isReferenceable()
9380          ? BuildReferenceType(BaseType,
9381                               UKind == UnaryTransformType::AddLvalueReference,
9382                               Loc, DeclarationName())
9383          : BaseType;
9384  return Reference.isNull() ? QualType() : Reference;
9385}
9386
9387QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9388                                   SourceLocation Loc) {
9389  if (UKind == UnaryTransformType::RemoveAllExtents)
9390    return Context.getBaseElementType(BaseType);
9391
9392  if (const auto *AT = Context.getAsArrayType(BaseType))
9393    return AT->getElementType();
9394
9395  return BaseType;
9396}
9397
9398QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9399                                      SourceLocation Loc) {
9400  assert(LangOpts.CPlusPlus);
9401  QualType T = BaseType.getNonReferenceType();
9402  if (UKind == UTTKind::RemoveCVRef &&
9403      (T.isConstQualified() || T.isVolatileQualified())) {
9404    Qualifiers Quals;
9405    QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9406    Quals.removeConst();
9407    Quals.removeVolatile();
9408    T = Context.getQualifiedType(Unqual, Quals);
9409  }
9410  return T;
9411}
9412
9413QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9414                                          SourceLocation Loc) {
9415  if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9416      BaseType->isFunctionType())
9417    return BaseType;
9418
9419  Qualifiers Quals;
9420  QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9421
9422  if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9423    Quals.removeConst();
9424  if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9425    Quals.removeVolatile();
9426  if (UKind == UTTKind::RemoveRestrict)
9427    Quals.removeRestrict();
9428
9429  return Context.getQualifiedType(Unqual, Quals);
9430}
9431
9432static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9433                                         bool IsMakeSigned,
9434                                         SourceLocation Loc) {
9435  if (BaseType->isEnumeralType()) {
9436    QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9437    if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9438      unsigned int Bits = BitInt->getNumBits();
9439      if (Bits > 1)
9440        return S.Context.getBitIntType(!IsMakeSigned, Bits);
9441
9442      S.Diag(Loc, diag::err_make_signed_integral_only)
9443          << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9444      return QualType();
9445    }
9446    if (Underlying->isBooleanType()) {
9447      S.Diag(Loc, diag::err_make_signed_integral_only)
9448          << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9449          << Underlying;
9450      return QualType();
9451    }
9452  }
9453
9454  bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9455  std::array<CanQualType *, 6> AllSignedIntegers = {
9456      &S.Context.SignedCharTy, &S.Context.ShortTy,    &S.Context.IntTy,
9457      &S.Context.LongTy,       &S.Context.LongLongTy, &S.Context.Int128Ty};
9458  ArrayRef<CanQualType *> AvailableSignedIntegers(
9459      AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9460  std::array<CanQualType *, 6> AllUnsignedIntegers = {
9461      &S.Context.UnsignedCharTy,     &S.Context.UnsignedShortTy,
9462      &S.Context.UnsignedIntTy,      &S.Context.UnsignedLongTy,
9463      &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9464  ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9465                                                    AllUnsignedIntegers.size() -
9466                                                        Int128Unsupported);
9467  ArrayRef<CanQualType *> *Consider =
9468      IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9469
9470  uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9471  auto *Result =
9472      llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9473        return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9474      });
9475
9476  assert(Result != Consider->end());
9477  return QualType((*Result)->getTypePtr(), 0);
9478}
9479
9480QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9481                                       SourceLocation Loc) {
9482  bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9483  if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9484      BaseType->isBooleanType() ||
9485      (BaseType->isBitIntType() &&
9486       BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9487    Diag(Loc, diag::err_make_signed_integral_only)
9488        << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9489    return QualType();
9490  }
9491
9492  bool IsNonIntIntegral =
9493      BaseType->isChar16Type() || BaseType->isChar32Type() ||
9494      BaseType->isWideCharType() || BaseType->isEnumeralType();
9495
9496  QualType Underlying =
9497      IsNonIntIntegral
9498          ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9499      : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9500                     : Context.getCorrespondingUnsignedType(BaseType);
9501  if (Underlying.isNull())
9502    return Underlying;
9503  return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9504}
9505
9506QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9507                                       SourceLocation Loc) {
9508  if (BaseType->isDependentType())
9509    return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9510  QualType Result;
9511  switch (UKind) {
9512  case UnaryTransformType::EnumUnderlyingType: {
9513    Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9514    break;
9515  }
9516  case UnaryTransformType::AddPointer: {
9517    Result = BuiltinAddPointer(BaseType, Loc);
9518    break;
9519  }
9520  case UnaryTransformType::RemovePointer: {
9521    Result = BuiltinRemovePointer(BaseType, Loc);
9522    break;
9523  }
9524  case UnaryTransformType::Decay: {
9525    Result = BuiltinDecay(BaseType, Loc);
9526    break;
9527  }
9528  case UnaryTransformType::AddLvalueReference:
9529  case UnaryTransformType::AddRvalueReference: {
9530    Result = BuiltinAddReference(BaseType, UKind, Loc);
9531    break;
9532  }
9533  case UnaryTransformType::RemoveAllExtents:
9534  case UnaryTransformType::RemoveExtent: {
9535    Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9536    break;
9537  }
9538  case UnaryTransformType::RemoveCVRef:
9539  case UnaryTransformType::RemoveReference: {
9540    Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9541    break;
9542  }
9543  case UnaryTransformType::RemoveConst:
9544  case UnaryTransformType::RemoveCV:
9545  case UnaryTransformType::RemoveRestrict:
9546  case UnaryTransformType::RemoveVolatile: {
9547    Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9548    break;
9549  }
9550  case UnaryTransformType::MakeSigned:
9551  case UnaryTransformType::MakeUnsigned: {
9552    Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9553    break;
9554  }
9555  }
9556
9557  return !Result.isNull()
9558             ? Context.getUnaryTransformType(BaseType, Result, UKind)
9559             : Result;
9560}
9561
9562QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9563  if (!isDependentOrGNUAutoType(T)) {
9564    // FIXME: It isn't entirely clear whether incomplete atomic types
9565    // are allowed or not; for simplicity, ban them for the moment.
9566    if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9567      return QualType();
9568
9569    int DisallowedKind = -1;
9570    if (T->isArrayType())
9571      DisallowedKind = 1;
9572    else if (T->isFunctionType())
9573      DisallowedKind = 2;
9574    else if (T->isReferenceType())
9575      DisallowedKind = 3;
9576    else if (T->isAtomicType())
9577      DisallowedKind = 4;
9578    else if (T.hasQualifiers())
9579      DisallowedKind = 5;
9580    else if (T->isSizelessType())
9581      DisallowedKind = 6;
9582    else if (!T.isTriviallyCopyableType(Context))
9583      // Some other non-trivially-copyable type (probably a C++ class)
9584      DisallowedKind = 7;
9585    else if (T->isBitIntType())
9586      DisallowedKind = 8;
9587
9588    if (DisallowedKind != -1) {
9589      Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9590      return QualType();
9591    }
9592
9593    // FIXME: Do we need any handling for ARC here?
9594  }
9595
9596  // Build the pointer type.
9597  return Context.getAtomicType(T);
9598}
9599