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