Coverage Report

Created: 2019-07-24 05:18

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