PathDiagnostic.h revision 651f13cea278ec967336033dd032faef0e9fc2ec
1//===--- PathDiagnostic.h - Path-Specific Diagnostic Handling ---*- 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 defines the PathDiagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_PATH_DIAGNOSTIC_H
15#define LLVM_CLANG_PATH_DIAGNOSTIC_H
16
17#include "clang/Analysis/ProgramPoint.h"
18#include "clang/Basic/SourceLocation.h"
19#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/IntrusiveRefCntPtr.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/PointerUnion.h"
23#include <deque>
24#include <iterator>
25#include <list>
26#include <string>
27#include <vector>
28
29namespace clang {
30class ConditionalOperator;
31class AnalysisDeclContext;
32class BinaryOperator;
33class CompoundStmt;
34class Decl;
35class LocationContext;
36class MemberExpr;
37class ParentMap;
38class ProgramPoint;
39class SourceManager;
40class Stmt;
41class CallExpr;
42
43namespace ento {
44
45class ExplodedNode;
46class SymExpr;
47typedef const SymExpr* SymbolRef;
48
49//===----------------------------------------------------------------------===//
50// High-level interface for handlers of path-sensitive diagnostics.
51//===----------------------------------------------------------------------===//
52
53class PathDiagnostic;
54
55class PathDiagnosticConsumer {
56public:
57  class PDFileEntry : public llvm::FoldingSetNode {
58  public:
59    PDFileEntry(llvm::FoldingSetNodeID &NodeID) : NodeID(NodeID) {}
60
61    typedef std::vector<std::pair<StringRef, StringRef> > ConsumerFiles;
62
63    /// \brief A vector of <consumer,file> pairs.
64    ConsumerFiles files;
65
66    /// \brief A precomputed hash tag used for uniquing PDFileEntry objects.
67    const llvm::FoldingSetNodeID NodeID;
68
69    /// \brief Used for profiling in the FoldingSet.
70    void Profile(llvm::FoldingSetNodeID &ID) { ID = NodeID; }
71  };
72
73  struct FilesMade : public llvm::FoldingSet<PDFileEntry> {
74    llvm::BumpPtrAllocator Alloc;
75
76    void addDiagnostic(const PathDiagnostic &PD,
77                       StringRef ConsumerName,
78                       StringRef fileName);
79
80    PDFileEntry::ConsumerFiles *getFiles(const PathDiagnostic &PD);
81  };
82
83private:
84  virtual void anchor();
85public:
86  PathDiagnosticConsumer() : flushed(false) {}
87  virtual ~PathDiagnosticConsumer();
88
89  void FlushDiagnostics(FilesMade *FilesMade);
90
91  virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
92                                    FilesMade *filesMade) = 0;
93
94  virtual StringRef getName() const = 0;
95
96  void HandlePathDiagnostic(PathDiagnostic *D);
97
98  enum PathGenerationScheme { None, Minimal, Extensive, AlternateExtensive };
99  virtual PathGenerationScheme getGenerationScheme() const { return Minimal; }
100  virtual bool supportsLogicalOpControlFlow() const { return false; }
101
102  /// Return true if the PathDiagnosticConsumer supports individual
103  /// PathDiagnostics that span multiple files.
104  virtual bool supportsCrossFileDiagnostics() const { return false; }
105
106protected:
107  bool flushed;
108  llvm::FoldingSet<PathDiagnostic> Diags;
109};
110
111//===----------------------------------------------------------------------===//
112// Path-sensitive diagnostics.
113//===----------------------------------------------------------------------===//
114
115class PathDiagnosticRange : public SourceRange {
116public:
117  bool isPoint;
118
119  PathDiagnosticRange(const SourceRange &R, bool isP = false)
120    : SourceRange(R), isPoint(isP) {}
121
122  PathDiagnosticRange() : isPoint(false) {}
123};
124
125typedef llvm::PointerUnion<const LocationContext*, AnalysisDeclContext*>
126                                                   LocationOrAnalysisDeclContext;
127
128class PathDiagnosticLocation {
129private:
130  enum Kind { RangeK, SingleLocK, StmtK, DeclK } K;
131  const Stmt *S;
132  const Decl *D;
133  const SourceManager *SM;
134  FullSourceLoc Loc;
135  PathDiagnosticRange Range;
136
137  PathDiagnosticLocation(SourceLocation L, const SourceManager &sm,
138                         Kind kind)
139    : K(kind), S(0), D(0), SM(&sm),
140      Loc(genLocation(L)), Range(genRange()) {
141  }
142
143  FullSourceLoc
144    genLocation(SourceLocation L = SourceLocation(),
145                LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext*)0) const;
146
147  PathDiagnosticRange
148    genRange(LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext*)0) const;
149
150public:
151  /// Create an invalid location.
152  PathDiagnosticLocation()
153    : K(SingleLocK), S(0), D(0), SM(0) {}
154
155  /// Create a location corresponding to the given statement.
156  PathDiagnosticLocation(const Stmt *s,
157                         const SourceManager &sm,
158                         LocationOrAnalysisDeclContext lac)
159    : K(s->getLocStart().isValid() ? StmtK : SingleLocK),
160      S(K == StmtK ? s : 0),
161      D(0), SM(&sm),
162      Loc(genLocation(SourceLocation(), lac)),
163      Range(genRange(lac)) {
164    assert(K == SingleLocK || S);
165    assert(K == SingleLocK || Loc.isValid());
166    assert(K == SingleLocK || Range.isValid());
167  }
168
169  /// Create a location corresponding to the given declaration.
170  PathDiagnosticLocation(const Decl *d, const SourceManager &sm)
171    : K(DeclK), S(0), D(d), SM(&sm),
172      Loc(genLocation()), Range(genRange()) {
173    assert(D);
174    assert(Loc.isValid());
175    assert(Range.isValid());
176  }
177
178  /// Create a location at an explicit offset in the source.
179  ///
180  /// This should only be used if there are no more appropriate constructors.
181  PathDiagnosticLocation(SourceLocation loc, const SourceManager &sm)
182    : K(SingleLocK), S(0), D(0), SM(&sm), Loc(loc, sm), Range(genRange()) {
183    assert(Loc.isValid());
184    assert(Range.isValid());
185  }
186
187  /// Create a location corresponding to the given declaration.
188  static PathDiagnosticLocation create(const Decl *D,
189                                       const SourceManager &SM) {
190    return PathDiagnosticLocation(D, SM);
191  }
192
193  /// Create a location for the beginning of the declaration.
194  static PathDiagnosticLocation createBegin(const Decl *D,
195                                            const SourceManager &SM);
196
197  /// Create a location for the beginning of the statement.
198  static PathDiagnosticLocation createBegin(const Stmt *S,
199                                            const SourceManager &SM,
200                                            const LocationOrAnalysisDeclContext LAC);
201
202  /// Create a location for the end of the statement.
203  ///
204  /// If the statement is a CompoundStatement, the location will point to the
205  /// closing brace instead of following it.
206  static PathDiagnosticLocation createEnd(const Stmt *S,
207                                          const SourceManager &SM,
208                                       const LocationOrAnalysisDeclContext LAC);
209
210  /// Create the location for the operator of the binary expression.
211  /// Assumes the statement has a valid location.
212  static PathDiagnosticLocation createOperatorLoc(const BinaryOperator *BO,
213                                                  const SourceManager &SM);
214  static PathDiagnosticLocation createConditionalColonLoc(
215                                                  const ConditionalOperator *CO,
216                                                  const SourceManager &SM);
217
218  /// For member expressions, return the location of the '.' or '->'.
219  /// Assumes the statement has a valid location.
220  static PathDiagnosticLocation createMemberLoc(const MemberExpr *ME,
221                                                const SourceManager &SM);
222
223  /// Create a location for the beginning of the compound statement.
224  /// Assumes the statement has a valid location.
225  static PathDiagnosticLocation createBeginBrace(const CompoundStmt *CS,
226                                                 const SourceManager &SM);
227
228  /// Create a location for the end of the compound statement.
229  /// Assumes the statement has a valid location.
230  static PathDiagnosticLocation createEndBrace(const CompoundStmt *CS,
231                                               const SourceManager &SM);
232
233  /// Create a location for the beginning of the enclosing declaration body.
234  /// Defaults to the beginning of the first statement in the declaration body.
235  static PathDiagnosticLocation createDeclBegin(const LocationContext *LC,
236                                                const SourceManager &SM);
237
238  /// Constructs a location for the end of the enclosing declaration body.
239  /// Defaults to the end of brace.
240  static PathDiagnosticLocation createDeclEnd(const LocationContext *LC,
241                                                   const SourceManager &SM);
242
243  /// Create a location corresponding to the given valid ExplodedNode.
244  static PathDiagnosticLocation create(const ProgramPoint& P,
245                                       const SourceManager &SMng);
246
247  /// Create a location corresponding to the next valid ExplodedNode as end
248  /// of path location.
249  static PathDiagnosticLocation createEndOfPath(const ExplodedNode* N,
250                                                const SourceManager &SM);
251
252  /// Convert the given location into a single kind location.
253  static PathDiagnosticLocation createSingleLocation(
254                                             const PathDiagnosticLocation &PDL);
255
256  bool operator==(const PathDiagnosticLocation &X) const {
257    return K == X.K && Loc == X.Loc && Range == X.Range;
258  }
259
260  bool operator!=(const PathDiagnosticLocation &X) const {
261    return !(*this == X);
262  }
263
264  bool isValid() const {
265    return SM != 0;
266  }
267
268  FullSourceLoc asLocation() const {
269    return Loc;
270  }
271
272  PathDiagnosticRange asRange() const {
273    return Range;
274  }
275
276  const Stmt *asStmt() const { assert(isValid()); return S; }
277  const Decl *asDecl() const { assert(isValid()); return D; }
278
279  bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; }
280
281  void invalidate() {
282    *this = PathDiagnosticLocation();
283  }
284
285  void flatten();
286
287  const SourceManager& getManager() const { assert(isValid()); return *SM; }
288
289  void Profile(llvm::FoldingSetNodeID &ID) const;
290
291  void dump() const;
292
293  /// \brief Given an exploded node, retrieve the statement that should be used
294  /// for the diagnostic location.
295  static const Stmt *getStmt(const ExplodedNode *N);
296
297  /// \brief Retrieve the statement corresponding to the successor node.
298  static const Stmt *getNextStmt(const ExplodedNode *N);
299};
300
301class PathDiagnosticLocationPair {
302private:
303  PathDiagnosticLocation Start, End;
304public:
305  PathDiagnosticLocationPair(const PathDiagnosticLocation &start,
306                             const PathDiagnosticLocation &end)
307    : Start(start), End(end) {}
308
309  const PathDiagnosticLocation &getStart() const { return Start; }
310  const PathDiagnosticLocation &getEnd() const { return End; }
311
312  void setStart(const PathDiagnosticLocation &L) { Start = L; }
313  void setEnd(const PathDiagnosticLocation &L) { End = L; }
314
315  void flatten() {
316    Start.flatten();
317    End.flatten();
318  }
319
320  void Profile(llvm::FoldingSetNodeID &ID) const {
321    Start.Profile(ID);
322    End.Profile(ID);
323  }
324};
325
326//===----------------------------------------------------------------------===//
327// Path "pieces" for path-sensitive diagnostics.
328//===----------------------------------------------------------------------===//
329
330class PathDiagnosticPiece : public RefCountedBaseVPTR {
331public:
332  enum Kind { ControlFlow, Event, Macro, Call };
333  enum DisplayHint { Above, Below };
334
335private:
336  const std::string str;
337  const Kind kind;
338  const DisplayHint Hint;
339
340  /// \brief In the containing bug report, this piece is the last piece from
341  /// the main source file.
342  bool LastInMainSourceFile;
343
344  /// A constant string that can be used to tag the PathDiagnosticPiece,
345  /// typically with the identification of the creator.  The actual pointer
346  /// value is meant to be an identifier; the string itself is useful for
347  /// debugging.
348  StringRef Tag;
349
350  std::vector<SourceRange> ranges;
351
352  PathDiagnosticPiece() LLVM_DELETED_FUNCTION;
353  PathDiagnosticPiece(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
354  void operator=(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
355
356protected:
357  PathDiagnosticPiece(StringRef s, Kind k, DisplayHint hint = Below);
358
359  PathDiagnosticPiece(Kind k, DisplayHint hint = Below);
360
361public:
362  virtual ~PathDiagnosticPiece();
363
364  StringRef getString() const { return str; }
365
366  /// Tag this PathDiagnosticPiece with the given C-string.
367  void setTag(const char *tag) { Tag = tag; }
368
369  /// Return the opaque tag (if any) on the PathDiagnosticPiece.
370  const void *getTag() const { return Tag.data(); }
371
372  /// Return the string representation of the tag.  This is useful
373  /// for debugging.
374  StringRef getTagStr() const { return Tag; }
375
376  /// getDisplayHint - Return a hint indicating where the diagnostic should
377  ///  be displayed by the PathDiagnosticConsumer.
378  DisplayHint getDisplayHint() const { return Hint; }
379
380  virtual PathDiagnosticLocation getLocation() const = 0;
381  virtual void flattenLocations() = 0;
382
383  Kind getKind() const { return kind; }
384
385  void addRange(SourceRange R) {
386    if (!R.isValid())
387      return;
388    ranges.push_back(R);
389  }
390
391  void addRange(SourceLocation B, SourceLocation E) {
392    if (!B.isValid() || !E.isValid())
393      return;
394    ranges.push_back(SourceRange(B,E));
395  }
396
397  /// Return the SourceRanges associated with this PathDiagnosticPiece.
398  ArrayRef<SourceRange> getRanges() const { return ranges; }
399
400  virtual void Profile(llvm::FoldingSetNodeID &ID) const;
401
402  void setAsLastInMainSourceFile() {
403    LastInMainSourceFile = true;
404  }
405
406  bool isLastInMainSourceFile() const {
407    return LastInMainSourceFile;
408  }
409
410  virtual void dump() const = 0;
411};
412
413
414class PathPieces : public std::list<IntrusiveRefCntPtr<PathDiagnosticPiece> > {
415  void flattenTo(PathPieces &Primary, PathPieces &Current,
416                 bool ShouldFlattenMacros) const;
417public:
418  ~PathPieces();
419
420  PathPieces flatten(bool ShouldFlattenMacros) const {
421    PathPieces Result;
422    flattenTo(Result, Result, ShouldFlattenMacros);
423    return Result;
424  }
425
426  void dump() const;
427};
428
429class PathDiagnosticSpotPiece : public PathDiagnosticPiece {
430private:
431  PathDiagnosticLocation Pos;
432public:
433  PathDiagnosticSpotPiece(const PathDiagnosticLocation &pos,
434                          StringRef s,
435                          PathDiagnosticPiece::Kind k,
436                          bool addPosRange = true)
437  : PathDiagnosticPiece(s, k), Pos(pos) {
438    assert(Pos.isValid() && Pos.asLocation().isValid() &&
439           "PathDiagnosticSpotPiece's must have a valid location.");
440    if (addPosRange && Pos.hasRange()) addRange(Pos.asRange());
441  }
442
443  PathDiagnosticLocation getLocation() const override { return Pos; }
444  void flattenLocations() override { Pos.flatten(); }
445
446  void Profile(llvm::FoldingSetNodeID &ID) const override;
447
448  static bool classof(const PathDiagnosticPiece *P) {
449    return P->getKind() == Event || P->getKind() == Macro;
450  }
451};
452
453/// \brief Interface for classes constructing Stack hints.
454///
455/// If a PathDiagnosticEvent occurs in a different frame than the final
456/// diagnostic the hints can be used to summarize the effect of the call.
457class StackHintGenerator {
458public:
459  virtual ~StackHintGenerator() = 0;
460
461  /// \brief Construct the Diagnostic message for the given ExplodedNode.
462  virtual std::string getMessage(const ExplodedNode *N) = 0;
463};
464
465/// \brief Constructs a Stack hint for the given symbol.
466///
467/// The class knows how to construct the stack hint message based on
468/// traversing the CallExpr associated with the call and checking if the given
469/// symbol is returned or is one of the arguments.
470/// The hint can be customized by redefining 'getMessageForX()' methods.
471class StackHintGeneratorForSymbol : public StackHintGenerator {
472private:
473  SymbolRef Sym;
474  std::string Msg;
475
476public:
477  StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
478  virtual ~StackHintGeneratorForSymbol() {}
479
480  /// \brief Search the call expression for the symbol Sym and dispatch the
481  /// 'getMessageForX()' methods to construct a specific message.
482  std::string getMessage(const ExplodedNode *N) override;
483
484  /// Produces the message of the following form:
485  ///   'Msg via Nth parameter'
486  virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex);
487  virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
488    return Msg;
489  }
490  virtual std::string getMessageForSymbolNotFound() {
491    return Msg;
492  }
493};
494
495class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece {
496  Optional<bool> IsPrunable;
497
498  /// If the event occurs in a different frame than the final diagnostic,
499  /// supply a message that will be used to construct an extra hint on the
500  /// returns from all the calls on the stack from this event to the final
501  /// diagnostic.
502  std::unique_ptr<StackHintGenerator> CallStackHint;
503
504public:
505  PathDiagnosticEventPiece(const PathDiagnosticLocation &pos,
506                           StringRef s, bool addPosRange = true,
507                           StackHintGenerator *stackHint = 0)
508    : PathDiagnosticSpotPiece(pos, s, Event, addPosRange),
509      CallStackHint(stackHint) {}
510
511  ~PathDiagnosticEventPiece();
512
513  /// Mark the diagnostic piece as being potentially prunable.  This
514  /// flag may have been previously set, at which point it will not
515  /// be reset unless one specifies to do so.
516  void setPrunable(bool isPrunable, bool override = false) {
517    if (IsPrunable.hasValue() && !override)
518     return;
519    IsPrunable = isPrunable;
520  }
521
522  /// Return true if the diagnostic piece is prunable.
523  bool isPrunable() const {
524    return IsPrunable.hasValue() ? IsPrunable.getValue() : false;
525  }
526
527  bool hasCallStackHint() { return (bool)CallStackHint; }
528
529  /// Produce the hint for the given node. The node contains
530  /// information about the call for which the diagnostic can be generated.
531  std::string getCallStackMessage(const ExplodedNode *N) {
532    if (CallStackHint)
533      return CallStackHint->getMessage(N);
534    return "";
535  }
536
537  void dump() const override;
538
539  static inline bool classof(const PathDiagnosticPiece *P) {
540    return P->getKind() == Event;
541  }
542};
543
544class PathDiagnosticCallPiece : public PathDiagnosticPiece {
545  PathDiagnosticCallPiece(const Decl *callerD,
546                          const PathDiagnosticLocation &callReturnPos)
547    : PathDiagnosticPiece(Call), Caller(callerD), Callee(0),
548      NoExit(false), callReturn(callReturnPos) {}
549
550  PathDiagnosticCallPiece(PathPieces &oldPath, const Decl *caller)
551    : PathDiagnosticPiece(Call), Caller(caller), Callee(0),
552      NoExit(true), path(oldPath) {}
553
554  const Decl *Caller;
555  const Decl *Callee;
556
557  // Flag signifying that this diagnostic has only call enter and no matching
558  // call exit.
559  bool NoExit;
560
561  // The custom string, which should appear after the call Return Diagnostic.
562  // TODO: Should we allow multiple diagnostics?
563  std::string CallStackMessage;
564
565public:
566  PathDiagnosticLocation callEnter;
567  PathDiagnosticLocation callEnterWithin;
568  PathDiagnosticLocation callReturn;
569  PathPieces path;
570
571  virtual ~PathDiagnosticCallPiece();
572
573  const Decl *getCaller() const { return Caller; }
574
575  const Decl *getCallee() const { return Callee; }
576  void setCallee(const CallEnter &CE, const SourceManager &SM);
577
578  bool hasCallStackMessage() { return !CallStackMessage.empty(); }
579  void setCallStackMessage(StringRef st) {
580    CallStackMessage = st;
581  }
582
583  PathDiagnosticLocation getLocation() const override {
584    return callEnter;
585  }
586
587  IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallEnterEvent() const;
588  IntrusiveRefCntPtr<PathDiagnosticEventPiece>
589    getCallEnterWithinCallerEvent() const;
590  IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallExitEvent() const;
591
592  void flattenLocations() override {
593    callEnter.flatten();
594    callReturn.flatten();
595    for (PathPieces::iterator I = path.begin(),
596         E = path.end(); I != E; ++I) (*I)->flattenLocations();
597  }
598
599  static PathDiagnosticCallPiece *construct(const ExplodedNode *N,
600                                            const CallExitEnd &CE,
601                                            const SourceManager &SM);
602
603  static PathDiagnosticCallPiece *construct(PathPieces &pieces,
604                                            const Decl *caller);
605
606  void dump() const override;
607
608  void Profile(llvm::FoldingSetNodeID &ID) const override;
609
610  static inline bool classof(const PathDiagnosticPiece *P) {
611    return P->getKind() == Call;
612  }
613};
614
615class PathDiagnosticControlFlowPiece : public PathDiagnosticPiece {
616  std::vector<PathDiagnosticLocationPair> LPairs;
617public:
618  PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos,
619                                 const PathDiagnosticLocation &endPos,
620                                 StringRef s)
621    : PathDiagnosticPiece(s, ControlFlow) {
622      LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos));
623    }
624
625  PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos,
626                                 const PathDiagnosticLocation &endPos)
627    : PathDiagnosticPiece(ControlFlow) {
628      LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos));
629    }
630
631  ~PathDiagnosticControlFlowPiece();
632
633  PathDiagnosticLocation getStartLocation() const {
634    assert(!LPairs.empty() &&
635           "PathDiagnosticControlFlowPiece needs at least one location.");
636    return LPairs[0].getStart();
637  }
638
639  PathDiagnosticLocation getEndLocation() const {
640    assert(!LPairs.empty() &&
641           "PathDiagnosticControlFlowPiece needs at least one location.");
642    return LPairs[0].getEnd();
643  }
644
645  void setStartLocation(const PathDiagnosticLocation &L) {
646    LPairs[0].setStart(L);
647  }
648
649  void setEndLocation(const PathDiagnosticLocation &L) {
650    LPairs[0].setEnd(L);
651  }
652
653  void push_back(const PathDiagnosticLocationPair &X) { LPairs.push_back(X); }
654
655  PathDiagnosticLocation getLocation() const override {
656    return getStartLocation();
657  }
658
659  typedef std::vector<PathDiagnosticLocationPair>::iterator iterator;
660  iterator begin() { return LPairs.begin(); }
661  iterator end()   { return LPairs.end(); }
662
663  void flattenLocations() override {
664    for (iterator I=begin(), E=end(); I!=E; ++I) I->flatten();
665  }
666
667  typedef std::vector<PathDiagnosticLocationPair>::const_iterator
668          const_iterator;
669  const_iterator begin() const { return LPairs.begin(); }
670  const_iterator end() const   { return LPairs.end(); }
671
672  static inline bool classof(const PathDiagnosticPiece *P) {
673    return P->getKind() == ControlFlow;
674  }
675
676  void dump() const override;
677
678  void Profile(llvm::FoldingSetNodeID &ID) const override;
679};
680
681class PathDiagnosticMacroPiece : public PathDiagnosticSpotPiece {
682public:
683  PathDiagnosticMacroPiece(const PathDiagnosticLocation &pos)
684    : PathDiagnosticSpotPiece(pos, "", Macro) {}
685
686  ~PathDiagnosticMacroPiece();
687
688  PathPieces subPieces;
689
690  bool containsEvent() const;
691
692  void flattenLocations() override {
693    PathDiagnosticSpotPiece::flattenLocations();
694    for (PathPieces::iterator I = subPieces.begin(),
695         E = subPieces.end(); I != E; ++I) (*I)->flattenLocations();
696  }
697
698  static inline bool classof(const PathDiagnosticPiece *P) {
699    return P->getKind() == Macro;
700  }
701
702  void dump() const override;
703
704  void Profile(llvm::FoldingSetNodeID &ID) const override;
705};
706
707/// PathDiagnostic - PathDiagnostic objects represent a single path-sensitive
708///  diagnostic.  It represents an ordered-collection of PathDiagnosticPieces,
709///  each which represent the pieces of the path.
710class PathDiagnostic : public llvm::FoldingSetNode {
711  std::string CheckName;
712  const Decl *DeclWithIssue;
713  std::string BugType;
714  std::string VerboseDesc;
715  std::string ShortDesc;
716  std::string Category;
717  std::deque<std::string> OtherDesc;
718
719  /// \brief Loc The location of the path diagnostic report.
720  PathDiagnosticLocation Loc;
721
722  PathPieces pathImpl;
723  SmallVector<PathPieces *, 3> pathStack;
724
725  /// \brief Important bug uniqueing location.
726  /// The location info is useful to differentiate between bugs.
727  PathDiagnosticLocation UniqueingLoc;
728  const Decl *UniqueingDecl;
729
730  PathDiagnostic() LLVM_DELETED_FUNCTION;
731public:
732  PathDiagnostic(StringRef CheckName, const Decl *DeclWithIssue,
733                 StringRef bugtype, StringRef verboseDesc, StringRef shortDesc,
734                 StringRef category, PathDiagnosticLocation LocationToUnique,
735                 const Decl *DeclToUnique);
736
737  ~PathDiagnostic();
738
739  const PathPieces &path;
740
741  /// Return the path currently used by builders for constructing the
742  /// PathDiagnostic.
743  PathPieces &getActivePath() {
744    if (pathStack.empty())
745      return pathImpl;
746    return *pathStack.back();
747  }
748
749  /// Return a mutable version of 'path'.
750  PathPieces &getMutablePieces() {
751    return pathImpl;
752  }
753
754  /// Return the unrolled size of the path.
755  unsigned full_size();
756
757  void pushActivePath(PathPieces *p) { pathStack.push_back(p); }
758  void popActivePath() { if (!pathStack.empty()) pathStack.pop_back(); }
759
760  bool isWithinCall() const { return !pathStack.empty(); }
761
762  void setEndOfPath(PathDiagnosticPiece *EndPiece) {
763    assert(!Loc.isValid() && "End location already set!");
764    Loc = EndPiece->getLocation();
765    assert(Loc.isValid() && "Invalid location for end-of-path piece");
766    getActivePath().push_back(EndPiece);
767  }
768
769  void appendToDesc(StringRef S) {
770    if (!ShortDesc.empty())
771      ShortDesc.append(S);
772    VerboseDesc.append(S);
773  }
774
775  void resetPath() {
776    pathStack.clear();
777    pathImpl.clear();
778    Loc = PathDiagnosticLocation();
779  }
780
781  /// \brief If the last piece of the report point to the header file, resets
782  /// the location of the report to be the last location in the main source
783  /// file.
784  void resetDiagnosticLocationToMainFile();
785
786  StringRef getVerboseDescription() const { return VerboseDesc; }
787  StringRef getShortDescription() const {
788    return ShortDesc.empty() ? VerboseDesc : ShortDesc;
789  }
790  StringRef getCheckName() const { return CheckName; }
791  StringRef getBugType() const { return BugType; }
792  StringRef getCategory() const { return Category; }
793
794  /// Return the semantic context where an issue occurred.  If the
795  /// issue occurs along a path, this represents the "central" area
796  /// where the bug manifests.
797  const Decl *getDeclWithIssue() const { return DeclWithIssue; }
798
799  typedef std::deque<std::string>::const_iterator meta_iterator;
800  meta_iterator meta_begin() const { return OtherDesc.begin(); }
801  meta_iterator meta_end() const { return OtherDesc.end(); }
802  void addMeta(StringRef s) { OtherDesc.push_back(s); }
803
804  PathDiagnosticLocation getLocation() const {
805    assert(Loc.isValid() && "No report location set yet!");
806    return Loc;
807  }
808
809  /// \brief Get the location on which the report should be uniqued.
810  PathDiagnosticLocation getUniqueingLoc() const {
811    return UniqueingLoc;
812  }
813
814  /// \brief Get the declaration containing the uniqueing location.
815  const Decl *getUniqueingDecl() const {
816    return UniqueingDecl;
817  }
818
819  void flattenLocations() {
820    Loc.flatten();
821    for (PathPieces::iterator I = pathImpl.begin(), E = pathImpl.end();
822         I != E; ++I) (*I)->flattenLocations();
823  }
824
825  /// Profiles the diagnostic, independent of the path it references.
826  ///
827  /// This can be used to merge diagnostics that refer to the same issue
828  /// along different paths.
829  void Profile(llvm::FoldingSetNodeID &ID) const;
830
831  /// Profiles the diagnostic, including its path.
832  ///
833  /// Two diagnostics with the same issue along different paths will generate
834  /// different profiles.
835  void FullProfile(llvm::FoldingSetNodeID &ID) const;
836};
837
838} // end GR namespace
839
840} //end clang namespace
841
842#endif
843