1 //===--- PreprocessorTracker.cpp - Preprocessor tracking -*- 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 // The Basic Idea (Macro and Conditional Checking)
11 //
12 // Basically we install a PPCallbacks-derived object to track preprocessor
13 // activity, namely when a header file is entered/exited, when a macro
14 // is expanded, when "defined" is used, and when #if, #elif, #ifdef,
15 // and #ifndef are used.  We save the state of macro and "defined"
16 // expressions in a map, keyed on a name/file/line/column quadruple.
17 // The map entries store the different states (values) that a macro expansion,
18 // "defined" expression, or condition expression has in the course of
19 // processing for the one location in the one header containing it,
20 // plus a list of the nested include stacks for the states.  When a macro
21 // or "defined" expression evaluates to the same value, which is the
22 // desired case, only one state is stored.  Similarly, for conditional
23 // directives, we save the condition expression states in a separate map.
24 //
25 // This information is collected as modularize compiles all the headers
26 // given to it to process.  After all the compilations are performed,
27 // a check is performed for any entries in the maps that contain more
28 // than one different state, and for these an output message is generated.
29 //
30 // For example:
31 //
32 //   (...)/SubHeader.h:11:5:
33 //   #if SYMBOL == 1
34 //       ^
35 //   error: Macro instance 'SYMBOL' has different values in this header,
36 //          depending on how it was included.
37 //     'SYMBOL' expanded to: '1' with respect to these inclusion paths:
38 //       (...)/Header1.h
39 //         (...)/SubHeader.h
40 //   (...)/SubHeader.h:3:9:
41 //   #define SYMBOL 1
42 //             ^
43 //   Macro defined here.
44 //     'SYMBOL' expanded to: '2' with respect to these inclusion paths:
45 //       (...)/Header2.h
46 //           (...)/SubHeader.h
47 //   (...)/SubHeader.h:7:9:
48 //   #define SYMBOL 2
49 //             ^
50 //   Macro defined here.
51 //
52 // The Basic Idea ('Extern "C/C++" {}' Or 'namespace {}') With Nested
53 // '#include' Checking)
54 //
55 // To check for '#include' directives nested inside 'Extern "C/C++" {}'
56 // or 'namespace {}' blocks, we keep track of the '#include' directives
57 // while running the preprocessor, and later during a walk of the AST
58 // we call a function to check for any '#include' directies inside
59 // an 'Extern "C/C++" {}' or 'namespace {}' block, given its source
60 // range.
61 //
62 // Design and Implementation Details (Macro and Conditional Checking)
63 //
64 // A PreprocessorTrackerImpl class implements the PreprocessorTracker
65 // interface. It uses a PreprocessorCallbacks class derived from PPCallbacks
66 // to track preprocessor activity, namely entering/exiting a header, macro
67 // expansions, use of "defined" expressions, and #if, #elif, #ifdef, and
68 // #ifndef conditional directives. PreprocessorTrackerImpl stores a map
69 // of MacroExpansionTracker objects keyed on a name/file/line/column
70 // value represented by a light-weight PPItemKey value object. This
71 // is the key top-level data structure tracking the values of macro
72 // expansion instances.  Similarly, it stores a map of ConditionalTracker
73 // objects with the same kind of key, for tracking preprocessor conditional
74 // directives.
75 //
76 // The MacroExpansionTracker object represents one macro reference or use
77 // of a "defined" expression in a header file. It stores a handle to a
78 // string representing the unexpanded macro instance, a handle to a string
79 // representing the unpreprocessed source line containing the unexpanded
80 // macro instance, and a vector of one or more MacroExpansionInstance
81 // objects.
82 //
83 // The MacroExpansionInstance object represents one or more expansions
84 // of a macro reference, for the case where the macro expands to the same
85 // value. MacroExpansionInstance stores a handle to a string representing
86 // the expanded macro value, a PPItemKey representing the file/line/column
87 // where the macro was defined, a handle to a string representing the source
88 // line containing the macro definition, and a vector of InclusionPathHandle
89 // values that represents the hierarchies of include files for each case
90 // where the particular header containing the macro reference was referenced
91 // or included.
92 
93 // In the normal case where a macro instance always expands to the same
94 // value, the MacroExpansionTracker object will only contain one
95 // MacroExpansionInstance representing all the macro expansion instances.
96 // If a case was encountered where a macro instance expands to a value
97 // that is different from that seen before, or the macro was defined in
98 // a different place, a new MacroExpansionInstance object representing
99 // that case will be added to the vector in MacroExpansionTracker. If a
100 // macro instance expands to a value already seen before, the
101 // InclusionPathHandle representing that case's include file hierarchy
102 // will be added to the existing MacroExpansionInstance object.
103 
104 // For checking conditional directives, the ConditionalTracker class
105 // functions similarly to MacroExpansionTracker, but tracks an #if,
106 // #elif, #ifdef, or #ifndef directive in a header file.  It stores
107 // a vector of one or two ConditionalExpansionInstance objects,
108 // representing the cases where the conditional expression evaluates
109 // to true or false.  This latter object stores the evaluated value
110 // of the condition expression (a bool) and a vector of
111 // InclusionPathHandles.
112 //
113 // To reduce the instances of string and object copying, the
114 // PreprocessorTrackerImpl class uses a StringPool to save all stored
115 // strings, and defines a StringHandle type to abstract the references
116 // to the strings.
117 //
118 // PreprocessorTrackerImpl also maintains a list representing the unique
119 // headers, which is just a vector of StringHandle's for the header file
120 // paths. A HeaderHandle abstracts a reference to a header, and is simply
121 // the index of the stored header file path.
122 //
123 // A HeaderInclusionPath class abstracts a unique hierarchy of header file
124 // inclusions. It simply stores a vector of HeaderHandles ordered from the
125 // top-most header (the one from the header list passed to modularize) down
126 // to the header containing the macro reference. PreprocessorTrackerImpl
127 // stores a vector of these objects. An InclusionPathHandle typedef
128 // abstracts a reference to one of the HeaderInclusionPath objects, and is
129 // simply the index of the stored HeaderInclusionPath object. The
130 // MacroExpansionInstance object stores a vector of these handles so that
131 // the reporting function can display the include hierarchies for the macro
132 // expansion instances represented by that object, to help the user
133 // understand how the header was included. (A future enhancement might
134 // be to associate a line number for the #include directives, but I
135 // think not doing so is good enough for the present.)
136 //
137 // A key reason for using these opaque handles was to try to keep all the
138 // internal objects light-weight value objects, in order to reduce string
139 // and object copying overhead, and to abstract this implementation detail.
140 //
141 // The key data structures are built up while modularize runs the headers
142 // through the compilation. A PreprocessorTracker instance is created and
143 // passed down to the AST action and consumer objects in modularize. For
144 // each new compilation instance, the consumer calls the
145 // PreprocessorTracker's handleNewPreprocessorEntry function, which sets
146 // up a PreprocessorCallbacks object for the preprocessor. At the end of
147 // the compilation instance, the PreprocessorTracker's
148 // handleNewPreprocessorExit function handles cleaning up with respect
149 // to the preprocessing instance.
150 //
151 // The PreprocessorCallbacks object uses an overidden FileChanged callback
152 // to determine when a header is entered and exited (including exiting the
153 // header during #include directives). It calls PreprocessorTracker's
154 // handleHeaderEntry and handleHeaderExit functions upon entering and
155 // exiting a header. These functions manage a stack of header handles
156 // representing by a vector, pushing and popping header handles as headers
157 // are entered and exited. When a HeaderInclusionPath object is created,
158 // it simply copies this stack.
159 //
160 // The PreprocessorCallbacks object uses an overridden MacroExpands callback
161 // to track when a macro expansion is performed. It calls a couple of helper
162 // functions to get the unexpanded and expanded macro values as strings, but
163 // then calls PreprocessorTrackerImpl's addMacroExpansionInstance function to
164 // do the rest of the work. The getMacroExpandedString function uses the
165 // preprocessor's getSpelling to convert tokens to strings using the
166 // information passed to the MacroExpands callback, and simply concatenates
167 // them. It makes recursive calls to itself to handle nested macro
168 // definitions, and also handles function-style macros.
169 //
170 // PreprocessorTrackerImpl's addMacroExpansionInstance function looks for
171 // an existing MacroExpansionTracker entry in its map of MacroExampleTracker
172 // objects. If none exists, it adds one with one MacroExpansionInstance and
173 // returns. If a MacroExpansionTracker object already exists, it looks for
174 // an existing MacroExpansionInstance object stored in the
175 // MacroExpansionTracker object, one that matches the macro expanded value
176 // and the macro definition location. If a matching MacroExpansionInstance
177 // object is found, it just adds the current HeaderInclusionPath object to
178 // it. If not found, it creates and stores a new MacroExpantionInstance
179 // object. The addMacroExpansionInstance function calls a couple of helper
180 // functions to get the pre-formatted location and source line strings for
181 // the macro reference and the macro definition stored as string handles.
182 // These helper functions use the current source manager from the
183 // preprocessor. This is done in advance at this point in time because the
184 // source manager doesn't exist at the time of the reporting.
185 //
186 // For conditional check, the PreprocessorCallbacks class overrides the
187 // PPCallbacks handlers for #if, #elif, #ifdef, and #ifndef.  These handlers
188 // call the addConditionalExpansionInstance method of
189 // PreprocessorTrackerImpl.  The process is similar to that of macros, but
190 // with some different data and error messages.  A lookup is performed for
191 // the conditional, and if a ConditionalTracker object doesn't yet exist for
192 // the conditional, a new one is added, including adding a
193 // ConditionalExpansionInstance object to it to represent the condition
194 // expression state.  If a ConditionalTracker for the conditional does
195 // exist, a lookup is made for a ConditionalExpansionInstance object
196 // matching the condition expression state.  If one exists, a
197 // HeaderInclusionPath is added to it.  Otherwise a new
198 // ConditionalExpansionInstance  entry is made.  If a ConditionalTracker
199 // has two ConditionalExpansionInstance objects, it means there was a
200 // conflict, meaning the conditional expression evaluated differently in
201 // one or more cases.
202 //
203 // After modularize has performed all the compilations, it enters a phase
204 // of error reporting. This new feature adds to this reporting phase calls
205 // to the PreprocessorTracker's reportInconsistentMacros and
206 // reportInconsistentConditionals functions. These functions walk the maps
207 // of MacroExpansionTracker's and ConditionalTracker's respectively. If
208 // any of these objects have more than one MacroExpansionInstance or
209 // ConditionalExpansionInstance objects, it formats and outputs an error
210 // message like the example shown previously, using the stored data.
211 //
212 // A potential issue is that there is some overlap between the #if/#elif
213 // conditional and macro reporting.  I could disable the #if and #elif,
214 // leaving just the #ifdef and #ifndef, since these don't overlap.  Or,
215 // to make clearer the separate reporting phases, I could add an output
216 // message marking the phases.
217 //
218 // Design and Implementation Details ('Extern "C/C++" {}' Or
219 // 'namespace {}') With Nested '#include' Checking)
220 //
221 // We override the InclusionDirective in PPCallbacks to record information
222 // about each '#include' directive encountered during preprocessing.
223 // We co-opt the PPItemKey class to store the information about each
224 // '#include' directive, including the source file name containing the
225 // directive, the name of the file being included, and the source line
226 // and column of the directive.  We store these object in a vector,
227 // after first check to see if an entry already exists.
228 //
229 // Later, while the AST is being walked for other checks, we provide
230 // visit handlers for 'extern "C/C++" {}' and 'namespace (name) {}'
231 // blocks, checking to see if any '#include' directives occurred
232 // within the blocks, reporting errors if any found.
233 //
234 // Future Directions
235 //
236 // We probably should add options to disable any of the checks, in case
237 // there is some problem with them, or the messages get too verbose.
238 //
239 // With the map of all the macro and conditional expansion instances,
240 // it might be possible to add to the existing modularize error messages
241 // (the second part referring to definitions being different), attempting
242 // to tie them to the last macro conflict encountered with respect to the
243 // order of the code encountered.
244 //
245 //===--------------------------------------------------------------------===//
246 
247 #include "clang/Lex/LexDiagnostic.h"
248 #include "PreprocessorTracker.h"
249 #include "clang/Lex/MacroArgs.h"
250 #include "clang/Lex/PPCallbacks.h"
251 #include "llvm/ADT/SmallSet.h"
252 #include "llvm/Support/StringPool.h"
253 #include "llvm/Support/raw_ostream.h"
254 #include "ModularizeUtilities.h"
255 
256 namespace Modularize {
257 
258 // Some handle types
259 typedef llvm::PooledStringPtr StringHandle;
260 
261 typedef int HeaderHandle;
262 const HeaderHandle HeaderHandleInvalid = -1;
263 
264 typedef int InclusionPathHandle;
265 const InclusionPathHandle InclusionPathHandleInvalid = -1;
266 
267 // Some utility functions.
268 
269 // Get a "file:line:column" source location string.
270 static std::string getSourceLocationString(clang::Preprocessor &PP,
271                                            clang::SourceLocation Loc) {
272   if (Loc.isInvalid())
273     return std::string("(none)");
274   else
275     return Loc.printToString(PP.getSourceManager());
276 }
277 
278 // Get just the file name from a source location.
279 static std::string getSourceLocationFile(clang::Preprocessor &PP,
280                                          clang::SourceLocation Loc) {
281   std::string Source(getSourceLocationString(PP, Loc));
282   size_t Offset = Source.find(':', 2);
283   if (Offset == std::string::npos)
284     return Source;
285   return Source.substr(0, Offset);
286 }
287 
288 // Get just the line and column from a source location.
289 static void getSourceLocationLineAndColumn(clang::Preprocessor &PP,
290                                            clang::SourceLocation Loc, int &Line,
291                                            int &Column) {
292   clang::PresumedLoc PLoc = PP.getSourceManager().getPresumedLoc(Loc);
293   if (PLoc.isInvalid()) {
294     Line = 0;
295     Column = 0;
296     return;
297   }
298   Line = PLoc.getLine();
299   Column = PLoc.getColumn();
300 }
301 
302 // Retrieve source snippet from file image.
303 static std::string getSourceString(clang::Preprocessor &PP,
304                                    clang::SourceRange Range) {
305   clang::SourceLocation BeginLoc = Range.getBegin();
306   clang::SourceLocation EndLoc = Range.getEnd();
307   const char *BeginPtr = PP.getSourceManager().getCharacterData(BeginLoc);
308   const char *EndPtr = PP.getSourceManager().getCharacterData(EndLoc);
309   size_t Length = EndPtr - BeginPtr;
310   return llvm::StringRef(BeginPtr, Length).trim().str();
311 }
312 
313 // Retrieve source line from file image given a location.
314 static std::string getSourceLine(clang::Preprocessor &PP,
315                                  clang::SourceLocation Loc) {
316   const llvm::MemoryBuffer *MemBuffer =
317       PP.getSourceManager().getBuffer(PP.getSourceManager().getFileID(Loc));
318   const char *Buffer = MemBuffer->getBufferStart();
319   const char *BufferEnd = MemBuffer->getBufferEnd();
320   const char *BeginPtr = PP.getSourceManager().getCharacterData(Loc);
321   const char *EndPtr = BeginPtr;
322   while (BeginPtr > Buffer) {
323     if (*BeginPtr == '\n') {
324       BeginPtr++;
325       break;
326     }
327     BeginPtr--;
328   }
329   while (EndPtr < BufferEnd) {
330     if (*EndPtr == '\n') {
331       break;
332     }
333     EndPtr++;
334   }
335   size_t Length = EndPtr - BeginPtr;
336   return llvm::StringRef(BeginPtr, Length).str();
337 }
338 
339 // Retrieve source line from file image given a file ID and line number.
340 static std::string getSourceLine(clang::Preprocessor &PP, clang::FileID FileID,
341                                  int Line) {
342   const llvm::MemoryBuffer *MemBuffer = PP.getSourceManager().getBuffer(FileID);
343   const char *Buffer = MemBuffer->getBufferStart();
344   const char *BufferEnd = MemBuffer->getBufferEnd();
345   const char *BeginPtr = Buffer;
346   const char *EndPtr = BufferEnd;
347   int LineCounter = 1;
348   if (Line == 1)
349     BeginPtr = Buffer;
350   else {
351     while (Buffer < BufferEnd) {
352       if (*Buffer == '\n') {
353         if (++LineCounter == Line) {
354           BeginPtr = Buffer++ + 1;
355           break;
356         }
357       }
358       Buffer++;
359     }
360   }
361   while (Buffer < BufferEnd) {
362     if (*Buffer == '\n') {
363       EndPtr = Buffer;
364       break;
365     }
366     Buffer++;
367   }
368   size_t Length = EndPtr - BeginPtr;
369   return llvm::StringRef(BeginPtr, Length).str();
370 }
371 
372 // Get the string for the Unexpanded macro instance.
373 // The soureRange is expected to end at the last token
374 // for the macro instance, which in the case of a function-style
375 // macro will be a ')', but for an object-style macro, it
376 // will be the macro name itself.
377 static std::string getMacroUnexpandedString(clang::SourceRange Range,
378                                             clang::Preprocessor &PP,
379                                             llvm::StringRef MacroName,
380                                             const clang::MacroInfo *MI) {
381   clang::SourceLocation BeginLoc(Range.getBegin());
382   const char *BeginPtr = PP.getSourceManager().getCharacterData(BeginLoc);
383   size_t Length;
384   std::string Unexpanded;
385   if (MI->isFunctionLike()) {
386     clang::SourceLocation EndLoc(Range.getEnd());
387     const char *EndPtr = PP.getSourceManager().getCharacterData(EndLoc) + 1;
388     Length = (EndPtr - BeginPtr) + 1; // +1 is ')' width.
389   } else
390     Length = MacroName.size();
391   return llvm::StringRef(BeginPtr, Length).trim().str();
392 }
393 
394 // Get the expansion for a macro instance, given the information
395 // provided by PPCallbacks.
396 // FIXME: This doesn't support function-style macro instances
397 // passed as arguments to another function-style macro. However,
398 // since it still expands the inner arguments, it still
399 // allows modularize to effectively work with respect to macro
400 // consistency checking, although it displays the incorrect
401 // expansion in error messages.
402 static std::string getMacroExpandedString(clang::Preprocessor &PP,
403                                           llvm::StringRef MacroName,
404                                           const clang::MacroInfo *MI,
405                                           const clang::MacroArgs *Args) {
406   std::string Expanded;
407   // Walk over the macro Tokens.
408   typedef clang::MacroInfo::tokens_iterator Iter;
409   for (Iter I = MI->tokens_begin(), E = MI->tokens_end(); I != E; ++I) {
410     clang::IdentifierInfo *II = I->getIdentifierInfo();
411     int ArgNo = (II && Args ? MI->getArgumentNum(II) : -1);
412     if (ArgNo == -1) {
413       // This isn't an argument, just add it.
414       if (II == nullptr)
415         Expanded += PP.getSpelling((*I)); // Not an identifier.
416       else {
417         // Token is for an identifier.
418         std::string Name = II->getName().str();
419         // Check for nexted macro references.
420         clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
421         if (MacroInfo)
422           Expanded += getMacroExpandedString(PP, Name, MacroInfo, nullptr);
423         else
424           Expanded += Name;
425       }
426       continue;
427     }
428     // We get here if it's a function-style macro with arguments.
429     const clang::Token *ResultArgToks;
430     const clang::Token *ArgTok = Args->getUnexpArgument(ArgNo);
431     if (Args->ArgNeedsPreexpansion(ArgTok, PP))
432       ResultArgToks = &(const_cast<clang::MacroArgs *>(Args))
433           ->getPreExpArgument(ArgNo, MI, PP)[0];
434     else
435       ResultArgToks = ArgTok; // Use non-preexpanded Tokens.
436     // If the arg token didn't expand into anything, ignore it.
437     if (ResultArgToks->is(clang::tok::eof))
438       continue;
439     unsigned NumToks = clang::MacroArgs::getArgLength(ResultArgToks);
440     // Append the resulting argument expansions.
441     for (unsigned ArgumentIndex = 0; ArgumentIndex < NumToks; ++ArgumentIndex) {
442       const clang::Token &AT = ResultArgToks[ArgumentIndex];
443       clang::IdentifierInfo *II = AT.getIdentifierInfo();
444       if (II == nullptr)
445         Expanded += PP.getSpelling(AT); // Not an identifier.
446       else {
447         // It's an identifier.  Check for further expansion.
448         std::string Name = II->getName().str();
449         clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
450         if (MacroInfo)
451           Expanded += getMacroExpandedString(PP, Name, MacroInfo, nullptr);
452         else
453           Expanded += Name;
454       }
455     }
456   }
457   return Expanded;
458 }
459 
460 namespace {
461 
462 // ConditionValueKind strings.
463 const char *
464 ConditionValueKindStrings[] = {
465   "(not evaluated)", "false", "true"
466 };
467 
468 bool operator<(const StringHandle &H1, const StringHandle &H2) {
469   const char *S1 = (H1 ? *H1 : "");
470   const char *S2 = (H2 ? *H2 : "");
471   int Diff = strcmp(S1, S2);
472   return Diff < 0;
473 }
474 bool operator>(const StringHandle &H1, const StringHandle &H2) {
475   const char *S1 = (H1 ? *H1 : "");
476   const char *S2 = (H2 ? *H2 : "");
477   int Diff = strcmp(S1, S2);
478   return Diff > 0;
479 }
480 
481 // Preprocessor item key.
482 //
483 // This class represents a location in a source file, for use
484 // as a key representing a unique name/file/line/column quadruplet,
485 // which in this case is used to identify a macro expansion instance,
486 // but could be used for other things as well.
487 // The file is a header file handle, the line is a line number,
488 // and the column is a column number.
489 class PPItemKey {
490 public:
491   PPItemKey(clang::Preprocessor &PP, StringHandle Name, HeaderHandle File,
492             clang::SourceLocation Loc)
493       : Name(Name), File(File) {
494     getSourceLocationLineAndColumn(PP, Loc, Line, Column);
495   }
496   PPItemKey(StringHandle Name, HeaderHandle File, int Line, int Column)
497       : Name(Name), File(File), Line(Line), Column(Column) {}
498   PPItemKey(const PPItemKey &Other)
499       : Name(Other.Name), File(Other.File), Line(Other.Line),
500         Column(Other.Column) {}
501   PPItemKey() : File(HeaderHandleInvalid), Line(0), Column(0) {}
502   bool operator==(const PPItemKey &Other) const {
503     if (Name != Other.Name)
504       return false;
505     if (File != Other.File)
506       return false;
507     if (Line != Other.Line)
508       return false;
509     return Column == Other.Column;
510   }
511   bool operator<(const PPItemKey &Other) const {
512     if (Name < Other.Name)
513       return true;
514     else if (Name > Other.Name)
515       return false;
516     if (File < Other.File)
517       return true;
518     else if (File > Other.File)
519       return false;
520     if (Line < Other.Line)
521       return true;
522     else if (Line > Other.Line)
523       return false;
524     return Column < Other.Column;
525   }
526   StringHandle Name;
527   HeaderHandle File;
528   int Line;
529   int Column;
530 };
531 
532 // Header inclusion path.
533 class HeaderInclusionPath {
534 public:
535   HeaderInclusionPath(std::vector<HeaderHandle> HeaderInclusionPath)
536       : Path(HeaderInclusionPath) {}
537   HeaderInclusionPath(const HeaderInclusionPath &Other) : Path(Other.Path) {}
538   HeaderInclusionPath() {}
539   std::vector<HeaderHandle> Path;
540 };
541 
542 // Macro expansion instance.
543 //
544 // This class represents an instance of a macro expansion with a
545 // unique value.  It also stores the unique header inclusion paths
546 // for use in telling the user the nested include path to the header.
547 class MacroExpansionInstance {
548 public:
549   MacroExpansionInstance(StringHandle MacroExpanded,
550                          PPItemKey &DefinitionLocation,
551                          StringHandle DefinitionSourceLine,
552                          InclusionPathHandle H)
553       : MacroExpanded(MacroExpanded), DefinitionLocation(DefinitionLocation),
554         DefinitionSourceLine(DefinitionSourceLine) {
555     InclusionPathHandles.push_back(H);
556   }
557   MacroExpansionInstance() {}
558 
559   // Check for the presence of a header inclusion path handle entry.
560   // Return false if not found.
561   bool haveInclusionPathHandle(InclusionPathHandle H) {
562     for (std::vector<InclusionPathHandle>::iterator
563              I = InclusionPathHandles.begin(),
564              E = InclusionPathHandles.end();
565          I != E; ++I) {
566       if (*I == H)
567         return true;
568     }
569     return InclusionPathHandleInvalid;
570   }
571   // Add a new header inclusion path entry, if not already present.
572   void addInclusionPathHandle(InclusionPathHandle H) {
573     if (!haveInclusionPathHandle(H))
574       InclusionPathHandles.push_back(H);
575   }
576 
577   // A string representing the macro instance after preprocessing.
578   StringHandle MacroExpanded;
579   // A file/line/column triplet representing the macro definition location.
580   PPItemKey DefinitionLocation;
581   // A place to save the macro definition line string.
582   StringHandle DefinitionSourceLine;
583   // The header inclusion path handles for all the instances.
584   std::vector<InclusionPathHandle> InclusionPathHandles;
585 };
586 
587 // Macro expansion instance tracker.
588 //
589 // This class represents one macro expansion, keyed by a PPItemKey.
590 // It stores a string representing the macro reference in the source,
591 // and a list of ConditionalExpansionInstances objects representing
592 // the unique values the condition expands to in instances of the header.
593 class MacroExpansionTracker {
594 public:
595   MacroExpansionTracker(StringHandle MacroUnexpanded,
596                         StringHandle MacroExpanded,
597                         StringHandle InstanceSourceLine,
598                         PPItemKey &DefinitionLocation,
599                         StringHandle DefinitionSourceLine,
600                         InclusionPathHandle InclusionPathHandle)
601       : MacroUnexpanded(MacroUnexpanded),
602         InstanceSourceLine(InstanceSourceLine) {
603     addMacroExpansionInstance(MacroExpanded, DefinitionLocation,
604                               DefinitionSourceLine, InclusionPathHandle);
605   }
606   MacroExpansionTracker() {}
607 
608   // Find a matching macro expansion instance.
609   MacroExpansionInstance *
610   findMacroExpansionInstance(StringHandle MacroExpanded,
611                              PPItemKey &DefinitionLocation) {
612     for (std::vector<MacroExpansionInstance>::iterator
613              I = MacroExpansionInstances.begin(),
614              E = MacroExpansionInstances.end();
615          I != E; ++I) {
616       if ((I->MacroExpanded == MacroExpanded) &&
617           (I->DefinitionLocation == DefinitionLocation)) {
618         return &*I; // Found.
619       }
620     }
621     return nullptr; // Not found.
622   }
623 
624   // Add a macro expansion instance.
625   void addMacroExpansionInstance(StringHandle MacroExpanded,
626                                  PPItemKey &DefinitionLocation,
627                                  StringHandle DefinitionSourceLine,
628                                  InclusionPathHandle InclusionPathHandle) {
629     MacroExpansionInstances.push_back(
630         MacroExpansionInstance(MacroExpanded, DefinitionLocation,
631                                DefinitionSourceLine, InclusionPathHandle));
632   }
633 
634   // Return true if there is a mismatch.
635   bool hasMismatch() { return MacroExpansionInstances.size() > 1; }
636 
637   // A string representing the macro instance without expansion.
638   StringHandle MacroUnexpanded;
639   // A place to save the macro instance source line string.
640   StringHandle InstanceSourceLine;
641   // The macro expansion instances.
642   // If all instances of the macro expansion expand to the same value,
643   // This vector will only have one instance.
644   std::vector<MacroExpansionInstance> MacroExpansionInstances;
645 };
646 
647 // Conditional expansion instance.
648 //
649 // This class represents an instance of a condition exoression result
650 // with a unique value.  It also stores the unique header inclusion paths
651 // for use in telling the user the nested include path to the header.
652 class ConditionalExpansionInstance {
653 public:
654   ConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue, InclusionPathHandle H)
655       : ConditionValue(ConditionValue) {
656     InclusionPathHandles.push_back(H);
657   }
658   ConditionalExpansionInstance() {}
659 
660   // Check for the presence of a header inclusion path handle entry.
661   // Return false if not found.
662   bool haveInclusionPathHandle(InclusionPathHandle H) {
663     for (std::vector<InclusionPathHandle>::iterator
664              I = InclusionPathHandles.begin(),
665              E = InclusionPathHandles.end();
666          I != E; ++I) {
667       if (*I == H)
668         return true;
669     }
670     return InclusionPathHandleInvalid;
671   }
672   // Add a new header inclusion path entry, if not already present.
673   void addInclusionPathHandle(InclusionPathHandle H) {
674     if (!haveInclusionPathHandle(H))
675       InclusionPathHandles.push_back(H);
676   }
677 
678   // A flag representing the evaluated condition value.
679   clang::PPCallbacks::ConditionValueKind ConditionValue;
680   // The header inclusion path handles for all the instances.
681   std::vector<InclusionPathHandle> InclusionPathHandles;
682 };
683 
684 // Conditional directive instance tracker.
685 //
686 // This class represents one conditional directive, keyed by a PPItemKey.
687 // It stores a string representing the macro reference in the source,
688 // and a list of ConditionExpansionInstance objects representing
689 // the unique value the condition expression expands to in instances of
690 // the header.
691 class ConditionalTracker {
692 public:
693   ConditionalTracker(clang::tok::PPKeywordKind DirectiveKind,
694                      clang::PPCallbacks::ConditionValueKind ConditionValue,
695                      StringHandle ConditionUnexpanded,
696                      InclusionPathHandle InclusionPathHandle)
697       : DirectiveKind(DirectiveKind), ConditionUnexpanded(ConditionUnexpanded) {
698     addConditionalExpansionInstance(ConditionValue, InclusionPathHandle);
699   }
700   ConditionalTracker() {}
701 
702   // Find a matching condition expansion instance.
703   ConditionalExpansionInstance *
704   findConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue) {
705     for (std::vector<ConditionalExpansionInstance>::iterator
706              I = ConditionalExpansionInstances.begin(),
707              E = ConditionalExpansionInstances.end();
708          I != E; ++I) {
709       if (I->ConditionValue == ConditionValue) {
710         return &*I; // Found.
711       }
712     }
713     return nullptr; // Not found.
714   }
715 
716   // Add a conditional expansion instance.
717   void
718   addConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue,
719                                   InclusionPathHandle InclusionPathHandle) {
720     ConditionalExpansionInstances.push_back(
721         ConditionalExpansionInstance(ConditionValue, InclusionPathHandle));
722   }
723 
724   // Return true if there is a mismatch.
725   bool hasMismatch() { return ConditionalExpansionInstances.size() > 1; }
726 
727   // The kind of directive.
728   clang::tok::PPKeywordKind DirectiveKind;
729   // A string representing the macro instance without expansion.
730   StringHandle ConditionUnexpanded;
731   // The condition expansion instances.
732   // If all instances of the conditional expression expand to the same value,
733   // This vector will only have one instance.
734   std::vector<ConditionalExpansionInstance> ConditionalExpansionInstances;
735 };
736 
737 class PreprocessorTrackerImpl;
738 
739 // Preprocessor callbacks for modularize.
740 //
741 // This class derives from the Clang PPCallbacks class to track preprocessor
742 // actions, such as changing files and handling preprocessor directives and
743 // macro expansions.  It has to figure out when a new header file is entered
744 // and left, as the provided handler is not particularly clear about it.
745 class PreprocessorCallbacks : public clang::PPCallbacks {
746 public:
747   PreprocessorCallbacks(PreprocessorTrackerImpl &ppTracker,
748                         clang::Preprocessor &PP, llvm::StringRef rootHeaderFile)
749       : PPTracker(ppTracker), PP(PP), RootHeaderFile(rootHeaderFile) {}
750   ~PreprocessorCallbacks() {}
751 
752   // Overridden handlers.
753   void InclusionDirective(clang::SourceLocation HashLoc,
754                           const clang::Token &IncludeTok,
755                           llvm::StringRef FileName, bool IsAngled,
756                           clang::CharSourceRange FilenameRange,
757                           const clang::FileEntry *File,
758                           llvm::StringRef SearchPath,
759                           llvm::StringRef RelativePath,
760                           const clang::Module *Imported);
761   void FileChanged(clang::SourceLocation Loc,
762                    clang::PPCallbacks::FileChangeReason Reason,
763                    clang::SrcMgr::CharacteristicKind FileType,
764                    clang::FileID PrevFID = clang::FileID());
765   void MacroExpands(const clang::Token &MacroNameTok,
766                     const clang::MacroDirective *MD, clang::SourceRange Range,
767                     const clang::MacroArgs *Args);
768   void Defined(const clang::Token &MacroNameTok,
769                const clang::MacroDirective *MD, clang::SourceRange Range);
770   void If(clang::SourceLocation Loc, clang::SourceRange ConditionRange,
771           clang::PPCallbacks::ConditionValueKind ConditionResult);
772   void Elif(clang::SourceLocation Loc, clang::SourceRange ConditionRange,
773             clang::PPCallbacks::ConditionValueKind ConditionResult, clang::SourceLocation IfLoc);
774   void Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok,
775              const clang::MacroDirective *MD);
776   void Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok,
777               const clang::MacroDirective *MD);
778 
779 private:
780   PreprocessorTrackerImpl &PPTracker;
781   clang::Preprocessor &PP;
782   std::string RootHeaderFile;
783 };
784 
785 // Preprocessor macro expansion item map types.
786 typedef std::map<PPItemKey, MacroExpansionTracker> MacroExpansionMap;
787 typedef std::map<PPItemKey, MacroExpansionTracker>::iterator
788 MacroExpansionMapIter;
789 
790 // Preprocessor conditional expansion item map types.
791 typedef std::map<PPItemKey, ConditionalTracker> ConditionalExpansionMap;
792 typedef std::map<PPItemKey, ConditionalTracker>::iterator
793 ConditionalExpansionMapIter;
794 
795 // Preprocessor tracker for modularize.
796 //
797 // This class stores information about all the headers processed in the
798 // course of running modularize.
799 class PreprocessorTrackerImpl : public PreprocessorTracker {
800 public:
801   PreprocessorTrackerImpl(llvm::SmallVector<std::string, 32> &Headers,
802         bool DoBlockCheckHeaderListOnly)
803       : BlockCheckHeaderListOnly(DoBlockCheckHeaderListOnly),
804         CurrentInclusionPathHandle(InclusionPathHandleInvalid),
805         InNestedHeader(false) {
806     // Use canonical header path representation.
807     for (llvm::ArrayRef<std::string>::iterator I = Headers.begin(),
808       E = Headers.end();
809       I != E; ++I) {
810       HeaderList.push_back(getCanonicalPath(*I));
811     }
812   }
813 
814   ~PreprocessorTrackerImpl() {}
815 
816   // Handle entering a preprocessing session.
817   void handlePreprocessorEntry(clang::Preprocessor &PP,
818                                llvm::StringRef rootHeaderFile) {
819     HeadersInThisCompile.clear();
820     assert((HeaderStack.size() == 0) && "Header stack should be empty.");
821     pushHeaderHandle(addHeader(rootHeaderFile));
822     PP.addPPCallbacks(llvm::make_unique<PreprocessorCallbacks>(*this, PP,
823                                                                rootHeaderFile));
824   }
825   // Handle exiting a preprocessing session.
826   void handlePreprocessorExit() { HeaderStack.clear(); }
827 
828   // Handle include directive.
829   // This function is called every time an include directive is seen by the
830   // preprocessor, for the purpose of later checking for 'extern "" {}' or
831   // "namespace {}" blocks containing #include directives.
832   void handleIncludeDirective(llvm::StringRef DirectivePath, int DirectiveLine,
833                               int DirectiveColumn, llvm::StringRef TargetPath) {
834     // If it's not a header in the header list, ignore it with respect to
835     // the check.
836     if (BlockCheckHeaderListOnly && !isHeaderListHeader(TargetPath))
837       return;
838     HeaderHandle CurrentHeaderHandle = findHeaderHandle(DirectivePath);
839     StringHandle IncludeHeaderHandle = addString(TargetPath);
840     for (std::vector<PPItemKey>::const_iterator I = IncludeDirectives.begin(),
841                                                 E = IncludeDirectives.end();
842          I != E; ++I) {
843       // If we already have an entry for this directive, return now.
844       if ((I->File == CurrentHeaderHandle) && (I->Line == DirectiveLine))
845         return;
846     }
847     PPItemKey IncludeDirectiveItem(IncludeHeaderHandle, CurrentHeaderHandle,
848                                    DirectiveLine, DirectiveColumn);
849     IncludeDirectives.push_back(IncludeDirectiveItem);
850   }
851 
852   // Check for include directives within the given source line range.
853   // Report errors if any found.  Returns true if no include directives
854   // found in block.
855   bool checkForIncludesInBlock(clang::Preprocessor &PP,
856                                clang::SourceRange BlockSourceRange,
857                                const char *BlockIdentifierMessage,
858                                llvm::raw_ostream &OS) {
859     clang::SourceLocation BlockStartLoc = BlockSourceRange.getBegin();
860     clang::SourceLocation BlockEndLoc = BlockSourceRange.getEnd();
861     // Use block location to get FileID of both the include directive
862     // and block statement.
863     clang::FileID FileID = PP.getSourceManager().getFileID(BlockStartLoc);
864     std::string SourcePath = getSourceLocationFile(PP, BlockStartLoc);
865     SourcePath = ModularizeUtilities::getCanonicalPath(SourcePath);
866     HeaderHandle SourceHandle = findHeaderHandle(SourcePath);
867     if (SourceHandle == -1)
868       return true;
869     int BlockStartLine, BlockStartColumn, BlockEndLine, BlockEndColumn;
870     bool returnValue = true;
871     getSourceLocationLineAndColumn(PP, BlockStartLoc, BlockStartLine,
872                                    BlockStartColumn);
873     getSourceLocationLineAndColumn(PP, BlockEndLoc, BlockEndLine,
874                                    BlockEndColumn);
875     for (std::vector<PPItemKey>::const_iterator I = IncludeDirectives.begin(),
876                                                 E = IncludeDirectives.end();
877          I != E; ++I) {
878       // If we find an entry within the block, report an error.
879       if ((I->File == SourceHandle) && (I->Line >= BlockStartLine) &&
880           (I->Line < BlockEndLine)) {
881         returnValue = false;
882         OS << SourcePath << ":" << I->Line << ":" << I->Column << ":\n";
883         OS << getSourceLine(PP, FileID, I->Line) << "\n";
884         if (I->Column > 0)
885           OS << std::string(I->Column - 1, ' ') << "^\n";
886         OS << "error: Include directive within " << BlockIdentifierMessage
887            << ".\n";
888         OS << SourcePath << ":" << BlockStartLine << ":" << BlockStartColumn
889            << ":\n";
890         OS << getSourceLine(PP, BlockStartLoc) << "\n";
891         if (BlockStartColumn > 0)
892           OS << std::string(BlockStartColumn - 1, ' ') << "^\n";
893         OS << "The \"" << BlockIdentifierMessage << "\" block is here.\n";
894       }
895     }
896     return returnValue;
897   }
898 
899   // Handle entering a header source file.
900   void handleHeaderEntry(clang::Preprocessor &PP, llvm::StringRef HeaderPath) {
901     // Ignore <built-in> and <command-line> to reduce message clutter.
902     if (HeaderPath.startswith("<"))
903       return;
904     HeaderHandle H = addHeader(HeaderPath);
905     if (H != getCurrentHeaderHandle())
906       pushHeaderHandle(H);
907     // Check for nested header.
908     if (!InNestedHeader)
909       InNestedHeader = !HeadersInThisCompile.insert(H).second;
910   }
911 
912   // Handle exiting a header source file.
913   void handleHeaderExit(llvm::StringRef HeaderPath) {
914     // Ignore <built-in> and <command-line> to reduce message clutter.
915     if (HeaderPath.startswith("<"))
916       return;
917     HeaderHandle H = findHeaderHandle(HeaderPath);
918     HeaderHandle TH;
919     if (isHeaderHandleInStack(H)) {
920       do {
921         TH = getCurrentHeaderHandle();
922         popHeaderHandle();
923       } while ((TH != H) && (HeaderStack.size() != 0));
924     }
925     InNestedHeader = false;
926   }
927 
928   // Lookup/add string.
929   StringHandle addString(llvm::StringRef Str) { return Strings.intern(Str); }
930 
931   // Convert to a canonical path.
932   std::string getCanonicalPath(llvm::StringRef path) const {
933     std::string CanonicalPath(path);
934     std::replace(CanonicalPath.begin(), CanonicalPath.end(), '\\', '/');
935     return CanonicalPath;
936   }
937 
938   // Return true if the given header is in the header list.
939   bool isHeaderListHeader(llvm::StringRef HeaderPath) const {
940     std::string CanonicalPath = getCanonicalPath(HeaderPath);
941     for (llvm::ArrayRef<std::string>::iterator I = HeaderList.begin(),
942         E = HeaderList.end();
943         I != E; ++I) {
944       if (*I == CanonicalPath)
945         return true;
946     }
947     return false;
948   }
949 
950   // Get the handle of a header file entry.
951   // Return HeaderHandleInvalid if not found.
952   HeaderHandle findHeaderHandle(llvm::StringRef HeaderPath) const {
953     std::string CanonicalPath = getCanonicalPath(HeaderPath);
954     HeaderHandle H = 0;
955     for (std::vector<StringHandle>::const_iterator I = HeaderPaths.begin(),
956                                                    E = HeaderPaths.end();
957          I != E; ++I, ++H) {
958       if (**I == CanonicalPath)
959         return H;
960     }
961     return HeaderHandleInvalid;
962   }
963 
964   // Add a new header file entry, or return existing handle.
965   // Return the header handle.
966   HeaderHandle addHeader(llvm::StringRef HeaderPath) {
967     std::string CanonicalPath = getCanonicalPath(HeaderPath);
968     HeaderHandle H = findHeaderHandle(CanonicalPath);
969     if (H == HeaderHandleInvalid) {
970       H = HeaderPaths.size();
971       HeaderPaths.push_back(addString(CanonicalPath));
972     }
973     return H;
974   }
975 
976   // Return a header file path string given its handle.
977   StringHandle getHeaderFilePath(HeaderHandle H) const {
978     if ((H >= 0) && (H < (HeaderHandle)HeaderPaths.size()))
979       return HeaderPaths[H];
980     return StringHandle();
981   }
982 
983   // Returns a handle to the inclusion path.
984   InclusionPathHandle pushHeaderHandle(HeaderHandle H) {
985     HeaderStack.push_back(H);
986     return CurrentInclusionPathHandle = addInclusionPathHandle(HeaderStack);
987   }
988   // Pops the last header handle from the stack;
989   void popHeaderHandle() {
990     // assert((HeaderStack.size() != 0) && "Header stack already empty.");
991     if (HeaderStack.size() != 0) {
992       HeaderStack.pop_back();
993       CurrentInclusionPathHandle = addInclusionPathHandle(HeaderStack);
994     }
995   }
996   // Get the top handle on the header stack.
997   HeaderHandle getCurrentHeaderHandle() const {
998     if (HeaderStack.size() != 0)
999       return HeaderStack.back();
1000     return HeaderHandleInvalid;
1001   }
1002 
1003   // Check for presence of header handle in the header stack.
1004   bool isHeaderHandleInStack(HeaderHandle H) const {
1005     for (std::vector<HeaderHandle>::const_iterator I = HeaderStack.begin(),
1006                                                    E = HeaderStack.end();
1007          I != E; ++I) {
1008       if (*I == H)
1009         return true;
1010     }
1011     return false;
1012   }
1013 
1014   // Get the handle of a header inclusion path entry.
1015   // Return InclusionPathHandleInvalid if not found.
1016   InclusionPathHandle
1017   findInclusionPathHandle(const std::vector<HeaderHandle> &Path) const {
1018     InclusionPathHandle H = 0;
1019     for (std::vector<HeaderInclusionPath>::const_iterator
1020              I = InclusionPaths.begin(),
1021              E = InclusionPaths.end();
1022          I != E; ++I, ++H) {
1023       if (I->Path == Path)
1024         return H;
1025     }
1026     return HeaderHandleInvalid;
1027   }
1028   // Add a new header inclusion path entry, or return existing handle.
1029   // Return the header inclusion path entry handle.
1030   InclusionPathHandle
1031   addInclusionPathHandle(const std::vector<HeaderHandle> &Path) {
1032     InclusionPathHandle H = findInclusionPathHandle(Path);
1033     if (H == HeaderHandleInvalid) {
1034       H = InclusionPaths.size();
1035       InclusionPaths.push_back(HeaderInclusionPath(Path));
1036     }
1037     return H;
1038   }
1039   // Return the current inclusion path handle.
1040   InclusionPathHandle getCurrentInclusionPathHandle() const {
1041     return CurrentInclusionPathHandle;
1042   }
1043 
1044   // Return an inclusion path given its handle.
1045   const std::vector<HeaderHandle> &
1046   getInclusionPath(InclusionPathHandle H) const {
1047     if ((H >= 0) && (H <= (InclusionPathHandle)InclusionPaths.size()))
1048       return InclusionPaths[H].Path;
1049     static std::vector<HeaderHandle> Empty;
1050     return Empty;
1051   }
1052 
1053   // Add a macro expansion instance.
1054   void addMacroExpansionInstance(clang::Preprocessor &PP, HeaderHandle H,
1055                                  clang::SourceLocation InstanceLoc,
1056                                  clang::SourceLocation DefinitionLoc,
1057                                  clang::IdentifierInfo *II,
1058                                  llvm::StringRef MacroUnexpanded,
1059                                  llvm::StringRef MacroExpanded,
1060                                  InclusionPathHandle InclusionPathHandle) {
1061     if (InNestedHeader)
1062       return;
1063     StringHandle MacroName = addString(II->getName());
1064     PPItemKey InstanceKey(PP, MacroName, H, InstanceLoc);
1065     PPItemKey DefinitionKey(PP, MacroName, H, DefinitionLoc);
1066     MacroExpansionMapIter I = MacroExpansions.find(InstanceKey);
1067     // If existing instance of expansion not found, add one.
1068     if (I == MacroExpansions.end()) {
1069       std::string InstanceSourceLine =
1070           getSourceLocationString(PP, InstanceLoc) + ":\n" +
1071           getSourceLine(PP, InstanceLoc) + "\n";
1072       std::string DefinitionSourceLine =
1073           getSourceLocationString(PP, DefinitionLoc) + ":\n" +
1074           getSourceLine(PP, DefinitionLoc) + "\n";
1075       MacroExpansions[InstanceKey] = MacroExpansionTracker(
1076           addString(MacroUnexpanded), addString(MacroExpanded),
1077           addString(InstanceSourceLine), DefinitionKey,
1078           addString(DefinitionSourceLine), InclusionPathHandle);
1079     } else {
1080       // We've seen the macro before.  Get its tracker.
1081       MacroExpansionTracker &CondTracker = I->second;
1082       // Look up an existing instance value for the macro.
1083       MacroExpansionInstance *MacroInfo =
1084           CondTracker.findMacroExpansionInstance(addString(MacroExpanded),
1085                                                  DefinitionKey);
1086       // If found, just add the inclusion path to the instance.
1087       if (MacroInfo)
1088         MacroInfo->addInclusionPathHandle(InclusionPathHandle);
1089       else {
1090         // Otherwise add a new instance with the unique value.
1091         std::string DefinitionSourceLine =
1092             getSourceLocationString(PP, DefinitionLoc) + ":\n" +
1093             getSourceLine(PP, DefinitionLoc) + "\n";
1094         CondTracker.addMacroExpansionInstance(
1095             addString(MacroExpanded), DefinitionKey,
1096             addString(DefinitionSourceLine), InclusionPathHandle);
1097       }
1098     }
1099   }
1100 
1101   // Add a conditional expansion instance.
1102   void
1103   addConditionalExpansionInstance(clang::Preprocessor &PP, HeaderHandle H,
1104                                   clang::SourceLocation InstanceLoc,
1105                                   clang::tok::PPKeywordKind DirectiveKind,
1106                                   clang::PPCallbacks::ConditionValueKind ConditionValue,
1107                                   llvm::StringRef ConditionUnexpanded,
1108                                   InclusionPathHandle InclusionPathHandle) {
1109     // Ignore header guards, assuming the header guard is the only conditional.
1110     if (InNestedHeader)
1111       return;
1112     StringHandle ConditionUnexpandedHandle(addString(ConditionUnexpanded));
1113     PPItemKey InstanceKey(PP, ConditionUnexpandedHandle, H, InstanceLoc);
1114     ConditionalExpansionMapIter I = ConditionalExpansions.find(InstanceKey);
1115     // If existing instance of condition not found, add one.
1116     if (I == ConditionalExpansions.end()) {
1117       std::string InstanceSourceLine =
1118           getSourceLocationString(PP, InstanceLoc) + ":\n" +
1119           getSourceLine(PP, InstanceLoc) + "\n";
1120       ConditionalExpansions[InstanceKey] =
1121           ConditionalTracker(DirectiveKind, ConditionValue,
1122                              ConditionUnexpandedHandle, InclusionPathHandle);
1123     } else {
1124       // We've seen the conditional before.  Get its tracker.
1125       ConditionalTracker &CondTracker = I->second;
1126       // Look up an existing instance value for the condition.
1127       ConditionalExpansionInstance *MacroInfo =
1128           CondTracker.findConditionalExpansionInstance(ConditionValue);
1129       // If found, just add the inclusion path to the instance.
1130       if (MacroInfo)
1131         MacroInfo->addInclusionPathHandle(InclusionPathHandle);
1132       else {
1133         // Otherwise add a new instance with the unique value.
1134         CondTracker.addConditionalExpansionInstance(ConditionValue,
1135                                                     InclusionPathHandle);
1136       }
1137     }
1138   }
1139 
1140   // Report on inconsistent macro instances.
1141   // Returns true if any mismatches.
1142   bool reportInconsistentMacros(llvm::raw_ostream &OS) {
1143     bool ReturnValue = false;
1144     // Walk all the macro expansion trackers in the map.
1145     for (MacroExpansionMapIter I = MacroExpansions.begin(),
1146                                E = MacroExpansions.end();
1147          I != E; ++I) {
1148       const PPItemKey &ItemKey = I->first;
1149       MacroExpansionTracker &MacroExpTracker = I->second;
1150       // If no mismatch (only one instance value) continue.
1151       if (!MacroExpTracker.hasMismatch())
1152         continue;
1153       // Tell caller we found one or more errors.
1154       ReturnValue = true;
1155       // Start the error message.
1156       OS << *MacroExpTracker.InstanceSourceLine;
1157       if (ItemKey.Column > 0)
1158         OS << std::string(ItemKey.Column - 1, ' ') << "^\n";
1159       OS << "error: Macro instance '" << *MacroExpTracker.MacroUnexpanded
1160          << "' has different values in this header, depending on how it was "
1161             "included.\n";
1162       // Walk all the instances.
1163       for (std::vector<MacroExpansionInstance>::iterator
1164                IMT = MacroExpTracker.MacroExpansionInstances.begin(),
1165                EMT = MacroExpTracker.MacroExpansionInstances.end();
1166            IMT != EMT; ++IMT) {
1167         MacroExpansionInstance &MacroInfo = *IMT;
1168         OS << "  '" << *MacroExpTracker.MacroUnexpanded << "' expanded to: '"
1169            << *MacroInfo.MacroExpanded
1170            << "' with respect to these inclusion paths:\n";
1171         // Walk all the inclusion path hierarchies.
1172         for (std::vector<InclusionPathHandle>::iterator
1173                  IIP = MacroInfo.InclusionPathHandles.begin(),
1174                  EIP = MacroInfo.InclusionPathHandles.end();
1175              IIP != EIP; ++IIP) {
1176           const std::vector<HeaderHandle> &ip = getInclusionPath(*IIP);
1177           int Count = (int)ip.size();
1178           for (int Index = 0; Index < Count; ++Index) {
1179             HeaderHandle H = ip[Index];
1180             OS << std::string((Index * 2) + 4, ' ') << *getHeaderFilePath(H)
1181                << "\n";
1182           }
1183         }
1184         // For a macro that wasn't defined, we flag it by using the
1185         // instance location.
1186         // If there is a definition...
1187         if (MacroInfo.DefinitionLocation.Line != ItemKey.Line) {
1188           OS << *MacroInfo.DefinitionSourceLine;
1189           if (MacroInfo.DefinitionLocation.Column > 0)
1190             OS << std::string(MacroInfo.DefinitionLocation.Column - 1, ' ')
1191                << "^\n";
1192           OS << "Macro defined here.\n";
1193         } else
1194           OS << "(no macro definition)"
1195              << "\n";
1196       }
1197     }
1198     return ReturnValue;
1199   }
1200 
1201   // Report on inconsistent conditional instances.
1202   // Returns true if any mismatches.
1203   bool reportInconsistentConditionals(llvm::raw_ostream &OS) {
1204     bool ReturnValue = false;
1205     // Walk all the conditional trackers in the map.
1206     for (ConditionalExpansionMapIter I = ConditionalExpansions.begin(),
1207                                      E = ConditionalExpansions.end();
1208          I != E; ++I) {
1209       const PPItemKey &ItemKey = I->first;
1210       ConditionalTracker &CondTracker = I->second;
1211       if (!CondTracker.hasMismatch())
1212         continue;
1213       // Tell caller we found one or more errors.
1214       ReturnValue = true;
1215       // Start the error message.
1216       OS << *HeaderPaths[ItemKey.File] << ":" << ItemKey.Line << ":"
1217          << ItemKey.Column << "\n";
1218       OS << "#" << getDirectiveSpelling(CondTracker.DirectiveKind) << " "
1219          << *CondTracker.ConditionUnexpanded << "\n";
1220       OS << "^\n";
1221       OS << "error: Conditional expression instance '"
1222          << *CondTracker.ConditionUnexpanded
1223          << "' has different values in this header, depending on how it was "
1224             "included.\n";
1225       // Walk all the instances.
1226       for (std::vector<ConditionalExpansionInstance>::iterator
1227                IMT = CondTracker.ConditionalExpansionInstances.begin(),
1228                EMT = CondTracker.ConditionalExpansionInstances.end();
1229            IMT != EMT; ++IMT) {
1230         ConditionalExpansionInstance &MacroInfo = *IMT;
1231         OS << "  '" << *CondTracker.ConditionUnexpanded << "' expanded to: '"
1232            << ConditionValueKindStrings[MacroInfo.ConditionValue]
1233            << "' with respect to these inclusion paths:\n";
1234         // Walk all the inclusion path hierarchies.
1235         for (std::vector<InclusionPathHandle>::iterator
1236                  IIP = MacroInfo.InclusionPathHandles.begin(),
1237                  EIP = MacroInfo.InclusionPathHandles.end();
1238              IIP != EIP; ++IIP) {
1239           const std::vector<HeaderHandle> &ip = getInclusionPath(*IIP);
1240           int Count = (int)ip.size();
1241           for (int Index = 0; Index < Count; ++Index) {
1242             HeaderHandle H = ip[Index];
1243             OS << std::string((Index * 2) + 4, ' ') << *getHeaderFilePath(H)
1244                << "\n";
1245           }
1246         }
1247       }
1248     }
1249     return ReturnValue;
1250   }
1251 
1252   // Get directive spelling.
1253   static const char *getDirectiveSpelling(clang::tok::PPKeywordKind kind) {
1254     switch (kind) {
1255     case clang::tok::pp_if:
1256       return "if";
1257     case clang::tok::pp_elif:
1258       return "elif";
1259     case clang::tok::pp_ifdef:
1260       return "ifdef";
1261     case clang::tok::pp_ifndef:
1262       return "ifndef";
1263     default:
1264       return "(unknown)";
1265     }
1266   }
1267 
1268 private:
1269   llvm::SmallVector<std::string, 32> HeaderList;
1270   // Only do extern, namespace check for headers in HeaderList.
1271   bool BlockCheckHeaderListOnly;
1272   llvm::StringPool Strings;
1273   std::vector<StringHandle> HeaderPaths;
1274   std::vector<HeaderHandle> HeaderStack;
1275   std::vector<HeaderInclusionPath> InclusionPaths;
1276   InclusionPathHandle CurrentInclusionPathHandle;
1277   llvm::SmallSet<HeaderHandle, 128> HeadersInThisCompile;
1278   std::vector<PPItemKey> IncludeDirectives;
1279   MacroExpansionMap MacroExpansions;
1280   ConditionalExpansionMap ConditionalExpansions;
1281   bool InNestedHeader;
1282 };
1283 
1284 } // namespace
1285 
1286 // PreprocessorTracker functions.
1287 
1288 // PreprocessorTracker desctructor.
1289 PreprocessorTracker::~PreprocessorTracker() {}
1290 
1291 // Create instance of PreprocessorTracker.
1292 PreprocessorTracker *PreprocessorTracker::create(
1293     llvm::SmallVector<std::string, 32> &Headers,
1294     bool DoBlockCheckHeaderListOnly) {
1295   return new PreprocessorTrackerImpl(Headers, DoBlockCheckHeaderListOnly);
1296 }
1297 
1298 // Preprocessor callbacks for modularize.
1299 
1300 // Handle include directive.
1301 void PreprocessorCallbacks::InclusionDirective(
1302     clang::SourceLocation HashLoc, const clang::Token &IncludeTok,
1303     llvm::StringRef FileName, bool IsAngled,
1304     clang::CharSourceRange FilenameRange, const clang::FileEntry *File,
1305     llvm::StringRef SearchPath, llvm::StringRef RelativePath,
1306     const clang::Module *Imported) {
1307   int DirectiveLine, DirectiveColumn;
1308   std::string HeaderPath = getSourceLocationFile(PP, HashLoc);
1309   getSourceLocationLineAndColumn(PP, HashLoc, DirectiveLine, DirectiveColumn);
1310   PPTracker.handleIncludeDirective(HeaderPath, DirectiveLine, DirectiveColumn,
1311                                    FileName);
1312 }
1313 
1314 // Handle file entry/exit.
1315 void PreprocessorCallbacks::FileChanged(
1316     clang::SourceLocation Loc, clang::PPCallbacks::FileChangeReason Reason,
1317     clang::SrcMgr::CharacteristicKind FileType, clang::FileID PrevFID) {
1318   switch (Reason) {
1319   case EnterFile:
1320     PPTracker.handleHeaderEntry(PP, getSourceLocationFile(PP, Loc));
1321     break;
1322   case ExitFile: {
1323     const clang::FileEntry *F =
1324         PP.getSourceManager().getFileEntryForID(PrevFID);
1325     if (F)
1326       PPTracker.handleHeaderExit(F->getName());
1327   } break;
1328   case SystemHeaderPragma:
1329   case RenameFile:
1330     break;
1331   }
1332 }
1333 
1334 // Handle macro expansion.
1335 void PreprocessorCallbacks::MacroExpands(const clang::Token &MacroNameTok,
1336                                          const clang::MacroDirective *MD,
1337                                          clang::SourceRange Range,
1338                                          const clang::MacroArgs *Args) {
1339   clang::SourceLocation Loc = Range.getBegin();
1340   // Ignore macro argument expansions.
1341   if (!Loc.isFileID())
1342     return;
1343   clang::IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1344   const clang::MacroInfo *MI = PP.getMacroInfo(II);
1345   std::string MacroName = II->getName().str();
1346   std::string Unexpanded(getMacroUnexpandedString(Range, PP, MacroName, MI));
1347   std::string Expanded(getMacroExpandedString(PP, MacroName, MI, Args));
1348   PPTracker.addMacroExpansionInstance(
1349       PP, PPTracker.getCurrentHeaderHandle(), Loc, MI->getDefinitionLoc(), II,
1350       Unexpanded, Expanded, PPTracker.getCurrentInclusionPathHandle());
1351 }
1352 
1353 void PreprocessorCallbacks::Defined(const clang::Token &MacroNameTok,
1354                                     const clang::MacroDirective *MD,
1355                                     clang::SourceRange Range) {
1356   clang::SourceLocation Loc(Range.getBegin());
1357   clang::IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1358   const clang::MacroInfo *MI = PP.getMacroInfo(II);
1359   std::string MacroName = II->getName().str();
1360   std::string Unexpanded(getSourceString(PP, Range));
1361   PPTracker.addMacroExpansionInstance(
1362       PP, PPTracker.getCurrentHeaderHandle(), Loc,
1363       (MI ? MI->getDefinitionLoc() : Loc), II, Unexpanded,
1364       (MI ? "true" : "false"), PPTracker.getCurrentInclusionPathHandle());
1365 }
1366 
1367 void PreprocessorCallbacks::If(clang::SourceLocation Loc,
1368                                clang::SourceRange ConditionRange,
1369                                clang::PPCallbacks::ConditionValueKind ConditionResult) {
1370   std::string Unexpanded(getSourceString(PP, ConditionRange));
1371   PPTracker.addConditionalExpansionInstance(
1372       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_if,
1373       ConditionResult, Unexpanded, PPTracker.getCurrentInclusionPathHandle());
1374 }
1375 
1376 void PreprocessorCallbacks::Elif(clang::SourceLocation Loc,
1377                                  clang::SourceRange ConditionRange,
1378                                  clang::PPCallbacks::ConditionValueKind ConditionResult,
1379                                  clang::SourceLocation IfLoc) {
1380   std::string Unexpanded(getSourceString(PP, ConditionRange));
1381   PPTracker.addConditionalExpansionInstance(
1382       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_elif,
1383       ConditionResult, Unexpanded, PPTracker.getCurrentInclusionPathHandle());
1384 }
1385 
1386 void PreprocessorCallbacks::Ifdef(clang::SourceLocation Loc,
1387                                   const clang::Token &MacroNameTok,
1388                                   const clang::MacroDirective *MD) {
1389   clang::PPCallbacks::ConditionValueKind IsDefined =
1390     (MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False );
1391   PPTracker.addConditionalExpansionInstance(
1392       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifdef,
1393       IsDefined, PP.getSpelling(MacroNameTok),
1394       PPTracker.getCurrentInclusionPathHandle());
1395 }
1396 
1397 void PreprocessorCallbacks::Ifndef(clang::SourceLocation Loc,
1398                                    const clang::Token &MacroNameTok,
1399                                    const clang::MacroDirective *MD) {
1400   clang::PPCallbacks::ConditionValueKind IsNotDefined =
1401     (!MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False );
1402   PPTracker.addConditionalExpansionInstance(
1403       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifndef,
1404       IsNotDefined, PP.getSpelling(MacroNameTok),
1405       PPTracker.getCurrentInclusionPathHandle());
1406 }
1407 } // end namespace Modularize
1408