Coverage Report

Created: 2020-09-15 12:33

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