Coverage Report

Created: 2022-05-14 11:35

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaType.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements type-related semantic analysis.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/ASTStructuralEquivalence.h"
18
#include "clang/AST/CXXInheritance.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DeclTemplate.h"
21
#include "clang/AST/Expr.h"
22
#include "clang/AST/TypeLoc.h"
23
#include "clang/AST/TypeLocVisitor.h"
24
#include "clang/Basic/PartialDiagnostic.h"
25
#include "clang/Basic/Specifiers.h"
26
#include "clang/Basic/TargetInfo.h"
27
#include "clang/Lex/Preprocessor.h"
28
#include "clang/Sema/DeclSpec.h"
29
#include "clang/Sema/DelayedDiagnostic.h"
30
#include "clang/Sema/Lookup.h"
31
#include "clang/Sema/ParsedTemplate.h"
32
#include "clang/Sema/ScopeInfo.h"
33
#include "clang/Sema/SemaInternal.h"
34
#include "clang/Sema/Template.h"
35
#include "clang/Sema/TemplateInstCallback.h"
36
#include "llvm/ADT/SmallPtrSet.h"
37
#include "llvm/ADT/SmallString.h"
38
#include "llvm/ADT/StringSwitch.h"
39
#include "llvm/IR/DerivedTypes.h"
40
#include "llvm/Support/ErrorHandling.h"
41
#include <bitset>
42
43
using namespace clang;
44
45
enum TypeDiagSelector {
46
  TDS_Function,
47
  TDS_Pointer,
48
  TDS_ObjCObjOrBlock
49
};
50
51
/// isOmittedBlockReturnType - Return true if this declarator is missing a
52
/// return type because this is a omitted return type on a block literal.
53
3.33k
static bool isOmittedBlockReturnType(const Declarator &D) {
54
3.33k
  if (D.getContext() != DeclaratorContext::BlockLiteral ||
55
3.33k
      
D.getDeclSpec().hasTypeSpecifier()3.00k
)
56
335
    return false;
57
58
3.00k
  if (D.getNumTypeObjects() == 0)
59
5
    return true;   // ^{ ... }
60
61
2.99k
  if (D.getNumTypeObjects() == 1 &&
62
2.99k
      
D.getTypeObject(0).Kind == DeclaratorChunk::Function2.99k
)
63
2.99k
    return true;   // ^(int X, float Y) { ... }
64
65
1
  return false;
66
2.99k
}
67
68
/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
69
/// doesn't apply to the given type.
70
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
71
33
                                     QualType type) {
72
33
  TypeDiagSelector WhichType;
73
33
  bool useExpansionLoc = true;
74
33
  switch (attr.getKind()) {
75
1
  case ParsedAttr::AT_ObjCGC:
76
1
    WhichType = TDS_Pointer;
77
1
    break;
78
6
  case ParsedAttr::AT_ObjCOwnership:
79
6
    WhichType = TDS_ObjCObjOrBlock;
80
6
    break;
81
26
  default:
82
    // Assume everything else was a function attribute.
83
26
    WhichType = TDS_Function;
84
26
    useExpansionLoc = false;
85
26
    break;
86
33
  }
87
88
33
  SourceLocation loc = attr.getLoc();
89
33
  StringRef name = attr.getAttrName()->getName();
90
91
  // The GC attributes are usually written with macros;  special-case them.
92
33
  IdentifierInfo *II = attr.isArgIdent(0) ? 
attr.getArgAsIdent(0)->Ident7
93
33
                                          : 
nullptr26
;
94
33
  if (useExpansionLoc && 
loc.isMacroID()7
&&
II5
) {
95
5
    if (II->isStr("strong")) {
96
2
      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
97
3
    } else if (II->isStr("weak")) {
98
3
      if (S.findMacroSpelling(loc, "__weak")) 
name = "__weak"2
;
99
3
    }
100
5
  }
101
102
33
  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
103
33
    << type;
104
33
}
105
106
// objc_gc applies to Objective-C pointers or, otherwise, to the
107
// smallest available pointer type (i.e. 'void*' in 'void**').
108
#define OBJC_POINTER_TYPE_ATTRS_CASELIST                                       \
109
289
  case ParsedAttr::AT_ObjCGC:                                                  \
110
8.22k
  case ParsedAttr::AT_ObjCOwnership
111
112
// Calling convention attributes.
113
#define CALLING_CONV_ATTRS_CASELIST                                            \
114
106k
  case ParsedAttr::AT_CDecl:                                                   \
115
107k
  case ParsedAttr::AT_FastCall:                                                \
116
107k
  case ParsedAttr::AT_StdCall:                                                 \
117
108k
  case ParsedAttr::AT_ThisCall:                                                \
118
108k
  case ParsedAttr::AT_RegCall:                                                 \
119
108k
  case ParsedAttr::AT_Pascal:                                                  \
120
112k
  case ParsedAttr::AT_SwiftCall:                                               \
121
112k
  case ParsedAttr::AT_SwiftAsyncCall:                                          \
122
113k
  case ParsedAttr::AT_VectorCall:                                              \
123
113k
  case ParsedAttr::AT_AArch64VectorPcs:                                        \
124
113k
  case ParsedAttr::AT_AArch64SVEPcs:                                           \
125
113k
  case ParsedAttr::AT_MSABI:                                                   \
126
113k
  case ParsedAttr::AT_SysVABI:                                                 \
127
113k
  case ParsedAttr::AT_Pcs:                                                     \
128
113k
  case ParsedAttr::AT_IntelOclBicc:                                            \
129
113k
  case ParsedAttr::AT_PreserveMost:                                            \
130
113k
  case ParsedAttr::AT_PreserveAll
131
132
// Function type attributes.
133
#define FUNCTION_TYPE_ATTRS_CASELIST                                           \
134
91.6k
  case ParsedAttr::AT_NSReturnsRetained:                                       \
135
105k
  case ParsedAttr::AT_NoReturn:                                                \
136
105k
  case ParsedAttr::AT_Regparm:                                                 \
137
105k
  case ParsedAttr::AT_CmseNSCall:                                              \
138
105k
  case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:                            \
139
105k
  case ParsedAttr::AT_AnyX86NoCfCheck:                                         \
140
106k
    CALLING_CONV_ATTRS_CASELIST
141
142
// Microsoft-specific type qualifiers.
143
#define MS_TYPE_ATTRS_CASELIST                                                 \
144
52
  case ParsedAttr::AT_Ptr32:                                                   \
145
82
  case ParsedAttr::AT_Ptr64:                                                   \
146
106
  case ParsedAttr::AT_SPtr:                                                    \
147
124
  case ParsedAttr::AT_UPtr
148
149
// Nullability qualifiers.
150
#define NULLABILITY_TYPE_ATTRS_CASELIST                                        \
151
1.04M
  case ParsedAttr::AT_TypeNonNull:                                             \
152
1.99M
  case ParsedAttr::AT_TypeNullable:                                            \
153
1.99M
  case ParsedAttr::AT_TypeNullableResult:                                      \
154
2.04M
  case ParsedAttr::AT_TypeNullUnspecified
155
156
namespace {
157
  /// An object which stores processing state for the entire
158
  /// GetTypeForDeclarator process.
159
  class TypeProcessingState {
160
    Sema &sema;
161
162
    /// The declarator being processed.
163
    Declarator &declarator;
164
165
    /// The index of the declarator chunk we're currently processing.
166
    /// May be the total number of valid chunks, indicating the
167
    /// DeclSpec.
168
    unsigned chunkIndex;
169
170
    /// The original set of attributes on the DeclSpec.
171
    SmallVector<ParsedAttr *, 2> savedAttrs;
172
173
    /// A list of attributes to diagnose the uselessness of when the
174
    /// processing is complete.
175
    SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
176
177
    /// Attributes corresponding to AttributedTypeLocs that we have not yet
178
    /// populated.
179
    // FIXME: The two-phase mechanism by which we construct Types and fill
180
    // their TypeLocs makes it hard to correctly assign these. We keep the
181
    // attributes in creation order as an attempt to make them line up
182
    // properly.
183
    using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
184
    SmallVector<TypeAttrPair, 8> AttrsForTypes;
185
    bool AttrsForTypesSorted = true;
186
187
    /// MacroQualifiedTypes mapping to macro expansion locations that will be
188
    /// stored in a MacroQualifiedTypeLoc.
189
    llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
190
191
    /// Flag to indicate we parsed a noderef attribute. This is used for
192
    /// validating that noderef was used on a pointer or array.
193
    bool parsedNoDeref;
194
195
  public:
196
    TypeProcessingState(Sema &sema, Declarator &declarator)
197
        : sema(sema), declarator(declarator),
198
107M
          chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
199
200
459M
    Sema &getSema() const {
201
459M
      return sema;
202
459M
    }
203
204
695M
    Declarator &getDeclarator() const {
205
695M
      return declarator;
206
695M
    }
207
208
108M
    bool isProcessingDeclSpec() const {
209
108M
      return chunkIndex == declarator.getNumTypeObjects();
210
108M
    }
211
212
1.55M
    unsigned getCurrentChunkIndex() const {
213
1.55M
      return chunkIndex;
214
1.55M
    }
215
216
34.2M
    void setCurrentChunkIndex(unsigned idx) {
217
34.2M
      assert(idx <= declarator.getNumTypeObjects());
218
0
      chunkIndex = idx;
219
34.2M
    }
220
221
108M
    ParsedAttributesView &getCurrentAttributes() const {
222
108M
      if (isProcessingDeclSpec())
223
108M
        return getMutableDeclSpec().getAttributes();
224
30
      return declarator.getTypeObject(chunkIndex).getAttrs();
225
108M
    }
226
227
    /// Save the current set of attributes on the DeclSpec.
228
41.3k
    void saveDeclSpecAttrs() {
229
      // Don't try to save them multiple times.
230
41.3k
      if (!savedAttrs.empty())
231
670
        return;
232
233
40.7k
      DeclSpec &spec = getMutableDeclSpec();
234
40.7k
      llvm::append_range(savedAttrs,
235
40.7k
                         llvm::make_pointer_range(spec.getAttributes()));
236
40.7k
    }
237
238
    /// Record that we had nowhere to put the given type attribute.
239
    /// We will diagnose such attributes later.
240
26
    void addIgnoredTypeAttr(ParsedAttr &attr) {
241
26
      ignoredTypeAttrs.push_back(&attr);
242
26
    }
243
244
    /// Diagnose all the ignored type attributes, given that the
245
    /// declarator worked out to the given type.
246
107M
    void diagnoseIgnoredTypeAttrs(QualType type) const {
247
107M
      for (auto *Attr : ignoredTypeAttrs)
248
26
        diagnoseBadTypeAttribute(getSema(), *Attr, type);
249
107M
    }
250
251
    /// Get an attributed type for the given attribute, and remember the Attr
252
    /// object so that we can attach it to the AttributedTypeLoc.
253
    QualType getAttributedType(Attr *A, QualType ModifiedType,
254
3.27M
                               QualType EquivType) {
255
3.27M
      QualType T =
256
3.27M
          sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
257
3.27M
      AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
258
3.27M
      AttrsForTypesSorted = false;
259
3.27M
      return T;
260
3.27M
    }
261
262
    /// Get a BTFTagAttributed type for the btf_type_tag attribute.
263
    QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
264
52
                                     QualType WrappedType) {
265
52
      return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
266
52
    }
267
268
    /// Completely replace the \c auto in \p TypeWithAuto by
269
    /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
270
    /// necessary.
271
2.31k
    QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
272
2.31k
      QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
273
2.31k
      if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
274
        // Attributed type still should be an attributed type after replacement.
275
1
        auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
276
1
        for (TypeAttrPair &A : AttrsForTypes) {
277
1
          if (A.first == AttrTy)
278
1
            A.first = NewAttrTy;
279
1
        }
280
1
        AttrsForTypesSorted = false;
281
1
      }
282
2.31k
      return T;
283
2.31k
    }
284
285
    /// Extract and remove the Attr* for a given attributed type.
286
3.27M
    const Attr *takeAttrForAttributedType(const AttributedType *AT) {
287
3.27M
      if (!AttrsForTypesSorted) {
288
3.13M
        llvm::stable_sort(AttrsForTypes, llvm::less_first());
289
3.13M
        AttrsForTypesSorted = true;
290
3.13M
      }
291
292
      // FIXME: This is quadratic if we have lots of reuses of the same
293
      // attributed type.
294
3.27M
      for (auto It = std::partition_point(
295
3.27M
               AttrsForTypes.begin(), AttrsForTypes.end(),
296
3.55M
               [=](const TypeAttrPair &A) { return A.first < AT; });
297
3.27M
           It != AttrsForTypes.end() && It->first == AT; 
++It0
) {
298
3.27M
        if (It->second) {
299
3.27M
          const Attr *Result = It->second;
300
3.27M
          It->second = nullptr;
301
3.27M
          return Result;
302
3.27M
        }
303
3.27M
      }
304
305
0
      llvm_unreachable("no Attr* for AttributedType*");
306
0
    }
307
308
    SourceLocation
309
243k
    getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
310
243k
      auto FoundLoc = LocsForMacros.find(MQT);
311
243k
      assert(FoundLoc != LocsForMacros.end() &&
312
243k
             "Unable to find macro expansion location for MacroQualifedType");
313
0
      return FoundLoc->second;
314
243k
    }
315
316
    void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
317
244k
                                              SourceLocation Loc) {
318
244k
      LocsForMacros[MQT] = Loc;
319
244k
    }
320
321
250M
    void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
322
323
33.8M
    bool didParseNoDeref() const { return parsedNoDeref; }
324
325
107M
    ~TypeProcessingState() {
326
107M
      if (savedAttrs.empty())
327
107M
        return;
328
329
40.6k
      getMutableDeclSpec().getAttributes().clearListOnly();
330
40.6k
      for (ParsedAttr *AL : savedAttrs)
331
158k
        getMutableDeclSpec().getAttributes().addAtEnd(AL);
332
40.6k
    }
333
334
  private:
335
108M
    DeclSpec &getMutableDeclSpec() const {
336
108M
      return const_cast<DeclSpec&>(declarator.getDeclSpec());
337
108M
    }
338
  };
339
} // end anonymous namespace
340
341
static void moveAttrFromListToList(ParsedAttr &attr,
342
                                   ParsedAttributesView &fromList,
343
49.7k
                                   ParsedAttributesView &toList) {
344
49.7k
  fromList.remove(&attr);
345
49.7k
  toList.addAtEnd(&attr);
346
49.7k
}
347
348
/// The location of a type attribute.
349
enum TypeAttrLocation {
350
  /// The attribute is in the decl-specifier-seq.
351
  TAL_DeclSpec,
352
  /// The attribute is part of a DeclaratorChunk.
353
  TAL_DeclChunk,
354
  /// The attribute is immediately after the declaration's name.
355
  TAL_DeclName
356
};
357
358
static void processTypeAttrs(TypeProcessingState &state, QualType &type,
359
                             TypeAttrLocation TAL,
360
                             const ParsedAttributesView &attrs);
361
362
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
363
                                   QualType &type);
364
365
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
366
                                             ParsedAttr &attr, QualType &type);
367
368
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
369
                                 QualType &type);
370
371
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
372
                                        ParsedAttr &attr, QualType &type);
373
374
static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
375
8.22k
                                      ParsedAttr &attr, QualType &type) {
376
8.22k
  if (attr.getKind() == ParsedAttr::AT_ObjCGC)
377
289
    return handleObjCGCTypeAttr(state, attr, type);
378
7.93k
  assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
379
0
  return handleObjCOwnershipTypeAttr(state, attr, type);
380
8.22k
}
381
382
/// Given the index of a declarator chunk, check whether that chunk
383
/// directly specifies the return type of a function and, if so, find
384
/// an appropriate place for it.
385
///
386
/// \param i - a notional index which the search will start
387
///   immediately inside
388
///
389
/// \param onlyBlockPointers Whether we should only look into block
390
/// pointer types (vs. all pointer types).
391
static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
392
                                                unsigned i,
393
5.41k
                                                bool onlyBlockPointers) {
394
5.41k
  assert(i <= declarator.getNumTypeObjects());
395
396
0
  DeclaratorChunk *result = nullptr;
397
398
  // First, look inwards past parens for a function declarator.
399
5.45k
  for (; i != 0; 
--i37
) {
400
3.80k
    DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
401
3.80k
    switch (fnChunk.Kind) {
402
9
    case DeclaratorChunk::Paren:
403
9
      continue;
404
405
    // If we find anything except a function, bail out.
406
1.55k
    case DeclaratorChunk::Pointer:
407
1.55k
    case DeclaratorChunk::BlockPointer:
408
3.58k
    case DeclaratorChunk::Array:
409
3.75k
    case DeclaratorChunk::Reference:
410
3.75k
    case DeclaratorChunk::MemberPointer:
411
3.75k
    case DeclaratorChunk::Pipe:
412
3.75k
      return result;
413
414
    // If we do find a function declarator, scan inwards from that,
415
    // looking for a (block-)pointer declarator.
416
42
    case DeclaratorChunk::Function:
417
78
      for (--i; i != 0; 
--i36
) {
418
64
        DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
419
64
        switch (ptrChunk.Kind) {
420
32
        case DeclaratorChunk::Paren:
421
32
        case DeclaratorChunk::Array:
422
32
        case DeclaratorChunk::Function:
423
32
        case DeclaratorChunk::Reference:
424
32
        case DeclaratorChunk::Pipe:
425
32
          continue;
426
427
2
        case DeclaratorChunk::MemberPointer:
428
10
        case DeclaratorChunk::Pointer:
429
10
          if (onlyBlockPointers)
430
4
            continue;
431
432
10
          
LLVM_FALLTHROUGH6
;6
433
434
28
        case DeclaratorChunk::BlockPointer:
435
28
          result = &ptrChunk;
436
28
          goto continue_outer;
437
64
        }
438
0
        llvm_unreachable("bad declarator chunk kind");
439
0
      }
440
441
      // If we run out of declarators doing that, we're done.
442
14
      return result;
443
3.80k
    }
444
0
    llvm_unreachable("bad declarator chunk kind");
445
446
    // Okay, reconsider from our new point.
447
28
  continue_outer: ;
448
28
  }
449
450
  // Ran out of chunks, bail out.
451
1.64k
  return result;
452
5.41k
}
453
454
/// Given that an objc_gc attribute was written somewhere on a
455
/// declaration *other* than on the declarator itself (for which, use
456
/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
457
/// didn't apply in whatever position it was written in, try to move
458
/// it to a more appropriate position.
459
static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
460
1.62k
                                          ParsedAttr &attr, QualType type) {
461
1.62k
  Declarator &declarator = state.getDeclarator();
462
463
  // Move it to the outermost normal or block pointer declarator.
464
1.62k
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i0
) {
465
1.62k
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
466
1.62k
    switch (chunk.Kind) {
467
1.61k
    case DeclaratorChunk::Pointer:
468
1.61k
    case DeclaratorChunk::BlockPointer: {
469
      // But don't move an ARC ownership attribute to the return type
470
      // of a block.
471
1.61k
      DeclaratorChunk *destChunk = nullptr;
472
1.61k
      if (state.isProcessingDeclSpec() &&
473
1.61k
          attr.getKind() == ParsedAttr::AT_ObjCOwnership)
474
1.53k
        destChunk = maybeMovePastReturnType(declarator, i - 1,
475
1.53k
                                            /*onlyBlockPointers=*/true);
476
1.61k
      if (!destChunk) 
destChunk = &chunk1.60k
;
477
478
1.61k
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
479
1.61k
                             destChunk->getAttrs());
480
1.61k
      return;
481
1.61k
    }
482
483
0
    case DeclaratorChunk::Paren:
484
0
    case DeclaratorChunk::Array:
485
0
      continue;
486
487
    // We may be starting at the return type of a block.
488
8
    case DeclaratorChunk::Function:
489
8
      if (state.isProcessingDeclSpec() &&
490
8
          attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
491
8
        if (DeclaratorChunk *dest = maybeMovePastReturnType(
492
8
                                      declarator, i,
493
8
                                      /*onlyBlockPointers=*/true)) {
494
8
          moveAttrFromListToList(attr, state.getCurrentAttributes(),
495
8
                                 dest->getAttrs());
496
8
          return;
497
8
        }
498
8
      }
499
0
      goto error;
500
501
    // Don't walk through these.
502
0
    case DeclaratorChunk::Reference:
503
0
    case DeclaratorChunk::MemberPointer:
504
0
    case DeclaratorChunk::Pipe:
505
0
      goto error;
506
1.62k
    }
507
1.62k
  }
508
6
 error:
509
510
6
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
511
6
}
512
513
/// Distribute an objc_gc type attribute that was written on the
514
/// declarator.
515
static void distributeObjCPointerTypeAttrFromDeclarator(
516
18
    TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
517
18
  Declarator &declarator = state.getDeclarator();
518
519
  // objc_gc goes on the innermost pointer to something that's not a
520
  // pointer.
521
18
  unsigned innermost = -1U;
522
18
  bool considerDeclSpec = true;
523
28
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i10
) {
524
15
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
525
15
    switch (chunk.Kind) {
526
0
    case DeclaratorChunk::Pointer:
527
4
    case DeclaratorChunk::BlockPointer:
528
4
      innermost = i;
529
4
      continue;
530
531
0
    case DeclaratorChunk::Reference:
532
0
    case DeclaratorChunk::MemberPointer:
533
4
    case DeclaratorChunk::Paren:
534
6
    case DeclaratorChunk::Array:
535
6
    case DeclaratorChunk::Pipe:
536
6
      continue;
537
538
5
    case DeclaratorChunk::Function:
539
5
      considerDeclSpec = false;
540
5
      goto done;
541
15
    }
542
15
  }
543
18
 done:
544
545
  // That might actually be the decl spec if we weren't blocked by
546
  // anything in the declarator.
547
18
  if (considerDeclSpec) {
548
13
    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
549
      // Splice the attribute into the decl spec.  Prevents the
550
      // attribute from being applied multiple times and gives
551
      // the source-location-filler something to work with.
552
13
      state.saveDeclSpecAttrs();
553
13
      declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
554
13
          declarator.getAttributes(), &attr);
555
13
      return;
556
13
    }
557
13
  }
558
559
  // Otherwise, if we found an appropriate chunk, splice the attribute
560
  // into it.
561
5
  if (innermost != -1U) {
562
4
    moveAttrFromListToList(attr, declarator.getAttributes(),
563
4
                           declarator.getTypeObject(innermost).getAttrs());
564
4
    return;
565
4
  }
566
567
  // Otherwise, diagnose when we're done building the type.
568
1
  declarator.getAttributes().remove(&attr);
569
1
  state.addIgnoredTypeAttr(attr);
570
1
}
571
572
/// A function type attribute was written somewhere in a declaration
573
/// *other* than on the declarator itself or in the decl spec.  Given
574
/// that it didn't apply in whatever position it was written in, try
575
/// to move it to a more appropriate position.
576
static void distributeFunctionTypeAttr(TypeProcessingState &state,
577
31
                                       ParsedAttr &attr, QualType type) {
578
31
  Declarator &declarator = state.getDeclarator();
579
580
  // Try to push the attribute from the return type of a function to
581
  // the function itself.
582
33
  for (unsigned i = state.getCurrentChunkIndex(); i != 0; 
--i2
) {
583
32
    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
584
32
    switch (chunk.Kind) {
585
30
    case DeclaratorChunk::Function:
586
30
      moveAttrFromListToList(attr, state.getCurrentAttributes(),
587
30
                             chunk.getAttrs());
588
30
      return;
589
590
2
    case DeclaratorChunk::Paren:
591
2
    case DeclaratorChunk::Pointer:
592
2
    case DeclaratorChunk::BlockPointer:
593
2
    case DeclaratorChunk::Array:
594
2
    case DeclaratorChunk::Reference:
595
2
    case DeclaratorChunk::MemberPointer:
596
2
    case DeclaratorChunk::Pipe:
597
2
      continue;
598
32
    }
599
32
  }
600
601
1
  diagnoseBadTypeAttribute(state.getSema(), attr, type);
602
1
}
603
604
/// Try to distribute a function type attribute to the innermost
605
/// function chunk or type.  Returns true if the attribute was
606
/// distributed, false if no location was found.
607
static bool distributeFunctionTypeAttrToInnermost(
608
    TypeProcessingState &state, ParsedAttr &attr,
609
48.0k
    ParsedAttributesView &attrList, QualType &declSpecType) {
610
48.0k
  Declarator &declarator = state.getDeclarator();
611
612
  // Put it on the innermost function chunk, if there is one.
613
48.3k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i306
) {
614
48.2k
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
615
48.2k
    if (chunk.Kind != DeclaratorChunk::Function) 
continue306
;
616
617
47.9k
    moveAttrFromListToList(attr, attrList, chunk.getAttrs());
618
47.9k
    return true;
619
48.2k
  }
620
621
59
  return handleFunctionTypeAttr(state, attr, declSpecType);
622
48.0k
}
623
624
/// A function type attribute was written in the decl spec.  Try to
625
/// apply it somewhere.
626
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
627
                                                   ParsedAttr &attr,
628
41.3k
                                                   QualType &declSpecType) {
629
41.3k
  state.saveDeclSpecAttrs();
630
631
  // C++11 attributes before the decl specifiers actually appertain to
632
  // the declarators. Move them straight there. We don't support the
633
  // 'put them wherever you like' semantics we allow for GNU attributes.
634
41.3k
  if (attr.isStandardAttributeSyntax()) {
635
17
    moveAttrFromListToList(attr, state.getCurrentAttributes(),
636
17
                           state.getDeclarator().getAttributes());
637
17
    return;
638
17
  }
639
640
  // Try to distribute to the innermost.
641
41.3k
  if (distributeFunctionTypeAttrToInnermost(
642
41.3k
          state, attr, state.getCurrentAttributes(), declSpecType))
643
41.3k
    return;
644
645
  // If that failed, diagnose the bad attribute when the declarator is
646
  // fully built.
647
10
  state.addIgnoredTypeAttr(attr);
648
10
}
649
650
/// A function type attribute was written on the declarator.  Try to
651
/// apply it somewhere.
652
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
653
                                                     ParsedAttr &attr,
654
6.69k
                                                     QualType &declSpecType) {
655
6.69k
  Declarator &declarator = state.getDeclarator();
656
657
  // Try to distribute to the innermost.
658
6.69k
  if (distributeFunctionTypeAttrToInnermost(
659
6.69k
          state, attr, declarator.getAttributes(), declSpecType))
660
6.68k
    return;
661
662
  // If that failed, diagnose the bad attribute when the declarator is
663
  // fully built.
664
15
  declarator.getAttributes().remove(&attr);
665
15
  state.addIgnoredTypeAttr(attr);
666
15
}
667
668
/// Given that there are attributes written on the declarator
669
/// itself, try to distribute any type attributes to the appropriate
670
/// declarator chunk.
671
///
672
/// These are attributes like the following:
673
///   int f ATTR;
674
///   int (f ATTR)();
675
/// but not necessarily this:
676
///   int f() ATTR;
677
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
678
2.08M
                                              QualType &declSpecType) {
679
  // Collect all the type attributes from the declarator itself.
680
2.08M
  assert(!state.getDeclarator().getAttributes().empty() &&
681
2.08M
         "declarator has no attrs!");
682
  // The called functions in this loop actually remove things from the current
683
  // list, so iterating over the existing list isn't possible.  Instead, make a
684
  // non-owning copy and iterate over that.
685
0
  ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
686
4.58M
  for (ParsedAttr &attr : AttrsCopy) {
687
    // Do not distribute [[]] attributes. They have strict rules for what
688
    // they appertain to.
689
4.58M
    if (attr.isStandardAttributeSyntax())
690
268
      continue;
691
692
4.58M
    switch (attr.getKind()) {
693
18
    
OBJC_POINTER_TYPE_ATTRS_CASELIST2
:
694
18
      distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
695
18
      break;
696
697
6.69k
    
FUNCTION_TYPE_ATTRS_CASELIST517
:
698
6.69k
      distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
699
6.69k
      break;
700
701
0
    MS_TYPE_ATTRS_CASELIST:
702
      // Microsoft type attributes cannot go after the declarator-id.
703
0
      continue;
704
705
0
    NULLABILITY_TYPE_ATTRS_CASELIST:
706
      // Nullability specifiers cannot go after the declarator-id.
707
708
    // Objective-C __kindof does not get distributed.
709
0
    case ParsedAttr::AT_ObjCKindOf:
710
0
      continue;
711
712
4.57M
    default:
713
4.57M
      break;
714
4.58M
    }
715
4.58M
  }
716
2.08M
}
717
718
/// Add a synthetic '()' to a block-literal declarator if it is
719
/// required, given the return type.
720
static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
721
3.33k
                                          QualType declSpecType) {
722
3.33k
  Declarator &declarator = state.getDeclarator();
723
724
  // First, check whether the declarator would produce a function,
725
  // i.e. whether the innermost semantic chunk is a function.
726
3.33k
  if (declarator.isFunctionDeclarator()) {
727
    // If so, make that declarator a prototyped declarator.
728
3.30k
    declarator.getFunctionTypeInfo().hasPrototype = true;
729
3.30k
    return;
730
3.30k
  }
731
732
  // If there are any type objects, the type as written won't name a
733
  // function, regardless of the decl spec type.  This is because a
734
  // block signature declarator is always an abstract-declarator, and
735
  // abstract-declarators can't just be parentheses chunks.  Therefore
736
  // we need to build a function chunk unless there are no type
737
  // objects and the decl spec type is a function.
738
24
  if (!declarator.getNumTypeObjects() && 
declSpecType->isFunctionType()21
)
739
4
    return;
740
741
  // Note that there *are* cases with invalid declarators where
742
  // declarators consist solely of parentheses.  In general, these
743
  // occur only in failed efforts to make function declarators, so
744
  // faking up the function chunk is still the right thing to do.
745
746
  // Otherwise, we need to fake up a function declarator.
747
20
  SourceLocation loc = declarator.getBeginLoc();
748
749
  // ...and *prepend* it to the declarator.
750
20
  SourceLocation NoLoc;
751
20
  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
752
20
      /*HasProto=*/true,
753
20
      /*IsAmbiguous=*/false,
754
20
      /*LParenLoc=*/NoLoc,
755
20
      /*ArgInfo=*/nullptr,
756
20
      /*NumParams=*/0,
757
20
      /*EllipsisLoc=*/NoLoc,
758
20
      /*RParenLoc=*/NoLoc,
759
20
      /*RefQualifierIsLvalueRef=*/true,
760
20
      /*RefQualifierLoc=*/NoLoc,
761
20
      /*MutableLoc=*/NoLoc, EST_None,
762
20
      /*ESpecRange=*/SourceRange(),
763
20
      /*Exceptions=*/nullptr,
764
20
      /*ExceptionRanges=*/nullptr,
765
20
      /*NumExceptions=*/0,
766
20
      /*NoexceptExpr=*/nullptr,
767
20
      /*ExceptionSpecTokens=*/nullptr,
768
20
      /*DeclsInPrototype=*/None, loc, loc, declarator));
769
770
  // For consistency, make sure the state still has us as processing
771
  // the decl spec.
772
20
  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
773
0
  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
774
20
}
775
776
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
777
                                            unsigned &TypeQuals,
778
                                            QualType TypeSoFar,
779
                                            unsigned RemoveTQs,
780
3.08k
                                            unsigned DiagID) {
781
  // If this occurs outside a template instantiation, warn the user about
782
  // it; they probably didn't mean to specify a redundant qualifier.
783
3.08k
  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
784
3.08k
  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
785
3.08k
                       QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
786
3.08k
                       QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
787
12.3k
                       QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
788
12.3k
    if (!(RemoveTQs & Qual.first))
789
98
      continue;
790
791
12.2k
    if (!S.inTemplateInstantiation()) {
792
12.2k
      if (TypeQuals & Qual.first)
793
79
        S.Diag(Qual.second, DiagID)
794
79
          << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
795
79
          << FixItHint::CreateRemoval(Qual.second);
796
12.2k
    }
797
798
12.2k
    TypeQuals &= ~Qual.first;
799
12.2k
  }
800
3.08k
}
801
802
/// Return true if this is omitted block return type. Also check type
803
/// attributes and type qualifiers when returning true.
804
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
805
3.33k
                                        QualType Result) {
806
3.33k
  if (!isOmittedBlockReturnType(declarator))
807
336
    return false;
808
809
  // Warn if we see type attributes for omitted return type on a block literal.
810
3.00k
  SmallVector<ParsedAttr *, 2> ToBeRemoved;
811
3.00k
  for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
812
22
    if (AL.isInvalid() || !AL.isTypeAttr())
813
17
      continue;
814
5
    S.Diag(AL.getLoc(),
815
5
           diag::warn_block_literal_attributes_on_omitted_return_type)
816
5
        << AL;
817
5
    ToBeRemoved.push_back(&AL);
818
5
  }
819
  // Remove bad attributes from the list.
820
3.00k
  for (ParsedAttr *AL : ToBeRemoved)
821
5
    declarator.getMutableDeclSpec().getAttributes().remove(AL);
822
823
  // Warn if we see type qualifiers for omitted return type on a block literal.
824
3.00k
  const DeclSpec &DS = declarator.getDeclSpec();
825
3.00k
  unsigned TypeQuals = DS.getTypeQualifiers();
826
3.00k
  diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
827
3.00k
      diag::warn_block_literal_qualifiers_on_omitted_return_type);
828
3.00k
  declarator.getMutableDeclSpec().ClearTypeQualifiers();
829
830
3.00k
  return true;
831
3.33k
}
832
833
/// Apply Objective-C type arguments to the given type.
834
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
835
                                  ArrayRef<TypeSourceInfo *> typeArgs,
836
                                  SourceRange typeArgsRange,
837
130k
                                  bool failOnError = false) {
838
  // We can only apply type arguments to an Objective-C class type.
839
130k
  const auto *objcObjectType = type->getAs<ObjCObjectType>();
840
130k
  if (!objcObjectType || 
!objcObjectType->getInterface()130k
) {
841
1
    S.Diag(loc, diag::err_objc_type_args_non_class)
842
1
      << type
843
1
      << typeArgsRange;
844
845
1
    if (failOnError)
846
0
      return QualType();
847
1
    return type;
848
1
  }
849
850
  // The class type must be parameterized.
851
130k
  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
852
130k
  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
853
130k
  if (!typeParams) {
854
1
    S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
855
1
      << objcClass->getDeclName()
856
1
      << FixItHint::CreateRemoval(typeArgsRange);
857
858
1
    if (failOnError)
859
0
      return QualType();
860
861
1
    return type;
862
1
  }
863
864
  // The type must not already be specialized.
865
130k
  if (objcObjectType->isSpecialized()) {
866
3
    S.Diag(loc, diag::err_objc_type_args_specialized_class)
867
3
      << type
868
3
      << FixItHint::CreateRemoval(typeArgsRange);
869
870
3
    if (failOnError)
871
0
      return QualType();
872
873
3
    return type;
874
3
  }
875
876
  // Check the type arguments.
877
130k
  SmallVector<QualType, 4> finalTypeArgs;
878
130k
  unsigned numTypeParams = typeParams->size();
879
130k
  bool anyPackExpansions = false;
880
291k
  for (unsigned i = 0, n = typeArgs.size(); i != n; 
++i161k
) {
881
161k
    TypeSourceInfo *typeArgInfo = typeArgs[i];
882
161k
    QualType typeArg = typeArgInfo->getType();
883
884
    // Type arguments cannot have explicit qualifiers or nullability.
885
    // We ignore indirect sources of these, e.g. behind typedefs or
886
    // template arguments.
887
161k
    if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
888
17
      bool diagnosed = false;
889
17
      SourceRange rangeToRemove;
890
17
      if (auto attr = qual.getAs<AttributedTypeLoc>()) {
891
12
        rangeToRemove = attr.getLocalSourceRange();
892
12
        if (attr.getTypePtr()->getImmediateNullability()) {
893
1
          typeArg = attr.getTypePtr()->getModifiedType();
894
1
          S.Diag(attr.getBeginLoc(),
895
1
                 diag::err_objc_type_arg_explicit_nullability)
896
1
              << typeArg << FixItHint::CreateRemoval(rangeToRemove);
897
1
          diagnosed = true;
898
1
        }
899
12
      }
900
901
17
      if (!diagnosed) {
902
16
        S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
903
16
            << typeArg << typeArg.getQualifiers().getAsString()
904
16
            << FixItHint::CreateRemoval(rangeToRemove);
905
16
      }
906
17
    }
907
908
    // Remove qualifiers even if they're non-local.
909
161k
    typeArg = typeArg.getUnqualifiedType();
910
911
161k
    finalTypeArgs.push_back(typeArg);
912
913
161k
    if (typeArg->getAs<PackExpansionType>())
914
1
      anyPackExpansions = true;
915
916
    // Find the corresponding type parameter, if there is one.
917
161k
    ObjCTypeParamDecl *typeParam = nullptr;
918
161k
    if (!anyPackExpansions) {
919
161k
      if (i < numTypeParams) {
920
161k
        typeParam = typeParams->begin()[i];
921
161k
      } else {
922
        // Too many arguments.
923
2
        S.Diag(loc, diag::err_objc_type_args_wrong_arity)
924
2
          << false
925
2
          << objcClass->getDeclName()
926
2
          << (unsigned)typeArgs.size()
927
2
          << numTypeParams;
928
2
        S.Diag(objcClass->getLocation(), diag::note_previous_decl)
929
2
          << objcClass;
930
931
2
        if (failOnError)
932
1
          return QualType();
933
934
1
        return type;
935
2
      }
936
161k
    }
937
938
    // Objective-C object pointer types must be substitutable for the bounds.
939
161k
    if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
940
      // If we don't have a type parameter to match against, assume
941
      // everything is fine. There was a prior pack expansion that
942
      // means we won't be able to match anything.
943
161k
      if (!typeParam) {
944
0
        assert(anyPackExpansions && "Too many arguments?");
945
0
        continue;
946
0
      }
947
948
      // Retrieve the bound.
949
161k
      QualType bound = typeParam->getUnderlyingType();
950
161k
      const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
951
952
      // Determine whether the type argument is substitutable for the bound.
953
161k
      if (typeArgObjC->isObjCIdType()) {
954
        // When the type argument is 'id', the only acceptable type
955
        // parameter bound is 'id'.
956
64.3k
        if (boundObjC->isObjCIdType())
957
64.3k
          continue;
958
96.9k
      } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
959
        // Otherwise, we follow the assignability rules.
960
96.8k
        continue;
961
96.8k
      }
962
963
      // Diagnose the mismatch.
964
6
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
965
6
             diag::err_objc_type_arg_does_not_match_bound)
966
6
          << typeArg << bound << typeParam->getDeclName();
967
6
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
968
6
        << typeParam->getDeclName();
969
970
6
      if (failOnError)
971
2
        return QualType();
972
973
4
      return type;
974
6
    }
975
976
    // Block pointer types are permitted for unqualified 'id' bounds.
977
239
    if (typeArg->isBlockPointerType()) {
978
      // If we don't have a type parameter to match against, assume
979
      // everything is fine. There was a prior pack expansion that
980
      // means we won't be able to match anything.
981
231
      if (!typeParam) {
982
0
        assert(anyPackExpansions && "Too many arguments?");
983
0
        continue;
984
0
      }
985
986
      // Retrieve the bound.
987
231
      QualType bound = typeParam->getUnderlyingType();
988
231
      if (bound->isBlockCompatibleObjCPointerType(S.Context))
989
231
        continue;
990
991
      // Diagnose the mismatch.
992
0
      S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
993
0
             diag::err_objc_type_arg_does_not_match_bound)
994
0
          << typeArg << bound << typeParam->getDeclName();
995
0
      S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
996
0
        << typeParam->getDeclName();
997
998
0
      if (failOnError)
999
0
        return QualType();
1000
1001
0
      return type;
1002
0
    }
1003
1004
    // Dependent types will be checked at instantiation time.
1005
8
    if (typeArg->isDependentType()) {
1006
8
      continue;
1007
8
    }
1008
1009
    // Diagnose non-id-compatible type arguments.
1010
0
    S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1011
0
           diag::err_objc_type_arg_not_id_compatible)
1012
0
        << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1013
1014
0
    if (failOnError)
1015
0
      return QualType();
1016
1017
0
    return type;
1018
0
  }
1019
1020
  // Make sure we didn't have the wrong number of arguments.
1021
130k
  if (!anyPackExpansions && 
finalTypeArgs.size() != numTypeParams130k
) {
1022
3
    S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1023
3
      << (typeArgs.size() < typeParams->size())
1024
3
      << objcClass->getDeclName()
1025
3
      << (unsigned)finalTypeArgs.size()
1026
3
      << (unsigned)numTypeParams;
1027
3
    S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1028
3
      << objcClass;
1029
1030
3
    if (failOnError)
1031
1
      return QualType();
1032
1033
2
    return type;
1034
3
  }
1035
1036
  // Success. Form the specialized type.
1037
130k
  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1038
130k
}
1039
1040
QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1041
                                      SourceLocation ProtocolLAngleLoc,
1042
                                      ArrayRef<ObjCProtocolDecl *> Protocols,
1043
                                      ArrayRef<SourceLocation> ProtocolLocs,
1044
                                      SourceLocation ProtocolRAngleLoc,
1045
0
                                      bool FailOnError) {
1046
0
  QualType Result = QualType(Decl->getTypeForDecl(), 0);
1047
0
  if (!Protocols.empty()) {
1048
0
    bool HasError;
1049
0
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1050
0
                                                 HasError);
1051
0
    if (HasError) {
1052
0
      Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1053
0
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1054
0
      if (FailOnError) Result = QualType();
1055
0
    }
1056
0
    if (FailOnError && Result.isNull())
1057
0
      return QualType();
1058
0
  }
1059
1060
0
  return Result;
1061
0
}
1062
1063
QualType Sema::BuildObjCObjectType(QualType BaseType,
1064
                                   SourceLocation Loc,
1065
                                   SourceLocation TypeArgsLAngleLoc,
1066
                                   ArrayRef<TypeSourceInfo *> TypeArgs,
1067
                                   SourceLocation TypeArgsRAngleLoc,
1068
                                   SourceLocation ProtocolLAngleLoc,
1069
                                   ArrayRef<ObjCProtocolDecl *> Protocols,
1070
                                   ArrayRef<SourceLocation> ProtocolLocs,
1071
                                   SourceLocation ProtocolRAngleLoc,
1072
152k
                                   bool FailOnError) {
1073
152k
  QualType Result = BaseType;
1074
152k
  if (!TypeArgs.empty()) {
1075
130k
    Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1076
130k
                               SourceRange(TypeArgsLAngleLoc,
1077
130k
                                           TypeArgsRAngleLoc),
1078
130k
                               FailOnError);
1079
130k
    if (FailOnError && 
Result.isNull()17
)
1080
4
      return QualType();
1081
130k
  }
1082
1083
152k
  if (!Protocols.empty()) {
1084
22.6k
    bool HasError;
1085
22.6k
    Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1086
22.6k
                                                 HasError);
1087
22.6k
    if (HasError) {
1088
1
      Diag(Loc, diag::err_invalid_protocol_qualifiers)
1089
1
        << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1090
1
      if (FailOnError) 
Result = QualType()0
;
1091
1
    }
1092
22.6k
    if (FailOnError && 
Result.isNull()0
)
1093
0
      return QualType();
1094
22.6k
  }
1095
1096
152k
  return Result;
1097
152k
}
1098
1099
TypeResult Sema::actOnObjCProtocolQualifierType(
1100
             SourceLocation lAngleLoc,
1101
             ArrayRef<Decl *> protocols,
1102
             ArrayRef<SourceLocation> protocolLocs,
1103
7
             SourceLocation rAngleLoc) {
1104
  // Form id<protocol-list>.
1105
7
  QualType Result = Context.getObjCObjectType(
1106
7
                      Context.ObjCBuiltinIdTy, { },
1107
7
                      llvm::makeArrayRef(
1108
7
                        (ObjCProtocolDecl * const *)protocols.data(),
1109
7
                        protocols.size()),
1110
7
                      false);
1111
7
  Result = Context.getObjCObjectPointerType(Result);
1112
1113
7
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1114
7
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1115
1116
7
  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1117
7
  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1118
1119
7
  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1120
7
                        .castAs<ObjCObjectTypeLoc>();
1121
7
  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1122
7
  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1123
1124
  // No type arguments.
1125
7
  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1126
7
  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1127
1128
  // Fill in protocol qualifiers.
1129
7
  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1130
7
  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1131
14
  for (unsigned i = 0, n = protocols.size(); i != n; 
++i7
)
1132
7
    ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1133
1134
  // We're done. Return the completed type to the parser.
1135
7
  return CreateParsedType(Result, ResultTInfo);
1136
7
}
1137
1138
TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1139
             Scope *S,
1140
             SourceLocation Loc,
1141
             ParsedType BaseType,
1142
             SourceLocation TypeArgsLAngleLoc,
1143
             ArrayRef<ParsedType> TypeArgs,
1144
             SourceLocation TypeArgsRAngleLoc,
1145
             SourceLocation ProtocolLAngleLoc,
1146
             ArrayRef<Decl *> Protocols,
1147
             ArrayRef<SourceLocation> ProtocolLocs,
1148
152k
             SourceLocation ProtocolRAngleLoc) {
1149
152k
  TypeSourceInfo *BaseTypeInfo = nullptr;
1150
152k
  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1151
152k
  if (T.isNull())
1152
0
    return true;
1153
1154
  // Handle missing type-source info.
1155
152k
  if (!BaseTypeInfo)
1156
152k
    BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1157
1158
  // Extract type arguments.
1159
152k
  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1160
314k
  for (unsigned i = 0, n = TypeArgs.size(); i != n; 
++i161k
) {
1161
161k
    TypeSourceInfo *TypeArgInfo = nullptr;
1162
161k
    QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1163
161k
    if (TypeArg.isNull()) {
1164
0
      ActualTypeArgInfos.clear();
1165
0
      break;
1166
0
    }
1167
1168
161k
    assert(TypeArgInfo && "No type source info?");
1169
0
    ActualTypeArgInfos.push_back(TypeArgInfo);
1170
161k
  }
1171
1172
  // Build the object type.
1173
152k
  QualType Result = BuildObjCObjectType(
1174
152k
      T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1175
152k
      TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1176
152k
      ProtocolLAngleLoc,
1177
152k
      llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1178
152k
                         Protocols.size()),
1179
152k
      ProtocolLocs, ProtocolRAngleLoc,
1180
152k
      /*FailOnError=*/false);
1181
1182
152k
  if (Result == T)
1183
57
    return BaseType;
1184
1185
  // Create source information for this type.
1186
152k
  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1187
152k
  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1188
1189
  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1190
  // object pointer type. Fill in source information for it.
1191
152k
  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1192
    // The '*' is implicit.
1193
15.6k
    ObjCObjectPointerTL.setStarLoc(SourceLocation());
1194
15.6k
    ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1195
15.6k
  }
1196
1197
152k
  if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1198
    // Protocol qualifier information.
1199
1.78k
    if (OTPTL.getNumProtocols() > 0) {
1200
1.78k
      assert(OTPTL.getNumProtocols() == Protocols.size());
1201
0
      OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1202
1.78k
      OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1203
3.56k
      for (unsigned i = 0, n = Protocols.size(); i != n; 
++i1.78k
)
1204
1.78k
        OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1205
1.78k
    }
1206
1207
    // We're done. Return the completed type to the parser.
1208
0
    return CreateParsedType(Result, ResultTInfo);
1209
1.78k
  }
1210
1211
151k
  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1212
1213
  // Type argument information.
1214
151k
  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1215
130k
    assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1216
0
    ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1217
130k
    ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1218
291k
    for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; 
++i161k
)
1219
161k
      ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1220
130k
  } else {
1221
20.8k
    ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1222
20.8k
    ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1223
20.8k
  }
1224
1225
  // Protocol qualifier information.
1226
151k
  if (ObjCObjectTL.getNumProtocols() > 0) {
1227
20.8k
    assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1228
0
    ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1229
20.8k
    ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1230
42.6k
    for (unsigned i = 0, n = Protocols.size(); i != n; 
++i21.7k
)
1231
21.7k
      ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1232
130k
  } else {
1233
130k
    ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1234
130k
    ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1235
130k
  }
1236
1237
  // Base type.
1238
0
  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1239
151k
  if (ObjCObjectTL.getType() == T)
1240
0
    ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1241
151k
  else
1242
151k
    ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1243
1244
  // We're done. Return the completed type to the parser.
1245
151k
  return CreateParsedType(Result, ResultTInfo);
1246
152k
}
1247
1248
static OpenCLAccessAttr::Spelling
1249
8.05k
getImageAccess(const ParsedAttributesView &Attrs) {
1250
8.05k
  for (const ParsedAttr &AL : Attrs)
1251
7.90k
    if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1252
7.90k
      return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1253
147
  return OpenCLAccessAttr::Keyword_read_only;
1254
8.05k
}
1255
1256
/// Convert the specified declspec to the appropriate type
1257
/// object.
1258
/// \param state Specifies the declarator containing the declaration specifier
1259
/// to be converted, along with other associated processing state.
1260
/// \returns The type described by the declaration specifiers.  This function
1261
/// never returns null.
1262
107M
static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1263
  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1264
  // checking.
1265
1266
107M
  Sema &S = state.getSema();
1267
107M
  Declarator &declarator = state.getDeclarator();
1268
107M
  DeclSpec &DS = declarator.getMutableDeclSpec();
1269
107M
  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1270
107M
  if (DeclLoc.isInvalid())
1271
693k
    DeclLoc = DS.getBeginLoc();
1272
1273
107M
  ASTContext &Context = S.Context;
1274
1275
107M
  QualType Result;
1276
107M
  switch (DS.getTypeSpecType()) {
1277
3.44M
  case DeclSpec::TST_void:
1278
3.44M
    Result = Context.VoidTy;
1279
3.44M
    break;
1280
985k
  case DeclSpec::TST_char:
1281
985k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1282
805k
      Result = Context.CharTy;
1283
180k
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1284
47.9k
      Result = Context.SignedCharTy;
1285
132k
    else {
1286
132k
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1287
132k
             "Unknown TSS value");
1288
0
      Result = Context.UnsignedCharTy;
1289
132k
    }
1290
0
    break;
1291
129k
  case DeclSpec::TST_wchar:
1292
129k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1293
129k
      Result = Context.WCharTy;
1294
6
    else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1295
3
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1296
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1297
3
                               Context.getPrintingPolicy());
1298
3
      Result = Context.getSignedWCharType();
1299
3
    } else {
1300
3
      assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1301
3
             "Unknown TSS value");
1302
0
      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1303
3
        << DS.getSpecifierName(DS.getTypeSpecType(),
1304
3
                               Context.getPrintingPolicy());
1305
3
      Result = Context.getUnsignedWCharType();
1306
3
    }
1307
0
    break;
1308
67
  case DeclSpec::TST_char8:
1309
67
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1310
67
           "Unknown TSS value");
1311
0
    Result = Context.Char8Ty;
1312
67
    break;
1313
9.82k
  case DeclSpec::TST_char16:
1314
9.82k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1315
9.82k
           "Unknown TSS value");
1316
0
    Result = Context.Char16Ty;
1317
9.82k
    break;
1318
9.82k
  case DeclSpec::TST_char32:
1319
9.82k
    assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1320
9.82k
           "Unknown TSS value");
1321
0
    Result = Context.Char32Ty;
1322
9.82k
    break;
1323
9.83k
  case DeclSpec::TST_unspecified:
1324
    // If this is a missing declspec in a block literal return context, then it
1325
    // is inferred from the return statements inside the block.
1326
    // The declspec is always missing in a lambda expr context; it is either
1327
    // specified with a trailing return type or inferred.
1328
9.83k
    if (S.getLangOpts().CPlusPlus14 &&
1329
9.83k
        
declarator.getContext() == DeclaratorContext::LambdaExpr5.37k
) {
1330
      // In C++1y, a lambda's implicit return type is 'auto'.
1331
4.38k
      Result = Context.getAutoDeductType();
1332
4.38k
      break;
1333
5.45k
    } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1334
5.45k
               checkOmittedBlockReturnType(S, declarator,
1335
5.11k
                                           Context.DependentTy)) {
1336
5.11k
      Result = Context.DependentTy;
1337
5.11k
      break;
1338
5.11k
    }
1339
1340
    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1341
    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1342
    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1343
    // Note that the one exception to this is function definitions, which are
1344
    // allowed to be completely missing a declspec.  This is handled in the
1345
    // parser already though by it pretending to have seen an 'int' in this
1346
    // case.
1347
336
    if (S.getLangOpts().isImplicitIntRequired()) {
1348
12
      S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1349
12
          << DS.getSourceRange()
1350
12
          << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1351
324
    } else if (!DS.hasTypeSpecifier()) {
1352
      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1353
      // "At least one type specifier shall be given in the declaration
1354
      // specifiers in each declaration, and in the specifier-qualifier list in
1355
      // each struct declaration and type name."
1356
324
      if (!S.getLangOpts().isImplicitIntAllowed() && 
!DS.isTypeSpecPipe()223
) {
1357
220
        S.Diag(DeclLoc, diag::err_missing_type_specifier)
1358
220
            << DS.getSourceRange();
1359
1360
        // When this occurs, often something is very broken with the value
1361
        // being declared, poison it as invalid so we don't get chains of
1362
        // errors.
1363
220
        declarator.setInvalidType(true);
1364
220
      } else 
if (104
S.getLangOpts().getOpenCLCompatibleVersion() >= 200104
&&
1365
104
                 
DS.isTypeSpecPipe()7
) {
1366
6
        S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1367
6
            << DS.getSourceRange();
1368
6
        declarator.setInvalidType(true);
1369
98
      } else {
1370
98
        assert(S.getLangOpts().isImplicitIntAllowed() &&
1371
98
               "implicit int is disabled?");
1372
0
        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1373
98
            << DS.getSourceRange()
1374
98
            << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1375
98
      }
1376
324
    }
1377
1378
336
    LLVM_FALLTHROUGH;
1379
2.92M
  case DeclSpec::TST_int: {
1380
2.92M
    if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1381
2.34M
      switch (DS.getTypeSpecWidth()) {
1382
1.91M
      case TypeSpecifierWidth::Unspecified:
1383
1.91M
        Result = Context.IntTy;
1384
1.91M
        break;
1385
148k
      case TypeSpecifierWidth::Short:
1386
148k
        Result = Context.ShortTy;
1387
148k
        break;
1388
185k
      case TypeSpecifierWidth::Long:
1389
185k
        Result = Context.LongTy;
1390
185k
        break;
1391
100k
      case TypeSpecifierWidth::LongLong:
1392
100k
        Result = Context.LongLongTy;
1393
1394
        // 'long long' is a C99 or C++11 feature.
1395
100k
        if (!S.getLangOpts().C99) {
1396
55.0k
          if (S.getLangOpts().CPlusPlus)
1397
54.9k
            S.Diag(DS.getTypeSpecWidthLoc(),
1398
54.9k
                   S.getLangOpts().CPlusPlus11 ?
1399
54.0k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong935
);
1400
41
          else
1401
41
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1402
55.0k
        }
1403
100k
        break;
1404
2.34M
      }
1405
2.34M
    } else {
1406
583k
      switch (DS.getTypeSpecWidth()) {
1407
282k
      case TypeSpecifierWidth::Unspecified:
1408
282k
        Result = Context.UnsignedIntTy;
1409
282k
        break;
1410
115k
      case TypeSpecifierWidth::Short:
1411
115k
        Result = Context.UnsignedShortTy;
1412
115k
        break;
1413
105k
      case TypeSpecifierWidth::Long:
1414
105k
        Result = Context.UnsignedLongTy;
1415
105k
        break;
1416
80.0k
      case TypeSpecifierWidth::LongLong:
1417
80.0k
        Result = Context.UnsignedLongLongTy;
1418
1419
        // 'long long' is a C99 or C++11 feature.
1420
80.0k
        if (!S.getLangOpts().C99) {
1421
42.7k
          if (S.getLangOpts().CPlusPlus)
1422
42.7k
            S.Diag(DS.getTypeSpecWidthLoc(),
1423
42.7k
                   S.getLangOpts().CPlusPlus11 ?
1424
42.0k
                   diag::warn_cxx98_compat_longlong : 
diag::ext_cxx11_longlong757
);
1425
11
          else
1426
11
            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1427
42.7k
        }
1428
80.0k
        break;
1429
583k
      }
1430
583k
    }
1431
2.92M
    break;
1432
2.92M
  }
1433
2.92M
  case DeclSpec::TST_bitint: {
1434
1.05k
    if (!S.Context.getTargetInfo().hasBitIntType())
1435
0
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1436
1.05k
    Result =
1437
1.05k
        S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1438
1.05k
                          DS.getRepAsExpr(), DS.getBeginLoc());
1439
1.05k
    if (Result.isNull()) {
1440
9
      Result = Context.IntTy;
1441
9
      declarator.setInvalidType(true);
1442
9
    }
1443
1.05k
    break;
1444
2.92M
  }
1445
1.02k
  case DeclSpec::TST_accum: {
1446
1.02k
    switch (DS.getTypeSpecWidth()) {
1447
518
    case TypeSpecifierWidth::Short:
1448
518
      Result = Context.ShortAccumTy;
1449
518
      break;
1450
315
    case TypeSpecifierWidth::Unspecified:
1451
315
      Result = Context.AccumTy;
1452
315
      break;
1453
191
    case TypeSpecifierWidth::Long:
1454
191
      Result = Context.LongAccumTy;
1455
191
      break;
1456
0
    case TypeSpecifierWidth::LongLong:
1457
0
      llvm_unreachable("Unable to specify long long as _Accum width");
1458
1.02k
    }
1459
1460
1.02k
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1461
327
      Result = Context.getCorrespondingUnsignedType(Result);
1462
1463
1.02k
    if (DS.isTypeSpecSat())
1464
369
      Result = Context.getCorrespondingSaturatedType(Result);
1465
1466
1.02k
    break;
1467
1.02k
  }
1468
545
  case DeclSpec::TST_fract: {
1469
545
    switch (DS.getTypeSpecWidth()) {
1470
168
    case TypeSpecifierWidth::Short:
1471
168
      Result = Context.ShortFractTy;
1472
168
      break;
1473
214
    case TypeSpecifierWidth::Unspecified:
1474
214
      Result = Context.FractTy;
1475
214
      break;
1476
163
    case TypeSpecifierWidth::Long:
1477
163
      Result = Context.LongFractTy;
1478
163
      break;
1479
0
    case TypeSpecifierWidth::LongLong:
1480
0
      llvm_unreachable("Unable to specify long long as _Fract width");
1481
545
    }
1482
1483
545
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1484
208
      Result = Context.getCorrespondingUnsignedType(Result);
1485
1486
545
    if (DS.isTypeSpecSat())
1487
176
      Result = Context.getCorrespondingSaturatedType(Result);
1488
1489
545
    break;
1490
545
  }
1491
912
  case DeclSpec::TST_int128:
1492
912
    if (!S.Context.getTargetInfo().hasInt128Type() &&
1493
912
        
!(31
S.getLangOpts().SYCLIsDevice31
||
S.getLangOpts().CUDAIsDevice13
||
1494
31
          
(9
S.getLangOpts().OpenMP9
&&
S.getLangOpts().OpenMPIsDevice0
)))
1495
9
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1496
9
        << "__int128";
1497
912
    if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1498
604
      Result = Context.UnsignedInt128Ty;
1499
308
    else
1500
308
      Result = Context.Int128Ty;
1501
912
    break;
1502
1.09k
  case DeclSpec::TST_float16:
1503
    // CUDA host and device may have different _Float16 support, therefore
1504
    // do not diagnose _Float16 usage to avoid false alarm.
1505
    // ToDo: more precise diagnostics for CUDA.
1506
1.09k
    if (!S.Context.getTargetInfo().hasFloat16Type() && 
!S.getLangOpts().CUDA5
&&
1507
1.09k
        
!(3
S.getLangOpts().OpenMP3
&&
S.getLangOpts().OpenMPIsDevice0
))
1508
3
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1509
3
        << "_Float16";
1510
1.09k
    Result = Context.Float16Ty;
1511
1.09k
    break;
1512
20.1k
  case DeclSpec::TST_half:    Result = Context.HalfTy; break;
1513
724
  case DeclSpec::TST_BFloat16:
1514
724
    if (!S.Context.getTargetInfo().hasBFloat16Type())
1515
5
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1516
5
        << "__bf16";
1517
724
    Result = Context.BFloat16Ty;
1518
724
    break;
1519
326k
  case DeclSpec::TST_float:   Result = Context.FloatTy; break;
1520
497k
  case DeclSpec::TST_double:
1521
497k
    if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1522
174k
      Result = Context.LongDoubleTy;
1523
323k
    else
1524
323k
      Result = Context.DoubleTy;
1525
497k
    if (S.getLangOpts().OpenCL) {
1526
12.8k
      if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1527
38
        S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1528
38
            << 0 << Result
1529
38
            << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1530
38
                    ? 
"cl_khr_fp64 and __opencl_c_fp64"16
1531
38
                    : 
"cl_khr_fp64"22
);
1532
12.7k
      else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1533
24
        S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1534
12.8k
    }
1535
497k
    break;
1536
455
  case DeclSpec::TST_float128:
1537
455
    if (!S.Context.getTargetInfo().hasFloat128Type() &&
1538
455
        
!S.getLangOpts().SYCLIsDevice40
&&
1539
455
        
!(23
S.getLangOpts().OpenMP23
&&
S.getLangOpts().OpenMPIsDevice11
))
1540
12
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1541
12
        << "__float128";
1542
455
    Result = Context.Float128Ty;
1543
455
    break;
1544
108
  case DeclSpec::TST_ibm128:
1545
108
    if (!S.Context.getTargetInfo().hasIbm128Type() &&
1546
108
        
!S.getLangOpts().SYCLIsDevice17
&&
1547
108
        
!(17
S.getLangOpts().OpenMP17
&&
S.getLangOpts().OpenMPIsDevice2
))
1548
15
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1549
108
    Result = Context.Ibm128Ty;
1550
108
    break;
1551
690k
  case DeclSpec::TST_bool:
1552
690k
    Result = Context.BoolTy; // _Bool or bool
1553
690k
    break;
1554
6
  case DeclSpec::TST_decimal32:    // _Decimal32
1555
6
  case DeclSpec::TST_decimal64:    // _Decimal64
1556
8
  case DeclSpec::TST_decimal128:   // _Decimal128
1557
8
    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1558
8
    Result = Context.IntTy;
1559
8
    declarator.setInvalidType(true);
1560
8
    break;
1561
14.6k
  case DeclSpec::TST_class:
1562
428k
  case DeclSpec::TST_enum:
1563
459k
  case DeclSpec::TST_union:
1564
1.36M
  case DeclSpec::TST_struct:
1565
1.36M
  case DeclSpec::TST_interface: {
1566
1.36M
    TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1567
1.36M
    if (!D) {
1568
      // This can happen in C++ with ambiguous lookups.
1569
7.77k
      Result = Context.IntTy;
1570
7.77k
      declarator.setInvalidType(true);
1571
7.77k
      break;
1572
7.77k
    }
1573
1574
    // If the type is deprecated or unavailable, diagnose it.
1575
1.35M
    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1576
1577
1.35M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1578
1.35M
           DS.getTypeSpecComplex() == 0 &&
1579
1.35M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1580
1.35M
           "No qualifiers on tag names!");
1581
1582
    // TypeQuals handled by caller.
1583
0
    Result = Context.getTypeDeclType(D);
1584
1585
    // In both C and C++, make an ElaboratedType.
1586
1.35M
    ElaboratedTypeKeyword Keyword
1587
1.35M
      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1588
1.35M
    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1589
1.35M
                                 DS.isTypeSpecOwned() ? 
D459k
:
nullptr897k
);
1590
1.35M
    break;
1591
1.36M
  }
1592
97.1M
  case DeclSpec::TST_typename: {
1593
97.1M
    assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1594
97.1M
           DS.getTypeSpecComplex() == 0 &&
1595
97.1M
           DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1596
97.1M
           "Can't handle qualifiers on typedef names yet!");
1597
0
    Result = S.GetTypeFromParser(DS.getRepAsType());
1598
97.1M
    if (Result.isNull()) {
1599
0
      declarator.setInvalidType(true);
1600
0
    }
1601
1602
    // TypeQuals handled by caller.
1603
97.1M
    break;
1604
1.36M
  }
1605
98
  case DeclSpec::TST_typeofType:
1606
    // FIXME: Preserve type source info.
1607
98
    Result = S.GetTypeFromParser(DS.getRepAsType());
1608
98
    assert(!Result.isNull() && "Didn't get a type for typeof?");
1609
98
    if (!Result->isDependentType())
1610
96
      if (const TagType *TT = Result->getAs<TagType>())
1611
8
        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1612
    // TypeQuals handled by caller.
1613
98
    Result = Context.getTypeOfType(Result);
1614
98
    break;
1615
2.73k
  case DeclSpec::TST_typeofExpr: {
1616
2.73k
    Expr *E = DS.getRepAsExpr();
1617
2.73k
    assert(E && "Didn't get an expression for typeof?");
1618
    // TypeQuals handled by caller.
1619
0
    Result = S.BuildTypeofExprType(E);
1620
2.73k
    if (Result.isNull()) {
1621
0
      Result = Context.IntTy;
1622
0
      declarator.setInvalidType(true);
1623
0
    }
1624
2.73k
    break;
1625
1.36M
  }
1626
38.2k
  case DeclSpec::TST_decltype: {
1627
38.2k
    Expr *E = DS.getRepAsExpr();
1628
38.2k
    assert(E && "Didn't get an expression for decltype?");
1629
    // TypeQuals handled by caller.
1630
0
    Result = S.BuildDecltypeType(E);
1631
38.2k
    if (Result.isNull()) {
1632
0
      Result = Context.IntTy;
1633
0
      declarator.setInvalidType(true);
1634
0
    }
1635
38.2k
    break;
1636
1.36M
  }
1637
523
  case DeclSpec::TST_underlyingType:
1638
523
    Result = S.GetTypeFromParser(DS.getRepAsType());
1639
523
    assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1640
0
    Result = S.BuildUnaryTransformType(Result,
1641
523
                                       UnaryTransformType::EnumUnderlyingType,
1642
523
                                       DS.getTypeSpecTypeLoc());
1643
523
    if (Result.isNull()) {
1644
4
      Result = Context.IntTy;
1645
4
      declarator.setInvalidType(true);
1646
4
    }
1647
523
    break;
1648
1649
40.4k
  case DeclSpec::TST_auto:
1650
40.9k
  case DeclSpec::TST_decltype_auto: {
1651
40.9k
    auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1652
40.9k
                      ? 
AutoTypeKeyword::DecltypeAuto528
1653
40.9k
                      : 
AutoTypeKeyword::Auto40.4k
;
1654
1655
40.9k
    ConceptDecl *TypeConstraintConcept = nullptr;
1656
40.9k
    llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1657
40.9k
    if (DS.isConstrainedAuto()) {
1658
165
      if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1659
163
        TypeConstraintConcept =
1660
163
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1661
163
        TemplateArgumentListInfo TemplateArgsInfo;
1662
163
        TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1663
163
        TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1664
163
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1665
163
                                           TemplateId->NumArgs);
1666
163
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1667
163
        for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1668
73
          TemplateArgs.push_back(ArgLoc.getArgument());
1669
163
      } else {
1670
2
        declarator.setInvalidType(true);
1671
2
      }
1672
165
    }
1673
40.9k
    Result = S.Context.getAutoType(QualType(), AutoKW,
1674
40.9k
                                   /*IsDependent*/ false, /*IsPack=*/false,
1675
40.9k
                                   TypeConstraintConcept, TemplateArgs);
1676
40.9k
    break;
1677
40.4k
  }
1678
1679
49
  case DeclSpec::TST_auto_type:
1680
49
    Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1681
49
    break;
1682
1683
62
  case DeclSpec::TST_unknown_anytype:
1684
62
    Result = Context.UnknownAnyTy;
1685
62
    break;
1686
1687
2.83k
  case DeclSpec::TST_atomic:
1688
2.83k
    Result = S.GetTypeFromParser(DS.getRepAsType());
1689
2.83k
    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1690
0
    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1691
2.83k
    if (Result.isNull()) {
1692
11
      Result = Context.IntTy;
1693
11
      declarator.setInvalidType(true);
1694
11
    }
1695
2.83k
    break;
1696
1697
0
#define GENERIC_IMAGE_TYPE(ImgType, Id)                                        \
1698
8.05k
  case DeclSpec::TST_##ImgType##_t:                                            \
1699
8.05k
    switch (getImageAccess(DS.getAttributes())) {                              \
1700
2.13k
    case OpenCLAccessAttr::Keyword_write_only:                                 \
1701
2.13k
      Result = Context.Id##WOTy;                                               \
1702
2.13k
      break;                                                                   \
1703
2.21k
    case OpenCLAccessAttr::Keyword_read_write:                                 \
1704
2.21k
      Result = Context.Id##RWTy;                                               \
1705
2.21k
      break;                                                                   \
1706
3.70k
    case OpenCLAccessAttr::Keyword_read_only:                                  \
1707
3.70k
      Result = Context.Id##ROTy;                                               \
1708
3.70k
      break;                                                                   \
1709
0
    case OpenCLAccessAttr::SpellingNotCalculated:                              \
1710
0
      llvm_unreachable("Spelling not yet calculated");                         \
1711
8.05k
    }                                                                          \
1712
8.05k
    break;
1713
2.83k
#include "clang/Basic/OpenCLImageTypes.def"
1714
1715
1.83k
  case DeclSpec::TST_error:
1716
1.83k
    Result = Context.IntTy;
1717
1.83k
    declarator.setInvalidType(true);
1718
1.83k
    break;
1719
107M
  }
1720
1721
  // FIXME: we want resulting declarations to be marked invalid, but claiming
1722
  // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1723
  // a null type.
1724
107M
  if (Result->containsErrors())
1725
101
    declarator.setInvalidType();
1726
1727
107M
  if (S.getLangOpts().OpenCL) {
1728
667k
    const auto &OpenCLOptions = S.getOpenCLOptions();
1729
667k
    bool IsOpenCLC30Compatible =
1730
667k
        S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1731
    // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1732
    // support.
1733
    // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1734
    // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1735
    // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1736
    // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1737
    // only when the optional feature is supported
1738
667k
    if ((Result->isImageType() || 
Result->isSamplerT()659k
) &&
1739
667k
        
(10.1k
IsOpenCLC30Compatible10.1k
&&
1740
10.1k
         
!OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts())1.55k
)) {
1741
24
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1742
24
          << 0 << Result << "__opencl_c_images";
1743
24
      declarator.setInvalidType();
1744
667k
    } else if (Result->isOCLImage3dWOType() &&
1745
667k
               !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1746
287
                                          S.getLangOpts())) {
1747
3
      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1748
3
          << 0 << Result
1749
3
          << (IsOpenCLC30Compatible
1750
3
                  ? 
"cl_khr_3d_image_writes and __opencl_c_3d_image_writes"2
1751
3
                  : 
"cl_khr_3d_image_writes"1
);
1752
3
      declarator.setInvalidType();
1753
3
    }
1754
667k
  }
1755
1756
107M
  bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1757
107M
                          
DS.getTypeSpecType() == DeclSpec::TST_fract107M
;
1758
1759
  // Only fixed point types can be saturated
1760
107M
  if (DS.isTypeSpecSat() && 
!IsFixedPointType556
)
1761
11
    S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1762
11
        << DS.getSpecifierName(DS.getTypeSpecType(),
1763
11
                               Context.getPrintingPolicy());
1764
1765
  // Handle complex types.
1766
107M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1767
8.17k
    if (S.getLangOpts().Freestanding)
1768
54
      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1769
8.17k
    Result = Context.getComplexType(Result);
1770
107M
  } else if (DS.isTypeAltiVecVector()) {
1771
104k
    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1772
104k
    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1773
0
    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1774
104k
    if (DS.isTypeAltiVecPixel())
1775
2.57k
      VecKind = VectorType::AltiVecPixel;
1776
101k
    else if (DS.isTypeAltiVecBool())
1777
18.8k
      VecKind = VectorType::AltiVecBool;
1778
104k
    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1779
104k
  }
1780
1781
  // FIXME: Imaginary.
1782
107M
  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1783
4
    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1784
1785
  // Before we process any type attributes, synthesize a block literal
1786
  // function declarator if necessary.
1787
107M
  if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1788
3.33k
    maybeSynthesizeBlockSignature(state, Result);
1789
1790
  // Apply any type attributes from the decl spec.  This may cause the
1791
  // list of type attributes to be temporarily saved while the type
1792
  // attributes are pushed around.
1793
  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1794
107M
  if (!DS.isTypeSpecPipe())
1795
107M
    processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1796
1797
  // Apply const/volatile/restrict qualifiers to T.
1798
107M
  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1799
    // Warn about CV qualifiers on function types.
1800
    // C99 6.7.3p8:
1801
    //   If the specification of a function type includes any type qualifiers,
1802
    //   the behavior is undefined.
1803
    // C++11 [dcl.fct]p7:
1804
    //   The effect of a cv-qualifier-seq in a function declarator is not the
1805
    //   same as adding cv-qualification on top of the function type. In the
1806
    //   latter case, the cv-qualifiers are ignored.
1807
4.82M
    if (Result->isFunctionType()) {
1808
19
      diagnoseAndRemoveTypeQualifiers(
1809
19
          S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1810
19
          S.getLangOpts().CPlusPlus
1811
19
              ? 
diag::warn_typecheck_function_qualifiers_ignored15
1812
19
              : 
diag::warn_typecheck_function_qualifiers_unspecified4
);
1813
      // No diagnostic for 'restrict' or '_Atomic' applied to a
1814
      // function type; we'll diagnose those later, in BuildQualifiedType.
1815
19
    }
1816
1817
    // C++11 [dcl.ref]p1:
1818
    //   Cv-qualified references are ill-formed except when the
1819
    //   cv-qualifiers are introduced through the use of a typedef-name
1820
    //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1821
    //
1822
    // There don't appear to be any other contexts in which a cv-qualified
1823
    // reference type could be formed, so the 'ill-formed' clause here appears
1824
    // to never happen.
1825
4.82M
    if (TypeQuals && 
Result->isReferenceType()4.82M
) {
1826
60
      diagnoseAndRemoveTypeQualifiers(
1827
60
          S, DS, TypeQuals, Result,
1828
60
          DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1829
60
          diag::warn_typecheck_reference_qualifiers);
1830
60
    }
1831
1832
    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1833
    // than once in the same specifier-list or qualifier-list, either directly
1834
    // or via one or more typedefs."
1835
4.82M
    if (!S.getLangOpts().C99 && 
!S.getLangOpts().CPlusPlus2.42M
1836
4.82M
        && 
TypeQuals & Result.getCVRQualifiers()551
) {
1837
8
      if (TypeQuals & DeclSpec::TQ_const && 
Result.isConstQualified()6
) {
1838
6
        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1839
6
          << "const";
1840
6
      }
1841
1842
8
      if (TypeQuals & DeclSpec::TQ_volatile && 
Result.isVolatileQualified()2
) {
1843
2
        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1844
2
          << "volatile";
1845
2
      }
1846
1847
      // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1848
      // produce a warning in this case.
1849
8
    }
1850
1851
4.82M
    QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1852
1853
    // If adding qualifiers fails, just use the unqualified type.
1854
4.82M
    if (Qualified.isNull())
1855
16
      declarator.setInvalidType(true);
1856
4.82M
    else
1857
4.82M
      Result = Qualified;
1858
4.82M
  }
1859
1860
107M
  assert(!Result.isNull() && "This function should not return a null type");
1861
0
  return Result;
1862
107M
}
1863
1864
136
static std::string getPrintableNameForEntity(DeclarationName Entity) {
1865
136
  if (Entity)
1866
104
    return Entity.getAsString();
1867
1868
32
  return "type name";
1869
136
}
1870
1871
3.60k
static bool isDependentOrGNUAutoType(QualType T) {
1872
3.60k
  if (T->isDependentType())
1873
440
    return true;
1874
1875
3.16k
  const auto *AT = dyn_cast<AutoType>(T);
1876
3.16k
  return AT && 
AT->isGNUAutoType()3
;
1877
3.60k
}
1878
1879
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1880
5.47M
                                  Qualifiers Qs, const DeclSpec *DS) {
1881
5.47M
  if (T.isNull())
1882
0
    return QualType();
1883
1884
  // Ignore any attempt to form a cv-qualified reference.
1885
5.47M
  if (T->isReferenceType()) {
1886
72
    Qs.removeConst();
1887
72
    Qs.removeVolatile();
1888
72
  }
1889
1890
  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1891
  // object or incomplete types shall not be restrict-qualified."
1892
5.47M
  if (Qs.hasRestrict()) {
1893
70.6k
    unsigned DiagID = 0;
1894
70.6k
    QualType ProblemTy;
1895
1896
70.6k
    if (T->isAnyPointerType() || 
T->isReferenceType()40
||
1897
70.6k
        
T->isMemberPointerType()29
) {
1898
70.5k
      QualType EltTy;
1899
70.5k
      if (T->isObjCObjectPointerType())
1900
6
        EltTy = T;
1901
70.5k
      else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1902
2
        EltTy = PTy->getPointeeType();
1903
70.5k
      else
1904
70.5k
        EltTy = T->getPointeeType();
1905
1906
      // If we have a pointer or reference, the pointee must have an object
1907
      // incomplete type.
1908
70.5k
      if (!EltTy->isIncompleteOrObjectType()) {
1909
2
        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1910
2
        ProblemTy = EltTy;
1911
2
      }
1912
70.5k
    } else 
if (27
!isDependentOrGNUAutoType(T)27
) {
1913
      // For an __auto_type variable, we may not have seen the initializer yet
1914
      // and so have no idea whether the underlying type is a pointer type or
1915
      // not.
1916
20
      DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1917
20
      ProblemTy = T;
1918
20
    }
1919
1920
70.6k
    if (DiagID) {
1921
22
      Diag(DS ? 
DS->getRestrictSpecLoc()15
:
Loc7
, DiagID) << ProblemTy;
1922
22
      Qs.removeRestrict();
1923
22
    }
1924
70.6k
  }
1925
1926
5.47M
  return Context.getQualifiedType(T, Qs);
1927
5.47M
}
1928
1929
QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1930
4.97M
                                  unsigned CVRAU, const DeclSpec *DS) {
1931
4.97M
  if (T.isNull())
1932
6
    return QualType();
1933
1934
  // Ignore any attempt to form a cv-qualified reference.
1935
4.97M
  if (T->isReferenceType())
1936
67
    CVRAU &=
1937
67
        ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1938
1939
  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1940
  // TQ_unaligned;
1941
4.97M
  unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1942
1943
  // C11 6.7.3/5:
1944
  //   If the same qualifier appears more than once in the same
1945
  //   specifier-qualifier-list, either directly or via one or more typedefs,
1946
  //   the behavior is the same as if it appeared only once.
1947
  //
1948
  // It's not specified what happens when the _Atomic qualifier is applied to
1949
  // a type specified with the _Atomic specifier, but we assume that this
1950
  // should be treated as if the _Atomic qualifier appeared multiple times.
1951
4.97M
  if (CVRAU & DeclSpec::TQ_atomic && 
!T->isAtomicType()153
) {
1952
    // C11 6.7.3/5:
1953
    //   If other qualifiers appear along with the _Atomic qualifier in a
1954
    //   specifier-qualifier-list, the resulting type is the so-qualified
1955
    //   atomic type.
1956
    //
1957
    // Don't need to worry about array types here, since _Atomic can't be
1958
    // applied to such types.
1959
151
    SplitQualType Split = T.getSplitUnqualifiedType();
1960
151
    T = BuildAtomicType(QualType(Split.Ty, 0),
1961
151
                        DS ? 
DS->getAtomicSpecLoc()135
:
Loc16
);
1962
151
    if (T.isNull())
1963
16
      return T;
1964
135
    Split.Quals.addCVRQualifiers(CVR);
1965
135
    return BuildQualifiedType(T, Loc, Split.Quals);
1966
151
  }
1967
1968
4.97M
  Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1969
4.97M
  Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1970
4.97M
  return BuildQualifiedType(T, Loc, Q, DS);
1971
4.97M
}
1972
1973
/// Build a paren type including \p T.
1974
310k
QualType Sema::BuildParenType(QualType T) {
1975
310k
  return Context.getParenType(T);
1976
310k
}
1977
1978
/// Given that we're building a pointer or reference to the given
1979
static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1980
                                           SourceLocation loc,
1981
43.5k
                                           bool isReference) {
1982
  // Bail out if retention is unrequired or already specified.
1983
43.5k
  if (!type->isObjCLifetimeType() ||
1984
43.5k
      
type.getObjCLifetime() != Qualifiers::OCL_None1.57k
)
1985
43.5k
    return type;
1986
1987
24
  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1988
1989
  // If the object type is const-qualified, we can safely use
1990
  // __unsafe_unretained.  This is safe (because there are no read
1991
  // barriers), and it'll be safe to coerce anything but __weak* to
1992
  // the resulting type.
1993
24
  if (type.isConstQualified()) {
1994
2
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1995
1996
  // Otherwise, check whether the static type does not require
1997
  // retaining.  This currently only triggers for Class (possibly
1998
  // protocol-qualifed, and arrays thereof).
1999
22
  } else if (type->isObjCARCImplicitlyUnretainedType()) {
2000
3
    implicitLifetime = Qualifiers::OCL_ExplicitNone;
2001
2002
  // If we are in an unevaluated context, like sizeof, skip adding a
2003
  // qualification.
2004
19
  } else if (S.isUnevaluatedContext()) {
2005
4
    return type;
2006
2007
  // If that failed, give an error and recover using __strong.  __strong
2008
  // is the option most likely to prevent spurious second-order diagnostics,
2009
  // like when binding a reference to a field.
2010
15
  } else {
2011
    // These types can show up in private ivars in system headers, so
2012
    // we need this to not be an error in those cases.  Instead we
2013
    // want to delay.
2014
15
    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2015
14
      S.DelayedDiagnostics.add(
2016
14
          sema::DelayedDiagnostic::makeForbiddenType(loc,
2017
14
              diag::err_arc_indirect_no_ownership, type, isReference));
2018
14
    } else {
2019
1
      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2020
1
    }
2021
15
    implicitLifetime = Qualifiers::OCL_Strong;
2022
15
  }
2023
20
  assert(implicitLifetime && "didn't infer any lifetime!");
2024
2025
0
  Qualifiers qs;
2026
20
  qs.addObjCLifetime(implicitLifetime);
2027
20
  return S.Context.getQualifiedType(type, qs);
2028
24
}
2029
2030
80
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2031
80
  std::string Quals = FnTy->getMethodQuals().getAsString();
2032
2033
80
  switch (FnTy->getRefQualifier()) {
2034
43
  case RQ_None:
2035
43
    break;
2036
2037
17
  case RQ_LValue:
2038
17
    if (!Quals.empty())
2039
0
      Quals += ' ';
2040
17
    Quals += '&';
2041
17
    break;
2042
2043
20
  case RQ_RValue:
2044
20
    if (!Quals.empty())
2045
2
      Quals += ' ';
2046
20
    Quals += "&&";
2047
20
    break;
2048
80
  }
2049
2050
80
  return Quals;
2051
80
}
2052
2053
namespace {
2054
/// Kinds of declarator that cannot contain a qualified function type.
2055
///
2056
/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2057
///     a function type with a cv-qualifier or a ref-qualifier can only appear
2058
///     at the topmost level of a type.
2059
///
2060
/// Parens and member pointers are permitted. We don't diagnose array and
2061
/// function declarators, because they don't allow function types at all.
2062
///
2063
/// The values of this enum are used in diagnostics.
2064
enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2065
} // end anonymous namespace
2066
2067
/// Check whether the type T is a qualified function type, and if it is,
2068
/// diagnose that it cannot be contained within the given kind of declarator.
2069
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2070
9.01M
                                   QualifiedFunctionKind QFK) {
2071
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2072
9.01M
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2073
9.01M
  if (!FPT ||
2074
9.01M
      
(274k
FPT->getMethodQuals().empty()274k
&&
FPT->getRefQualifier() == RQ_None274k
))
2075
9.01M
    return false;
2076
2077
24
  S.Diag(Loc, diag::err_compound_qualified_function_type)
2078
24
    << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2079
24
    << getFunctionQualifiersAsString(FPT);
2080
24
  return true;
2081
9.01M
}
2082
2083
1.66k
bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2084
1.66k
  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2085
1.66k
  if (!FPT ||
2086
1.66k
      
(6
FPT->getMethodQuals().empty()6
&&
FPT->getRefQualifier() == RQ_None3
))
2087
1.66k
    return false;
2088
2089
6
  Diag(Loc, diag::err_qualified_function_typeid)
2090
6
      << T << getFunctionQualifiersAsString(FPT);
2091
6
  return true;
2092
1.66k
}
2093
2094
// Helper to deduce addr space of a pointee type in OpenCL mode.
2095
40.4k
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2096
40.4k
  if (!PointeeType->isUndeducedAutoType() && 
!PointeeType->isDependentType()40.4k
&&
2097
40.4k
      
!PointeeType->isSamplerT()40.4k
&&
2098
40.4k
      
!PointeeType.hasAddressSpace()40.4k
)
2099
7.50k
    PointeeType = S.getASTContext().getAddrSpaceQualType(
2100
7.50k
        PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2101
40.4k
  return PointeeType;
2102
40.4k
}
2103
2104
/// Build a pointer type.
2105
///
2106
/// \param T The type to which we'll be building a pointer.
2107
///
2108
/// \param Loc The location of the entity whose type involves this
2109
/// pointer type or, if there is no such entity, the location of the
2110
/// type that will have pointer type.
2111
///
2112
/// \param Entity The name of the entity that involves the pointer
2113
/// type, if known.
2114
///
2115
/// \returns A suitable pointer type, if there are no
2116
/// errors. Otherwise, returns a NULL type.
2117
QualType Sema::BuildPointerType(QualType T,
2118
6.88M
                                SourceLocation Loc, DeclarationName Entity) {
2119
6.88M
  if (T->isReferenceType()) {
2120
    // C++ 8.3.2p4: There shall be no ... pointers to references ...
2121
57
    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2122
57
      << getPrintableNameForEntity(Entity) << T;
2123
57
    return QualType();
2124
57
  }
2125
2126
6.88M
  if (T->isFunctionType() && 
getLangOpts().OpenCL208k
&&
2127
6.88M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2128
11
                                            getLangOpts())) {
2129
7
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2130
7
    return QualType();
2131
7
  }
2132
2133
6.88M
  if (getLangOpts().HLSL) {
2134
6
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2135
6
    return QualType();
2136
6
  }
2137
2138
6.88M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2139
12
    return QualType();
2140
2141
6.88M
  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2142
2143
  // In ARC, it is forbidden to build pointers to unqualified pointers.
2144
6.88M
  if (getLangOpts().ObjCAutoRefCount)
2145
41.7k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2146
2147
6.88M
  if (getLangOpts().OpenCL)
2148
40.1k
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2149
2150
  // Build the pointer type.
2151
6.88M
  return Context.getPointerType(T);
2152
6.88M
}
2153
2154
/// Build a reference type.
2155
///
2156
/// \param T The type to which we'll be building a reference.
2157
///
2158
/// \param Loc The location of the entity whose type involves this
2159
/// reference type or, if there is no such entity, the location of the
2160
/// type that will have reference type.
2161
///
2162
/// \param Entity The name of the entity that involves the reference
2163
/// type, if known.
2164
///
2165
/// \returns A suitable reference type, if there are no
2166
/// errors. Otherwise, returns a NULL type.
2167
QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2168
                                  SourceLocation Loc,
2169
2.07M
                                  DeclarationName Entity) {
2170
2.07M
  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2171
2.07M
         "Unresolved overloaded function type");
2172
2173
  // C++0x [dcl.ref]p6:
2174
  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2175
  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2176
  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
2177
  //   the type "lvalue reference to T", while an attempt to create the type
2178
  //   "rvalue reference to cv TR" creates the type TR.
2179
2.07M
  bool LValueRef = SpelledAsLValue || 
T->getAs<LValueReferenceType>()474k
;
2180
2181
  // C++ [dcl.ref]p4: There shall be no references to references.
2182
  //
2183
  // According to C++ DR 106, references to references are only
2184
  // diagnosed when they are written directly (e.g., "int & &"),
2185
  // but not when they happen via a typedef:
2186
  //
2187
  //   typedef int& intref;
2188
  //   typedef intref& intref2;
2189
  //
2190
  // Parser::ParseDeclaratorInternal diagnoses the case where
2191
  // references are written directly; here, we handle the
2192
  // collapsing of references-to-references as described in C++0x.
2193
  // DR 106 and 540 introduce reference-collapsing into C++98/03.
2194
2195
  // C++ [dcl.ref]p1:
2196
  //   A declarator that specifies the type "reference to cv void"
2197
  //   is ill-formed.
2198
2.07M
  if (T->isVoidType()) {
2199
451
    Diag(Loc, diag::err_reference_to_void);
2200
451
    return QualType();
2201
451
  }
2202
2203
2.07M
  if (getLangOpts().HLSL) {
2204
5
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2205
5
    return QualType();
2206
5
  }
2207
2208
2.07M
  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2209
12
    return QualType();
2210
2211
2.07M
  if (T->isFunctionType() && 
getLangOpts().OpenCL5.27k
&&
2212
2.07M
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2213
10
                                            getLangOpts())) {
2214
5
    Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2215
5
    return QualType();
2216
5
  }
2217
2218
  // In ARC, it is forbidden to build references to unqualified pointers.
2219
2.07M
  if (getLangOpts().ObjCAutoRefCount)
2220
1.79k
    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2221
2222
2.07M
  if (getLangOpts().OpenCL)
2223
108
    T = deduceOpenCLPointeeAddrSpace(*this, T);
2224
2225
  // Handle restrict on references.
2226
2.07M
  if (LValueRef)
2227
1.64M
    return Context.getLValueReferenceType(T, SpelledAsLValue);
2228
432k
  return Context.getRValueReferenceType(T);
2229
2.07M
}
2230
2231
/// Build a Read-only Pipe type.
2232
///
2233
/// \param T The type to which we'll be building a Pipe.
2234
///
2235
/// \param Loc We do not use it for now.
2236
///
2237
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2238
/// NULL type.
2239
249
QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2240
249
  return Context.getReadPipeType(T);
2241
249
}
2242
2243
/// Build a Write-only Pipe type.
2244
///
2245
/// \param T The type to which we'll be building a Pipe.
2246
///
2247
/// \param Loc We do not use it for now.
2248
///
2249
/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2250
/// NULL type.
2251
0
QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2252
0
  return Context.getWritePipeType(T);
2253
0
}
2254
2255
/// Build a bit-precise integer type.
2256
///
2257
/// \param IsUnsigned Boolean representing the signedness of the type.
2258
///
2259
/// \param BitWidth Size of this int type in bits, or an expression representing
2260
/// that.
2261
///
2262
/// \param Loc Location of the keyword.
2263
QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2264
1.08k
                               SourceLocation Loc) {
2265
1.08k
  if (BitWidth->isInstantiationDependent())
2266
14
    return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2267
2268
1.06k
  llvm::APSInt Bits(32);
2269
1.06k
  ExprResult ICE =
2270
1.06k
      VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2271
2272
1.06k
  if (ICE.isInvalid())
2273
2
    return QualType();
2274
2275
1.06k
  size_t NumBits = Bits.getZExtValue();
2276
1.06k
  if (!IsUnsigned && 
NumBits < 2949
) {
2277
5
    Diag(Loc, diag::err_bit_int_bad_size) << 0;
2278
5
    return QualType();
2279
5
  }
2280
2281
1.06k
  if (IsUnsigned && 
NumBits < 1117
) {
2282
2
    Diag(Loc, diag::err_bit_int_bad_size) << 1;
2283
2
    return QualType();
2284
2
  }
2285
2286
1.05k
  const TargetInfo &TI = getASTContext().getTargetInfo();
2287
1.05k
  if (NumBits > TI.getMaxBitIntWidth()) {
2288
5
    Diag(Loc, diag::err_bit_int_max_size)
2289
5
        << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2290
5
    return QualType();
2291
5
  }
2292
2293
1.05k
  return Context.getBitIntType(IsUnsigned, NumBits);
2294
1.05k
}
2295
2296
/// Check whether the specified array bound can be evaluated using the relevant
2297
/// language rules. If so, returns the possibly-converted expression and sets
2298
/// SizeVal to the size. If not, but the expression might be a VLA bound,
2299
/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2300
/// ExprError().
2301
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2302
                                 llvm::APSInt &SizeVal, unsigned VLADiag,
2303
261k
                                 bool VLAIsError) {
2304
261k
  if (S.getLangOpts().CPlusPlus14 &&
2305
261k
      
(27.0k
VLAIsError27.0k
||
2306
27.0k
       
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()26.3k
)) {
2307
    // C++14 [dcl.array]p1:
2308
    //   The constant-expression shall be a converted constant expression of
2309
    //   type std::size_t.
2310
    //
2311
    // Don't apply this rule if we might be forming a VLA: in that case, we
2312
    // allow non-constant expressions and constant-folding. We only need to use
2313
    // the converted constant expression rules (to properly convert the source)
2314
    // when the source expression is of class type.
2315
717
    return S.CheckConvertedConstantExpression(
2316
717
        ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2317
717
  }
2318
2319
  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2320
  // (like gnu99, but not c99) accept any evaluatable value as an extension.
2321
260k
  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2322
260k
  public:
2323
260k
    unsigned VLADiag;
2324
260k
    bool VLAIsError;
2325
260k
    bool IsVLA = false;
2326
2327
260k
    VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2328
260k
        : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2329
2330
260k
    Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2331
260k
                                                   QualType T) override {
2332
1
      return S.Diag(Loc, diag::err_array_size_non_int) << T;
2333
1
    }
2334
2335
260k
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2336
260k
                                               SourceLocation Loc) override {
2337
3.56k
      IsVLA = !VLAIsError;
2338
3.56k
      return S.Diag(Loc, VLADiag);
2339
3.56k
    }
2340
2341
260k
    Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2342
260k
                                             SourceLocation Loc) override {
2343
0
      return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2344
0
    }
2345
260k
  } Diagnoser(VLADiag, VLAIsError);
2346
2347
260k
  ExprResult R =
2348
260k
      S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2349
260k
  if (Diagnoser.IsVLA)
2350
3.54k
    return ExprResult();
2351
257k
  return R;
2352
260k
}
2353
2354
/// Build an array type.
2355
///
2356
/// \param T The type of each element in the array.
2357
///
2358
/// \param ASM C99 array size modifier (e.g., '*', 'static').
2359
///
2360
/// \param ArraySize Expression describing the size of the array.
2361
///
2362
/// \param Brackets The range from the opening '[' to the closing ']'.
2363
///
2364
/// \param Entity The name of the entity that involves the array
2365
/// type, if known.
2366
///
2367
/// \returns A suitable array type, if there are no errors. Otherwise,
2368
/// returns a NULL type.
2369
QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2370
                              Expr *ArraySize, unsigned Quals,
2371
332k
                              SourceRange Brackets, DeclarationName Entity) {
2372
2373
332k
  SourceLocation Loc = Brackets.getBegin();
2374
332k
  if (getLangOpts().CPlusPlus) {
2375
    // C++ [dcl.array]p1:
2376
    //   T is called the array element type; this type shall not be a reference
2377
    //   type, the (possibly cv-qualified) type void, a function type or an
2378
    //   abstract class type.
2379
    //
2380
    // C++ [dcl.array]p3:
2381
    //   When several "array of" specifications are adjacent, [...] only the
2382
    //   first of the constant expressions that specify the bounds of the arrays
2383
    //   may be omitted.
2384
    //
2385
    // Note: function types are handled in the common path with C.
2386
156k
    if (T->isReferenceType()) {
2387
9
      Diag(Loc, diag::err_illegal_decl_array_of_references)
2388
9
      << getPrintableNameForEntity(Entity) << T;
2389
9
      return QualType();
2390
9
    }
2391
2392
156k
    if (T->isVoidType() || 
T->isIncompleteArrayType()156k
) {
2393
2
      Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2394
2
      return QualType();
2395
2
    }
2396
2397
156k
    if (RequireNonAbstractType(Brackets.getBegin(), T,
2398
156k
                               diag::err_array_of_abstract_type))
2399
20
      return QualType();
2400
2401
    // Mentioning a member pointer type for an array type causes us to lock in
2402
    // an inheritance model, even if it's inside an unused typedef.
2403
156k
    if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2404
878
      if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2405
0
        if (!MPTy->getClass()->isDependentType())
2406
0
          (void)isCompleteType(Loc, T);
2407
2408
175k
  } else {
2409
    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2410
    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2411
175k
    if (RequireCompleteSizedType(Loc, T,
2412
175k
                                 diag::err_array_incomplete_or_sizeless_type))
2413
21
      return QualType();
2414
175k
  }
2415
2416
332k
  if (T->isSizelessType()) {
2417
19
    Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2418
19
    return QualType();
2419
19
  }
2420
2421
332k
  if (T->isFunctionType()) {
2422
8
    Diag(Loc, diag::err_illegal_decl_array_of_functions)
2423
8
      << getPrintableNameForEntity(Entity) << T;
2424
8
    return QualType();
2425
8
  }
2426
2427
332k
  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2428
    // If the element type is a struct or union that contains a variadic
2429
    // array, accept it as a GNU extension: C99 6.7.2.1p2.
2430
31.0k
    if (EltTy->getDecl()->hasFlexibleArrayMember())
2431
6
      Diag(Loc, diag::ext_flexible_array_in_array) << T;
2432
301k
  } else if (T->isObjCObjectType()) {
2433
1
    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2434
1
    return QualType();
2435
1
  }
2436
2437
  // Do placeholder conversions on the array size expression.
2438
332k
  if (ArraySize && 
ArraySize->hasPlaceholderType()279k
) {
2439
2
    ExprResult Result = CheckPlaceholderExpr(ArraySize);
2440
2
    if (Result.isInvalid()) 
return QualType()0
;
2441
2
    ArraySize = Result.get();
2442
2
  }
2443
2444
  // Do lvalue-to-rvalue conversions on the array size expression.
2445
332k
  if (ArraySize && 
!ArraySize->isPRValue()279k
) {
2446
6.50k
    ExprResult Result = DefaultLvalueConversion(ArraySize);
2447
6.50k
    if (Result.isInvalid())
2448
0
      return QualType();
2449
2450
6.50k
    ArraySize = Result.get();
2451
6.50k
  }
2452
2453
  // C99 6.7.5.2p1: The size expression shall have integer type.
2454
  // C++11 allows contextual conversions to such types.
2455
332k
  if (!getLangOpts().CPlusPlus11 &&
2456
332k
      
ArraySize178k
&&
!ArraySize->isTypeDependent()152k
&&
2457
332k
      
!ArraySize->getType()->isIntegralOrUnscopedEnumerationType()152k
) {
2458
4
    Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2459
4
        << ArraySize->getType() << ArraySize->getSourceRange();
2460
4
    return QualType();
2461
4
  }
2462
2463
  // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2464
332k
  unsigned VLADiag;
2465
332k
  bool VLAIsError;
2466
332k
  if (getLangOpts().OpenCL) {
2467
    // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2468
476
    VLADiag = diag::err_opencl_vla;
2469
476
    VLAIsError = true;
2470
331k
  } else if (getLangOpts().C99) {
2471
174k
    VLADiag = diag::warn_vla_used;
2472
174k
    VLAIsError = false;
2473
174k
  } else 
if (156k
isSFINAEContext()156k
) {
2474
1.10k
    VLADiag = diag::err_vla_in_sfinae;
2475
1.10k
    VLAIsError = true;
2476
155k
  } else if (getLangOpts().OpenMP && 
isInOpenMPTaskUntiedContext()27.6k
) {
2477
10
    VLADiag = diag::err_openmp_vla_in_task_untied;
2478
10
    VLAIsError = true;
2479
155k
  } else {
2480
155k
    VLADiag = diag::ext_vla;
2481
155k
    VLAIsError = false;
2482
155k
  }
2483
2484
332k
  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2485
332k
  if (!ArraySize) {
2486
52.4k
    if (ASM == ArrayType::Star) {
2487
25
      Diag(Loc, VLADiag);
2488
25
      if (VLAIsError)
2489
0
        return QualType();
2490
2491
25
      T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2492
52.4k
    } else {
2493
52.4k
      T = Context.getIncompleteArrayType(T, ASM, Quals);
2494
52.4k
    }
2495
279k
  } else if (ArraySize->isTypeDependent() || 
ArraySize->isValueDependent()278k
) {
2496
18.0k
    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2497
261k
  } else {
2498
261k
    ExprResult R =
2499
261k
        checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2500
261k
    if (R.isInvalid())
2501
23
      return QualType();
2502
2503
261k
    if (!R.isUsable()) {
2504
      // C99: an array with a non-ICE size is a VLA. We accept any expression
2505
      // that we can fold to a non-zero positive value as a non-VLA as an
2506
      // extension.
2507
3.54k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2508
258k
    } else if (!T->isDependentType() && 
!T->isIncompleteType()254k
&&
2509
258k
               
!T->isConstantSizeType()254k
) {
2510
      // C99: an array with an element type that has a non-constant-size is a
2511
      // VLA.
2512
      // FIXME: Add a note to explain why this isn't a VLA.
2513
1.15k
      Diag(Loc, VLADiag);
2514
1.15k
      if (VLAIsError)
2515
0
        return QualType();
2516
1.15k
      T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2517
256k
    } else {
2518
      // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2519
      // have a value greater than zero.
2520
      // In C++, this follows from narrowing conversions being disallowed.
2521
256k
      if (ConstVal.isSigned() && 
ConstVal.isNegative()249k
) {
2522
153
        if (Entity)
2523
51
          Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2524
51
              << getPrintableNameForEntity(Entity)
2525
51
              << ArraySize->getSourceRange();
2526
102
        else
2527
102
          Diag(ArraySize->getBeginLoc(),
2528
102
               diag::err_typecheck_negative_array_size)
2529
102
              << ArraySize->getSourceRange();
2530
153
        return QualType();
2531
153
      }
2532
256k
      if (ConstVal == 0) {
2533
        // GCC accepts zero sized static arrays. We allow them when
2534
        // we're not in a SFINAE context.
2535
3.13k
        Diag(ArraySize->getBeginLoc(),
2536
3.13k
             isSFINAEContext() ? 
diag::err_typecheck_zero_array_size3
2537
3.13k
                               : 
diag::ext_typecheck_zero_array_size3.12k
)
2538
3.13k
            << 0 << ArraySize->getSourceRange();
2539
3.13k
      }
2540
2541
      // Is the array too large?
2542
256k
      unsigned ActiveSizeBits =
2543
256k
          (!T->isDependentType() && 
!T->isVariablyModifiedType()252k
&&
2544
256k
           
!T->isIncompleteType()252k
&&
!T->isUndeducedType()252k
)
2545
256k
              ? 
ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)252k
2546
256k
              : 
ConstVal.getActiveBits()4.07k
;
2547
256k
      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2548
8
        Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2549
8
            << toString(ConstVal, 10) << ArraySize->getSourceRange();
2550
8
        return QualType();
2551
8
      }
2552
2553
256k
      T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2554
256k
    }
2555
261k
  }
2556
2557
331k
  if (T->isVariableArrayType() && 
!Context.getTargetInfo().isVLASupported()4.72k
) {
2558
    // CUDA device code and some other targets don't support VLAs.
2559
30
    targetDiag(Loc, (getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice6
)
2560
30
                        ? 
diag::err_cuda_vla6
2561
30
                        : 
diag::err_vla_unsupported24
)
2562
30
        << ((getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice6
)
2563
30
                ? 
CurrentCUDATarget()6
2564
30
                : 
CFT_InvalidTarget24
);
2565
30
  }
2566
2567
  // If this is not C99, diagnose array size modifiers on non-VLAs.
2568
331k
  if (!getLangOpts().C99 && 
!T->isVariableArrayType()156k
&&
2569
331k
      
(152k
ASM != ArrayType::Normal152k
||
Quals != 0152k
)) {
2570
5
    Diag(Loc, getLangOpts().CPlusPlus ? 
diag::err_c99_array_usage_cxx3
2571
5
                                      : 
diag::ext_c99_array_usage2
)
2572
5
        << ASM;
2573
5
  }
2574
2575
  // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2576
  // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2577
  // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2578
331k
  if (getLangOpts().OpenCL) {
2579
469
    const QualType ArrType = Context.getBaseElementType(T);
2580
469
    if (ArrType->isBlockPointerType() || 
ArrType->isPipeType()467
||
2581
469
        
ArrType->isSamplerT()467
||
ArrType->isImageType()461
) {
2582
12
      Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2583
12
      return QualType();
2584
12
    }
2585
469
  }
2586
2587
331k
  return T;
2588
331k
}
2589
2590
QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2591
29.7k
                               SourceLocation AttrLoc) {
2592
  // The base type must be integer (not Boolean or enumeration) or float, and
2593
  // can't already be a vector.
2594
29.7k
  if ((!CurType->isDependentType() &&
2595
29.7k
       
(29.6k
!CurType->isBuiltinType()29.6k
||
CurType->isBooleanType()29.6k
||
2596
29.6k
        
(29.6k
!CurType->isIntegerType()29.6k
&&
!CurType->isRealFloatingType()10.0k
))) ||
2597
29.7k
      
CurType->isArrayType()29.6k
) {
2598
40
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2599
40
    return QualType();
2600
40
  }
2601
2602
29.6k
  if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2603
30
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2604
30
                                               VectorType::GenericVector);
2605
2606
29.6k
  Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2607
29.6k
  if (!VecSize) {
2608
0
    Diag(AttrLoc, diag::err_attribute_argument_type)
2609
0
        << "vector_size" << AANT_ArgumentIntegerConstant
2610
0
        << SizeExpr->getSourceRange();
2611
0
    return QualType();
2612
0
  }
2613
2614
29.6k
  if (CurType->isDependentType())
2615
15
    return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2616
15
                                               VectorType::GenericVector);
2617
2618
  // vecSize is specified in bytes - convert to bits.
2619
29.6k
  if (!VecSize->isIntN(61)) {
2620
    // Bit size will overflow uint64.
2621
12
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2622
12
        << SizeExpr->getSourceRange() << "vector";
2623
12
    return QualType();
2624
12
  }
2625
29.6k
  uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2626
29.6k
  unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2627
2628
29.6k
  if (VectorSizeBits == 0) {
2629
11
    Diag(AttrLoc, diag::err_attribute_zero_size)
2630
11
        << SizeExpr->getSourceRange() << "vector";
2631
11
    return QualType();
2632
11
  }
2633
2634
29.6k
  if (!TypeSize || 
VectorSizeBits % TypeSize29.6k
) {
2635
11
    Diag(AttrLoc, diag::err_attribute_invalid_size)
2636
11
        << SizeExpr->getSourceRange();
2637
11
    return QualType();
2638
11
  }
2639
2640
29.6k
  if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2641
21
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2642
21
        << SizeExpr->getSourceRange() << "vector";
2643
21
    return QualType();
2644
21
  }
2645
2646
29.5k
  return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2647
29.5k
                               VectorType::GenericVector);
2648
29.6k
}
2649
2650
/// Build an ext-vector type.
2651
///
2652
/// Run the required checks for the extended vector type.
2653
QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2654
4.33k
                                  SourceLocation AttrLoc) {
2655
  // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2656
  // in conjunction with complex types (pointers, arrays, functions, etc.).
2657
  //
2658
  // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2659
  // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2660
  // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2661
  // of bool aren't allowed.
2662
  //
2663
  // We explictly allow bool elements in ext_vector_type for C/C++.
2664
4.33k
  bool IsNoBoolVecLang = getLangOpts().OpenCL || 
getLangOpts().OpenCLCPlusPlus665
;
2665
4.33k
  if ((!T->isDependentType() && 
!T->isIntegerType()4.31k
&&
2666
4.33k
       
!T->isRealFloatingType()1.29k
) ||
2667
4.33k
      
(4.32k
IsNoBoolVecLang4.32k
&&
T->isBooleanType()3.66k
)) {
2668
16
    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2669
16
    return QualType();
2670
16
  }
2671
2672
4.31k
  if (!ArraySize->isTypeDependent() && 
!ArraySize->isValueDependent()4.31k
) {
2673
4.28k
    Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2674
4.28k
    if (!vecSize) {
2675
0
      Diag(AttrLoc, diag::err_attribute_argument_type)
2676
0
        << "ext_vector_type" << AANT_ArgumentIntegerConstant
2677
0
        << ArraySize->getSourceRange();
2678
0
      return QualType();
2679
0
    }
2680
2681
4.28k
    if (!vecSize->isIntN(32)) {
2682
6
      Diag(AttrLoc, diag::err_attribute_size_too_large)
2683
6
          << ArraySize->getSourceRange() << "vector";
2684
6
      return QualType();
2685
6
    }
2686
    // Unlike gcc's vector_size attribute, the size is specified as the
2687
    // number of elements, not the number of bytes.
2688
4.28k
    unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2689
2690
4.28k
    if (vectorSize == 0) {
2691
9
      Diag(AttrLoc, diag::err_attribute_zero_size)
2692
9
          << ArraySize->getSourceRange() << "vector";
2693
9
      return QualType();
2694
9
    }
2695
2696
4.27k
    return Context.getExtVectorType(T, vectorSize);
2697
4.28k
  }
2698
2699
27
  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2700
4.31k
}
2701
2702
QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2703
413
                               SourceLocation AttrLoc) {
2704
413
  assert(Context.getLangOpts().MatrixTypes &&
2705
413
         "Should never build a matrix type when it is disabled");
2706
2707
  // Check element type, if it is not dependent.
2708
413
  if (!ElementTy->isDependentType() &&
2709
413
      
!MatrixType::isValidElementType(ElementTy)373
) {
2710
6
    Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2711
6
    return QualType();
2712
6
  }
2713
2714
407
  if (NumRows->isTypeDependent() || 
NumCols->isTypeDependent()406
||
2715
407
      
NumRows->isValueDependent()406
||
NumCols->isValueDependent()356
)
2716
77
    return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2717
77
                                               AttrLoc);
2718
2719
330
  Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2720
330
  Optional<llvm::APSInt> ValueColumns =
2721
330
      NumCols->getIntegerConstantExpr(Context);
2722
2723
330
  auto const RowRange = NumRows->getSourceRange();
2724
330
  auto const ColRange = NumCols->getSourceRange();
2725
2726
  // Both are row and column expressions are invalid.
2727
330
  if (!ValueRows && 
!ValueColumns2
) {
2728
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2729
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2730
1
        << ColRange;
2731
1
    return QualType();
2732
1
  }
2733
2734
  // Only the row expression is invalid.
2735
329
  if (!ValueRows) {
2736
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2737
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2738
1
    return QualType();
2739
1
  }
2740
2741
  // Only the column expression is invalid.
2742
328
  if (!ValueColumns) {
2743
1
    Diag(AttrLoc, diag::err_attribute_argument_type)
2744
1
        << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2745
1
    return QualType();
2746
1
  }
2747
2748
  // Check the matrix dimensions.
2749
327
  unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2750
327
  unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2751
327
  if (MatrixRows == 0 && 
MatrixColumns == 03
) {
2752
0
    Diag(AttrLoc, diag::err_attribute_zero_size)
2753
0
        << "matrix" << RowRange << ColRange;
2754
0
    return QualType();
2755
0
  }
2756
327
  if (MatrixRows == 0) {
2757
3
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2758
3
    return QualType();
2759
3
  }
2760
324
  if (MatrixColumns == 0) {
2761
1
    Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2762
1
    return QualType();
2763
1
  }
2764
323
  if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2765
3
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2766
3
        << RowRange << "matrix row";
2767
3
    return QualType();
2768
3
  }
2769
320
  if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2770
1
    Diag(AttrLoc, diag::err_attribute_size_too_large)
2771
1
        << ColRange << "matrix column";
2772
1
    return QualType();
2773
1
  }
2774
319
  return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2775
320
}
2776
2777
1.59M
bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2778
1.59M
  if (T->isArrayType() || 
T->isFunctionType()1.59M
) {
2779
18
    Diag(Loc, diag::err_func_returning_array_function)
2780
18
      << T->isFunctionType() << T;
2781
18
    return true;
2782
18
  }
2783
2784
  // Functions cannot return half FP.
2785
1.59M
  if (T->isHalfType() && 
!getLangOpts().HalfArgsAndReturns0
) {
2786
0
    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2787
0
      FixItHint::CreateInsertion(Loc, "*");
2788
0
    return true;
2789
0
  }
2790
2791
  // Methods cannot return interface types. All ObjC objects are
2792
  // passed by reference.
2793
1.59M
  if (T->isObjCObjectType()) {
2794
3
    Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2795
3
        << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2796
3
    return true;
2797
3
  }
2798
2799
1.59M
  if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2800
1.59M
      
T.hasNonTrivialToPrimitiveCopyCUnion()1.59M
)
2801
2
    checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2802
2
                          NTCUK_Destruct|NTCUK_Copy);
2803
2804
  // C++2a [dcl.fct]p12:
2805
  //   A volatile-qualified return type is deprecated
2806
1.59M
  if (T.isVolatileQualified() && 
getLangOpts().CPlusPlus2031
)
2807
5
    Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2808
2809
1.59M
  return false;
2810
1.59M
}
2811
2812
/// Check the extended parameter information.  Most of the necessary
2813
/// checking should occur when applying the parameter attribute; the
2814
/// only other checks required are positional restrictions.
2815
static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2816
                    const FunctionProtoType::ExtProtoInfo &EPI,
2817
8.81k
                    llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2818
8.81k
  assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2819
2820
0
  bool emittedError = false;
2821
8.81k
  auto actualCC = EPI.ExtInfo.getCC();
2822
8.81k
  enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2823
8.81k
  auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2824
181
    bool isCompatible =
2825
181
        (required == RequiredCC::OnlySwift)
2826
181
            ? 
(actualCC == CC_Swift)34
2827
181
            : 
(147
actualCC == CC_Swift147
||
actualCC == CC_SwiftAsync21
);
2828
181
    if (isCompatible || 
emittedError9
)
2829
172
      return;
2830
9
    S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2831
9
        << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2832
9
        << (required == RequiredCC::OnlySwift);
2833
9
    emittedError = true;
2834
9
  };
2835
8.81k
  for (size_t paramIndex = 0, numParams = paramTypes.size();
2836
35.3k
          paramIndex != numParams; 
++paramIndex26.5k
) {
2837
26.5k
    switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2838
    // Nothing interesting to check for orindary-ABI parameters.
2839
26.2k
    case ParameterABI::Ordinary:
2840
26.2k
      continue;
2841
2842
    // swift_indirect_result parameters must be a prefix of the function
2843
    // arguments.
2844
83
    case ParameterABI::SwiftIndirectResult:
2845
83
      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2846
83
      if (paramIndex != 0 &&
2847
83
          EPI.ExtParameterInfos[paramIndex - 1].getABI()
2848
33
            != ParameterABI::SwiftIndirectResult) {
2849
3
        S.Diag(getParamLoc(paramIndex),
2850
3
               diag::err_swift_indirect_result_not_first);
2851
3
      }
2852
83
      continue;
2853
2854
64
    case ParameterABI::SwiftContext:
2855
64
      checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2856
64
      continue;
2857
2858
    // SwiftAsyncContext is not limited to swiftasynccall functions.
2859
149
    case ParameterABI::SwiftAsyncContext:
2860
149
      continue;
2861
2862
    // swift_error parameters must be preceded by a swift_context parameter.
2863
34
    case ParameterABI::SwiftErrorResult:
2864
34
      checkCompatible(paramIndex, RequiredCC::OnlySwift);
2865
34
      if (paramIndex == 0 ||
2866
34
          EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2867
31
              ParameterABI::SwiftContext) {
2868
6
        S.Diag(getParamLoc(paramIndex),
2869
6
               diag::err_swift_error_result_not_after_swift_context);
2870
6
      }
2871
34
      continue;
2872
26.5k
    }
2873
0
    llvm_unreachable("bad ABI kind");
2874
0
  }
2875
8.81k
}
2876
2877
QualType Sema::BuildFunctionType(QualType T,
2878
                                 MutableArrayRef<QualType> ParamTypes,
2879
                                 SourceLocation Loc, DeclarationName Entity,
2880
930k
                                 const FunctionProtoType::ExtProtoInfo &EPI) {
2881
930k
  bool Invalid = false;
2882
2883
930k
  Invalid |= CheckFunctionReturnType(T, Loc);
2884
2885
2.20M
  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; 
++Idx1.27M
) {
2886
    // FIXME: Loc is too inprecise here, should use proper locations for args.
2887
1.27M
    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2888
1.27M
    if (ParamType->isVoidType()) {
2889
0
      Diag(Loc, diag::err_param_with_void_type);
2890
0
      Invalid = true;
2891
1.27M
    } else if (ParamType->isHalfType() && 
!getLangOpts().HalfArgsAndReturns0
) {
2892
      // Disallow half FP arguments.
2893
0
      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2894
0
        FixItHint::CreateInsertion(Loc, "*");
2895
0
      Invalid = true;
2896
0
    }
2897
2898
    // C++2a [dcl.fct]p4:
2899
    //   A parameter with volatile-qualified type is deprecated
2900
1.27M
    if (ParamType.isVolatileQualified() && 
getLangOpts().CPlusPlus206
)
2901
1
      Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2902
2903
1.27M
    ParamTypes[Idx] = ParamType;
2904
1.27M
  }
2905
2906
930k
  if (EPI.ExtParameterInfos) {
2907
86
    checkExtParameterInfos(*this, ParamTypes, EPI,
2908
86
                           [=](unsigned i) 
{ return Loc; }0
);
2909
86
  }
2910
2911
930k
  if (EPI.ExtInfo.getProducesResult()) {
2912
    // This is just a warning, so we can't fail to build if we see it.
2913
18
    checkNSReturnsRetainedReturnType(Loc, T);
2914
18
  }
2915
2916
930k
  if (Invalid)
2917
17
    return QualType();
2918
2919
930k
  return Context.getFunctionType(T, ParamTypes, EPI);
2920
930k
}
2921
2922
/// Build a member pointer type \c T Class::*.
2923
///
2924
/// \param T the type to which the member pointer refers.
2925
/// \param Class the class type into which the member pointer points.
2926
/// \param Loc the location where this type begins
2927
/// \param Entity the name of the entity that will have this member pointer type
2928
///
2929
/// \returns a member pointer type, if successful, or a NULL type if there was
2930
/// an error.
2931
QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2932
                                      SourceLocation Loc,
2933
23.3k
                                      DeclarationName Entity) {
2934
  // Verify that we're not building a pointer to pointer to function with
2935
  // exception specification.
2936
23.3k
  if (CheckDistantExceptionSpec(T)) {
2937
3
    Diag(Loc, diag::err_distant_exception_spec);
2938
3
    return QualType();
2939
3
  }
2940
2941
  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2942
  //   with reference type, or "cv void."
2943
23.3k
  if (T->isReferenceType()) {
2944
4
    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2945
4
      << getPrintableNameForEntity(Entity) << T;
2946
4
    return QualType();
2947
4
  }
2948
2949
23.3k
  if (T->isVoidType()) {
2950
5
    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2951
5
      << getPrintableNameForEntity(Entity);
2952
5
    return QualType();
2953
5
  }
2954
2955
23.3k
  if (!Class->isDependentType() && 
!Class->isRecordType()3.70k
) {
2956
35
    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2957
35
    return QualType();
2958
35
  }
2959
2960
23.3k
  if (T->isFunctionType() && 
getLangOpts().OpenCL19.7k
&&
2961
23.3k
      !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2962
4
                                            getLangOpts())) {
2963
2
    Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2964
2
    return QualType();
2965
2
  }
2966
2967
23.3k
  if (getLangOpts().HLSL) {
2968
2
    Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2969
2
    return QualType();
2970
2
  }
2971
2972
  // Adjust the default free function calling convention to the default method
2973
  // calling convention.
2974
23.3k
  bool IsCtorOrDtor =
2975
23.3k
      (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2976
23.3k
      (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2977
23.3k
  if (T->isFunctionType())
2978
19.7k
    adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2979
2980
23.3k
  return Context.getMemberPointerType(T, Class.getTypePtr());
2981
23.3k
}
2982
2983
/// Build a block pointer type.
2984
///
2985
/// \param T The type to which we'll be building a block pointer.
2986
///
2987
/// \param Loc The source location, used for diagnostics.
2988
///
2989
/// \param Entity The name of the entity that involves the block pointer
2990
/// type, if known.
2991
///
2992
/// \returns A suitable block pointer type, if there are no
2993
/// errors. Otherwise, returns a NULL type.
2994
QualType Sema::BuildBlockPointerType(QualType T,
2995
                                     SourceLocation Loc,
2996
61.0k
                                     DeclarationName Entity) {
2997
61.0k
  if (!T->isFunctionType()) {
2998
11
    Diag(Loc, diag::err_nonfunction_block_type);
2999
11
    return QualType();
3000
11
  }
3001
3002
61.0k
  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3003
0
    return QualType();
3004
3005
61.0k
  if (getLangOpts().OpenCL)
3006
147
    T = deduceOpenCLPointeeAddrSpace(*this, T);
3007
3008
61.0k
  return Context.getBlockPointerType(T);
3009
61.0k
}
3010
3011
111M
QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3012
111M
  QualType QT = Ty.get();
3013
111M
  if (QT.isNull()) {
3014
1.05M
    if (TInfo) 
*TInfo = nullptr225
;
3015
1.05M
    return QualType();
3016
1.05M
  }
3017
3018
110M
  TypeSourceInfo *DI = nullptr;
3019
110M
  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3020
14.4M
    QT = LIT->getType();
3021
14.4M
    DI = LIT->getTypeSourceInfo();
3022
14.4M
  }
3023
3024
110M
  if (TInfo) 
*TInfo = DI13.5M
;
3025
110M
  return QT;
3026
111M
}
3027
3028
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3029
                                            Qualifiers::ObjCLifetime ownership,
3030
                                            unsigned chunkIndex);
3031
3032
/// Given that this is the declaration of a parameter under ARC,
3033
/// attempt to infer attributes and such for pointer-to-whatever
3034
/// types.
3035
static void inferARCWriteback(TypeProcessingState &state,
3036
137k
                              QualType &declSpecType) {
3037
137k
  Sema &S = state.getSema();
3038
137k
  Declarator &declarator = state.getDeclarator();
3039
3040
  // TODO: should we care about decl qualifiers?
3041
3042
  // Check whether the declarator has the expected form.  We walk
3043
  // from the inside out in order to make the block logic work.
3044
137k
  unsigned outermostPointerIndex = 0;
3045
137k
  bool isBlockPointer = false;
3046
137k
  unsigned numPointers = 0;
3047
182k
  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; 
++i44.8k
) {
3048
46.4k
    unsigned chunkIndex = i;
3049
46.4k
    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3050
46.4k
    switch (chunk.Kind) {
3051
165
    case DeclaratorChunk::Paren:
3052
      // Ignore parens.
3053
165
      break;
3054
3055
930
    case DeclaratorChunk::Reference:
3056
44.6k
    case DeclaratorChunk::Pointer:
3057
      // Count the number of pointers.  Treat references
3058
      // interchangeably as pointers; if they're mis-ordered, normal
3059
      // type building will discover that.
3060
44.6k
      outermostPointerIndex = chunkIndex;
3061
44.6k
      numPointers++;
3062
44.6k
      break;
3063
3064
773
    case DeclaratorChunk::BlockPointer:
3065
      // If we have a pointer to block pointer, that's an acceptable
3066
      // indirect reference; anything else is not an application of
3067
      // the rules.
3068
773
      if (numPointers != 1) return;
3069
0
      numPointers++;
3070
0
      outermostPointerIndex = chunkIndex;
3071
0
      isBlockPointer = true;
3072
3073
      // We don't care about pointer structure in return values here.
3074
0
      goto done;
3075
3076
615
    case DeclaratorChunk::Array: // suppress if written (id[])?
3077
780
    case DeclaratorChunk::Function:
3078
780
    case DeclaratorChunk::MemberPointer:
3079
780
    case DeclaratorChunk::Pipe:
3080
780
      return;
3081
46.4k
    }
3082
46.4k
  }
3083
136k
 done:
3084
3085
  // If we have *one* pointer, then we want to throw the qualifier on
3086
  // the declaration-specifiers, which means that it needs to be a
3087
  // retainable object type.
3088
136k
  if (numPointers == 1) {
3089
    // If it's not a retainable object type, the rule doesn't apply.
3090
41.5k
    if (!declSpecType->isObjCRetainableType()) 
return41.3k
;
3091
3092
    // If it already has lifetime, don't do anything.
3093
232
    if (declSpecType.getObjCLifetime()) 
return130
;
3094
3095
    // Otherwise, modify the type in-place.
3096
102
    Qualifiers qs;
3097
3098
102
    if (declSpecType->isObjCARCImplicitlyUnretainedType())
3099
4
      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3100
98
    else
3101
98
      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3102
102
    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3103
3104
  // If we have *two* pointers, then we want to throw the qualifier on
3105
  // the outermost pointer.
3106
94.5k
  } else if (numPointers == 2) {
3107
    // If we don't have a block pointer, we need to check whether the
3108
    // declaration-specifiers gave us something that will turn into a
3109
    // retainable object pointer after we slap the first pointer on it.
3110
1.46k
    if (!isBlockPointer && !declSpecType->isObjCObjectType())
3111
647
      return;
3112
3113
    // Look for an explicit lifetime attribute there.
3114
821
    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3115
821
    if (chunk.Kind != DeclaratorChunk::Pointer &&
3116
821
        
chunk.Kind != DeclaratorChunk::BlockPointer1
)
3117
1
      return;
3118
820
    for (const ParsedAttr &AL : chunk.getAttrs())
3119
259
      if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3120
87
        return;
3121
3122
733
    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3123
733
                                          outermostPointerIndex);
3124
3125
  // Any other number of pointers/references does not trigger the rule.
3126
93.0k
  } else return;
3127
3128
  // TODO: mark whether we did this inference?
3129
136k
}
3130
3131
void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3132
                                     SourceLocation FallbackLoc,
3133
                                     SourceLocation ConstQualLoc,
3134
                                     SourceLocation VolatileQualLoc,
3135
                                     SourceLocation RestrictQualLoc,
3136
                                     SourceLocation AtomicQualLoc,
3137
402
                                     SourceLocation UnalignedQualLoc) {
3138
402
  if (!Quals)
3139
18
    return;
3140
3141
384
  struct Qual {
3142
384
    const char *Name;
3143
384
    unsigned Mask;
3144
384
    SourceLocation Loc;
3145
384
  } const QualKinds[5] = {
3146
384
    { "const", DeclSpec::TQ_const, ConstQualLoc },
3147
384
    { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3148
384
    { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3149
384
    { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3150
384
    { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3151
384
  };
3152
3153
384
  SmallString<32> QualStr;
3154
384
  unsigned NumQuals = 0;
3155
384
  SourceLocation Loc;
3156
384
  FixItHint FixIts[5];
3157
3158
  // Build a string naming the redundant qualifiers.
3159
1.92k
  for (auto &E : QualKinds) {
3160
1.92k
    if (Quals & E.Mask) {
3161
414
      if (!QualStr.empty()) 
QualStr += ' '30
;
3162
414
      QualStr += E.Name;
3163
3164
      // If we have a location for the qualifier, offer a fixit.
3165
414
      SourceLocation QualLoc = E.Loc;
3166
414
      if (QualLoc.isValid()) {
3167
393
        FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3168
393
        if (Loc.isInvalid() ||
3169
393
            
getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc)29
)
3170
365
          Loc = QualLoc;
3171
393
      }
3172
3173
414
      ++NumQuals;
3174
414
    }
3175
1.92k
  }
3176
3177
384
  Diag(Loc.isInvalid() ? 
FallbackLoc20
:
Loc364
, DiagID)
3178
384
    << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3179
384
}
3180
3181
// Diagnose pointless type qualifiers on the return type of a function.
3182
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3183
                                                  Declarator &D,
3184
414
                                                  unsigned FunctionChunkIndex) {
3185
414
  const DeclaratorChunk::FunctionTypeInfo &FTI =
3186
414
      D.getTypeObject(FunctionChunkIndex).Fun;
3187
414
  if (FTI.hasTrailingReturnType()) {
3188
10
    S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3189
10
                                RetTy.getLocalCVRQualifiers(),
3190
10
                                FTI.getTrailingReturnTypeLoc());
3191
10
    return;
3192
10
  }
3193
3194
404
  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3195
404
                End = D.getNumTypeObjects();
3196
407
       OuterChunkIndex != End; 
++OuterChunkIndex3
) {
3197
35
    DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3198
35
    switch (OuterChunk.Kind) {
3199
3
    case DeclaratorChunk::Paren:
3200
3
      continue;
3201
3202
22
    case DeclaratorChunk::Pointer: {
3203
22
      DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3204
22
      S.diagnoseIgnoredQualifiers(
3205
22
          diag::warn_qual_return_type,
3206
22
          PTI.TypeQuals,
3207
22
          SourceLocation(),
3208
22
          PTI.ConstQualLoc,
3209
22
          PTI.VolatileQualLoc,
3210
22
          PTI.RestrictQualLoc,
3211
22
          PTI.AtomicQualLoc,
3212
22
          PTI.UnalignedQualLoc);
3213
22
      return;
3214
0
    }
3215
3216
0
    case DeclaratorChunk::Function:
3217
0
    case DeclaratorChunk::BlockPointer:
3218
1
    case DeclaratorChunk::Reference:
3219
1
    case DeclaratorChunk::Array:
3220
10
    case DeclaratorChunk::MemberPointer:
3221
10
    case DeclaratorChunk::Pipe:
3222
      // FIXME: We can't currently provide an accurate source location and a
3223
      // fix-it hint for these.
3224
10
      unsigned AtomicQual = RetTy->isAtomicType() ? 
DeclSpec::TQ_atomic0
: 0;
3225
10
      S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3226
10
                                  RetTy.getCVRQualifiers() | AtomicQual,
3227
10
                                  D.getIdentifierLoc());
3228
10
      return;
3229
35
    }
3230
3231
0
    llvm_unreachable("unknown declarator chunk kind");
3232
0
  }
3233
3234
  // If the qualifiers come from a conversion function type, don't diagnose
3235
  // them -- they're not necessarily redundant, since such a conversion
3236
  // operator can be explicitly called as "x.operator const int()".
3237
372
  if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3238
15
    return;
3239
3240
  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3241
  // which are present there.
3242
357
  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3243
357
                              D.getDeclSpec().getTypeQualifiers(),
3244
357
                              D.getIdentifierLoc(),
3245
357
                              D.getDeclSpec().getConstSpecLoc(),
3246
357
                              D.getDeclSpec().getVolatileSpecLoc(),
3247
357
                              D.getDeclSpec().getRestrictSpecLoc(),
3248
357
                              D.getDeclSpec().getAtomicSpecLoc(),
3249
357
                              D.getDeclSpec().getUnalignedSpecLoc());
3250
357
}
3251
3252
static std::pair<QualType, TypeSourceInfo *>
3253
InventTemplateParameter(TypeProcessingState &state, QualType T,
3254
                        TypeSourceInfo *TrailingTSI, AutoType *Auto,
3255
2.31k
                        InventedTemplateParameterInfo &Info) {
3256
2.31k
  Sema &S = state.getSema();
3257
2.31k
  Declarator &D = state.getDeclarator();
3258
3259
2.31k
  const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3260
2.31k
  const unsigned AutoParameterPosition = Info.TemplateParams.size();
3261
2.31k
  const bool IsParameterPack = D.hasEllipsis();
3262
3263
  // If auto is mentioned in a lambda parameter or abbreviated function
3264
  // template context, convert it to a template parameter type.
3265
3266
  // Create the TemplateTypeParmDecl here to retrieve the corresponding
3267
  // template parameter type. Template parameters are temporarily added
3268
  // to the TU until the associated TemplateDecl is created.
3269
2.31k
  TemplateTypeParmDecl *InventedTemplateParam =
3270
2.31k
      TemplateTypeParmDecl::Create(
3271
2.31k
          S.Context, S.Context.getTranslationUnitDecl(),
3272
2.31k
          /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3273
2.31k
          /*NameLoc=*/D.getIdentifierLoc(),
3274
2.31k
          TemplateParameterDepth, AutoParameterPosition,
3275
2.31k
          S.InventAbbreviatedTemplateParameterTypeName(
3276
2.31k
              D.getIdentifier(), AutoParameterPosition), false,
3277
2.31k
          IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3278
2.31k
  InventedTemplateParam->setImplicit();
3279
2.31k
  Info.TemplateParams.push_back(InventedTemplateParam);
3280
3281
  // Attach type constraints to the new parameter.
3282
2.31k
  if (Auto->isConstrained()) {
3283
84
    if (TrailingTSI) {
3284
      // The 'auto' appears in a trailing return type we've already built;
3285
      // extract its type constraints to attach to the template parameter.
3286
0
      AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3287
0
      TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3288
0
      bool Invalid = false;
3289
0
      for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3290
0
        if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3291
0
            S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3292
0
                                              Sema::UPPC_TypeConstraint))
3293
0
          Invalid = true;
3294
0
        TAL.addArgument(AutoLoc.getArgLoc(Idx));
3295
0
      }
3296
3297
0
      if (!Invalid) {
3298
0
        S.AttachTypeConstraint(
3299
0
            AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3300
0
            AutoLoc.getNamedConcept(),
3301
0
            AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3302
0
            InventedTemplateParam, D.getEllipsisLoc());
3303
0
      }
3304
84
    } else {
3305
      // The 'auto' appears in the decl-specifiers; we've not finished forming
3306
      // TypeSourceInfo for it yet.
3307
84
      TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3308
84
      TemplateArgumentListInfo TemplateArgsInfo;
3309
84
      bool Invalid = false;
3310
84
      if (TemplateId->LAngleLoc.isValid()) {
3311
39
        ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3312
39
                                           TemplateId->NumArgs);
3313
39
        S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3314
3315
39
        if (D.getEllipsisLoc().isInvalid()) {
3316
31
          for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3317
31
            if (S.DiagnoseUnexpandedParameterPack(Arg,
3318
31
                                                  Sema::UPPC_TypeConstraint)) {
3319
2
              Invalid = true;
3320
2
              break;
3321
2
            }
3322
31
          }
3323
31
        }
3324
39
      }
3325
84
      if (!Invalid) {
3326
82
        S.AttachTypeConstraint(
3327
82
            D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3328
82
            DeclarationNameInfo(DeclarationName(TemplateId->Name),
3329
82
                                TemplateId->TemplateNameLoc),
3330
82
            cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3331
82
            TemplateId->LAngleLoc.isValid() ? 
&TemplateArgsInfo37
:
nullptr45
,
3332
82
            InventedTemplateParam, D.getEllipsisLoc());
3333
82
      }
3334
84
    }
3335
84
  }
3336
3337
  // Replace the 'auto' in the function parameter with this invented
3338
  // template type parameter.
3339
  // FIXME: Retain some type sugar to indicate that this was written
3340
  //  as 'auto'?
3341
2.31k
  QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3342
2.31k
  QualType NewT = state.ReplaceAutoType(T, Replacement);
3343
2.31k
  TypeSourceInfo *NewTSI =
3344
2.31k
      TrailingTSI ? 
S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)8
3345
2.31k
                  : 
nullptr2.30k
;
3346
2.31k
  return {NewT, NewTSI};
3347
2.31k
}
3348
3349
static TypeSourceInfo *
3350
GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3351
                               QualType T, TypeSourceInfo *ReturnTypeInfo);
3352
3353
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3354
107M
                                             TypeSourceInfo *&ReturnTypeInfo) {
3355
107M
  Sema &SemaRef = state.getSema();
3356
107M
  Declarator &D = state.getDeclarator();
3357
107M
  QualType T;
3358
107M
  ReturnTypeInfo = nullptr;
3359
3360
  // The TagDecl owned by the DeclSpec.
3361
107M
  TagDecl *OwnedTagDecl = nullptr;
3362
3363
107M
  switch (D.getName().getKind()) {
3364
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
3365
316k
  case UnqualifiedIdKind::IK_OperatorFunctionId:
3366
107M
  case UnqualifiedIdKind::IK_Identifier:
3367
107M
  case UnqualifiedIdKind::IK_LiteralOperatorId:
3368
107M
  case UnqualifiedIdKind::IK_TemplateId:
3369
107M
    T = ConvertDeclSpecToType(state);
3370
3371
107M
    if (!D.isInvalidType() && 
D.getDeclSpec().isTypeSpecOwned()107M
) {
3372
459k
      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3373
      // Owned declaration is embedded in declarator.
3374
459k
      OwnedTagDecl->setEmbeddedInDeclarator(true);
3375
459k
    }
3376
107M
    break;
3377
3378
263k
  case UnqualifiedIdKind::IK_ConstructorName:
3379
263k
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
3380
304k
  case UnqualifiedIdKind::IK_DestructorName:
3381
    // Constructors and destructors don't have return types. Use
3382
    // "void" instead.
3383
304k
    T = SemaRef.Context.VoidTy;
3384
304k
    processTypeAttrs(state, T, TAL_DeclSpec,
3385
304k
                     D.getMutableDeclSpec().getAttributes());
3386
304k
    break;
3387
3388
537
  case UnqualifiedIdKind::IK_DeductionGuideName:
3389
    // Deduction guides have a trailing return type and no type in their
3390
    // decl-specifier sequence. Use a placeholder return type for now.
3391
537
    T = SemaRef.Context.DependentTy;
3392
537
    break;
3393
3394
12.4k
  case UnqualifiedIdKind::IK_ConversionFunctionId:
3395
    // The result type of a conversion function is the type that it
3396
    // converts to.
3397
12.4k
    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3398
12.4k
                                  &ReturnTypeInfo);
3399
12.4k
    break;
3400
107M
  }
3401
3402
107M
  if (!D.getAttributes().empty())
3403
2.08M
    distributeTypeAttrsFromDeclarator(state, T);
3404
3405
  // Find the deduced type in this type. Look in the trailing return type if we
3406
  // have one, otherwise in the DeclSpec type.
3407
  // FIXME: The standard wording doesn't currently describe this.
3408
107M
  DeducedType *Deduced = T->getContainedDeducedType();
3409
107M
  bool DeducedIsTrailingReturnType = false;
3410
107M
  if (Deduced && 
isa<AutoType>(Deduced)46.4k
&&
D.hasTrailingReturnType()45.4k
) {
3411
11.5k
    QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3412
11.5k
    Deduced = T.isNull() ? 
nullptr47
:
T->getContainedDeducedType()11.4k
;
3413
11.5k
    DeducedIsTrailingReturnType = true;
3414
11.5k
  }
3415
3416
  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3417
107M
  if (Deduced) {
3418
35.1k
    AutoType *Auto = dyn_cast<AutoType>(Deduced);
3419
35.1k
    int Error = -1;
3420
3421
    // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3422
    // class template argument deduction)?
3423
35.1k
    bool IsCXXAutoType =
3424
35.1k
        (Auto && 
Auto->getKeyword() != AutoTypeKeyword::GNUAutoType34.1k
);
3425
35.1k
    bool IsDeducedReturnType = false;
3426
3427
35.1k
    switch (D.getContext()) {
3428
3.71k
    case DeclaratorContext::LambdaExpr:
3429
      // Declared return type of a lambda-declarator is implicit and is always
3430
      // 'auto'.
3431
3.71k
      break;
3432
0
    case DeclaratorContext::ObjCParameter:
3433
0
    case DeclaratorContext::ObjCResult:
3434
0
      Error = 0;
3435
0
      break;
3436
2
    case DeclaratorContext::RequiresExpr:
3437
2
      Error = 22;
3438
2
      break;
3439
151
    case DeclaratorContext::Prototype:
3440
2.33k
    case DeclaratorContext::LambdaExprParameter: {
3441
2.33k
      InventedTemplateParameterInfo *Info = nullptr;
3442
2.33k
      if (D.getContext() == DeclaratorContext::Prototype) {
3443
        // With concepts we allow 'auto' in function parameters.
3444
151
        if (!SemaRef.getLangOpts().CPlusPlus20 || 
!Auto138
||
3445
151
            
Auto->getKeyword() != AutoTypeKeyword::Auto137
) {
3446
18
          Error = 0;
3447
18
          break;
3448
133
        } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3449
4
          Error = 21;
3450
4
          break;
3451
4
        }
3452
3453
129
        Info = &SemaRef.InventedParameterInfos.back();
3454
2.18k
      } else {
3455
        // In C++14, generic lambdas allow 'auto' in their parameters.
3456
2.18k
        if (!SemaRef.getLangOpts().CPlusPlus14 || 
!Auto2.18k
||
3457
2.18k
            
Auto->getKeyword() != AutoTypeKeyword::Auto2.18k
) {
3458
4
          Error = 16;
3459
4
          break;
3460
4
        }
3461
2.18k
        Info = SemaRef.getCurLambda();
3462
2.18k
        assert(Info && "No LambdaScopeInfo on the stack!");
3463
2.18k
      }
3464
3465
      // We'll deal with inventing template parameters for 'auto' in trailing
3466
      // return types when we pick up the trailing return type when processing
3467
      // the function chunk.
3468
2.31k
      if (!DeducedIsTrailingReturnType)
3469
2.30k
        T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3470
2.31k
      break;
3471
2.33k
    }
3472
821
    case DeclaratorContext::Member: {
3473
821
      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3474
821
          
D.isFunctionDeclarator()560
)
3475
800
        break;
3476
21
      bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3477
21
      if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3478
4
        Error = 6; // Interface member.
3479
17
      } else {
3480
17
        switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3481
0
        case TTK_Enum: llvm_unreachable("unhandled tag kind");
3482
13
        case TTK_Struct: Error = Cxx ? 
112
:
21
; /* Struct member */ break;
3483
0
        case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
3484
4
        case TTK_Class:  Error = 5; /* Class member */ break;
3485
0
        case TTK_Interface: Error = 6; /* Interface member */ break;
3486
17
        }
3487
17
      }
3488
21
      if (D.getDeclSpec().isFriendSpecified())
3489
6
        Error = 20; // Friend type
3490
21
      break;
3491
21
    }
3492
8
    case DeclaratorContext::CXXCatch:
3493
9
    case DeclaratorContext::ObjCCatch:
3494
9
      Error = 7; // Exception declaration
3495
9
      break;
3496
215
    case DeclaratorContext::TemplateParam:
3497
215
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3498
215
          
!SemaRef.getLangOpts().CPlusPlus2019
)
3499
2
        Error = 19; // Template parameter (until C++20)
3500
213
      else if (!SemaRef.getLangOpts().CPlusPlus17)
3501
5
        Error = 8; // Template parameter (until C++17)
3502
215
      break;
3503
0
    case DeclaratorContext::BlockLiteral:
3504
0
      Error = 9; // Block literal
3505
0
      break;
3506
524
    case DeclaratorContext::TemplateArg:
3507
      // Within a template argument list, a deduced template specialization
3508
      // type will be reinterpreted as a template template argument.
3509
524
      if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3510
524
          
!D.getNumTypeObjects()512
&&
3511
524
          
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier511
)
3512
510
        break;
3513
524
      
LLVM_FALLTHROUGH14
;14
3514
15
    case DeclaratorContext::TemplateTypeArg:
3515
15
      Error = 10; // Template type argument
3516
15
      break;
3517
13
    case DeclaratorContext::AliasDecl:
3518
13
    case DeclaratorContext::AliasTemplate:
3519
13
      Error = 12; // Type alias
3520
13
      break;
3521
191
    case DeclaratorContext::TrailingReturn:
3522
238
    case DeclaratorContext::TrailingReturnVar:
3523
238
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType230
)
3524
9
        Error = 13; // Function return type
3525
238
      IsDeducedReturnType = true;
3526
238
      break;
3527
140
    case DeclaratorContext::ConversionId:
3528
140
      if (!SemaRef.getLangOpts().CPlusPlus14 || 
!IsCXXAutoType138
)
3529
6
        Error = 14; // conversion-type-id
3530
140
      IsDeducedReturnType = true;
3531
140
      break;
3532
135
    case DeclaratorContext::FunctionalCast:
3533
135
      if (isa<DeducedTemplateSpecializationType>(Deduced))
3534
83
        break;
3535
52
      if (SemaRef.getLangOpts().CPlusPlus2b && 
IsCXXAutoType48
&&
3536
52
          
!Auto->isDecltypeAuto()48
)
3537
48
        break; // auto(x)
3538
52
      
LLVM_FALLTHROUGH4
;4
3539
43
    case DeclaratorContext::TypeName:
3540
43
      Error = 15; // Generic
3541
43
      break;
3542
3.79k
    case DeclaratorContext::File:
3543
26.0k
    case DeclaratorContext::Block:
3544
26.7k
    case DeclaratorContext::ForInit:
3545
26.7k
    case DeclaratorContext::SelectionInit:
3546
26.8k
    case DeclaratorContext::Condition:
3547
      // FIXME: P0091R3 (erroneously) does not permit class template argument
3548
      // deduction in conditions, for-init-statements, and other declarations
3549
      // that are not simple-declarations.
3550
26.8k
      break;
3551
93
    case DeclaratorContext::CXXNew:
3552
      // FIXME: P0091R3 does not permit class template argument deduction here,
3553
      // but we follow GCC and allow it anyway.
3554
93
      if (!IsCXXAutoType && 
!isa<DeducedTemplateSpecializationType>(Deduced)18
)
3555
1
        Error = 17; // 'new' type
3556
93
      break;
3557
1
    case DeclaratorContext::KNRTypeList:
3558
1
      Error = 18; // K&R function parameter
3559
1
      break;
3560
35.1k
    }
3561
3562
35.1k
    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3563
10
      Error = 11;
3564
3565
    // In Objective-C it is an error to use 'auto' on a function declarator
3566
    // (and everywhere for '__auto_type').
3567
35.1k
    if (D.isFunctionDeclarator() &&
3568
35.1k
        
(5.77k
!SemaRef.getLangOpts().CPlusPlus115.77k
||
!IsCXXAutoType5.77k
))
3569
7
      Error = 13;
3570
3571
35.1k
    SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3572
35.1k
    if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3573
62
      AutoRange = D.getName().getSourceRange();
3574
3575
35.1k
    if (Error != -1) {
3576
169
      unsigned Kind;
3577
169
      if (Auto) {
3578
126
        switch (Auto->getKeyword()) {
3579
102
        case AutoTypeKeyword::Auto: Kind = 0; break;
3580
14
        case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3581
10
        case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3582
126
        }
3583
126
      } else {
3584
43
        assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3585
43
               "unknown auto type");
3586
0
        Kind = 3;
3587
43
      }
3588
3589
169
      auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3590
169
      TemplateName TN = DTST ? 
DTST->getTemplateName()43
:
TemplateName()126
;
3591
3592
169
      SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3593
169
        << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3594
169
        << QualType(Deduced, 0) << AutoRange;
3595
169
      if (auto *TD = TN.getAsTemplateDecl())
3596
43
        SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3597
3598
169
      T = SemaRef.Context.IntTy;
3599
169
      D.setInvalidType(true);
3600
34.9k
    } else if (Auto && 
D.getContext() != DeclaratorContext::LambdaExpr34.0k
) {
3601
      // If there was a trailing return type, we already got
3602
      // warn_cxx98_compat_trailing_return_type in the parser.
3603
30.2k
      SemaRef.Diag(AutoRange.getBegin(),
3604
30.2k
                   D.getContext() == DeclaratorContext::LambdaExprParameter
3605
30.2k
                       ? 
diag::warn_cxx11_compat_generic_lambda2.18k
3606
30.2k
                   : 
IsDeducedReturnType28.1k
3607
28.1k
                       ? 
diag::warn_cxx11_compat_deduced_return_type363
3608
28.1k
                       : 
diag::warn_cxx98_compat_auto_type_specifier27.7k
)
3609
30.2k
          << AutoRange;
3610
30.2k
    }
3611
35.1k
  }
3612
3613
107M
  if (SemaRef.getLangOpts().CPlusPlus &&
3614
107M
      
OwnedTagDecl45.9M
&&
OwnedTagDecl->isCompleteDefinition()89.7k
) {
3615
    // Check the contexts where C++ forbids the declaration of a new class
3616
    // or enumeration in a type-specifier-seq.
3617
69.8k
    unsigned DiagID = 0;
3618
69.8k
    switch (D.getContext()) {
3619
0
    case DeclaratorContext::TrailingReturn:
3620
0
    case DeclaratorContext::TrailingReturnVar:
3621
      // Class and enumeration definitions are syntactically not allowed in
3622
      // trailing return types.
3623
0
      llvm_unreachable("parser should not have allowed this");
3624
0
      break;
3625
56.3k
    case DeclaratorContext::File:
3626
64.5k
    case DeclaratorContext::Member:
3627
69.7k
    case DeclaratorContext::Block:
3628
69.7k
    case DeclaratorContext::ForInit:
3629
69.7k
    case DeclaratorContext::SelectionInit:
3630
69.7k
    case DeclaratorContext::BlockLiteral:
3631
69.7k
    case DeclaratorContext::LambdaExpr:
3632
      // C++11 [dcl.type]p3:
3633
      //   A type-specifier-seq shall not define a class or enumeration unless
3634
      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
3635
      //   the declaration of a template-declaration.
3636
69.8k
    case DeclaratorContext::AliasDecl:
3637
69.8k
      break;
3638
5
    case DeclaratorContext::AliasTemplate:
3639
5
      DiagID = diag::err_type_defined_in_alias_template;
3640
5
      break;
3641
43
    case DeclaratorContext::TypeName:
3642
43
    case DeclaratorContext::FunctionalCast:
3643
43
    case DeclaratorContext::ConversionId:
3644
43
    case DeclaratorContext::TemplateParam:
3645
43
    case DeclaratorContext::CXXNew:
3646
43
    case DeclaratorContext::CXXCatch:
3647
43
    case DeclaratorContext::ObjCCatch:
3648
43
    case DeclaratorContext::TemplateArg:
3649
43
    case DeclaratorContext::TemplateTypeArg:
3650
43
      DiagID = diag::err_type_defined_in_type_specifier;
3651
43
      break;
3652
5
    case DeclaratorContext::Prototype:
3653
5
    case DeclaratorContext::LambdaExprParameter:
3654
5
    case DeclaratorContext::ObjCParameter:
3655
6
    case DeclaratorContext::ObjCResult:
3656
6
    case DeclaratorContext::KNRTypeList:
3657
6
    case DeclaratorContext::RequiresExpr:
3658
      // C++ [dcl.fct]p6:
3659
      //   Types shall not be defined in return or parameter types.
3660
6
      DiagID = diag::err_type_defined_in_param_type;
3661
6
      break;
3662
15
    case DeclaratorContext::Condition:
3663
      // C++ 6.4p2:
3664
      // The type-specifier-seq shall not contain typedef and shall not declare
3665
      // a new class or enumeration.
3666
15
      DiagID = diag::err_type_defined_in_condition;
3667
15
      break;
3668
69.8k
    }
3669
3670
69.8k
    if (DiagID != 0) {
3671
69
      SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3672
69
          << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3673
69
      D.setInvalidType(true);
3674
69
    }
3675
69.8k
  }
3676
3677
107M
  assert(!T.isNull() && "This function should not return a null type");
3678
0
  return T;
3679
107M
}
3680
3681
/// Produce an appropriate diagnostic for an ambiguity between a function
3682
/// declarator and a C++ direct-initializer.
3683
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3684
16.7k
                                       DeclaratorChunk &DeclType, QualType RT) {
3685
16.7k
  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3686
16.7k
  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3687
3688
  // If the return type is void there is no ambiguity.
3689
16.7k
  if (RT->isVoidType())
3690
9.54k
    return;
3691
3692
  // An initializer for a non-class type can have at most one argument.
3693
7.18k
  if (!RT->isRecordType() && 
FTI.NumParams > 16.60k
)
3694
439
    return;
3695
3696
  // An initializer for a reference must have exactly one argument.
3697
6.74k
  if (RT->isReferenceType() && 
FTI.NumParams != 1493
)
3698
434
    return;
3699
3700
  // Only warn if this declarator is declaring a function at block scope, and
3701
  // doesn't have a storage class (such as 'extern') specified.
3702
6.31k
  if (!D.isFunctionDeclarator() ||
3703
6.31k
      
D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration6.25k
||
3704
6.31k
      
!S.CurContext->isFunctionOrMethod()6.21k
||
3705
6.31k
      
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified142
)
3706
6.17k
    return;
3707
3708
  // Inside a condition, a direct initializer is not permitted. We allow one to
3709
  // be parsed in order to give better diagnostics in condition parsing.
3710
136
  if (D.getContext() == DeclaratorContext::Condition)
3711
4
    return;
3712
3713
132
  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3714
3715
132
  S.Diag(DeclType.Loc,
3716
132
         FTI.NumParams ? 
diag::warn_parens_disambiguated_as_function_declaration24
3717
132
                       : 
diag::warn_empty_parens_are_function_decl108
)
3718
132
      << ParenRange;
3719
3720
  // If the declaration looks like:
3721
  //   T var1,
3722
  //   f();
3723
  // and name lookup finds a function named 'f', then the ',' was
3724
  // probably intended to be a ';'.
3725
132
  if (!D.isFirstDeclarator() && 
D.getIdentifier()19
) {
3726
19
    FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3727
19
    FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3728
19
    if (Comma.getFileID() != Name.getFileID() ||
3729
19
        Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3730
19
      LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3731
19
                          Sema::LookupOrdinaryName);
3732
19
      if (S.LookupName(Result, S.getCurScope()))
3733
13
        S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3734
13
          << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3735
13
          << D.getIdentifier();
3736
19
      Result.suppressDiagnostics();
3737
19
    }
3738
19
  }
3739
3740
132
  if (FTI.NumParams > 0) {
3741
    // For a declaration with parameters, eg. "T var(T());", suggest adding
3742
    // parens around the first parameter to turn the declaration into a
3743
    // variable declaration.
3744
24
    SourceRange Range = FTI.Params[0].Param->getSourceRange();
3745
24
    SourceLocation B = Range.getBegin();
3746
24
    SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3747
    // FIXME: Maybe we should suggest adding braces instead of parens
3748
    // in C++11 for classes that don't have an initializer_list constructor.
3749
24
    S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3750
24
      << FixItHint::CreateInsertion(B, "(")
3751
24
      << FixItHint::CreateInsertion(E, ")");
3752
108
  } else {
3753
    // For a declaration without parameters, eg. "T var();", suggest replacing
3754
    // the parens with an initializer to turn the declaration into a variable
3755
    // declaration.
3756
108
    const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3757
3758
    // Empty parens mean value-initialization, and no parens mean
3759
    // default initialization. These are equivalent if the default
3760
    // constructor is user-provided or if zero-initialization is a
3761
    // no-op.
3762
108
    if (RD && 
RD->hasDefinition()31
&&
3763
108
        
(27
RD->isEmpty()27
||
RD->hasUserProvidedDefaultConstructor()18
))
3764
13
      S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3765
13
        << FixItHint::CreateRemoval(ParenRange);
3766
95
    else {
3767
95
      std::string Init =
3768
95
          S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3769
95
      if (Init.empty() && 
S.LangOpts.CPlusPlus1112
)
3770
9
        Init = "{}";
3771
95
      if (!Init.empty())
3772
92
        S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3773
92
          << FixItHint::CreateReplacement(ParenRange, Init);
3774
95
    }
3775
108
  }
3776
132
}
3777
3778
/// Produce an appropriate diagnostic for a declarator with top-level
3779
/// parentheses.
3780
450
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3781
450
  DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3782
450
  assert(Paren.Kind == DeclaratorChunk::Paren &&
3783
450
         "do not have redundant top-level parentheses");
3784
3785
  // This is a syntactic check; we're not interested in cases that arise
3786
  // during template instantiation.
3787
450
  if (S.inTemplateInstantiation())
3788
0
    return;
3789
3790
  // Check whether this could be intended to be a construction of a temporary
3791
  // object in C++ via a function-style cast.
3792
450
  bool CouldBeTemporaryObject =
3793
450
      S.getLangOpts().CPlusPlus && 
D.isExpressionContext()419
&&
3794
450
      
!D.isInvalidType()142
&&
D.getIdentifier()126
&&
3795
450
      
D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier120
&&
3796
450
      
(109
T->isRecordType()109
||
T->isDependentType()64
) &&
3797
450
      
D.getDeclSpec().getTypeQualifiers() == 046
&&
D.isFirstDeclarator()46
;
3798
3799
450
  bool StartsWithDeclaratorId = true;
3800
738
  for (auto &C : D.type_objects()) {
3801
738
    switch (C.Kind) {
3802
509
    case DeclaratorChunk::Paren:
3803
509
      if (&C == &Paren)
3804
450
        continue;
3805
509
      
LLVM_FALLTHROUGH59
;59
3806
94
    case DeclaratorChunk::Pointer:
3807
94
      StartsWithDeclaratorId = false;
3808
94
      continue;
3809
3810
18
    case DeclaratorChunk::Array:
3811
18
      if (!C.Arr.NumElts)
3812
0
        CouldBeTemporaryObject = false;
3813
18
      continue;
3814
3815
9
    case DeclaratorChunk::Reference:
3816
      // FIXME: Suppress the warning here if there is no initializer; we're
3817
      // going to give an error anyway.
3818
      // We assume that something like 'T (&x) = y;' is highly likely to not
3819
      // be intended to be a temporary object.
3820
9
      CouldBeTemporaryObject = false;
3821
9
      StartsWithDeclaratorId = false;
3822
9
      continue;
3823
3824
53
    case DeclaratorChunk::Function:
3825
      // In a new-type-id, function chunks require parentheses.
3826
53
      if (D.getContext() == DeclaratorContext::CXXNew)
3827
0
        return;
3828
      // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3829
      // redundant-parens warning, but we don't know whether the function
3830
      // chunk was syntactically valid as an expression here.
3831
53
      CouldBeTemporaryObject = false;
3832
53
      continue;
3833
3834
0
    case DeclaratorChunk::BlockPointer:
3835
114
    case DeclaratorChunk::MemberPointer:
3836
114
    case DeclaratorChunk::Pipe:
3837
      // These cannot appear in expressions.
3838
114
      CouldBeTemporaryObject = false;
3839
114
      StartsWithDeclaratorId = false;
3840
114
      continue;
3841
738
    }
3842
738
  }
3843
3844
  // FIXME: If there is an initializer, assume that this is not intended to be
3845
  // a construction of a temporary object.
3846
3847
  // Check whether the name has already been declared; if not, this is not a
3848
  // function-style cast.
3849
450
  if (CouldBeTemporaryObject) {
3850
33
    LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3851
33
                        Sema::LookupOrdinaryName);
3852
33
    if (!S.LookupName(Result, S.getCurScope()))
3853
18
      CouldBeTemporaryObject = false;
3854
33
    Result.suppressDiagnostics();
3855
33
  }
3856
3857
450
  SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3858
3859
450
  if (!CouldBeTemporaryObject) {
3860
    // If we have A (::B), the parentheses affect the meaning of the program.
3861
    // Suppress the warning in that case. Don't bother looking at the DeclSpec
3862
    // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3863
    // formally unambiguous.
3864
435
    if (StartsWithDeclaratorId && 
D.getCXXScopeSpec().isValid()261
) {
3865
63
      for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3866
51
           
NNS = NNS->getPrefix()39
) {
3867
51
        if (NNS->getKind() == NestedNameSpecifier::Global)
3868
12
          return;
3869
51
      }
3870
24
    }
3871
3872
423
    S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3873
423
        << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3874
423
        << FixItHint::CreateRemoval(Paren.EndLoc);
3875
423
    return;
3876
435
  }
3877
3878
15
  S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3879
15
      << ParenRange << D.getIdentifier();
3880
15
  auto *RD = T->getAsCXXRecordDecl();
3881
15
  if (!RD || 
!RD->hasDefinition()14
||
RD->hasNonTrivialDestructor()14
)
3882
7
    S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3883
7
        << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3884
7
        << D.getIdentifier();
3885
  // FIXME: A cast to void is probably a better suggestion in cases where it's
3886
  // valid (when there is no initializer and we're not in a condition).
3887
15
  S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3888
15
      << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3889
15
      << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3890
15
  S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3891
15
      << FixItHint::CreateRemoval(Paren.Loc)
3892
15
      << FixItHint::CreateRemoval(Paren.EndLoc);
3893
15
}
3894
3895
/// Helper for figuring out the default CC for a function declarator type.  If
3896
/// this is the outermost chunk, then we can determine the CC from the
3897
/// declarator context.  If not, then this could be either a member function
3898
/// type or normal function type.
3899
static CallingConv getCCForDeclaratorChunk(
3900
    Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3901
24.7M
    const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3902
24.7M
  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3903
3904
  // Check for an explicit CC attribute.
3905
62.8k
  for (const ParsedAttr &AL : AttrList) {
3906
62.8k
    switch (AL.getKind()) {
3907
32.7k
    
CALLING_CONV_ATTRS_CASELIST375
: {
3908
      // Ignore attributes that don't validate or can't apply to the
3909
      // function type.  We'll diagnose the failure to apply them in
3910
      // handleFunctionTypeAttr.
3911
32.7k
      CallingConv CC;
3912
32.7k
      if (
!S.CheckCallingConvAttr(AL, CC)2.74k
&&
3913
2.74k
          
(2.70k
!FTI.isVariadic2.70k
||
supportsVariadicCall(CC)80
)) {
3914
2.68k
        return CC;
3915
2.68k
      }
3916
59
      break;
3917
32.7k
    }
3918
3919
60.1k
    default:
3920
60.1k
      break;
3921
62.8k
    }
3922
62.8k
  }
3923
3924
24.7M
  bool IsCXXInstanceMethod = false;
3925
3926
24.7M
  if (S.getLangOpts().CPlusPlus) {
3927
    // Look inwards through parentheses to see if this chunk will form a
3928
    // member pointer type or if we're the declarator.  Any type attributes
3929
    // between here and there will override the CC we choose here.
3930
10.6M
    unsigned I = ChunkIndex;
3931
10.6M
    bool FoundNonParen = false;
3932
10.8M
    while (I && 
!FoundNonParen217k
) {
3933
215k
      --I;
3934
215k
      if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3935
101k
        FoundNonParen = true;
3936
215k
    }
3937
3938
10.6M
    if (FoundNonParen) {
3939
      // If we're not the declarator, we're a regular function type unless we're
3940
      // in a member pointer.
3941
101k
      IsCXXInstanceMethod =
3942
101k
          D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3943
10.5M
    } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3944
      // This can only be a call operator for a lambda, which is an instance
3945
      // method.
3946
6.47k
      IsCXXInstanceMethod = true;
3947
10.5M
    } else {
3948
      // We're the innermost decl chunk, so must be a function declarator.
3949
10.5M
      assert(D.isFunctionDeclarator());
3950
3951
      // If we're inside a record, we're declaring a method, but it could be
3952
      // explicitly or implicitly static.
3953
0
      IsCXXInstanceMethod =
3954
10.5M
          D.isFirstDeclarationOfMember() &&
3955
10.5M
          
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef1.00M
&&
3956
10.5M
          
!D.isStaticMember()995k
;
3957
10.5M
    }
3958
10.6M
  }
3959
3960
0
  CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3961
24.7M
                                                         IsCXXInstanceMethod);
3962
3963
  // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3964
  // and AMDGPU targets, hence it cannot be treated as a calling
3965
  // convention attribute. This is the simplest place to infer
3966
  // calling convention for OpenCL kernels.
3967
24.7M
  if (S.getLangOpts().OpenCL) {
3968
430k
    for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3969
430k
      if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3970
1.07k
        CC = CC_OpenCLKernel;
3971
1.07k
        break;
3972
1.07k
      }
3973
430k
    }
3974
24.4M
  } else if (S.getLangOpts().CUDA) {
3975
    // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
3976
    // sure the kernels will be marked with the right calling convention so that
3977
    // they will be visible by the APIs that ingest SPIR-V.
3978
3.58k
    llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3979
3.58k
    if (Triple.getArch() == llvm::Triple::spirv32 ||
3980
3.58k
        
Triple.getArch() == llvm::Triple::spirv643.58k
) {
3981
11
      for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3982
11
        if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3983
5
          CC = CC_OpenCLKernel;
3984
5
          break;
3985
5
        }
3986
11
      }
3987
11
    }
3988
3.58k
  }
3989
3990
24.7M
  return CC;
3991
24.7M
}
3992
3993
namespace {
3994
  /// A simple notion of pointer kinds, which matches up with the various
3995
  /// pointer declarators.
3996
  enum class SimplePointerKind {
3997
    Pointer,
3998
    BlockPointer,
3999
    MemberPointer,
4000
    Array,
4001
  };
4002
} // end anonymous namespace
4003
4004
2.57M
IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4005
2.57M
  switch (nullability) {
4006
2.11M
  case NullabilityKind::NonNull:
4007
2.11M
    if (!Ident__Nonnull)
4008
1.02k
      Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4009
2.11M
    return Ident__Nonnull;
4010
4011
449k
  case NullabilityKind::Nullable:
4012
449k
    if (!Ident__Nullable)
4013
445
      Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4014
449k
    return Ident__Nullable;
4015
4016
0
  case NullabilityKind::NullableResult:
4017
0
    if (!Ident__Nullable_result)
4018
0
      Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4019
0
    return Ident__Nullable_result;
4020
4021
15.1k
  case NullabilityKind::Unspecified:
4022
15.1k
    if (!Ident__Null_unspecified)
4023
235
      Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4024
15.1k
    return Ident__Null_unspecified;
4025
2.57M
  }
4026
0
  llvm_unreachable("Unknown nullability kind.");
4027
0
}
4028
4029
/// Retrieve the identifier "NSError".
4030
1.12M
IdentifierInfo *Sema::getNSErrorIdent() {
4031
1.12M
  if (!Ident_NSError)
4032
2.64k
    Ident_NSError = PP.getIdentifierInfo("NSError");
4033
4034
1.12M
  return Ident_NSError;
4035
1.12M
}
4036
4037
/// Check whether there is a nullability attribute of any kind in the given
4038
/// attribute list.
4039
10.5M
static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4040
10.5M
  for (const ParsedAttr &AL : attrs) {
4041
859k
    if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4042
859k
        
AL.getKind() == ParsedAttr::AT_TypeNullable790k
||
4043
859k
        
AL.getKind() == ParsedAttr::AT_TypeNullableResult341k
||
4044
859k
        
AL.getKind() == ParsedAttr::AT_TypeNullUnspecified341k
)
4045
541k
      return true;
4046
859k
  }
4047
4048
10.0M
  return false;
4049
10.5M
}
4050
4051
namespace {
4052
  /// Describes the kind of a pointer a declarator describes.
4053
  enum class PointerDeclaratorKind {
4054
    // Not a pointer.
4055
    NonPointer,
4056
    // Single-level pointer.
4057
    SingleLevelPointer,
4058
    // Multi-level pointer (of any pointer kind).
4059
    MultiLevelPointer,
4060
    // CFFooRef*
4061
    MaybePointerToCFRef,
4062
    // CFErrorRef*
4063
    CFErrorRefPointer,
4064
    // NSError**
4065
    NSErrorPointerPointer,
4066
  };
4067
4068
  /// Describes a declarator chunk wrapping a pointer that marks inference as
4069
  /// unexpected.
4070
  // These values must be kept in sync with diagnostics.
4071
  enum class PointerWrappingDeclaratorKind {
4072
    /// Pointer is top-level.
4073
    None = -1,
4074
    /// Pointer is an array element.
4075
    Array = 0,
4076
    /// Pointer is the referent type of a C++ reference.
4077
    Reference = 1
4078
  };
4079
} // end anonymous namespace
4080
4081
/// Classify the given declarator, whose type-specified is \c type, based on
4082
/// what kind of pointer it refers to.
4083
///
4084
/// This is used to determine the default nullability.
4085
static PointerDeclaratorKind
4086
classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4087
94.7M
                          PointerWrappingDeclaratorKind &wrappingKind) {
4088
94.7M
  unsigned numNormalPointers = 0;
4089
4090
  // For any dependent type, we consider it a non-pointer.
4091
94.7M
  if (type->isDependentType())
4092
2.08M
    return PointerDeclaratorKind::NonPointer;
4093
4094
  // Look through the declarator chunks to identify pointers.
4095
123M
  
for (unsigned i = 0, n = declarator.getNumTypeObjects(); 92.6M
i != n;
++i31.1M
) {
4096
31.2M
    DeclaratorChunk &chunk = declarator.getTypeObject(i);
4097
31.2M
    switch (chunk.Kind) {
4098
243k
    case DeclaratorChunk::Array:
4099
243k
      if (numNormalPointers == 0)
4100
243k
        wrappingKind = PointerWrappingDeclaratorKind::Array;
4101
243k
      break;
4102
4103
23.9M
    case DeclaratorChunk::Function:
4104
23.9M
    case DeclaratorChunk::Pipe:
4105
23.9M
      break;
4106
4107
49.1k
    case DeclaratorChunk::BlockPointer:
4108
51.0k
    case DeclaratorChunk::MemberPointer:
4109
51.0k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer58
4110
51.0k
                                   : 
PointerDeclaratorKind::SingleLevelPointer50.9k
;
4111
4112
121k
    case DeclaratorChunk::Paren:
4113
121k
      break;
4114
4115
207k
    case DeclaratorChunk::Reference:
4116
207k
      if (numNormalPointers == 0)
4117
206k
        wrappingKind = PointerWrappingDeclaratorKind::Reference;
4118
207k
      break;
4119
4120
6.64M
    case DeclaratorChunk::Pointer:
4121
6.64M
      ++numNormalPointers;
4122
6.64M
      if (numNormalPointers > 2)
4123
560
        return PointerDeclaratorKind::MultiLevelPointer;
4124
6.64M
      break;
4125
31.2M
    }
4126
31.2M
  }
4127
4128
  // Then, dig into the type specifier itself.
4129
92.6M
  unsigned numTypeSpecifierPointers = 0;
4130
95.0M
  do {
4131
    // Decompose normal pointers.
4132
95.0M
    if (auto ptrType = type->getAs<PointerType>()) {
4133
2.37M
      ++numNormalPointers;
4134
4135
2.37M
      if (numNormalPointers > 2)
4136
4.96k
        return PointerDeclaratorKind::MultiLevelPointer;
4137
4138
2.37M
      type = ptrType->getPointeeType();
4139
2.37M
      ++numTypeSpecifierPointers;
4140
2.37M
      continue;
4141
2.37M
    }
4142
4143
    // Decompose block pointers.
4144
92.6M
    if (type->getAs<BlockPointerType>()) {
4145
22.9k
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer14
4146
22.9k
                                   : 
PointerDeclaratorKind::SingleLevelPointer22.9k
;
4147
22.9k
    }
4148
4149
    // Decompose member pointers.
4150
92.6M
    if (type->getAs<MemberPointerType>()) {
4151
797
      return numNormalPointers > 0 ? 
PointerDeclaratorKind::MultiLevelPointer9
4152
797
                                   : 
PointerDeclaratorKind::SingleLevelPointer788
;
4153
797
    }
4154
4155
    // Look at Objective-C object pointers.
4156
92.6M
    if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4157
502k
      ++numNormalPointers;
4158
502k
      ++numTypeSpecifierPointers;
4159
4160
      // If this is NSError**, report that.
4161
502k
      if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4162
211k
        if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4163
211k
            
numNormalPointers == 22
&&
numTypeSpecifierPointers < 22
) {
4164
1
          return PointerDeclaratorKind::NSErrorPointerPointer;
4165
1
        }
4166
211k
      }
4167
4168
502k
      break;
4169
502k
    }
4170
4171
    // Look at Objective-C class types.
4172
92.1M
    if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4173
903k
      if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4174
46.4k
        if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 230.9k
)
4175
30.9k
          return PointerDeclaratorKind::NSErrorPointerPointer;
4176
46.4k
      }
4177
4178
872k
      break;
4179
903k
    }
4180
4181
    // If at this point we haven't seen a pointer, we won't see one.
4182
91.2M
    if (numNormalPointers == 0)
4183
83.4M
      return PointerDeclaratorKind::NonPointer;
4184
4185
7.79M
    if (auto recordType = type->getAs<RecordType>()) {
4186
2.59M
      RecordDecl *recordDecl = recordType->getDecl();
4187
4188
      // If this is CFErrorRef*, report it as such.
4189
2.59M
      if (numNormalPointers == 2 && 
numTypeSpecifierPointers < 2140k
&&
4190
2.59M
          
S.isCFError(recordDecl)132k
) {
4191
18.8k
        return PointerDeclaratorKind::CFErrorRefPointer;
4192
18.8k
      }
4193
2.57M
      break;
4194
2.59M
    }
4195
4196
5.19M
    break;
4197
7.79M
  } while (
true2.37M
);
4198
4199
9.15M
  switch (numNormalPointers) {
4200
42
  case 0:
4201
42
    return PointerDeclaratorKind::NonPointer;
4202
4203
8.89M
  case 1:
4204
8.89M
    return PointerDeclaratorKind::SingleLevelPointer;
4205
4206
255k
  case 2:
4207
255k
    return PointerDeclaratorKind::MaybePointerToCFRef;
4208
4209
11
  default:
4210
11
    return PointerDeclaratorKind::MultiLevelPointer;
4211
9.15M
  }
4212
9.15M
}
4213
4214
132k
bool Sema::isCFError(RecordDecl *RD) {
4215
  // If we already know about CFError, test it directly.
4216
132k
  if (CFError)
4217
122k
    return CFError == RD;
4218
4219
  // Check whether this is CFError, which we identify based on its bridge to
4220
  // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4221
  // declared with "objc_bridge_mutable", so look for either one of the two
4222
  // attributes.
4223
9.76k
  if (RD->getTagKind() == TTK_Struct) {
4224
9.71k
    IdentifierInfo *bridgedType = nullptr;
4225
9.71k
    if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4226
1.56k
      bridgedType = bridgeAttr->getBridgedType();
4227
8.14k
    else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4228
439
      bridgedType = bridgeAttr->getBridgedType();
4229
4230
9.71k
    if (bridgedType == getNSErrorIdent()) {
4231
267
      CFError = RD;
4232
267
      return true;
4233
267
    }
4234
9.71k
  }
4235
4236
9.49k
  return false;
4237
9.76k
}
4238
4239
static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4240
13.7M
                                                    SourceLocation loc) {
4241
  // If we're anywhere in a function, method, or closure context, don't perform
4242
  // completeness checks.
4243
18.3M
  for (DeclContext *ctx = S.CurContext; ctx; 
ctx = ctx->getParent()4.65M
) {
4244
18.3M
    if (ctx->isFunctionOrMethod())
4245
31.2k
      return FileID();
4246
4247
18.3M
    if (ctx->isFileContext())
4248
13.7M
      break;
4249
18.3M
  }
4250
4251
  // We only care about the expansion location.
4252
13.7M
  loc = S.SourceMgr.getExpansionLoc(loc);
4253
13.7M
  FileID file = S.SourceMgr.getFileID(loc);
4254
13.7M
  if (file.isInvalid())
4255
505
    return FileID();
4256
4257
  // Retrieve file information.
4258
13.7M
  bool invalid = false;
4259
13.7M
  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4260
13.7M
  if (invalid || !sloc.isFile())
4261
0
    return FileID();
4262
4263
  // We don't want to perform completeness checks on the main file or in
4264
  // system headers.
4265
13.7M
  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4266
13.7M
  if (fileInfo.getIncludeLoc().isInvalid())
4267
189k
    return FileID();
4268
13.5M
  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4269
13.5M
      
S.Diags.getSuppressSystemWarnings()13.4M
) {
4270
13.4M
    return FileID();
4271
13.4M
  }
4272
4273
38.8k
  return file;
4274
13.5M
}
4275
4276
/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4277
/// taking into account whitespace before and after.
4278
template <typename DiagBuilderT>
4279
static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4280
                             SourceLocation PointerLoc,
4281
898
                             NullabilityKind Nullability) {
4282
898
  assert(PointerLoc.isValid());
4283
898
  if (PointerLoc.isMacroID())
4284
2
    return;
4285
4286
896
  SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4287
896
  if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4288
0
    return;
4289
4290
896
  const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4291
896
  if (!NextChar)
4292
0
    return;
4293
4294
896
  SmallString<32> InsertionTextBuf{" "};
4295
896
  InsertionTextBuf += getNullabilitySpelling(Nullability);
4296
896
  InsertionTextBuf += " ";
4297
896
  StringRef InsertionText = InsertionTextBuf.str();
4298
4299
896
  if (isWhitespace(*NextChar)) {
4300
152
    InsertionText = InsertionText.drop_back();
4301
744
  } else if (NextChar[-1] == '[') {
4302
152
    if (NextChar[0] == ']')
4303
120
      InsertionText = InsertionText.drop_back().drop_front();
4304
32
    else
4305
32
      InsertionText = InsertionText.drop_front();
4306
592
  } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4307
592
             
!isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)428
) {
4308
188
    InsertionText = InsertionText.drop_back().drop_front();
4309
188
  }
4310
4311
896
  Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4312
896
}
4313
4314
static void emitNullabilityConsistencyWarning(Sema &S,
4315
                                              SimplePointerKind PointerKind,
4316
                                              SourceLocation PointerLoc,
4317
429
                                              SourceLocation PointerEndLoc) {
4318
429
  assert(PointerLoc.isValid());
4319
4320
429
  if (PointerKind == SimplePointerKind::Array) {
4321
82
    S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4322
347
  } else {
4323
347
    S.Diag(PointerLoc, diag::warn_nullability_missing)
4324
347
      << static_cast<unsigned>(PointerKind);
4325
347
  }
4326
4327
429
  auto FixItLoc = PointerEndLoc.isValid() ? 
PointerEndLoc194
:
PointerLoc235
;
4328
429
  if (FixItLoc.isMacroID())
4329
6
    return;
4330
4331
846
  
auto addFixIt = [&](NullabilityKind Nullability) 423
{
4332
846
    auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4333
846
    Diag << static_cast<unsigned>(Nullability);
4334
846
    Diag << static_cast<unsigned>(PointerKind);
4335
846
    fixItNullability(S, Diag, FixItLoc, Nullability);
4336
846
  };
4337
423
  addFixIt(NullabilityKind::Nullable);
4338
423
  addFixIt(NullabilityKind::NonNull);
4339
423
}
4340
4341
/// Complains about missing nullability if the file containing \p pointerLoc
4342
/// has other uses of nullability (either the keywords or the \c assume_nonnull
4343
/// pragma).
4344
///
4345
/// If the file has \e not seen other uses of nullability, this particular
4346
/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4347
static void
4348
checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4349
                            SourceLocation pointerLoc,
4350
6.61M
                            SourceLocation pointerEndLoc = SourceLocation()) {
4351
  // Determine which file we're performing consistency checking for.
4352
6.61M
  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4353
6.61M
  if (file.isInvalid())
4354
6.57M
    return;
4355
4356
  // If we haven't seen any type nullability in this file, we won't warn now
4357
  // about anything.
4358
37.8k
  FileNullability &fileNullability = S.NullabilityMap[file];
4359
37.8k
  if (!fileNullability.SawTypeNullability) {
4360
    // If this is the first pointer declarator in the file, and the appropriate
4361
    // warning is on, record it in case we need to diagnose it retroactively.
4362
37.4k
    diag::kind diagKind;
4363
37.4k
    if (pointerKind == SimplePointerKind::Array)
4364
449
      diagKind = diag::warn_nullability_missing_array;
4365
36.9k
    else
4366
36.9k
      diagKind = diag::warn_nullability_missing;
4367
4368
37.4k
    if (fileNullability.PointerLoc.isInvalid() &&
4369
37.4k
        
!S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)20.5k
) {
4370
3.54k
      fileNullability.PointerLoc = pointerLoc;
4371
3.54k
      fileNullability.PointerEndLoc = pointerEndLoc;
4372
3.54k
      fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4373
3.54k
    }
4374
4375
37.4k
    return;
4376
37.4k
  }
4377
4378
  // Complain about missing nullability.
4379
411
  emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4380
411
}
4381
4382
/// Marks that a nullability feature has been used in the file containing
4383
/// \p loc.
4384
///
4385
/// If this file already had pointer types in it that were missing nullability,
4386
/// the first such instance is retroactively diagnosed.
4387
///
4388
/// \sa checkNullabilityConsistency
4389
7.12M
static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4390
7.12M
  FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4391
7.12M
  if (file.isInvalid())
4392
7.12M
    return;
4393
4394
961
  FileNullability &fileNullability = S.NullabilityMap[file];
4395
961
  if (fileNullability.SawTypeNullability)
4396
910
    return;
4397
51
  fileNullability.SawTypeNullability = true;
4398
4399
  // If we haven't seen any type nullability before, now we have. Retroactively
4400
  // diagnose the first unannotated pointer, if there was one.
4401
51
  if (fileNullability.PointerLoc.isInvalid())
4402
33
    return;
4403
4404
18
  auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4405
18
  emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4406
18
                                    fileNullability.PointerEndLoc);
4407
18
}
4408
4409
/// Returns true if any of the declarator chunks before \p endIndex include a
4410
/// level of indirection: array, pointer, reference, or pointer-to-member.
4411
///
4412
/// Because declarator chunks are stored in outer-to-inner order, testing
4413
/// every chunk before \p endIndex is testing all chunks that embed the current
4414
/// chunk as part of their type.
4415
///
4416
/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4417
/// end index, in which case all chunks are tested.
4418
1.63M
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4419
1.63M
  unsigned i = endIndex;
4420
1.64M
  while (i != 0) {
4421
    // Walk outwards along the declarator chunks.
4422
103k
    --i;
4423
103k
    const DeclaratorChunk &DC = D.getTypeObject(i);
4424
103k
    switch (DC.Kind) {
4425
6.00k
    case DeclaratorChunk::Paren:
4426
6.00k
      break;
4427
5.16k
    case DeclaratorChunk::Array:
4428
90.2k
    case DeclaratorChunk::Pointer:
4429
93.6k
    case DeclaratorChunk::Reference:
4430
93.6k
    case DeclaratorChunk::MemberPointer:
4431
93.6k
      return true;
4432
2.28k
    case DeclaratorChunk::Function:
4433
3.62k
    case DeclaratorChunk::BlockPointer:
4434
3.62k
    case DeclaratorChunk::Pipe:
4435
      // These are invalid anyway, so just ignore.
4436
3.62k
      break;
4437
103k
    }
4438
103k
  }
4439
1.54M
  return false;
4440
1.63M
}
4441
4442
85
static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4443
85
  return (Chunk.Kind == DeclaratorChunk::Pointer ||
4444
85
          
Chunk.Kind == DeclaratorChunk::Array14
);
4445
85
}
4446
4447
template<typename AttrT>
4448
3.27M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
3.27M
  AL.setUsedAsTypeAttr();
4450
3.27M
  return ::new (Ctx) AttrT(Ctx, AL);
4451
3.27M
}
SemaType.cpp:clang::ObjCInertUnsafeUnretainedAttr* createSimpleAttr<clang::ObjCInertUnsafeUnretainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
2.27k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
2.27k
  AL.setUsedAsTypeAttr();
4450
2.27k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
2.27k
}
SemaType.cpp:clang::ArmMveStrictPolymorphismAttr* createSimpleAttr<clang::ArmMveStrictPolymorphismAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
1.57k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
1.57k
  AL.setUsedAsTypeAttr();
4450
1.57k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
1.57k
}
SemaType.cpp:clang::LifetimeBoundAttr* createSimpleAttr<clang::LifetimeBoundAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
7
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
7
  AL.setUsedAsTypeAttr();
4450
7
  return ::new (Ctx) AttrT(Ctx, AL);
4451
7
}
SemaType.cpp:clang::NoDerefAttr* createSimpleAttr<clang::NoDerefAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
98
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
98
  AL.setUsedAsTypeAttr();
4450
98
  return ::new (Ctx) AttrT(Ctx, AL);
4451
98
}
SemaType.cpp:clang::Ptr32Attr* createSimpleAttr<clang::Ptr32Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
52
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
52
  AL.setUsedAsTypeAttr();
4450
52
  return ::new (Ctx) AttrT(Ctx, AL);
4451
52
}
SemaType.cpp:clang::Ptr64Attr* createSimpleAttr<clang::Ptr64Attr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
30
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
30
  AL.setUsedAsTypeAttr();
4450
30
  return ::new (Ctx) AttrT(Ctx, AL);
4451
30
}
SemaType.cpp:clang::SPtrAttr* createSimpleAttr<clang::SPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
24
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
24
  AL.setUsedAsTypeAttr();
4450
24
  return ::new (Ctx) AttrT(Ctx, AL);
4451
24
}
SemaType.cpp:clang::UPtrAttr* createSimpleAttr<clang::UPtrAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
18
  AL.setUsedAsTypeAttr();
4450
18
  return ::new (Ctx) AttrT(Ctx, AL);
4451
18
}
SemaType.cpp:clang::TypeNonNullAttr* createSimpleAttr<clang::TypeNonNullAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
2.21M
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
2.21M
  AL.setUsedAsTypeAttr();
4450
2.21M
  return ::new (Ctx) AttrT(Ctx, AL);
4451
2.21M
}
SemaType.cpp:clang::TypeNullableAttr* createSimpleAttr<clang::TypeNullableAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
987k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
987k
  AL.setUsedAsTypeAttr();
4450
987k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
987k
}
SemaType.cpp:clang::TypeNullableResultAttr* createSimpleAttr<clang::TypeNullableResultAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
18
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
18
  AL.setUsedAsTypeAttr();
4450
18
  return ::new (Ctx) AttrT(Ctx, AL);
4451
18
}
SemaType.cpp:clang::TypeNullUnspecifiedAttr* createSimpleAttr<clang::TypeNullUnspecifiedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
44.4k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
44.4k
  AL.setUsedAsTypeAttr();
4450
44.4k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
44.4k
}
SemaType.cpp:clang::ObjCKindOfAttr* createSimpleAttr<clang::ObjCKindOfAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
1.19k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
1.19k
  AL.setUsedAsTypeAttr();
4450
1.19k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
1.19k
}
SemaType.cpp:clang::NSReturnsRetainedAttr* createSimpleAttr<clang::NSReturnsRetainedAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
12.5k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
12.5k
  AL.setUsedAsTypeAttr();
4450
12.5k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
12.5k
}
SemaType.cpp:clang::CDeclAttr* createSimpleAttr<clang::CDeclAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
424
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
424
  AL.setUsedAsTypeAttr();
4450
424
  return ::new (Ctx) AttrT(Ctx, AL);
4451
424
}
SemaType.cpp:clang::FastCallAttr* createSimpleAttr<clang::FastCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
230
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
230
  AL.setUsedAsTypeAttr();
4450
230
  return ::new (Ctx) AttrT(Ctx, AL);
4451
230
}
SemaType.cpp:clang::StdCallAttr* createSimpleAttr<clang::StdCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
279
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
279
  AL.setUsedAsTypeAttr();
4450
279
  return ::new (Ctx) AttrT(Ctx, AL);
4451
279
}
SemaType.cpp:clang::ThisCallAttr* createSimpleAttr<clang::ThisCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
78
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
78
  AL.setUsedAsTypeAttr();
4450
78
  return ::new (Ctx) AttrT(Ctx, AL);
4451
78
}
SemaType.cpp:clang::RegCallAttr* createSimpleAttr<clang::RegCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
129
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
129
  AL.setUsedAsTypeAttr();
4450
129
  return ::new (Ctx) AttrT(Ctx, AL);
4451
129
}
SemaType.cpp:clang::PascalAttr* createSimpleAttr<clang::PascalAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
23
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
23
  AL.setUsedAsTypeAttr();
4450
23
  return ::new (Ctx) AttrT(Ctx, AL);
4451
23
}
SemaType.cpp:clang::SwiftCallAttr* createSimpleAttr<clang::SwiftCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
1.21k
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
1.21k
  AL.setUsedAsTypeAttr();
4450
1.21k
  return ::new (Ctx) AttrT(Ctx, AL);
4451
1.21k
}
SemaType.cpp:clang::SwiftAsyncCallAttr* createSimpleAttr<clang::SwiftAsyncCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
173
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
173
  AL.setUsedAsTypeAttr();
4450
173
  return ::new (Ctx) AttrT(Ctx, AL);
4451
173
}
SemaType.cpp:clang::VectorCallAttr* createSimpleAttr<clang::VectorCallAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
201
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
201
  AL.setUsedAsTypeAttr();
4450
201
  return ::new (Ctx) AttrT(Ctx, AL);
4451
201
}
SemaType.cpp:clang::AArch64VectorPcsAttr* createSimpleAttr<clang::AArch64VectorPcsAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
12
  AL.setUsedAsTypeAttr();
4450
12
  return ::new (Ctx) AttrT(Ctx, AL);
4451
12
}
SemaType.cpp:clang::AArch64SVEPcsAttr* createSimpleAttr<clang::AArch64SVEPcsAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
12
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
12
  AL.setUsedAsTypeAttr();
4450
12
  return ::new (Ctx) AttrT(Ctx, AL);
4451
12
}
SemaType.cpp:clang::IntelOclBiccAttr* createSimpleAttr<clang::IntelOclBiccAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
8
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
8
  AL.setUsedAsTypeAttr();
4450
8
  return ::new (Ctx) AttrT(Ctx, AL);
4451
8
}
SemaType.cpp:clang::MSABIAttr* createSimpleAttr<clang::MSABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
48
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
48
  AL.setUsedAsTypeAttr();
4450
48
  return ::new (Ctx) AttrT(Ctx, AL);
4451
48
}
SemaType.cpp:clang::SysVABIAttr* createSimpleAttr<clang::SysVABIAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
37
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
37
  AL.setUsedAsTypeAttr();
4450
37
  return ::new (Ctx) AttrT(Ctx, AL);
4451
37
}
SemaType.cpp:clang::PreserveMostAttr* createSimpleAttr<clang::PreserveMostAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
36
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
36
  AL.setUsedAsTypeAttr();
4450
36
  return ::new (Ctx) AttrT(Ctx, AL);
4451
36
}
SemaType.cpp:clang::PreserveAllAttr* createSimpleAttr<clang::PreserveAllAttr>(clang::ASTContext&, clang::ParsedAttr&)
Line
Count
Source
4448
27
static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4449
27
  AL.setUsedAsTypeAttr();
4450
27
  return ::new (Ctx) AttrT(Ctx, AL);
4451
27
}
4452
4453
static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4454
3.25M
                                   NullabilityKind NK) {
4455
3.25M
  switch (NK) {
4456
2.21M
  case NullabilityKind::NonNull:
4457
2.21M
    return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4458
4459
987k
  case NullabilityKind::Nullable:
4460
987k
    return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4461
4462
18
  case NullabilityKind::NullableResult:
4463
18
    return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4464
4465
44.4k
  case NullabilityKind::Unspecified:
4466
44.4k
    return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4467
3.25M
  }
4468
0
  llvm_unreachable("unknown NullabilityKind");
4469
0
}
4470
4471
// Diagnose whether this is a case with the multiple addr spaces.
4472
// Returns true if this is an invalid case.
4473
// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4474
// by qualifiers for two or more different address spaces."
4475
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4476
                                                LangAS ASNew,
4477
34.3k
                                                SourceLocation AttrLoc) {
4478
34.3k
  if (ASOld != LangAS::Default) {
4479
76
    if (ASOld != ASNew) {
4480
50
      S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4481
50
      return true;
4482
50
    }
4483
    // Emit a warning if they are identical; it's likely unintended.
4484
26
    S.Diag(AttrLoc,
4485
26
           diag::warn_attribute_address_multiple_identical_qualifiers);
4486
26
  }
4487
34.3k
  return false;
4488
34.3k
}
4489
4490
static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4491
                                                QualType declSpecType,
4492
107M
                                                TypeSourceInfo *TInfo) {
4493
  // The TypeSourceInfo that this function returns will not be a null type.
4494
  // If there is an error, this function will fill in a dummy type as fallback.
4495
107M
  QualType T = declSpecType;
4496
107M
  Declarator &D = state.getDeclarator();
4497
107M
  Sema &S = state.getSema();
4498
107M
  ASTContext &Context = S.Context;
4499
107M
  const LangOptions &LangOpts = S.getLangOpts();
4500
4501
  // The name we're declaring, if any.
4502
107M
  DeclarationName Name;
4503
107M
  if (D.getIdentifier())
4504
42.0M
    Name = D.getIdentifier();
4505
4506
  // Does this declaration declare a typedef-name?
4507
107M
  bool IsTypedefName =
4508
107M
      D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4509
107M
      
D.getContext() == DeclaratorContext::AliasDecl105M
||
4510
107M
      
D.getContext() == DeclaratorContext::AliasTemplate105M
;
4511
4512
  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4513
107M
  bool IsQualifiedFunction = T->isFunctionProtoType() &&
4514
107M
      
(1.94k
!T->castAs<FunctionProtoType>()->getMethodQuals().empty()1.94k
||
4515
1.94k
       
T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None1.89k
);
4516
4517
  // If T is 'decltype(auto)', the only declarators we can have are parens
4518
  // and at most one function declarator if this is a function declaration.
4519
  // If T is a deduced class template specialization type, we can have no
4520
  // declarator chunks at all.
4521
107M
  if (auto *DT = T->getAs<DeducedType>()) {
4522
43.9k
    const AutoType *AT = T->getAs<AutoType>();
4523
43.9k
    bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4524
43.9k
    if ((AT && 
AT->isDecltypeAuto()42.9k
) ||
IsClassTemplateDeduction43.4k
) {
4525
1.77k
      for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; 
++I324
) {
4526
373
        unsigned Index = E - I - 1;
4527
373
        DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4528
373
        unsigned DiagId = IsClassTemplateDeduction
4529
373
                              ? 
diag::err_deduced_class_template_compound_type14
4530
373
                              : 
diag::err_decltype_auto_compound_type359
;
4531
373
        unsigned DiagKind = 0;
4532
373
        switch (DeclChunk.Kind) {
4533
38
        case DeclaratorChunk::Paren:
4534
          // FIXME: Rejecting this is a little silly.
4535
38
          if (IsClassTemplateDeduction) {
4536
2
            DiagKind = 4;
4537
2
            break;
4538
2
          }
4539
36
          continue;
4540
299
        case DeclaratorChunk::Function: {
4541
299
          if (IsClassTemplateDeduction) {
4542
2
            DiagKind = 3;
4543
2
            break;
4544
2
          }
4545
297
          unsigned FnIndex;
4546
297
          if (D.isFunctionDeclarationContext() &&
4547
297
              D.isFunctionDeclarator(FnIndex) && 
FnIndex == Index291
)
4548
288
            continue;
4549
9
          DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4550
9
          break;
4551
297
        }
4552
16
        case DeclaratorChunk::Pointer:
4553
16
        case DeclaratorChunk::BlockPointer:
4554
18
        case DeclaratorChunk::MemberPointer:
4555
18
          DiagKind = 0;
4556
18
          break;
4557
10
        case DeclaratorChunk::Reference:
4558
10
          DiagKind = 1;
4559
10
          break;
4560
8
        case DeclaratorChunk::Array:
4561
8
          DiagKind = 2;
4562
8
          break;
4563
0
        case DeclaratorChunk::Pipe:
4564
0
          break;
4565
373
        }
4566
4567
49
        S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4568
49
        D.setInvalidType(true);
4569
49
        break;
4570
373
      }
4571
1.45k
    }
4572
43.9k
  }
4573
4574
  // Determine whether we should infer _Nonnull on pointer types.
4575
107M
  Optional<NullabilityKind> inferNullability;
4576
107M
  bool inferNullabilityCS = false;
4577
107M
  bool inferNullabilityInnerOnly = false;
4578
107M
  bool inferNullabilityInnerOnlyComplete = false;
4579
4580
  // Are we in an assume-nonnull region?
4581
107M
  bool inAssumeNonNullRegion = false;
4582
107M
  SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4583
107M
  if (assumeNonNullLoc.isValid()) {
4584
5.08M
    inAssumeNonNullRegion = true;
4585
5.08M
    recordNullabilitySeen(S, assumeNonNullLoc);
4586
5.08M
  }
4587
4588
  // Whether to complain about missing nullability specifiers or not.
4589
107M
  enum {
4590
    /// Never complain.
4591
107M
    CAMN_No,
4592
    /// Complain on the inner pointers (but not the outermost
4593
    /// pointer).
4594
107M
    CAMN_InnerPointers,
4595
    /// Complain about any pointers that don't have nullability
4596
    /// specified or inferred.
4597
107M
    CAMN_Yes
4598
107M
  } complainAboutMissingNullability = CAMN_No;
4599
107M
  unsigned NumPointersRemaining = 0;
4600
107M
  auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4601
4602
107M
  if (IsTypedefName) {
4603
    // For typedefs, we do not infer any nullability (the default),
4604
    // and we only complain about missing nullability specifiers on
4605
    // inner pointers.
4606
2.18M
    complainAboutMissingNullability = CAMN_InnerPointers;
4607
4608
2.18M
    if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4609
2.18M
        
!T->getNullability(S.Context)59.7k
) {
4610
      // Note that we allow but don't require nullability on dependent types.
4611
57.9k
      ++NumPointersRemaining;
4612
57.9k
    }
4613
4614
2.73M
    for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; 
++i555k
) {
4615
555k
      DeclaratorChunk &chunk = D.getTypeObject(i);
4616
555k
      switch (chunk.Kind) {
4617
18.2k
      case DeclaratorChunk::Array:
4618
116k
      case DeclaratorChunk::Function:
4619
116k
      case DeclaratorChunk::Pipe:
4620
116k
        break;
4621
4622
10.3k
      case DeclaratorChunk::BlockPointer:
4623
10.6k
      case DeclaratorChunk::MemberPointer:
4624
10.6k
        ++NumPointersRemaining;
4625
10.6k
        break;
4626
4627
96.6k
      case DeclaratorChunk::Paren:
4628
121k
      case DeclaratorChunk::Reference:
4629
121k
        continue;
4630
4631
306k
      case DeclaratorChunk::Pointer:
4632
306k
        ++NumPointersRemaining;
4633
306k
        continue;
4634
555k
      }
4635
555k
    }
4636
105M
  } else {
4637
105M
    bool isFunctionOrMethod = false;
4638
105M
    switch (auto context = state.getDeclarator().getContext()) {
4639
977k
    case DeclaratorContext::ObjCParameter:
4640
1.63M
    case DeclaratorContext::ObjCResult:
4641
65.8M
    case DeclaratorContext::Prototype:
4642
65.8M
    case DeclaratorContext::TrailingReturn:
4643
65.8M
    case DeclaratorContext::TrailingReturnVar:
4644
65.8M
      isFunctionOrMethod = true;
4645
65.8M
      LLVM_FALLTHROUGH;
4646
4647
70.4M
    case DeclaratorContext::Member:
4648
70.4M
      if (state.getDeclarator().isObjCIvar() && 
!isFunctionOrMethod136k
) {
4649
136k
        complainAboutMissingNullability = CAMN_No;
4650
136k
        break;
4651
136k
      }
4652
4653
      // Weak properties are inferred to be nullable.
4654
70.3M
      if (state.getDeclarator().isObjCWeakProperty() && 
inAssumeNonNullRegion1.04k
) {
4655
911
        inferNullability = NullabilityKind::Nullable;
4656
911
        break;
4657
911
      }
4658
4659
70.3M
      
LLVM_FALLTHROUGH70.3M
;70.3M
4660
4661
94.7M
    case DeclaratorContext::File:
4662
94.7M
    case DeclaratorContext::KNRTypeList: {
4663
94.7M
      complainAboutMissingNullability = CAMN_Yes;
4664
4665
      // Nullability inference depends on the type and declarator.
4666
94.7M
      auto wrappingKind = PointerWrappingDeclaratorKind::None;
4667
94.7M
      switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4668
85.4M
      case PointerDeclaratorKind::NonPointer:
4669
85.5M
      case PointerDeclaratorKind::MultiLevelPointer:
4670
        // Cannot infer nullability.
4671
85.5M
        break;
4672
4673
8.97M
      case PointerDeclaratorKind::SingleLevelPointer:
4674
        // Infer _Nonnull if we are in an assumes-nonnull region.
4675
8.97M
        if (inAssumeNonNullRegion) {
4676
2.89M
          complainAboutInferringWithinChunk = wrappingKind;
4677
2.89M
          inferNullability = NullabilityKind::NonNull;
4678
2.89M
          inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4679
2.89M
                                
context == DeclaratorContext::ObjCResult2.22M
);
4680
2.89M
        }
4681
8.97M
        break;
4682
4683
18.8k
      case PointerDeclaratorKind::CFErrorRefPointer:
4684
49.8k
      case PointerDeclaratorKind::NSErrorPointerPointer:
4685
        // Within a function or method signature, infer _Nullable at both
4686
        // levels.
4687
49.8k
        if (isFunctionOrMethod && 
inAssumeNonNullRegion49.8k
)
4688
44.5k
          inferNullability = NullabilityKind::Nullable;
4689
49.8k
        break;
4690
4691
255k
      case PointerDeclaratorKind::MaybePointerToCFRef:
4692
255k
        if (isFunctionOrMethod) {
4693
          // On pointer-to-pointer parameters marked cf_returns_retained or
4694
          // cf_returns_not_retained, if the outer pointer is explicit then
4695
          // infer the inner pointer as _Nullable.
4696
231k
          auto hasCFReturnsAttr =
4697
594k
              [](const ParsedAttributesView &AttrList) -> bool {
4698
594k
            return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4699
594k
                   
AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained)566k
;
4700
594k
          };
4701
231k
          if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4702
208k
            if (hasCFReturnsAttr(D.getAttributes()) ||
4703
208k
                
hasCFReturnsAttr(InnermostChunk->getAttrs())206k
||
4704
208k
                
hasCFReturnsAttr(D.getDeclSpec().getAttributes())179k
) {
4705
28.3k
              inferNullability = NullabilityKind::Nullable;
4706
28.3k
              inferNullabilityInnerOnly = true;
4707
28.3k
            }
4708
208k
          }
4709
231k
        }
4710
255k
        break;
4711
94.7M
      }
4712
94.7M
      break;
4713
94.7M
    }
4714
4715
94.7M
    case DeclaratorContext::ConversionId:
4716
12.7k
      complainAboutMissingNullability = CAMN_Yes;
4717
12.7k
      break;
4718
4719
0
    case DeclaratorContext::AliasDecl:
4720
0
    case DeclaratorContext::AliasTemplate:
4721
1.02M
    case DeclaratorContext::Block:
4722
1.02M
    case DeclaratorContext::BlockLiteral:
4723
1.02M
    case DeclaratorContext::Condition:
4724
1.03M
    case DeclaratorContext::CXXCatch:
4725
1.04M
    case DeclaratorContext::CXXNew:
4726
1.16M
    case DeclaratorContext::ForInit:
4727
1.16M
    case DeclaratorContext::SelectionInit:
4728
1.16M
    case DeclaratorContext::LambdaExpr:
4729
1.17M
    case DeclaratorContext::LambdaExprParameter:
4730
1.17M
    case DeclaratorContext::ObjCCatch:
4731
1.39M
    case DeclaratorContext::TemplateParam:
4732
4.95M
    case DeclaratorContext::TemplateArg:
4733
5.06M
    case DeclaratorContext::TemplateTypeArg:
4734
10.5M
    case DeclaratorContext::TypeName:
4735
10.8M
    case DeclaratorContext::FunctionalCast:
4736
10.8M
    case DeclaratorContext::RequiresExpr:
4737
      // Don't infer in these contexts.
4738
10.8M
      break;
4739
105M
    }
4740
105M
  }
4741
4742
  // Local function that returns true if its argument looks like a va_list.
4743
107M
  auto isVaList = [&S](QualType T) -> bool {
4744
2.64M
    auto *typedefTy = T->getAs<TypedefType>();
4745
2.64M
    if (!typedefTy)
4746
78.6k
      return false;
4747
2.56M
    TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4748
2.85M
    do {
4749
2.85M
      if (typedefTy->getDecl() == vaListTypedef)
4750
4.15k
        return true;
4751
2.85M
      if (auto *name = typedefTy->getDecl()->getIdentifier())
4752
2.85M
        if (name->isStr("va_list"))
4753
20.9k
          return true;
4754
2.83M
      typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4755
2.83M
    } while (typedefTy);
4756
2.54M
    return false;
4757
2.56M
  };
4758
4759
  // Local function that checks the nullability for a given pointer declarator.
4760
  // Returns true if _Nonnull was inferred.
4761
107M
  auto inferPointerNullability =
4762
107M
      [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4763
107M
          SourceLocation pointerEndLoc,
4764
107M
          ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4765
    // We've seen a pointer.
4766
10.3M
    if (NumPointersRemaining > 0)
4767
374k
      --NumPointersRemaining;
4768
4769
    // If a nullability attribute is present, there's nothing to do.
4770
10.3M
    if (hasNullabilityAttr(attrs))
4771
528k
      return nullptr;
4772
4773
    // If we're supposed to infer nullability, do so now.
4774
9.81M
    if (inferNullability && 
!inferNullabilityInnerOnlyComplete2.22M
) {
4775
2.22M
      ParsedAttr::Syntax syntax = inferNullabilityCS
4776
2.22M
                                      ? 
ParsedAttr::AS_ContextSensitiveKeyword729k
4777
2.22M
                                      : 
ParsedAttr::AS_Keyword1.49M
;
4778
2.22M
      ParsedAttr *nullabilityAttr = Pool.create(
4779
2.22M
          S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4780
2.22M
          nullptr, SourceLocation(), nullptr, 0, syntax);
4781
4782
2.22M
      attrs.addAtEnd(nullabilityAttr);
4783
4784
2.22M
      if (inferNullabilityCS) {
4785
729k
        state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4786
729k
          ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4787
729k
      }
4788
4789
2.22M
      if (pointerLoc.isValid() &&
4790
2.22M
          complainAboutInferringWithinChunk !=
4791
2.22M
            PointerWrappingDeclaratorKind::None) {
4792
52
        auto Diag =
4793
52
            S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4794
52
        Diag << static_cast<int>(complainAboutInferringWithinChunk);
4795
52
        fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4796
52
      }
4797
4798
2.22M
      if (inferNullabilityInnerOnly)
4799
23.9k
        inferNullabilityInnerOnlyComplete = true;
4800
2.22M
      return nullabilityAttr;
4801
2.22M
    }
4802
4803
    // If we're supposed to complain about missing nullability, do so
4804
    // now if it's truly missing.
4805
7.59M
    switch (complainAboutMissingNullability) {
4806
671k
    case CAMN_No:
4807
671k
      break;
4808
4809
374k
    case CAMN_InnerPointers:
4810
374k
      if (NumPointersRemaining == 0)
4811
351k
        break;
4812
374k
      
LLVM_FALLTHROUGH23.4k
;23.4k
4813
4814
6.57M
    case CAMN_Yes:
4815
6.57M
      checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4816
7.59M
    }
4817
7.59M
    return nullptr;
4818
7.59M
  };
4819
4820
  // If the type itself could have nullability but does not, infer pointer
4821
  // nullability and perform consistency checking.
4822
107M
  if (S.CodeSynthesisContexts.empty()) {
4823
107M
    if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4824
107M
        
!T->getNullability(S.Context)3.07M
) {
4825
2.58M
      if (isVaList(T)) {
4826
        // Record that we've seen a pointer, but do nothing else.
4827
527
        if (NumPointersRemaining > 0)
4828
112
          --NumPointersRemaining;
4829
2.58M
      } else {
4830
2.58M
        SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4831
2.58M
        if (T->isBlockPointerType())
4832
19.3k
          pointerKind = SimplePointerKind::BlockPointer;
4833
2.56M
        else if (T->isMemberPointerType())
4834
1.01k
          pointerKind = SimplePointerKind::MemberPointer;
4835
4836
2.58M
        if (auto *attr = inferPointerNullability(
4837
2.58M
                pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4838
2.58M
                D.getDeclSpec().getEndLoc(),
4839
2.58M
                D.getMutableDeclSpec().getAttributes(),
4840
2.58M
                D.getMutableDeclSpec().getAttributePool())) {
4841
1.20M
          T = state.getAttributedType(
4842
1.20M
              createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4843
1.20M
        }
4844
2.58M
      }
4845
2.58M
    }
4846
4847
107M
    if (complainAboutMissingNullability == CAMN_Yes &&
4848
107M
        
T->isArrayType()94.7M
&&
!T->getNullability(S.Context)59.9k
&&
!isVaList(T)58.7k
&&
4849
107M
        
D.isPrototypeContext()34.1k
&&
4850
107M
        
!hasOuterPointerLikeChunk(D, D.getNumTypeObjects())21.4k
) {
4851
19.5k
      checkNullabilityConsistency(S, SimplePointerKind::Array,
4852
19.5k
                                  D.getDeclSpec().getTypeSpecTypeLoc());
4853
19.5k
    }
4854
107M
  }
4855
4856
107M
  bool ExpectNoDerefChunk =
4857
107M
      state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4858
4859
  // Walk the DeclTypeInfo, building the recursive type as we go.
4860
  // DeclTypeInfos are ordered from the identifier out, which is
4861
  // opposite of what we want :).
4862
142M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i34.2M
) {
4863
34.2M
    unsigned chunkIndex = e - i - 1;
4864
34.2M
    state.setCurrentChunkIndex(chunkIndex);
4865
34.2M
    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4866
34.2M
    IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4867
34.2M
    switch (DeclType.Kind) {
4868
304k
    case DeclaratorChunk::Paren:
4869
304k
      if (i == 0)
4870
450
        warnAboutRedundantParens(S, D, T);
4871
304k
      T = S.BuildParenType(T);
4872
304k
      break;
4873
61.0k
    case DeclaratorChunk::BlockPointer:
4874
      // If blocks are disabled, emit an error.
4875
61.0k
      if (!LangOpts.Blocks)
4876
7
        S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4877
4878
      // Handle pointer nullability.
4879
61.0k
      inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4880
61.0k
                              DeclType.EndLoc, DeclType.getAttrs(),
4881
61.0k
                              state.getDeclarator().getAttributePool());
4882
4883
61.0k
      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4884
61.0k
      if (DeclType.Cls.TypeQuals || 
LangOpts.OpenCL60.9k
) {
4885
        // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4886
        // qualified with const.
4887
159
        if (LangOpts.OpenCL)
4888
147
          DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4889
159
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4890
159
      }
4891
61.0k
      break;
4892
7.67M
    case DeclaratorChunk::Pointer:
4893
      // Verify that we're not building a pointer to pointer to function with
4894
      // exception specification.
4895
7.67M
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)3.07M
) {
4896
7
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4897
7
        D.setInvalidType(true);
4898
        // Build the type anyway.
4899
7
      }
4900
4901
      // Handle pointer nullability
4902
7.67M
      inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4903
7.67M
                              DeclType.EndLoc, DeclType.getAttrs(),
4904
7.67M
                              state.getDeclarator().getAttributePool());
4905
4906
7.67M
      if (LangOpts.ObjC && 
T->getAs<ObjCObjectType>()3.07M
) {
4907
1.16M
        T = Context.getObjCObjectPointerType(T);
4908
1.16M
        if (DeclType.Ptr.TypeQuals)
4909
67.0k
          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4910
1.16M
        break;
4911
1.16M
      }
4912
4913
      // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4914
      // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4915
      // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4916
6.50M
      if (LangOpts.OpenCL) {
4917
40.1k
        if (T->isImageType() || 
T->isSamplerT()40.1k
||
T->isPipeType()40.1k
||
4918
40.1k
            
T->isBlockPointerType()40.1k
) {
4919
14
          S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4920
14
          D.setInvalidType(true);
4921
14
        }
4922
40.1k
      }
4923
4924
6.50M
      T = S.BuildPointerType(T, DeclType.Loc, Name);
4925
6.50M
      if (DeclType.Ptr.TypeQuals)
4926
87.6k
        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4927
6.50M
      break;
4928
1.11M
    case DeclaratorChunk::Reference: {
4929
      // Verify that we're not building a reference to pointer to function with
4930
      // exception specification.
4931
1.11M
      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4932
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4933
0
        D.setInvalidType(true);
4934
        // Build the type anyway.
4935
0
      }
4936
1.11M
      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4937
4938
1.11M
      if (DeclType.Ref.HasRestrict)
4939
7
        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4940
1.11M
      break;
4941
7.67M
    }
4942
318k
    case DeclaratorChunk::Array: {
4943
      // Verify that we're not building an array of pointers to function with
4944
      // exception specification.
4945
318k
      if (LangOpts.CPlusPlus && 
S.CheckDistantExceptionSpec(T)143k
) {
4946
0
        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4947
0
        D.setInvalidType(true);
4948
        // Build the type anyway.
4949
0
      }
4950
318k
      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4951
318k
      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4952
318k
      ArrayType::ArraySizeModifier ASM;
4953
318k
      if (ATI.isStar)
4954
26
        ASM = ArrayType::Star;
4955
318k
      else if (ATI.hasStatic)
4956
47
        ASM = ArrayType::Static;
4957
318k
      else
4958
318k
        ASM = ArrayType::Normal;
4959
318k
      if (ASM == ArrayType::Star && 
!D.isPrototypeContext()26
) {
4960
        // FIXME: This check isn't quite right: it allows star in prototypes
4961
        // for function definitions, and disallows some edge cases detailed
4962
        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4963
1
        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4964
1
        ASM = ArrayType::Normal;
4965
1
        D.setInvalidType(true);
4966
1
      }
4967
4968
      // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4969
      // shall appear only in a declaration of a function parameter with an
4970
      // array type, ...
4971
318k
      if (ASM == ArrayType::Static || 
ATI.TypeQuals318k
) {
4972