Coverage Report

Created: 2021-08-24 07:12

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