Coverage Report

Created: 2018-11-16 02:38

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Sema/SemaInternal.h
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file provides common API and #includes for the internal
11
// implementation of Sema.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
16
#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
17
18
#include "clang/AST/ASTContext.h"
19
#include "clang/Sema/Lookup.h"
20
#include "clang/Sema/Sema.h"
21
#include "clang/Sema/SemaDiagnostic.h"
22
23
namespace clang {
24
25
1.41M
inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
26
1.41M
  return PartialDiagnostic(DiagID, Context.getDiagAllocator());
27
1.41M
}
28
29
inline bool
30
4.64M
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
31
4.64M
  return FTI.NumParams == 1 && 
!FTI.isVariadic2.01M
&&
32
4.64M
         
FTI.Params[0].Ident == nullptr2.00M
&&
FTI.Params[0].Param827k
&&
33
4.64M
         
cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()827k
;
34
4.64M
}
35
36
inline bool
37
5.62M
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
38
5.62M
  // Assume FTI is well-formed.
39
5.62M
  return FTI.NumParams && 
!FTIHasSingleVoidParameter(FTI)4.64M
;
40
5.62M
}
41
42
// This requires the variable to be non-dependent and the initializer
43
// to not be value dependent.
44
8.30M
inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
45
8.30M
  const VarDecl *DefVD = nullptr;
46
8.30M
  return !isa<ParmVarDecl>(Var) &&
47
8.30M
    
Var->isUsableInConstantExpressions(Context)4.15M
&&
48
8.30M
    
Var->getAnyInitializer(DefVD)1.01M
&&
DefVD->checkInitIsICE()1.01M
;
49
8.30M
}
50
51
// Helper function to check whether D's attributes match current CUDA mode.
52
// Decls with mismatched attributes and related diagnostics may have to be
53
// ignored during this CUDA compilation pass.
54
25.7k
inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
55
25.7k
  if (!LangOpts.CUDA || 
!D28
)
56
25.7k
    return true;
57
28
  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
58
28
                          
D->hasAttr<CUDASharedAttr>()12
||
59
28
                          
D->hasAttr<CUDAGlobalAttr>()10
;
60
28
  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
61
28
}
62
63
// Directly mark a variable odr-used. Given a choice, prefer to use
64
// MarkVariableReferenced since it does additional checks and then
65
// calls MarkVarDeclODRUsed.
66
// If the variable must be captured:
67
//  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
68
//  - else capture it in the DeclContext that maps to the
69
//    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
70
inline void MarkVarDeclODRUsed(VarDecl *Var,
71
    SourceLocation Loc, Sema &SemaRef,
72
7.44M
    const unsigned *const FunctionScopeIndexToStopAt) {
73
7.44M
  // Keep track of used but undefined variables.
74
7.44M
  // FIXME: We shouldn't suppress this warning for static data members.
75
7.44M
  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
76
7.44M
      
(154k
!Var->isExternallyVisible()154k
||
Var->isInline()153k
||
77
154k
       
SemaRef.isExternalWithNoLinkageType(Var)153k
) &&
78
7.44M
      
!(132
Var->isStaticDataMember()132
&&
Var->hasInit()72
)) {
79
100
    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
80
100
    if (old.isInvalid())
81
82
      old = Loc;
82
100
  }
83
7.44M
  QualType CaptureType, DeclRefType;
84
7.44M
  SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
85
7.44M
    /*EllipsisLoc*/ SourceLocation(),
86
7.44M
    /*BuildAndDiagnose*/ true,
87
7.44M
    CaptureType, DeclRefType,
88
7.44M
    FunctionScopeIndexToStopAt);
89
7.44M
90
7.44M
  Var->markUsed(SemaRef.Context);
91
7.44M
}
92
93
/// Return a DLL attribute from the declaration.
94
12.2M
inline InheritableAttr *getDLLAttr(Decl *D) {
95
12.2M
  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
96
12.2M
         "A declaration cannot be both dllimport and dllexport.");
97
12.2M
  if (auto *Import = D->getAttr<DLLImportAttr>())
98
5.53k
    return Import;
99
12.2M
  if (auto *Export = D->getAttr<DLLExportAttr>())
100
6.38k
    return Export;
101
12.2M
  return nullptr;
102
12.2M
}
103
104
/// Retrieve the depth and index of a template parameter.
105
110k
inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
106
110k
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
107
34.7k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
108
75.3k
109
75.3k
  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
110
75.2k
    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
111
131
112
131
  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
113
131
  return std::make_pair(TTP->getDepth(), TTP->getIndex());
114
131
}
115
116
/// Retrieve the depth and index of an unexpanded parameter pack.
117
inline std::pair<unsigned, unsigned>
118
65.8k
getDepthAndIndex(UnexpandedParameterPack UPP) {
119
65.8k
  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
120
61.9k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
121
3.89k
122
3.89k
  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
123
3.89k
}
124
125
class TypoCorrectionConsumer : public VisibleDeclConsumer {
126
  typedef SmallVector<TypoCorrection, 1> TypoResultList;
127
  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
128
  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
129
130
public:
131
  TypoCorrectionConsumer(Sema &SemaRef,
132
                         const DeclarationNameInfo &TypoName,
133
                         Sema::LookupNameKind LookupKind,
134
                         Scope *S, CXXScopeSpec *SS,
135
                         std::unique_ptr<CorrectionCandidateCallback> CCC,
136
                         DeclContext *MemberContext,
137
                         bool EnteringContext)
138
      : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
139
        SavedTCIndex(0), SemaRef(SemaRef), S(S),
140
        SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
141
        CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
142
        Result(SemaRef, TypoName, LookupKind),
143
        Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
144
3.54k
        EnteringContext(EnteringContext), SearchNamespaces(false) {
145
3.54k
    Result.suppressDiagnostics();
146
3.54k
    // Arrange for ValidatedCorrections[0] to always be an empty correction.
147
3.54k
    ValidatedCorrections.push_back(TypoCorrection());
148
3.54k
  }
149
150
587
  bool includeHiddenDecls() const override { return true; }
151
152
  // Methods for adding potential corrections to the consumer.
153
  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
154
                 bool InBaseClass) override;
155
  void FoundName(StringRef Name);
156
  void addKeywordResult(StringRef Keyword);
157
  void addCorrection(TypoCorrection Correction);
158
159
3.38k
  bool empty() const {
160
3.38k
    return CorrectionResults.empty() && 
ValidatedCorrections.size() == 1112
;
161
3.38k
  }
162
163
  /// Return the list of TypoCorrections for the given identifier from
164
  /// the set of corrections that have the closest edit distance, if any.
165
0
  TypoResultList &operator[](StringRef Name) {
166
0
    return CorrectionResults.begin()->second[Name];
167
0
  }
168
169
  /// Return the edit distance of the corrections that have the
170
  /// closest/best edit distance from the original typop.
171
3.27k
  unsigned getBestEditDistance(bool Normalized) {
172
3.27k
    if (CorrectionResults.empty())
173
0
      return (std::numeric_limits<unsigned>::max)();
174
3.27k
175
3.27k
    unsigned BestED = CorrectionResults.begin()->first;
176
3.27k
    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : 
BestED0
;
177
3.27k
  }
178
179
  /// Set-up method to add to the consumer the set of namespaces to use
180
  /// in performing corrections to nested name specifiers. This method also
181
  /// implicitly adds all of the known classes in the current AST context to the
182
  /// to the consumer for correcting nested name specifiers.
183
  void
184
  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
185
186
  /// Return the next typo correction that passes all internal filters
187
  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
188
  /// starting with the corrections that have the closest edit distance. An
189
  /// empty TypoCorrection is returned once no more viable corrections remain
190
  /// in the consumer.
191
  const TypoCorrection &getNextCorrection();
192
193
  /// Get the last correction returned by getNextCorrection().
194
1.07k
  const TypoCorrection &getCurrentCorrection() {
195
1.07k
    return CurrentTCIndex < ValidatedCorrections.size()
196
1.07k
               ? ValidatedCorrections[CurrentTCIndex]
197
1.07k
               : 
ValidatedCorrections[0]0
; // The empty correction.
198
1.07k
  }
199
200
  /// Return the next typo correction like getNextCorrection, but keep
201
  /// the internal state pointed to the current correction (i.e. the next time
202
  /// getNextCorrection is called, it will return the same correction returned
203
  /// by peekNextcorrection).
204
508
  const TypoCorrection &peekNextCorrection() {
205
508
    auto Current = CurrentTCIndex;
206
508
    const TypoCorrection &TC = getNextCorrection();
207
508
    CurrentTCIndex = Current;
208
508
    return TC;
209
508
  }
210
211
  /// Reset the consumer's position in the stream of viable corrections
212
  /// (i.e. getNextCorrection() will return each of the previously returned
213
  /// corrections in order before returning any new corrections).
214
1.41k
  void resetCorrectionStream() {
215
1.41k
    CurrentTCIndex = 0;
216
1.41k
  }
217
218
  /// Return whether the end of the stream of corrections has been
219
  /// reached.
220
892
  bool finished() {
221
892
    return CorrectionResults.empty() &&
222
892
           
CurrentTCIndex >= ValidatedCorrections.size()799
;
223
892
  }
224
225
  /// Save the current position in the correction stream (overwriting any
226
  /// previously saved position).
227
40
  void saveCurrentPosition() {
228
40
    SavedTCIndex = CurrentTCIndex;
229
40
  }
230
231
  /// Restore the saved position in the correction stream.
232
4
  void restoreSavedPosition() {
233
4
    CurrentTCIndex = SavedTCIndex;
234
4
  }
235
236
0
  ASTContext &getContext() const { return SemaRef.Context; }
237
798
  const LookupResult &getLookupResult() const { return Result; }
238
239
64
  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
240
399
  const CXXScopeSpec *getSS() const { return SS.get(); }
241
17
  Scope *getScope() const { return S; }
242
86
  CorrectionCandidateCallback *getCorrectionValidator() const {
243
86
    return CorrectionValidator.get();
244
86
  }
245
246
private:
247
  class NamespaceSpecifierSet {
248
    struct SpecifierInfo {
249
      DeclContext* DeclCtx;
250
      NestedNameSpecifier* NameSpecifier;
251
      unsigned EditDistance;
252
    };
253
254
    typedef SmallVector<DeclContext*, 4> DeclContextList;
255
    typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
256
257
    ASTContext &Context;
258
    DeclContextList CurContextChain;
259
    std::string CurNameSpecifier;
260
    SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
261
    SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
262
263
    std::map<unsigned, SpecifierInfoList> DistanceMap;
264
265
    /// Helper for building the list of DeclContexts between the current
266
    /// context and the top of the translation unit
267
    static DeclContextList buildContextChain(DeclContext *Start);
268
269
    unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
270
                                      NestedNameSpecifier *&NNS);
271
272
   public:
273
    NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
274
                          CXXScopeSpec *CurScopeSpec);
275
276
    /// Add the DeclContext (a namespace or record) to the set, computing
277
    /// the corresponding NestedNameSpecifier and its distance in the process.
278
    void addNameSpecifier(DeclContext *Ctx);
279
280
    /// Provides flat iteration over specifiers, sorted by distance.
281
    class iterator
282
        : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
283
                                            SpecifierInfo> {
284
      /// Always points to the last element in the distance map.
285
      const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
286
      /// Iterator on the distance map.
287
      std::map<unsigned, SpecifierInfoList>::iterator Outer;
288
      /// Iterator on an element in the distance map.
289
      SpecifierInfoList::iterator Inner;
290
291
    public:
292
      iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
293
          : OuterBack(std::prev(Set.DistanceMap.end())),
294
            Outer(Set.DistanceMap.begin()),
295
5.90k
            Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
296
5.90k
        assert(!Set.DistanceMap.empty());
297
5.90k
      }
298
299
85.0k
      iterator &operator++() {
300
85.0k
        ++Inner;
301
85.0k
        if (Inner == Outer->second.end() && 
Outer != OuterBack5.46k
) {
302
2.51k
          ++Outer;
303
2.51k
          Inner = Outer->second.begin();
304
2.51k
        }
305
85.0k
        return *this;
306
85.0k
      }
307
308
85.0k
      SpecifierInfo &operator*() { return *Inner; }
309
87.9k
      bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
310
    };
311
312
2.95k
    iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
313
2.95k
    iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
314
  };
315
316
  void addName(StringRef Name, NamedDecl *ND,
317
               NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
318
319
  /// Find any visible decls for the given typo correction candidate.
320
  /// If none are found, it to the set of candidates for which qualified lookups
321
  /// will be performed to find possible nested name specifier changes.
322
  bool resolveCorrection(TypoCorrection &Candidate);
323
324
  /// Perform qualified lookups on the queued set of typo correction
325
  /// candidates and add the nested name specifier changes to each candidate if
326
  /// a lookup succeeds (at which point the candidate will be returned to the
327
  /// main pool of potential corrections).
328
  void performQualifiedLookups();
329
330
  /// The name written that is a typo in the source.
331
  IdentifierInfo *Typo;
332
333
  /// The results found that have the smallest edit distance
334
  /// found (so far) with the typo name.
335
  ///
336
  /// The pointer value being set to the current DeclContext indicates
337
  /// whether there is a keyword with this name.
338
  TypoEditDistanceMap CorrectionResults;
339
340
  SmallVector<TypoCorrection, 4> ValidatedCorrections;
341
  size_t CurrentTCIndex;
342
  size_t SavedTCIndex;
343
344
  Sema &SemaRef;
345
  Scope *S;
346
  std::unique_ptr<CXXScopeSpec> SS;
347
  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
348
  DeclContext *MemberContext;
349
  LookupResult Result;
350
  NamespaceSpecifierSet Namespaces;
351
  SmallVector<TypoCorrection, 2> QualifiedResults;
352
  bool EnteringContext;
353
  bool SearchNamespaces;
354
};
355
356
1.08k
inline Sema::TypoExprState::TypoExprState() {}
357
358
2.18k
inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
359
2.18k
  *this = std::move(other);
360
2.18k
}
361
362
inline Sema::TypoExprState &Sema::TypoExprState::
363
2.23k
operator=(Sema::TypoExprState &&other) noexcept {
364
2.23k
  Consumer = std::move(other.Consumer);
365
2.23k
  DiagHandler = std::move(other.DiagHandler);
366
2.23k
  RecoveryHandler = std::move(other.RecoveryHandler);
367
2.23k
  return *this;
368
2.23k
}
369
370
} // end namespace clang
371
372
#endif