1 //===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
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 /// \file
10 /// Defines the Diagnostic-related interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
16 
17 #include "clang/Basic/DiagnosticIDs.h"
18 #include "clang/Basic/DiagnosticOptions.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/Specifiers.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/IntrusiveRefCntPtr.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Support/Compiler.h"
29 #include <cassert>
30 #include <cstdint>
31 #include <limits>
32 #include <list>
33 #include <map>
34 #include <memory>
35 #include <string>
36 #include <type_traits>
37 #include <utility>
38 #include <vector>
39 
40 namespace llvm {
41 class Error;
42 }
43 
44 namespace clang {
45 
46 class DeclContext;
47 class DiagnosticBuilder;
48 class DiagnosticConsumer;
49 class IdentifierInfo;
50 class LangOptions;
51 class Preprocessor;
52 class SourceManager;
53 class StoredDiagnostic;
54 
55 namespace tok {
56 
57 enum TokenKind : unsigned short;
58 
59 } // namespace tok
60 
61 /// Annotates a diagnostic with some code that should be
62 /// inserted, removed, or replaced to fix the problem.
63 ///
64 /// This kind of hint should be used when we are certain that the
65 /// introduction, removal, or modification of a particular (small!)
66 /// amount of code will correct a compilation error. The compiler
67 /// should also provide full recovery from such errors, such that
68 /// suppressing the diagnostic output can still result in successful
69 /// compilation.
70 class FixItHint {
71 public:
72   /// Code that should be replaced to correct the error. Empty for an
73   /// insertion hint.
74   CharSourceRange RemoveRange;
75 
76   /// Code in the specific range that should be inserted in the insertion
77   /// location.
78   CharSourceRange InsertFromRange;
79 
80   /// The actual code to insert at the insertion location, as a
81   /// string.
82   std::string CodeToInsert;
83 
84   bool BeforePreviousInsertions = false;
85 
86   /// Empty code modification hint, indicating that no code
87   /// modification is known.
88   FixItHint() = default;
89 
90   bool isNull() const {
91     return !RemoveRange.isValid();
92   }
93 
94   /// Create a code modification hint that inserts the given
95   /// code string at a specific location.
96   static FixItHint CreateInsertion(SourceLocation InsertionLoc,
97                                    StringRef Code,
98                                    bool BeforePreviousInsertions = false) {
99     FixItHint Hint;
100     Hint.RemoveRange =
101       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
102     Hint.CodeToInsert = std::string(Code);
103     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
104     return Hint;
105   }
106 
107   /// Create a code modification hint that inserts the given
108   /// code from \p FromRange at a specific location.
109   static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
110                                             CharSourceRange FromRange,
111                                         bool BeforePreviousInsertions = false) {
112     FixItHint Hint;
113     Hint.RemoveRange =
114       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
115     Hint.InsertFromRange = FromRange;
116     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
117     return Hint;
118   }
119 
120   /// Create a code modification hint that removes the given
121   /// source range.
122   static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
123     FixItHint Hint;
124     Hint.RemoveRange = RemoveRange;
125     return Hint;
126   }
127   static FixItHint CreateRemoval(SourceRange RemoveRange) {
128     return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
129   }
130 
131   /// Create a code modification hint that replaces the given
132   /// source range with the given code string.
133   static FixItHint CreateReplacement(CharSourceRange RemoveRange,
134                                      StringRef Code) {
135     FixItHint Hint;
136     Hint.RemoveRange = RemoveRange;
137     Hint.CodeToInsert = std::string(Code);
138     return Hint;
139   }
140 
141   static FixItHint CreateReplacement(SourceRange RemoveRange,
142                                      StringRef Code) {
143     return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
144   }
145 };
146 
147 struct DiagnosticStorage {
148   enum {
149     /// The maximum number of arguments we can hold. We
150     /// currently only support up to 10 arguments (%0-%9).
151     ///
152     /// A single diagnostic with more than that almost certainly has to
153     /// be simplified anyway.
154     MaxArguments = 10
155   };
156 
157   /// The number of entries in Arguments.
158   unsigned char NumDiagArgs = 0;
159 
160   /// Specifies for each argument whether it is in DiagArgumentsStr
161   /// or in DiagArguments.
162   unsigned char DiagArgumentsKind[MaxArguments];
163 
164   /// The values for the various substitution positions.
165   ///
166   /// This is used when the argument is not an std::string. The specific value
167   /// is mangled into an intptr_t and the interpretation depends on exactly
168   /// what sort of argument kind it is.
169   intptr_t DiagArgumentsVal[MaxArguments];
170 
171   /// The values for the various substitution positions that have
172   /// string arguments.
173   std::string DiagArgumentsStr[MaxArguments];
174 
175   /// The list of ranges added to this diagnostic.
176   SmallVector<CharSourceRange, 8> DiagRanges;
177 
178   /// If valid, provides a hint with some code to insert, remove, or
179   /// modify at a particular position.
180   SmallVector<FixItHint, 6> FixItHints;
181 
182   DiagnosticStorage() = default;
183 };
184 
185 /// Concrete class used by the front-end to report problems and issues.
186 ///
187 /// This massages the diagnostics (e.g. handling things like "report warnings
188 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
189 /// the user. DiagnosticsEngine is tied to one translation unit and one
190 /// SourceManager.
191 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
192 public:
193   /// The level of the diagnostic, after it has been through mapping.
194   enum Level {
195     Ignored = DiagnosticIDs::Ignored,
196     Note = DiagnosticIDs::Note,
197     Remark = DiagnosticIDs::Remark,
198     Warning = DiagnosticIDs::Warning,
199     Error = DiagnosticIDs::Error,
200     Fatal = DiagnosticIDs::Fatal
201   };
202 
203   enum ArgumentKind {
204     /// std::string
205     ak_std_string,
206 
207     /// const char *
208     ak_c_string,
209 
210     /// int
211     ak_sint,
212 
213     /// unsigned
214     ak_uint,
215 
216     /// enum TokenKind : unsigned
217     ak_tokenkind,
218 
219     /// IdentifierInfo
220     ak_identifierinfo,
221 
222     /// address space
223     ak_addrspace,
224 
225     /// Qualifiers
226     ak_qual,
227 
228     /// QualType
229     ak_qualtype,
230 
231     /// DeclarationName
232     ak_declarationname,
233 
234     /// NamedDecl *
235     ak_nameddecl,
236 
237     /// NestedNameSpecifier *
238     ak_nestednamespec,
239 
240     /// DeclContext *
241     ak_declcontext,
242 
243     /// pair<QualType, QualType>
244     ak_qualtype_pair,
245 
246     /// Attr *
247     ak_attr
248   };
249 
250   /// Represents on argument value, which is a union discriminated
251   /// by ArgumentKind, with a value.
252   using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
253 
254 private:
255   // Used by __extension__
256   unsigned char AllExtensionsSilenced = 0;
257 
258   // Treat fatal errors like errors.
259   bool FatalsAsError = false;
260 
261   // Suppress all diagnostics.
262   bool SuppressAllDiagnostics = false;
263 
264   // Elide common types of templates.
265   bool ElideType = true;
266 
267   // Print a tree when comparing templates.
268   bool PrintTemplateTree = false;
269 
270   // Color printing is enabled.
271   bool ShowColors = false;
272 
273   // Which overload candidates to show.
274   OverloadsShown ShowOverloads = Ovl_All;
275 
276   // Cap of # errors emitted, 0 -> no limit.
277   unsigned ErrorLimit = 0;
278 
279   // Cap on depth of template backtrace stack, 0 -> no limit.
280   unsigned TemplateBacktraceLimit = 0;
281 
282   // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
283   unsigned ConstexprBacktraceLimit = 0;
284 
285   IntrusiveRefCntPtr<DiagnosticIDs> Diags;
286   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
287   DiagnosticConsumer *Client = nullptr;
288   std::unique_ptr<DiagnosticConsumer> Owner;
289   SourceManager *SourceMgr = nullptr;
290 
291   /// Mapping information for diagnostics.
292   ///
293   /// Mapping info is packed into four bits per diagnostic.  The low three
294   /// bits are the mapping (an instance of diag::Severity), or zero if unset.
295   /// The high bit is set when the mapping was established as a user mapping.
296   /// If the high bit is clear, then the low bits are set to the default
297   /// value, and should be mapped with -pedantic, -Werror, etc.
298   ///
299   /// A new DiagState is created and kept around when diagnostic pragmas modify
300   /// the state so that we know what is the diagnostic state at any given
301   /// source location.
302   class DiagState {
303     llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
304 
305   public:
306     // "Global" configuration state that can actually vary between modules.
307 
308     // Ignore all warnings: -w
309     unsigned IgnoreAllWarnings : 1;
310 
311     // Enable all warnings.
312     unsigned EnableAllWarnings : 1;
313 
314     // Treat warnings like errors.
315     unsigned WarningsAsErrors : 1;
316 
317     // Treat errors like fatal errors.
318     unsigned ErrorsAsFatal : 1;
319 
320     // Suppress warnings in system headers.
321     unsigned SuppressSystemWarnings : 1;
322 
323     // Map extensions to warnings or errors?
324     diag::Severity ExtBehavior = diag::Severity::Ignored;
325 
326     DiagState()
327         : IgnoreAllWarnings(false), EnableAllWarnings(false),
328           WarningsAsErrors(false), ErrorsAsFatal(false),
329           SuppressSystemWarnings(false) {}
330 
331     using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
332     using const_iterator =
333         llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
334 
335     void setMapping(diag::kind Diag, DiagnosticMapping Info) {
336       DiagMap[Diag] = Info;
337     }
338 
339     DiagnosticMapping lookupMapping(diag::kind Diag) const {
340       return DiagMap.lookup(Diag);
341     }
342 
343     DiagnosticMapping &getOrAddMapping(diag::kind Diag);
344 
345     const_iterator begin() const { return DiagMap.begin(); }
346     const_iterator end() const { return DiagMap.end(); }
347   };
348 
349   /// Keeps and automatically disposes all DiagStates that we create.
350   std::list<DiagState> DiagStates;
351 
352   /// A mapping from files to the diagnostic states for those files. Lazily
353   /// built on demand for files in which the diagnostic state has not changed.
354   class DiagStateMap {
355   public:
356     /// Add an initial diagnostic state.
357     void appendFirst(DiagState *State);
358 
359     /// Add a new latest state point.
360     void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
361 
362     /// Look up the diagnostic state at a given source location.
363     DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
364 
365     /// Determine whether this map is empty.
366     bool empty() const { return Files.empty(); }
367 
368     /// Clear out this map.
369     void clear() {
370       Files.clear();
371       FirstDiagState = CurDiagState = nullptr;
372       CurDiagStateLoc = SourceLocation();
373     }
374 
375     /// Produce a debugging dump of the diagnostic state.
376     LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
377                                StringRef DiagName = StringRef()) const;
378 
379     /// Grab the most-recently-added state point.
380     DiagState *getCurDiagState() const { return CurDiagState; }
381 
382     /// Get the location at which a diagnostic state was last added.
383     SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
384 
385   private:
386     friend class ASTReader;
387     friend class ASTWriter;
388 
389     /// Represents a point in source where the diagnostic state was
390     /// modified because of a pragma.
391     ///
392     /// 'Loc' can be null if the point represents the diagnostic state
393     /// modifications done through the command-line.
394     struct DiagStatePoint {
395       DiagState *State;
396       unsigned Offset;
397 
398       DiagStatePoint(DiagState *State, unsigned Offset)
399           : State(State), Offset(Offset) {}
400     };
401 
402     /// Description of the diagnostic states and state transitions for a
403     /// particular FileID.
404     struct File {
405       /// The diagnostic state for the parent file. This is strictly redundant,
406       /// as looking up the DecomposedIncludedLoc for the FileID in the Files
407       /// map would give us this, but we cache it here for performance.
408       File *Parent = nullptr;
409 
410       /// The offset of this file within its parent.
411       unsigned ParentOffset = 0;
412 
413       /// Whether this file has any local (not imported from an AST file)
414       /// diagnostic state transitions.
415       bool HasLocalTransitions = false;
416 
417       /// The points within the file where the state changes. There will always
418       /// be at least one of these (the state on entry to the file).
419       llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
420 
421       DiagState *lookup(unsigned Offset) const;
422     };
423 
424     /// The diagnostic states for each file.
425     mutable std::map<FileID, File> Files;
426 
427     /// The initial diagnostic state.
428     DiagState *FirstDiagState;
429 
430     /// The current diagnostic state.
431     DiagState *CurDiagState;
432 
433     /// The location at which the current diagnostic state was established.
434     SourceLocation CurDiagStateLoc;
435 
436     /// Get the diagnostic state information for a file.
437     File *getFile(SourceManager &SrcMgr, FileID ID) const;
438   };
439 
440   DiagStateMap DiagStatesByLoc;
441 
442   /// Keeps the DiagState that was active during each diagnostic 'push'
443   /// so we can get back at it when we 'pop'.
444   std::vector<DiagState *> DiagStateOnPushStack;
445 
446   DiagState *GetCurDiagState() const {
447     return DiagStatesByLoc.getCurDiagState();
448   }
449 
450   void PushDiagStatePoint(DiagState *State, SourceLocation L);
451 
452   /// Finds the DiagStatePoint that contains the diagnostic state of
453   /// the given source location.
454   DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
455     return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
456                      : DiagStatesByLoc.getCurDiagState();
457   }
458 
459   /// Sticky flag set to \c true when an error is emitted.
460   bool ErrorOccurred;
461 
462   /// Sticky flag set to \c true when an "uncompilable error" occurs.
463   /// I.e. an error that was not upgraded from a warning by -Werror.
464   bool UncompilableErrorOccurred;
465 
466   /// Sticky flag set to \c true when a fatal error is emitted.
467   bool FatalErrorOccurred;
468 
469   /// Indicates that an unrecoverable error has occurred.
470   bool UnrecoverableErrorOccurred;
471 
472   /// Counts for DiagnosticErrorTrap to check whether an error occurred
473   /// during a parsing section, e.g. during parsing a function.
474   unsigned TrapNumErrorsOccurred;
475   unsigned TrapNumUnrecoverableErrorsOccurred;
476 
477   /// The level of the last diagnostic emitted.
478   ///
479   /// This is used to emit continuation diagnostics with the same level as the
480   /// diagnostic that they follow.
481   DiagnosticIDs::Level LastDiagLevel;
482 
483   /// Number of warnings reported
484   unsigned NumWarnings;
485 
486   /// Number of errors reported
487   unsigned NumErrors;
488 
489   /// A function pointer that converts an opaque diagnostic
490   /// argument to a strings.
491   ///
492   /// This takes the modifiers and argument that was present in the diagnostic.
493   ///
494   /// The PrevArgs array indicates the previous arguments formatted for this
495   /// diagnostic.  Implementations of this function can use this information to
496   /// avoid redundancy across arguments.
497   ///
498   /// This is a hack to avoid a layering violation between libbasic and libsema.
499   using ArgToStringFnTy = void (*)(
500       ArgumentKind Kind, intptr_t Val,
501       StringRef Modifier, StringRef Argument,
502       ArrayRef<ArgumentValue> PrevArgs,
503       SmallVectorImpl<char> &Output,
504       void *Cookie,
505       ArrayRef<intptr_t> QualTypeVals);
506 
507   void *ArgToStringCookie = nullptr;
508   ArgToStringFnTy ArgToStringFn;
509 
510   /// ID of the "delayed" diagnostic, which is a (typically
511   /// fatal) diagnostic that had to be delayed because it was found
512   /// while emitting another diagnostic.
513   unsigned DelayedDiagID;
514 
515   /// First string argument for the delayed diagnostic.
516   std::string DelayedDiagArg1;
517 
518   /// Second string argument for the delayed diagnostic.
519   std::string DelayedDiagArg2;
520 
521   /// Third string argument for the delayed diagnostic.
522   std::string DelayedDiagArg3;
523 
524   /// Optional flag value.
525   ///
526   /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
527   /// -Rpass=<value>. The content of this string is emitted after the flag name
528   /// and '='.
529   std::string FlagValue;
530 
531 public:
532   explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
533                              IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
534                              DiagnosticConsumer *client = nullptr,
535                              bool ShouldOwnClient = true);
536   DiagnosticsEngine(const DiagnosticsEngine &) = delete;
537   DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
538   ~DiagnosticsEngine();
539 
540   LLVM_DUMP_METHOD void dump() const;
541   LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
542 
543   const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
544     return Diags;
545   }
546 
547   /// Retrieve the diagnostic options.
548   DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
549 
550   using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
551 
552   /// Get the current set of diagnostic mappings.
553   diag_mapping_range getDiagnosticMappings() const {
554     const DiagState &DS = *GetCurDiagState();
555     return diag_mapping_range(DS.begin(), DS.end());
556   }
557 
558   DiagnosticConsumer *getClient() { return Client; }
559   const DiagnosticConsumer *getClient() const { return Client; }
560 
561   /// Determine whether this \c DiagnosticsEngine object own its client.
562   bool ownsClient() const { return Owner != nullptr; }
563 
564   /// Return the current diagnostic client along with ownership of that
565   /// client.
566   std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
567 
568   bool hasSourceManager() const { return SourceMgr != nullptr; }
569 
570   SourceManager &getSourceManager() const {
571     assert(SourceMgr && "SourceManager not set!");
572     return *SourceMgr;
573   }
574 
575   void setSourceManager(SourceManager *SrcMgr) {
576     assert(DiagStatesByLoc.empty() &&
577            "Leftover diag state from a different SourceManager.");
578     SourceMgr = SrcMgr;
579   }
580 
581   //===--------------------------------------------------------------------===//
582   //  DiagnosticsEngine characterization methods, used by a client to customize
583   //  how diagnostics are emitted.
584   //
585 
586   /// Copies the current DiagMappings and pushes the new copy
587   /// onto the top of the stack.
588   void pushMappings(SourceLocation Loc);
589 
590   /// Pops the current DiagMappings off the top of the stack,
591   /// causing the new top of the stack to be the active mappings.
592   ///
593   /// \returns \c true if the pop happens, \c false if there is only one
594   /// DiagMapping on the stack.
595   bool popMappings(SourceLocation Loc);
596 
597   /// Set the diagnostic client associated with this diagnostic object.
598   ///
599   /// \param ShouldOwnClient true if the diagnostic object should take
600   /// ownership of \c client.
601   void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
602 
603   /// Specify a limit for the number of errors we should
604   /// emit before giving up.
605   ///
606   /// Zero disables the limit.
607   void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
608 
609   /// Specify the maximum number of template instantiation
610   /// notes to emit along with a given diagnostic.
611   void setTemplateBacktraceLimit(unsigned Limit) {
612     TemplateBacktraceLimit = Limit;
613   }
614 
615   /// Retrieve the maximum number of template instantiation
616   /// notes to emit along with a given diagnostic.
617   unsigned getTemplateBacktraceLimit() const {
618     return TemplateBacktraceLimit;
619   }
620 
621   /// Specify the maximum number of constexpr evaluation
622   /// notes to emit along with a given diagnostic.
623   void setConstexprBacktraceLimit(unsigned Limit) {
624     ConstexprBacktraceLimit = Limit;
625   }
626 
627   /// Retrieve the maximum number of constexpr evaluation
628   /// notes to emit along with a given diagnostic.
629   unsigned getConstexprBacktraceLimit() const {
630     return ConstexprBacktraceLimit;
631   }
632 
633   /// When set to true, any unmapped warnings are ignored.
634   ///
635   /// If this and WarningsAsErrors are both set, then this one wins.
636   void setIgnoreAllWarnings(bool Val) {
637     GetCurDiagState()->IgnoreAllWarnings = Val;
638   }
639   bool getIgnoreAllWarnings() const {
640     return GetCurDiagState()->IgnoreAllWarnings;
641   }
642 
643   /// When set to true, any unmapped ignored warnings are no longer
644   /// ignored.
645   ///
646   /// If this and IgnoreAllWarnings are both set, then that one wins.
647   void setEnableAllWarnings(bool Val) {
648     GetCurDiagState()->EnableAllWarnings = Val;
649   }
650   bool getEnableAllWarnings() const {
651     return GetCurDiagState()->EnableAllWarnings;
652   }
653 
654   /// When set to true, any warnings reported are issued as errors.
655   void setWarningsAsErrors(bool Val) {
656     GetCurDiagState()->WarningsAsErrors = Val;
657   }
658   bool getWarningsAsErrors() const {
659     return GetCurDiagState()->WarningsAsErrors;
660   }
661 
662   /// When set to true, any error reported is made a fatal error.
663   void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
664   bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
665 
666   /// \brief When set to true, any fatal error reported is made an error.
667   ///
668   /// This setting takes precedence over the setErrorsAsFatal setting above.
669   void setFatalsAsError(bool Val) { FatalsAsError = Val; }
670   bool getFatalsAsError() const { return FatalsAsError; }
671 
672   /// When set to true mask warnings that come from system headers.
673   void setSuppressSystemWarnings(bool Val) {
674     GetCurDiagState()->SuppressSystemWarnings = Val;
675   }
676   bool getSuppressSystemWarnings() const {
677     return GetCurDiagState()->SuppressSystemWarnings;
678   }
679 
680   /// Suppress all diagnostics, to silence the front end when we
681   /// know that we don't want any more diagnostics to be passed along to the
682   /// client
683   void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
684   bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
685 
686   /// Set type eliding, to skip outputting same types occurring in
687   /// template types.
688   void setElideType(bool Val) { ElideType = Val; }
689   bool getElideType() { return ElideType; }
690 
691   /// Set tree printing, to outputting the template difference in a
692   /// tree format.
693   void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
694   bool getPrintTemplateTree() { return PrintTemplateTree; }
695 
696   /// Set color printing, so the type diffing will inject color markers
697   /// into the output.
698   void setShowColors(bool Val) { ShowColors = Val; }
699   bool getShowColors() { return ShowColors; }
700 
701   /// Specify which overload candidates to show when overload resolution
702   /// fails.
703   ///
704   /// By default, we show all candidates.
705   void setShowOverloads(OverloadsShown Val) {
706     ShowOverloads = Val;
707   }
708   OverloadsShown getShowOverloads() const { return ShowOverloads; }
709 
710   /// Pretend that the last diagnostic issued was ignored, so any
711   /// subsequent notes will be suppressed, or restore a prior ignoring
712   /// state after ignoring some diagnostics and their notes, possibly in
713   /// the middle of another diagnostic.
714   ///
715   /// This can be used by clients who suppress diagnostics themselves.
716   void setLastDiagnosticIgnored(bool Ignored) {
717     if (LastDiagLevel == DiagnosticIDs::Fatal)
718       FatalErrorOccurred = true;
719     LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
720   }
721 
722   /// Determine whether the previous diagnostic was ignored. This can
723   /// be used by clients that want to determine whether notes attached to a
724   /// diagnostic will be suppressed.
725   bool isLastDiagnosticIgnored() const {
726     return LastDiagLevel == DiagnosticIDs::Ignored;
727   }
728 
729   /// Controls whether otherwise-unmapped extension diagnostics are
730   /// mapped onto ignore/warning/error.
731   ///
732   /// This corresponds to the GCC -pedantic and -pedantic-errors option.
733   void setExtensionHandlingBehavior(diag::Severity H) {
734     GetCurDiagState()->ExtBehavior = H;
735   }
736   diag::Severity getExtensionHandlingBehavior() const {
737     return GetCurDiagState()->ExtBehavior;
738   }
739 
740   /// Counter bumped when an __extension__  block is/ encountered.
741   ///
742   /// When non-zero, all extension diagnostics are entirely silenced, no
743   /// matter how they are mapped.
744   void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
745   void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
746   bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
747 
748   /// This allows the client to specify that certain warnings are
749   /// ignored.
750   ///
751   /// Notes can never be mapped, errors can only be mapped to fatal, and
752   /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
753   ///
754   /// \param Loc The source location that this change of diagnostic state should
755   /// take affect. It can be null if we are setting the latest state.
756   void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
757 
758   /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
759   /// have the specified mapping.
760   ///
761   /// \returns true (and ignores the request) if "Group" was unknown, false
762   /// otherwise.
763   ///
764   /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
765   /// state of the -Wfoo group and vice versa.
766   ///
767   /// \param Loc The source location that this change of diagnostic state should
768   /// take affect. It can be null if we are setting the state from command-line.
769   bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
770                            diag::Severity Map,
771                            SourceLocation Loc = SourceLocation());
772 
773   /// Set the warning-as-error flag for the given diagnostic group.
774   ///
775   /// This function always only operates on the current diagnostic state.
776   ///
777   /// \returns True if the given group is unknown, false otherwise.
778   bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
779 
780   /// Set the error-as-fatal flag for the given diagnostic group.
781   ///
782   /// This function always only operates on the current diagnostic state.
783   ///
784   /// \returns True if the given group is unknown, false otherwise.
785   bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
786 
787   /// Add the specified mapping to all diagnostics of the specified
788   /// flavor.
789   ///
790   /// Mainly to be used by -Wno-everything to disable all warnings but allow
791   /// subsequent -W options to enable specific warnings.
792   void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
793                          SourceLocation Loc = SourceLocation());
794 
795   bool hasErrorOccurred() const { return ErrorOccurred; }
796 
797   /// Errors that actually prevent compilation, not those that are
798   /// upgraded from a warning by -Werror.
799   bool hasUncompilableErrorOccurred() const {
800     return UncompilableErrorOccurred;
801   }
802   bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
803 
804   /// Determine whether any kind of unrecoverable error has occurred.
805   bool hasUnrecoverableErrorOccurred() const {
806     return FatalErrorOccurred || UnrecoverableErrorOccurred;
807   }
808 
809   unsigned getNumWarnings() const { return NumWarnings; }
810 
811   void setNumWarnings(unsigned NumWarnings) {
812     this->NumWarnings = NumWarnings;
813   }
814 
815   /// Return an ID for a diagnostic with the specified format string and
816   /// level.
817   ///
818   /// If this is the first request for this diagnostic, it is registered and
819   /// created, otherwise the existing ID is returned.
820   ///
821   /// \param FormatString A fixed diagnostic format string that will be hashed
822   /// and mapped to a unique DiagID.
823   template <unsigned N>
824   unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
825     return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
826                                   StringRef(FormatString, N - 1));
827   }
828 
829   /// Converts a diagnostic argument (as an intptr_t) into the string
830   /// that represents it.
831   void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
832                           StringRef Modifier, StringRef Argument,
833                           ArrayRef<ArgumentValue> PrevArgs,
834                           SmallVectorImpl<char> &Output,
835                           ArrayRef<intptr_t> QualTypeVals) const {
836     ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
837                   ArgToStringCookie, QualTypeVals);
838   }
839 
840   void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
841     ArgToStringFn = Fn;
842     ArgToStringCookie = Cookie;
843   }
844 
845   /// Note that the prior diagnostic was emitted by some other
846   /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
847   void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
848     LastDiagLevel = Other.LastDiagLevel;
849   }
850 
851   /// Reset the state of the diagnostic object to its initial
852   /// configuration.
853   void Reset();
854 
855   //===--------------------------------------------------------------------===//
856   // DiagnosticsEngine classification and reporting interfaces.
857   //
858 
859   /// Determine whether the diagnostic is known to be ignored.
860   ///
861   /// This can be used to opportunistically avoid expensive checks when it's
862   /// known for certain that the diagnostic has been suppressed at the
863   /// specified location \p Loc.
864   ///
865   /// \param Loc The source location we are interested in finding out the
866   /// diagnostic state. Can be null in order to query the latest state.
867   bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
868     return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
869            diag::Severity::Ignored;
870   }
871 
872   /// Based on the way the client configured the DiagnosticsEngine
873   /// object, classify the specified diagnostic ID into a Level, consumable by
874   /// the DiagnosticConsumer.
875   ///
876   /// To preserve invariant assumptions, this function should not be used to
877   /// influence parse or semantic analysis actions. Instead consider using
878   /// \c isIgnored().
879   ///
880   /// \param Loc The source location we are interested in finding out the
881   /// diagnostic state. Can be null in order to query the latest state.
882   Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
883     return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
884   }
885 
886   /// Issue the message to the client.
887   ///
888   /// This actually returns an instance of DiagnosticBuilder which emits the
889   /// diagnostics (through @c ProcessDiag) when it is destroyed.
890   ///
891   /// \param DiagID A member of the @c diag::kind enum.
892   /// \param Loc Represents the source location associated with the diagnostic,
893   /// which can be an invalid location if no position information is available.
894   inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
895   inline DiagnosticBuilder Report(unsigned DiagID);
896 
897   void Report(const StoredDiagnostic &storedDiag);
898 
899   /// Determine whethere there is already a diagnostic in flight.
900   bool isDiagnosticInFlight() const {
901     return CurDiagID != std::numeric_limits<unsigned>::max();
902   }
903 
904   /// Set the "delayed" diagnostic that will be emitted once
905   /// the current diagnostic completes.
906   ///
907   ///  If a diagnostic is already in-flight but the front end must
908   ///  report a problem (e.g., with an inconsistent file system
909   ///  state), this routine sets a "delayed" diagnostic that will be
910   ///  emitted after the current diagnostic completes. This should
911   ///  only be used for fatal errors detected at inconvenient
912   ///  times. If emitting a delayed diagnostic causes a second delayed
913   ///  diagnostic to be introduced, that second delayed diagnostic
914   ///  will be ignored.
915   ///
916   /// \param DiagID The ID of the diagnostic being delayed.
917   ///
918   /// \param Arg1 A string argument that will be provided to the
919   /// diagnostic. A copy of this string will be stored in the
920   /// DiagnosticsEngine object itself.
921   ///
922   /// \param Arg2 A string argument that will be provided to the
923   /// diagnostic. A copy of this string will be stored in the
924   /// DiagnosticsEngine object itself.
925   ///
926   /// \param Arg3 A string argument that will be provided to the
927   /// diagnostic. A copy of this string will be stored in the
928   /// DiagnosticsEngine object itself.
929   void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
930                             StringRef Arg2 = "", StringRef Arg3 = "");
931 
932   /// Clear out the current diagnostic.
933   void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
934 
935   /// Return the value associated with this diagnostic flag.
936   StringRef getFlagValue() const { return FlagValue; }
937 
938 private:
939   // This is private state used by DiagnosticBuilder.  We put it here instead of
940   // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
941   // object.  This implementation choice means that we can only have one
942   // diagnostic "in flight" at a time, but this seems to be a reasonable
943   // tradeoff to keep these objects small.  Assertions verify that only one
944   // diagnostic is in flight at a time.
945   friend class Diagnostic;
946   friend class DiagnosticBuilder;
947   friend class DiagnosticErrorTrap;
948   friend class DiagnosticIDs;
949   friend class PartialDiagnostic;
950 
951   /// Report the delayed diagnostic.
952   void ReportDelayed();
953 
954   /// The location of the current diagnostic that is in flight.
955   SourceLocation CurDiagLoc;
956 
957   /// The ID of the current diagnostic that is in flight.
958   ///
959   /// This is set to std::numeric_limits<unsigned>::max() when there is no
960   /// diagnostic in flight.
961   unsigned CurDiagID;
962 
963   enum {
964     /// The maximum number of arguments we can hold.
965     ///
966     /// We currently only support up to 10 arguments (%0-%9).  A single
967     /// diagnostic with more than that almost certainly has to be simplified
968     /// anyway.
969     MaxArguments = DiagnosticStorage::MaxArguments,
970   };
971 
972   DiagnosticStorage DiagStorage;
973 
974   DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
975     bool isPragma = L.isValid();
976     DiagnosticMapping Mapping =
977         DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
978 
979     // If this is a pragma mapping, then set the diagnostic mapping flags so
980     // that we override command line options.
981     if (isPragma) {
982       Mapping.setNoWarningAsError(true);
983       Mapping.setNoErrorAsFatal(true);
984     }
985 
986     return Mapping;
987   }
988 
989   /// Used to report a diagnostic that is finally fully formed.
990   ///
991   /// \returns true if the diagnostic was emitted, false if it was suppressed.
992   bool ProcessDiag() {
993     return Diags->ProcessDiag(*this);
994   }
995 
996   /// @name Diagnostic Emission
997   /// @{
998 protected:
999   friend class ASTReader;
1000   friend class ASTWriter;
1001 
1002   // Sema requires access to the following functions because the current design
1003   // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1004   // access us directly to ensure we minimize the emitted code for the common
1005   // Sema::Diag() patterns.
1006   friend class Sema;
1007 
1008   /// Emit the current diagnostic and clear the diagnostic state.
1009   ///
1010   /// \param Force Emit the diagnostic regardless of suppression settings.
1011   bool EmitCurrentDiagnostic(bool Force = false);
1012 
1013   unsigned getCurrentDiagID() const { return CurDiagID; }
1014 
1015   SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
1016 
1017   /// @}
1018 };
1019 
1020 /// RAII class that determines when any errors have occurred
1021 /// between the time the instance was created and the time it was
1022 /// queried.
1023 ///
1024 /// Note that you almost certainly do not want to use this. It's usually
1025 /// meaningless to ask whether a particular scope triggered an error message,
1026 /// because error messages outside that scope can mark things invalid (or cause
1027 /// us to reach an error limit), which can suppress errors within that scope.
1028 class DiagnosticErrorTrap {
1029   DiagnosticsEngine &Diag;
1030   unsigned NumErrors;
1031   unsigned NumUnrecoverableErrors;
1032 
1033 public:
1034   explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1035       : Diag(Diag) { reset(); }
1036 
1037   /// Determine whether any errors have occurred since this
1038   /// object instance was created.
1039   bool hasErrorOccurred() const {
1040     return Diag.TrapNumErrorsOccurred > NumErrors;
1041   }
1042 
1043   /// Determine whether any unrecoverable errors have occurred since this
1044   /// object instance was created.
1045   bool hasUnrecoverableErrorOccurred() const {
1046     return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1047   }
1048 
1049   /// Set to initial state of "no errors occurred".
1050   void reset() {
1051     NumErrors = Diag.TrapNumErrorsOccurred;
1052     NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1053   }
1054 };
1055 
1056 /// The streaming interface shared between DiagnosticBuilder and
1057 /// PartialDiagnostic. This class is not intended to be constructed directly
1058 /// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1059 ///
1060 /// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1061 /// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1062 ///
1063 /// const StreamingDiagnostic&
1064 /// operator<<(const StreamingDiagnostic&, NewArgType);
1065 ///
1066 class StreamingDiagnostic {
1067 public:
1068   /// An allocator for DiagnosticStorage objects, which uses a small cache to
1069   /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
1070   class DiagStorageAllocator {
1071     static const unsigned NumCached = 16;
1072     DiagnosticStorage Cached[NumCached];
1073     DiagnosticStorage *FreeList[NumCached];
1074     unsigned NumFreeListEntries;
1075 
1076   public:
1077     DiagStorageAllocator();
1078     ~DiagStorageAllocator();
1079 
1080     /// Allocate new storage.
1081     DiagnosticStorage *Allocate() {
1082       if (NumFreeListEntries == 0)
1083         return new DiagnosticStorage;
1084 
1085       DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
1086       Result->NumDiagArgs = 0;
1087       Result->DiagRanges.clear();
1088       Result->FixItHints.clear();
1089       return Result;
1090     }
1091 
1092     /// Free the given storage object.
1093     void Deallocate(DiagnosticStorage *S) {
1094       if (S >= Cached && S <= Cached + NumCached) {
1095         FreeList[NumFreeListEntries++] = S;
1096         return;
1097       }
1098 
1099       delete S;
1100     }
1101   };
1102 
1103 protected:
1104   mutable DiagnosticStorage *DiagStorage = nullptr;
1105 
1106   /// Allocator used to allocate storage for this diagnostic.
1107   DiagStorageAllocator *Allocator = nullptr;
1108 
1109 public:
1110   /// Retrieve storage for this particular diagnostic.
1111   DiagnosticStorage *getStorage() const {
1112     if (DiagStorage)
1113       return DiagStorage;
1114 
1115     assert(Allocator);
1116     DiagStorage = Allocator->Allocate();
1117     return DiagStorage;
1118   }
1119 
1120   void freeStorage() {
1121     if (!DiagStorage)
1122       return;
1123 
1124     // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1125     // (typically so we have the flexibility of passing a more complex
1126     // diagnostic into the callee, but that does not commonly occur).
1127     //
1128     // Split this out into a slow function for silly compilers (*cough*) which
1129     // can't do decent partial inlining.
1130     freeStorageSlow();
1131   }
1132 
1133   void freeStorageSlow() {
1134     if (!Allocator)
1135       return;
1136     Allocator->Deallocate(DiagStorage);
1137     DiagStorage = nullptr;
1138   }
1139 
1140   void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1141     if (!DiagStorage)
1142       DiagStorage = getStorage();
1143 
1144     assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1145            "Too many arguments to diagnostic!");
1146     DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
1147     DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
1148   }
1149 
1150   void AddString(StringRef V) const {
1151     if (!DiagStorage)
1152       DiagStorage = getStorage();
1153 
1154     assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1155            "Too many arguments to diagnostic!");
1156     DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
1157         DiagnosticsEngine::ak_std_string;
1158     DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
1159   }
1160 
1161   void AddSourceRange(const CharSourceRange &R) const {
1162     if (!DiagStorage)
1163       DiagStorage = getStorage();
1164 
1165     DiagStorage->DiagRanges.push_back(R);
1166   }
1167 
1168   void AddFixItHint(const FixItHint &Hint) const {
1169     if (Hint.isNull())
1170       return;
1171 
1172     if (!DiagStorage)
1173       DiagStorage = getStorage();
1174 
1175     DiagStorage->FixItHints.push_back(Hint);
1176   }
1177 
1178   /// Conversion of StreamingDiagnostic to bool always returns \c true.
1179   ///
1180   /// This allows is to be used in boolean error contexts (where \c true is
1181   /// used to indicate that an error has occurred), like:
1182   /// \code
1183   /// return Diag(...);
1184   /// \endcode
1185   operator bool() const { return true; }
1186 
1187 protected:
1188   StreamingDiagnostic() = default;
1189 
1190   /// Construct with an external storage not owned by itself. The allocator
1191   /// is a null pointer in this case.
1192   explicit StreamingDiagnostic(DiagnosticStorage *Storage)
1193       : DiagStorage(Storage) {}
1194 
1195   /// Construct with a storage allocator which will manage the storage. The
1196   /// allocator is not a null pointer in this case.
1197   explicit StreamingDiagnostic(DiagStorageAllocator &Alloc)
1198       : Allocator(&Alloc) {}
1199 
1200   StreamingDiagnostic(const StreamingDiagnostic &Diag) = default;
1201   StreamingDiagnostic(StreamingDiagnostic &&Diag) = default;
1202 
1203   ~StreamingDiagnostic() { freeStorage(); }
1204 };
1205 
1206 //===----------------------------------------------------------------------===//
1207 // DiagnosticBuilder
1208 //===----------------------------------------------------------------------===//
1209 
1210 /// A little helper class used to produce diagnostics.
1211 ///
1212 /// This is constructed by the DiagnosticsEngine::Report method, and
1213 /// allows insertion of extra information (arguments and source ranges) into
1214 /// the currently "in flight" diagnostic.  When the temporary for the builder
1215 /// is destroyed, the diagnostic is issued.
1216 ///
1217 /// Note that many of these will be created as temporary objects (many call
1218 /// sites), so we want them to be small and we never want their address taken.
1219 /// This ensures that compilers with somewhat reasonable optimizers will promote
1220 /// the common fields to registers, eliminating increments of the NumArgs field,
1221 /// for example.
1222 class DiagnosticBuilder : public StreamingDiagnostic {
1223   friend class DiagnosticsEngine;
1224   friend class PartialDiagnostic;
1225 
1226   mutable DiagnosticsEngine *DiagObj = nullptr;
1227 
1228   /// Status variable indicating if this diagnostic is still active.
1229   ///
1230   // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1231   // but LLVM is not currently smart enough to eliminate the null check that
1232   // Emit() would end up with if we used that as our status variable.
1233   mutable bool IsActive = false;
1234 
1235   /// Flag indicating that this diagnostic is being emitted via a
1236   /// call to ForceEmit.
1237   mutable bool IsForceEmit = false;
1238 
1239   DiagnosticBuilder() = default;
1240 
1241   explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1242       : StreamingDiagnostic(&diagObj->DiagStorage), DiagObj(diagObj),
1243         IsActive(true) {
1244     assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
1245     assert(DiagStorage &&
1246            "DiagnosticBuilder requires a valid DiagnosticStorage!");
1247     DiagStorage->NumDiagArgs = 0;
1248     DiagStorage->DiagRanges.clear();
1249     DiagStorage->FixItHints.clear();
1250   }
1251 
1252 protected:
1253   /// Clear out the current diagnostic.
1254   void Clear() const {
1255     DiagObj = nullptr;
1256     IsActive = false;
1257     IsForceEmit = false;
1258   }
1259 
1260   /// Determine whether this diagnostic is still active.
1261   bool isActive() const { return IsActive; }
1262 
1263   /// Force the diagnostic builder to emit the diagnostic now.
1264   ///
1265   /// Once this function has been called, the DiagnosticBuilder object
1266   /// should not be used again before it is destroyed.
1267   ///
1268   /// \returns true if a diagnostic was emitted, false if the
1269   /// diagnostic was suppressed.
1270   bool Emit() {
1271     // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1272     // (or by a subclass, as in SemaDiagnosticBuilder).
1273     if (!isActive()) return false;
1274 
1275     // Process the diagnostic.
1276     bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1277 
1278     // This diagnostic is dead.
1279     Clear();
1280 
1281     return Result;
1282   }
1283 
1284 public:
1285   /// Copy constructor.  When copied, this "takes" the diagnostic info from the
1286   /// input and neuters it.
1287   DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
1288     DiagObj = D.DiagObj;
1289     DiagStorage = D.DiagStorage;
1290     IsActive = D.IsActive;
1291     IsForceEmit = D.IsForceEmit;
1292     D.Clear();
1293   }
1294 
1295   template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1296     assert(isActive() && "Clients must not add to cleared diagnostic!");
1297     const StreamingDiagnostic &DB = *this;
1298     DB << V;
1299     return *this;
1300   }
1301 
1302   // It is necessary to limit this to rvalue reference to avoid calling this
1303   // function with a bitfield lvalue argument since non-const reference to
1304   // bitfield is not allowed.
1305   template <typename T, typename = typename std::enable_if<
1306                             !std::is_lvalue_reference<T>::value>::type>
1307   const DiagnosticBuilder &operator<<(T &&V) const {
1308     assert(isActive() && "Clients must not add to cleared diagnostic!");
1309     const StreamingDiagnostic &DB = *this;
1310     DB << std::move(V);
1311     return *this;
1312   }
1313 
1314   DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1315 
1316   /// Emits the diagnostic.
1317   ~DiagnosticBuilder() { Emit(); }
1318 
1319   /// Forces the diagnostic to be emitted.
1320   const DiagnosticBuilder &setForceEmit() const {
1321     IsForceEmit = true;
1322     return *this;
1323   }
1324 
1325   void addFlagValue(StringRef V) const { DiagObj->FlagValue = std::string(V); }
1326 };
1327 
1328 struct AddFlagValue {
1329   StringRef Val;
1330 
1331   explicit AddFlagValue(StringRef V) : Val(V) {}
1332 };
1333 
1334 /// Register a value for the flag in the current diagnostic. This
1335 /// value will be shown as the suffix "=value" after the flag name. It is
1336 /// useful in cases where the diagnostic flag accepts values (e.g.,
1337 /// -Rpass or -Wframe-larger-than).
1338 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1339                                            const AddFlagValue V) {
1340   DB.addFlagValue(V.Val);
1341   return DB;
1342 }
1343 
1344 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1345                                              StringRef S) {
1346   DB.AddString(S);
1347   return DB;
1348 }
1349 
1350 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1351                                              const char *Str) {
1352   DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1353                   DiagnosticsEngine::ak_c_string);
1354   return DB;
1355 }
1356 
1357 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1358                                              int I) {
1359   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1360   return DB;
1361 }
1362 
1363 // We use enable_if here to prevent that this overload is selected for
1364 // pointers or other arguments that are implicitly convertible to bool.
1365 template <typename T>
1366 inline std::enable_if_t<std::is_same<T, bool>::value,
1367                         const StreamingDiagnostic &>
1368 operator<<(const StreamingDiagnostic &DB, T I) {
1369   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1370   return DB;
1371 }
1372 
1373 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1374                                              unsigned I) {
1375   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1376   return DB;
1377 }
1378 
1379 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1380                                              tok::TokenKind I) {
1381   DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1382   return DB;
1383 }
1384 
1385 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1386                                              const IdentifierInfo *II) {
1387   DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1388                   DiagnosticsEngine::ak_identifierinfo);
1389   return DB;
1390 }
1391 
1392 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1393 // so that we only match those arguments that are (statically) DeclContexts;
1394 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1395 // match.
1396 template <typename T>
1397 inline std::enable_if_t<
1398     std::is_same<std::remove_const_t<T>, DeclContext>::value,
1399     const StreamingDiagnostic &>
1400 operator<<(const StreamingDiagnostic &DB, T *DC) {
1401   DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1402                   DiagnosticsEngine::ak_declcontext);
1403   return DB;
1404 }
1405 
1406 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1407                                              SourceRange R) {
1408   DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1409   return DB;
1410 }
1411 
1412 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1413                                              ArrayRef<SourceRange> Ranges) {
1414   for (SourceRange R : Ranges)
1415     DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1416   return DB;
1417 }
1418 
1419 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1420                                              const CharSourceRange &R) {
1421   DB.AddSourceRange(R);
1422   return DB;
1423 }
1424 
1425 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1426                                              const FixItHint &Hint) {
1427   DB.AddFixItHint(Hint);
1428   return DB;
1429 }
1430 
1431 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1432                                              ArrayRef<FixItHint> Hints) {
1433   for (const FixItHint &Hint : Hints)
1434     DB.AddFixItHint(Hint);
1435   return DB;
1436 }
1437 
1438 inline const StreamingDiagnostic &
1439 operator<<(const StreamingDiagnostic &DB,
1440            const llvm::Optional<SourceRange> &Opt) {
1441   if (Opt)
1442     DB << *Opt;
1443   return DB;
1444 }
1445 
1446 inline const StreamingDiagnostic &
1447 operator<<(const StreamingDiagnostic &DB,
1448            const llvm::Optional<CharSourceRange> &Opt) {
1449   if (Opt)
1450     DB << *Opt;
1451   return DB;
1452 }
1453 
1454 inline const StreamingDiagnostic &
1455 operator<<(const StreamingDiagnostic &DB,
1456            const llvm::Optional<FixItHint> &Opt) {
1457   if (Opt)
1458     DB << *Opt;
1459   return DB;
1460 }
1461 
1462 /// A nullability kind paired with a bit indicating whether it used a
1463 /// context-sensitive keyword.
1464 using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1465 
1466 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1467                                       DiagNullabilityKind nullability);
1468 
1469 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1470                                                    unsigned DiagID) {
1471   assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
1472          "Multiple diagnostics in flight at once!");
1473   CurDiagLoc = Loc;
1474   CurDiagID = DiagID;
1475   FlagValue.clear();
1476   return DiagnosticBuilder(this);
1477 }
1478 
1479 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1480                                       llvm::Error &&E);
1481 
1482 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1483   return Report(SourceLocation(), DiagID);
1484 }
1485 
1486 //===----------------------------------------------------------------------===//
1487 // Diagnostic
1488 //===----------------------------------------------------------------------===//
1489 
1490 /// A little helper class (which is basically a smart pointer that forwards
1491 /// info from DiagnosticsEngine) that allows clients to enquire about the
1492 /// currently in-flight diagnostic.
1493 class Diagnostic {
1494   const DiagnosticsEngine *DiagObj;
1495   StringRef StoredDiagMessage;
1496 
1497 public:
1498   explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1499   Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1500       : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1501 
1502   const DiagnosticsEngine *getDiags() const { return DiagObj; }
1503   unsigned getID() const { return DiagObj->CurDiagID; }
1504   const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1505   bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1506   SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1507 
1508   unsigned getNumArgs() const { return DiagObj->DiagStorage.NumDiagArgs; }
1509 
1510   /// Return the kind of the specified index.
1511   ///
1512   /// Based on the kind of argument, the accessors below can be used to get
1513   /// the value.
1514   ///
1515   /// \pre Idx < getNumArgs()
1516   DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1517     assert(Idx < getNumArgs() && "Argument index out of range!");
1518     return (DiagnosticsEngine::ArgumentKind)
1519         DiagObj->DiagStorage.DiagArgumentsKind[Idx];
1520   }
1521 
1522   /// Return the provided argument string specified by \p Idx.
1523   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1524   const std::string &getArgStdStr(unsigned Idx) const {
1525     assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1526            "invalid argument accessor!");
1527     return DiagObj->DiagStorage.DiagArgumentsStr[Idx];
1528   }
1529 
1530   /// Return the specified C string argument.
1531   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1532   const char *getArgCStr(unsigned Idx) const {
1533     assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1534            "invalid argument accessor!");
1535     return reinterpret_cast<const char *>(
1536         DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1537   }
1538 
1539   /// Return the specified signed integer argument.
1540   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1541   int getArgSInt(unsigned Idx) const {
1542     assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1543            "invalid argument accessor!");
1544     return (int)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1545   }
1546 
1547   /// Return the specified unsigned integer argument.
1548   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1549   unsigned getArgUInt(unsigned Idx) const {
1550     assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1551            "invalid argument accessor!");
1552     return (unsigned)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1553   }
1554 
1555   /// Return the specified IdentifierInfo argument.
1556   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1557   const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1558     assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1559            "invalid argument accessor!");
1560     return reinterpret_cast<IdentifierInfo *>(
1561         DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1562   }
1563 
1564   /// Return the specified non-string argument in an opaque form.
1565   /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1566   intptr_t getRawArg(unsigned Idx) const {
1567     assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1568            "invalid argument accessor!");
1569     return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1570   }
1571 
1572   /// Return the number of source ranges associated with this diagnostic.
1573   unsigned getNumRanges() const {
1574     return DiagObj->DiagStorage.DiagRanges.size();
1575   }
1576 
1577   /// \pre Idx < getNumRanges()
1578   const CharSourceRange &getRange(unsigned Idx) const {
1579     assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1580     return DiagObj->DiagStorage.DiagRanges[Idx];
1581   }
1582 
1583   /// Return an array reference for this diagnostic's ranges.
1584   ArrayRef<CharSourceRange> getRanges() const {
1585     return DiagObj->DiagStorage.DiagRanges;
1586   }
1587 
1588   unsigned getNumFixItHints() const {
1589     return DiagObj->DiagStorage.FixItHints.size();
1590   }
1591 
1592   const FixItHint &getFixItHint(unsigned Idx) const {
1593     assert(Idx < getNumFixItHints() && "Invalid index!");
1594     return DiagObj->DiagStorage.FixItHints[Idx];
1595   }
1596 
1597   ArrayRef<FixItHint> getFixItHints() const {
1598     return DiagObj->DiagStorage.FixItHints;
1599   }
1600 
1601   /// Format this diagnostic into a string, substituting the
1602   /// formal arguments into the %0 slots.
1603   ///
1604   /// The result is appended onto the \p OutStr array.
1605   void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1606 
1607   /// Format the given format-string into the output buffer using the
1608   /// arguments stored in this diagnostic.
1609   void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1610                         SmallVectorImpl<char> &OutStr) const;
1611 };
1612 
1613 /**
1614  * Represents a diagnostic in a form that can be retained until its
1615  * corresponding source manager is destroyed.
1616  */
1617 class StoredDiagnostic {
1618   unsigned ID;
1619   DiagnosticsEngine::Level Level;
1620   FullSourceLoc Loc;
1621   std::string Message;
1622   std::vector<CharSourceRange> Ranges;
1623   std::vector<FixItHint> FixIts;
1624 
1625 public:
1626   StoredDiagnostic() = default;
1627   StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1628   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1629                    StringRef Message);
1630   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1631                    StringRef Message, FullSourceLoc Loc,
1632                    ArrayRef<CharSourceRange> Ranges,
1633                    ArrayRef<FixItHint> Fixits);
1634 
1635   /// Evaluates true when this object stores a diagnostic.
1636   explicit operator bool() const { return !Message.empty(); }
1637 
1638   unsigned getID() const { return ID; }
1639   DiagnosticsEngine::Level getLevel() const { return Level; }
1640   const FullSourceLoc &getLocation() const { return Loc; }
1641   StringRef getMessage() const { return Message; }
1642 
1643   void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1644 
1645   using range_iterator = std::vector<CharSourceRange>::const_iterator;
1646 
1647   range_iterator range_begin() const { return Ranges.begin(); }
1648   range_iterator range_end() const { return Ranges.end(); }
1649   unsigned range_size() const { return Ranges.size(); }
1650 
1651   ArrayRef<CharSourceRange> getRanges() const {
1652     return llvm::makeArrayRef(Ranges);
1653   }
1654 
1655   using fixit_iterator = std::vector<FixItHint>::const_iterator;
1656 
1657   fixit_iterator fixit_begin() const { return FixIts.begin(); }
1658   fixit_iterator fixit_end() const { return FixIts.end(); }
1659   unsigned fixit_size() const { return FixIts.size(); }
1660 
1661   ArrayRef<FixItHint> getFixIts() const {
1662     return llvm::makeArrayRef(FixIts);
1663   }
1664 };
1665 
1666 /// Abstract interface, implemented by clients of the front-end, which
1667 /// formats and prints fully processed diagnostics.
1668 class DiagnosticConsumer {
1669 protected:
1670   unsigned NumWarnings = 0;       ///< Number of warnings reported
1671   unsigned NumErrors = 0;         ///< Number of errors reported
1672 
1673 public:
1674   DiagnosticConsumer() = default;
1675   virtual ~DiagnosticConsumer();
1676 
1677   unsigned getNumErrors() const { return NumErrors; }
1678   unsigned getNumWarnings() const { return NumWarnings; }
1679   virtual void clear() { NumWarnings = NumErrors = 0; }
1680 
1681   /// Callback to inform the diagnostic client that processing
1682   /// of a source file is beginning.
1683   ///
1684   /// Note that diagnostics may be emitted outside the processing of a source
1685   /// file, for example during the parsing of command line options. However,
1686   /// diagnostics with source range information are required to only be emitted
1687   /// in between BeginSourceFile() and EndSourceFile().
1688   ///
1689   /// \param LangOpts The language options for the source file being processed.
1690   /// \param PP The preprocessor object being used for the source; this is
1691   /// optional, e.g., it may not be present when processing AST source files.
1692   virtual void BeginSourceFile(const LangOptions &LangOpts,
1693                                const Preprocessor *PP = nullptr) {}
1694 
1695   /// Callback to inform the diagnostic client that processing
1696   /// of a source file has ended.
1697   ///
1698   /// The diagnostic client should assume that any objects made available via
1699   /// BeginSourceFile() are inaccessible.
1700   virtual void EndSourceFile() {}
1701 
1702   /// Callback to inform the diagnostic client that processing of all
1703   /// source files has ended.
1704   virtual void finish() {}
1705 
1706   /// Indicates whether the diagnostics handled by this
1707   /// DiagnosticConsumer should be included in the number of diagnostics
1708   /// reported by DiagnosticsEngine.
1709   ///
1710   /// The default implementation returns true.
1711   virtual bool IncludeInDiagnosticCounts() const;
1712 
1713   /// Handle this diagnostic, reporting it to the user or
1714   /// capturing it to a log as needed.
1715   ///
1716   /// The default implementation just keeps track of the total number of
1717   /// warnings and errors.
1718   virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1719                                 const Diagnostic &Info);
1720 };
1721 
1722 /// A diagnostic client that ignores all diagnostics.
1723 class IgnoringDiagConsumer : public DiagnosticConsumer {
1724   virtual void anchor();
1725 
1726   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1727                         const Diagnostic &Info) override {
1728     // Just ignore it.
1729   }
1730 };
1731 
1732 /// Diagnostic consumer that forwards diagnostics along to an
1733 /// existing, already-initialized diagnostic consumer.
1734 ///
1735 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1736   DiagnosticConsumer &Target;
1737 
1738 public:
1739   ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1740   ~ForwardingDiagnosticConsumer() override;
1741 
1742   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1743                         const Diagnostic &Info) override;
1744   void clear() override;
1745 
1746   bool IncludeInDiagnosticCounts() const override;
1747 };
1748 
1749 // Struct used for sending info about how a type should be printed.
1750 struct TemplateDiffTypes {
1751   intptr_t FromType;
1752   intptr_t ToType;
1753   unsigned PrintTree : 1;
1754   unsigned PrintFromType : 1;
1755   unsigned ElideType : 1;
1756   unsigned ShowColors : 1;
1757 
1758   // The printer sets this variable to true if the template diff was used.
1759   unsigned TemplateDiffUsed : 1;
1760 };
1761 
1762 /// Special character that the diagnostic printer will use to toggle the bold
1763 /// attribute.  The character itself will be not be printed.
1764 const char ToggleHighlight = 127;
1765 
1766 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1767 /// warning options specified on the command line.
1768 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1769                            const DiagnosticOptions &Opts,
1770                            bool ReportDiags = true);
1771 
1772 } // namespace clang
1773 
1774 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H
1775