Coverage Report

Created: 2022-01-18 06:27

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