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 "clang/Lex/MacroArgs.h"
249 #include "clang/Lex/PPCallbacks.h"
250 #include "llvm/Support/raw_ostream.h"
251 #include "llvm/Support/StringPool.h"
252 #include "llvm/ADT/SmallSet.h"
253 #include "PreprocessorTracker.h"
254 
255 namespace Modularize {
256 
257 // Forwards.
258 class PreprocessorTrackerImpl;
259 
260 // Some handle types
261 typedef llvm::PooledStringPtr StringHandle;
262 
263 typedef int HeaderHandle;
264 const HeaderHandle HeaderHandleInvalid = -1;
265 
266 typedef int InclusionPathHandle;
267 const InclusionPathHandle InclusionPathHandleInvalid = -1;
268 
269 // Some utility functions.
270 
271 // Get a "file:line:column" source location string.
272 static std::string getSourceLocationString(clang::Preprocessor &PP,
273                                            clang::SourceLocation Loc) {
274   if (Loc.isInvalid())
275     return std::string("(none)");
276   else
277     return Loc.printToString(PP.getSourceManager());
278 }
279 
280 // Get just the file name from a source location.
281 static std::string getSourceLocationFile(clang::Preprocessor &PP,
282                                          clang::SourceLocation Loc) {
283   std::string Source(getSourceLocationString(PP, Loc));
284   size_t Offset = Source.find(':', 2);
285   if (Offset == std::string::npos)
286     return Source;
287   return Source.substr(0, Offset);
288 }
289 
290 // Get just the line and column from a source location.
291 static void getSourceLocationLineAndColumn(clang::Preprocessor &PP,
292                                            clang::SourceLocation Loc, int &Line,
293                                            int &Column) {
294   clang::PresumedLoc PLoc = PP.getSourceManager().getPresumedLoc(Loc);
295   if (PLoc.isInvalid()) {
296     Line = 0;
297     Column = 0;
298     return;
299   }
300   Line = PLoc.getLine();
301   Column = PLoc.getColumn();
302 }
303 
304 // Retrieve source snippet from file image.
305 std::string getSourceString(clang::Preprocessor &PP, clang::SourceRange Range) {
306   clang::SourceLocation BeginLoc = Range.getBegin();
307   clang::SourceLocation EndLoc = Range.getEnd();
308   const char *BeginPtr = PP.getSourceManager().getCharacterData(BeginLoc);
309   const char *EndPtr = PP.getSourceManager().getCharacterData(EndLoc);
310   size_t Length = EndPtr - BeginPtr;
311   return llvm::StringRef(BeginPtr, Length).trim().str();
312 }
313 
314 // Retrieve source line from file image given a location.
315 std::string getSourceLine(clang::Preprocessor &PP, 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 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 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 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 == NULL)
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 != NULL)
422           Expanded += getMacroExpandedString(PP, Name, MacroInfo, NULL);
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 == NULL)
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 != NULL)
451           Expanded += getMacroExpandedString(PP, Name, MacroInfo, NULL);
452         else
453           Expanded += Name;
454       }
455     }
456   }
457   return Expanded;
458 }
459 
460 // Get the string representing a vector of Tokens.
461 std::string
462 getTokensSpellingString(clang::Preprocessor &PP,
463                         llvm::SmallVectorImpl<clang::Token> &Tokens) {
464   std::string Expanded;
465   // Walk over the macro Tokens.
466   typedef llvm::SmallVectorImpl<clang::Token>::iterator Iter;
467   for (Iter I = Tokens.begin(), E = Tokens.end(); I != E; ++I)
468     Expanded += PP.getSpelling(*I); // Not an identifier.
469   return llvm::StringRef(Expanded).trim().str();
470 }
471 
472 // Get the expansion for a macro instance, given the information
473 // provided by PPCallbacks.
474 std::string getExpandedString(clang::Preprocessor &PP,
475                               llvm::StringRef MacroName,
476                               const clang::MacroInfo *MI,
477                               const clang::MacroArgs *Args) {
478   std::string Expanded;
479   // Walk over the macro Tokens.
480   typedef clang::MacroInfo::tokens_iterator Iter;
481   for (Iter I = MI->tokens_begin(), E = MI->tokens_end(); I != E; ++I) {
482     clang::IdentifierInfo *II = I->getIdentifierInfo();
483     int ArgNo = (II && Args ? MI->getArgumentNum(II) : -1);
484     if (ArgNo == -1) {
485       // This isn't an argument, just add it.
486       if (II == NULL)
487         Expanded += PP.getSpelling((*I)); // Not an identifier.
488       else {
489         // Token is for an identifier.
490         std::string Name = II->getName().str();
491         // Check for nexted macro references.
492         clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
493         if (MacroInfo != NULL)
494           Expanded += getMacroExpandedString(PP, Name, MacroInfo, NULL);
495         else
496           Expanded += Name;
497       }
498       continue;
499     }
500     // We get here if it's a function-style macro with arguments.
501     const clang::Token *ResultArgToks;
502     const clang::Token *ArgTok = Args->getUnexpArgument(ArgNo);
503     if (Args->ArgNeedsPreexpansion(ArgTok, PP))
504       ResultArgToks = &(const_cast<clang::MacroArgs *>(Args))
505           ->getPreExpArgument(ArgNo, MI, PP)[0];
506     else
507       ResultArgToks = ArgTok; // Use non-preexpanded Tokens.
508     // If the arg token didn't expand into anything, ignore it.
509     if (ResultArgToks->is(clang::tok::eof))
510       continue;
511     unsigned NumToks = clang::MacroArgs::getArgLength(ResultArgToks);
512     // Append the resulting argument expansions.
513     for (unsigned ArgumentIndex = 0; ArgumentIndex < NumToks; ++ArgumentIndex) {
514       const clang::Token &AT = ResultArgToks[ArgumentIndex];
515       clang::IdentifierInfo *II = AT.getIdentifierInfo();
516       if (II == NULL)
517         Expanded += PP.getSpelling(AT); // Not an identifier.
518       else {
519         // It's an identifier.  Check for further expansion.
520         std::string Name = II->getName().str();
521         clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
522         if (MacroInfo != NULL)
523           Expanded += getMacroExpandedString(PP, Name, MacroInfo, NULL);
524         else
525           Expanded += Name;
526       }
527     }
528   }
529   return Expanded;
530 }
531 
532 // We need some operator overloads for string handles.
533 bool operator==(const StringHandle &H1, const StringHandle &H2) {
534   const char *S1 = (H1 ? *H1 : "");
535   const char *S2 = (H2 ? *H2 : "");
536   int Diff = strcmp(S1, S2);
537   return Diff == 0;
538 }
539 bool operator!=(const StringHandle &H1, const StringHandle &H2) {
540   const char *S1 = (H1 ? *H1 : "");
541   const char *S2 = (H2 ? *H2 : "");
542   int Diff = strcmp(S1, S2);
543   return Diff != 0;
544 }
545 bool operator<(const StringHandle &H1, const StringHandle &H2) {
546   const char *S1 = (H1 ? *H1 : "");
547   const char *S2 = (H2 ? *H2 : "");
548   int Diff = strcmp(S1, S2);
549   return Diff < 0;
550 }
551 bool operator>(const StringHandle &H1, const StringHandle &H2) {
552   const char *S1 = (H1 ? *H1 : "");
553   const char *S2 = (H2 ? *H2 : "");
554   int Diff = strcmp(S1, S2);
555   return Diff > 0;
556 }
557 
558 // Preprocessor item key.
559 //
560 // This class represents a location in a source file, for use
561 // as a key representing a unique name/file/line/column quadruplet,
562 // which in this case is used to identify a macro expansion instance,
563 // but could be used for other things as well.
564 // The file is a header file handle, the line is a line number,
565 // and the column is a column number.
566 class PPItemKey {
567 public:
568   PPItemKey(clang::Preprocessor &PP, StringHandle Name, HeaderHandle File,
569             clang::SourceLocation Loc)
570       : Name(Name), File(File) {
571     getSourceLocationLineAndColumn(PP, Loc, Line, Column);
572   }
573   PPItemKey(StringHandle Name, HeaderHandle File, int Line, int Column)
574       : Name(Name), File(File), Line(Line), Column(Column) {}
575   PPItemKey(const PPItemKey &Other)
576       : Name(Other.Name), File(Other.File), Line(Other.Line),
577         Column(Other.Column) {}
578   PPItemKey() : File(HeaderHandleInvalid), Line(0), Column(0) {}
579   bool operator==(const PPItemKey &Other) const {
580     if (Name != Other.Name)
581       return false;
582     if (File != Other.File)
583       return false;
584     if (Line != Other.Line)
585       return false;
586     return Column == Other.Column;
587   }
588   bool operator<(const PPItemKey &Other) const {
589     if (Name < Other.Name)
590       return true;
591     else if (Name > Other.Name)
592       return false;
593     if (File < Other.File)
594       return true;
595     else if (File > Other.File)
596       return false;
597     if (Line < Other.Line)
598       return true;
599     else if (Line > Other.Line)
600       return false;
601     return Column < Other.Column;
602   }
603   StringHandle Name;
604   HeaderHandle File;
605   int Line;
606   int Column;
607 };
608 
609 // Header inclusion path.
610 class HeaderInclusionPath {
611 public:
612   HeaderInclusionPath(std::vector<HeaderHandle> HeaderInclusionPath)
613       : Path(HeaderInclusionPath) {}
614   HeaderInclusionPath(const HeaderInclusionPath &Other) : Path(Other.Path) {}
615   HeaderInclusionPath() {}
616   std::vector<HeaderHandle> Path;
617 };
618 
619 // Macro expansion instance.
620 //
621 // This class represents an instance of a macro expansion with a
622 // unique value.  It also stores the unique header inclusion paths
623 // for use in telling the user the nested include path to the header.
624 class MacroExpansionInstance {
625 public:
626   MacroExpansionInstance(StringHandle MacroExpanded,
627                          PPItemKey &DefinitionLocation,
628                          StringHandle DefinitionSourceLine,
629                          InclusionPathHandle H)
630       : MacroExpanded(MacroExpanded), DefinitionLocation(DefinitionLocation),
631         DefinitionSourceLine(DefinitionSourceLine) {
632     InclusionPathHandles.push_back(H);
633   }
634   MacroExpansionInstance() {}
635 
636   // Check for the presence of a header inclusion path handle entry.
637   // Return false if not found.
638   bool haveInclusionPathHandle(InclusionPathHandle H) {
639     for (std::vector<InclusionPathHandle>::iterator
640              I = InclusionPathHandles.begin(),
641              E = InclusionPathHandles.end();
642          I != E; ++I) {
643       if (*I == H)
644         return true;
645     }
646     return InclusionPathHandleInvalid;
647   }
648   // Add a new header inclusion path entry, if not already present.
649   void addInclusionPathHandle(InclusionPathHandle H) {
650     if (!haveInclusionPathHandle(H))
651       InclusionPathHandles.push_back(H);
652   }
653 
654   // A string representing the macro instance after preprocessing.
655   StringHandle MacroExpanded;
656   // A file/line/column triplet representing the macro definition location.
657   PPItemKey DefinitionLocation;
658   // A place to save the macro definition line string.
659   StringHandle DefinitionSourceLine;
660   // The header inclusion path handles for all the instances.
661   std::vector<InclusionPathHandle> InclusionPathHandles;
662 };
663 
664 // Macro expansion instance tracker.
665 //
666 // This class represents one macro expansion, keyed by a PPItemKey.
667 // It stores a string representing the macro reference in the source,
668 // and a list of ConditionalExpansionInstances objects representing
669 // the unique values the condition expands to in instances of the header.
670 class MacroExpansionTracker {
671 public:
672   MacroExpansionTracker(StringHandle MacroUnexpanded,
673                         StringHandle MacroExpanded,
674                         StringHandle InstanceSourceLine,
675                         PPItemKey &DefinitionLocation,
676                         StringHandle DefinitionSourceLine,
677                         InclusionPathHandle InclusionPathHandle)
678       : MacroUnexpanded(MacroUnexpanded),
679         InstanceSourceLine(InstanceSourceLine) {
680     addMacroExpansionInstance(MacroExpanded, DefinitionLocation,
681                               DefinitionSourceLine, InclusionPathHandle);
682   }
683   MacroExpansionTracker() {}
684 
685   // Find a matching macro expansion instance.
686   MacroExpansionInstance *
687   findMacroExpansionInstance(StringHandle MacroExpanded,
688                              PPItemKey &DefinitionLocation) {
689     for (std::vector<MacroExpansionInstance>::iterator
690              I = MacroExpansionInstances.begin(),
691              E = MacroExpansionInstances.end();
692          I != E; ++I) {
693       if ((I->MacroExpanded == MacroExpanded) &&
694           (I->DefinitionLocation == DefinitionLocation)) {
695         return &*I; // Found.
696       }
697     }
698     return NULL; // Not found.
699   }
700 
701   // Add a macro expansion instance.
702   void addMacroExpansionInstance(StringHandle MacroExpanded,
703                                  PPItemKey &DefinitionLocation,
704                                  StringHandle DefinitionSourceLine,
705                                  InclusionPathHandle InclusionPathHandle) {
706     MacroExpansionInstances.push_back(
707         MacroExpansionInstance(MacroExpanded, DefinitionLocation,
708                                DefinitionSourceLine, InclusionPathHandle));
709   }
710 
711   // Return true if there is a mismatch.
712   bool hasMismatch() { return MacroExpansionInstances.size() > 1; }
713 
714   // A string representing the macro instance without expansion.
715   StringHandle MacroUnexpanded;
716   // A place to save the macro instance source line string.
717   StringHandle InstanceSourceLine;
718   // The macro expansion instances.
719   // If all instances of the macro expansion expand to the same value,
720   // This vector will only have one instance.
721   std::vector<MacroExpansionInstance> MacroExpansionInstances;
722 };
723 
724 // Conditional expansion instance.
725 //
726 // This class represents an instance of a condition exoression result
727 // with a unique value.  It also stores the unique header inclusion paths
728 // for use in telling the user the nested include path to the header.
729 class ConditionalExpansionInstance {
730 public:
731   ConditionalExpansionInstance(bool ConditionValue, InclusionPathHandle H)
732       : ConditionValue(ConditionValue) {
733     InclusionPathHandles.push_back(H);
734   }
735   ConditionalExpansionInstance() {}
736 
737   // Check for the presence of a header inclusion path handle entry.
738   // Return false if not found.
739   bool haveInclusionPathHandle(InclusionPathHandle H) {
740     for (std::vector<InclusionPathHandle>::iterator
741              I = InclusionPathHandles.begin(),
742              E = InclusionPathHandles.end();
743          I != E; ++I) {
744       if (*I == H)
745         return true;
746     }
747     return InclusionPathHandleInvalid;
748   }
749   // Add a new header inclusion path entry, if not already present.
750   void addInclusionPathHandle(InclusionPathHandle H) {
751     if (!haveInclusionPathHandle(H))
752       InclusionPathHandles.push_back(H);
753   }
754 
755   // A flag representing the evaluated condition value.
756   bool ConditionValue;
757   // The header inclusion path handles for all the instances.
758   std::vector<InclusionPathHandle> InclusionPathHandles;
759 };
760 
761 // Conditional directive instance tracker.
762 //
763 // This class represents one conditional directive, keyed by a PPItemKey.
764 // It stores a string representing the macro reference in the source,
765 // and a list of ConditionExpansionInstance objects representing
766 // the unique value the condition expression expands to in instances of
767 // the header.
768 class ConditionalTracker {
769 public:
770   ConditionalTracker(clang::tok::PPKeywordKind DirectiveKind,
771                      bool ConditionValue, StringHandle ConditionUnexpanded,
772                      InclusionPathHandle InclusionPathHandle)
773       : DirectiveKind(DirectiveKind), ConditionUnexpanded(ConditionUnexpanded) {
774     addConditionalExpansionInstance(ConditionValue, InclusionPathHandle);
775   }
776   ConditionalTracker() {}
777 
778   // Find a matching condition expansion instance.
779   ConditionalExpansionInstance *
780   findConditionalExpansionInstance(bool ConditionValue) {
781     for (std::vector<ConditionalExpansionInstance>::iterator
782              I = ConditionalExpansionInstances.begin(),
783              E = ConditionalExpansionInstances.end();
784          I != E; ++I) {
785       if (I->ConditionValue == ConditionValue) {
786         return &*I; // Found.
787       }
788     }
789     return NULL; // Not found.
790   }
791 
792   // Add a conditional expansion instance.
793   void
794   addConditionalExpansionInstance(bool ConditionValue,
795                                   InclusionPathHandle InclusionPathHandle) {
796     ConditionalExpansionInstances.push_back(
797         ConditionalExpansionInstance(ConditionValue, InclusionPathHandle));
798   }
799 
800   // Return true if there is a mismatch.
801   bool hasMismatch() { return ConditionalExpansionInstances.size() > 1; }
802 
803   // The kind of directive.
804   clang::tok::PPKeywordKind DirectiveKind;
805   // A string representing the macro instance without expansion.
806   StringHandle ConditionUnexpanded;
807   // The condition expansion instances.
808   // If all instances of the conditional expression expand to the same value,
809   // This vector will only have one instance.
810   std::vector<ConditionalExpansionInstance> ConditionalExpansionInstances;
811 };
812 
813 // Preprocessor callbacks for modularize.
814 //
815 // This class derives from the Clang PPCallbacks class to track preprocessor
816 // actions, such as changing files and handling preprocessor directives and
817 // macro expansions.  It has to figure out when a new header file is entered
818 // and left, as the provided handler is not particularly clear about it.
819 class PreprocessorCallbacks : public clang::PPCallbacks {
820 public:
821   PreprocessorCallbacks(PreprocessorTrackerImpl &ppTracker,
822                         clang::Preprocessor &PP, llvm::StringRef rootHeaderFile)
823       : PPTracker(ppTracker), PP(PP), RootHeaderFile(rootHeaderFile) {}
824   ~PreprocessorCallbacks() {}
825 
826   // Overridden handlers.
827   void InclusionDirective(clang::SourceLocation HashLoc,
828                           const clang::Token &IncludeTok,
829                           llvm::StringRef FileName, bool IsAngled,
830                           clang::CharSourceRange FilenameRange,
831                           const clang::FileEntry *File,
832                           llvm::StringRef SearchPath,
833                           llvm::StringRef RelativePath,
834                           const clang::Module *Imported);
835   void FileChanged(clang::SourceLocation Loc,
836                    clang::PPCallbacks::FileChangeReason Reason,
837                    clang::SrcMgr::CharacteristicKind FileType,
838                    clang::FileID PrevFID = clang::FileID());
839   void MacroExpands(const clang::Token &MacroNameTok,
840                     const clang::MacroDirective *MD, clang::SourceRange Range,
841                     const clang::MacroArgs *Args);
842   void Defined(const clang::Token &MacroNameTok,
843                const clang::MacroDirective *MD, clang::SourceRange Range);
844   void If(clang::SourceLocation Loc, clang::SourceRange ConditionRange,
845           bool ConditionResult);
846   void Elif(clang::SourceLocation Loc, clang::SourceRange ConditionRange,
847             bool ConditionResult, clang::SourceLocation IfLoc);
848   void Ifdef(clang::SourceLocation Loc, const clang::Token &MacroNameTok,
849              const clang::MacroDirective *MD);
850   void Ifndef(clang::SourceLocation Loc, const clang::Token &MacroNameTok,
851               const clang::MacroDirective *MD);
852 
853 private:
854   PreprocessorTrackerImpl &PPTracker;
855   clang::Preprocessor &PP;
856   std::string RootHeaderFile;
857 };
858 
859 // Preprocessor macro expansion item map types.
860 typedef std::map<PPItemKey, MacroExpansionTracker> MacroExpansionMap;
861 typedef std::map<PPItemKey, MacroExpansionTracker>::iterator
862 MacroExpansionMapIter;
863 
864 // Preprocessor conditional expansion item map types.
865 typedef std::map<PPItemKey, ConditionalTracker> ConditionalExpansionMap;
866 typedef std::map<PPItemKey, ConditionalTracker>::iterator
867 ConditionalExpansionMapIter;
868 
869 // Preprocessor tracker for modularize.
870 //
871 // This class stores information about all the headers processed in the
872 // course of running modularize.
873 class PreprocessorTrackerImpl : public PreprocessorTracker {
874 public:
875   PreprocessorTrackerImpl()
876       : CurrentInclusionPathHandle(InclusionPathHandleInvalid),
877         InNestedHeader(false) {}
878   ~PreprocessorTrackerImpl() {}
879 
880   // Handle entering a preprocessing session.
881   void handlePreprocessorEntry(clang::Preprocessor &PP,
882                                llvm::StringRef rootHeaderFile) {
883     HeadersInThisCompile.clear();
884     assert((HeaderStack.size() == 0) && "Header stack should be empty.");
885     pushHeaderHandle(addHeader(rootHeaderFile));
886     PP.addPPCallbacks(new PreprocessorCallbacks(*this, PP, rootHeaderFile));
887   }
888   // Handle exiting a preprocessing session.
889   void handlePreprocessorExit() { HeaderStack.clear(); }
890 
891   // Handle include directive.
892   // This function is called every time an include directive is seen by the
893   // preprocessor, for the purpose of later checking for 'extern "" {}' or
894   // "namespace {}" blocks containing #include directives.
895   void handleIncludeDirective(llvm::StringRef DirectivePath, int DirectiveLine,
896                               int DirectiveColumn, llvm::StringRef TargetPath) {
897     HeaderHandle CurrentHeaderHandle = findHeaderHandle(DirectivePath);
898     StringHandle IncludeHeaderHandle = addString(TargetPath);
899     for (std::vector<PPItemKey>::const_iterator I = IncludeDirectives.begin(),
900                                                 E = IncludeDirectives.end();
901          I != E; ++I) {
902       // If we already have an entry for this directive, return now.
903       if ((I->File == CurrentHeaderHandle) && (I->Line == DirectiveLine))
904         return;
905     }
906     PPItemKey IncludeDirectiveItem(IncludeHeaderHandle, CurrentHeaderHandle,
907                                    DirectiveLine, DirectiveColumn);
908     IncludeDirectives.push_back(IncludeDirectiveItem);
909   }
910 
911   // Check for include directives within the given source line range.
912   // Report errors if any found.  Returns true if no include directives
913   // found in block.
914   bool checkForIncludesInBlock(clang::Preprocessor &PP,
915                                clang::SourceRange BlockSourceRange,
916                                const char *BlockIdentifierMessage,
917                                llvm::raw_ostream &OS) {
918     clang::SourceLocation BlockStartLoc = BlockSourceRange.getBegin();
919     clang::SourceLocation BlockEndLoc = BlockSourceRange.getEnd();
920     // Use block location to get FileID of both the include directive
921     // and block statement.
922     clang::FileID FileID = PP.getSourceManager().getFileID(BlockStartLoc);
923     std::string SourcePath = getSourceLocationFile(PP, BlockStartLoc);
924     HeaderHandle SourceHandle = findHeaderHandle(SourcePath);
925     int BlockStartLine, BlockStartColumn, BlockEndLine, BlockEndColumn;
926     bool returnValue = true;
927     getSourceLocationLineAndColumn(PP, BlockStartLoc, BlockStartLine,
928                                    BlockStartColumn);
929     getSourceLocationLineAndColumn(PP, BlockEndLoc, BlockEndLine,
930                                    BlockEndColumn);
931     for (std::vector<PPItemKey>::const_iterator I = IncludeDirectives.begin(),
932                                                 E = IncludeDirectives.end();
933          I != E; ++I) {
934       // If we find an entry within the block, report an error.
935       if ((I->File == SourceHandle) && (I->Line >= BlockStartLine) &&
936           (I->Line < BlockEndLine)) {
937         returnValue = false;
938         OS << SourcePath << ":" << I->Line << ":" << I->Column << ":\n";
939         OS << getSourceLine(PP, FileID, I->Line) << "\n";
940         if (I->Column > 0)
941           OS << std::string(I->Column - 1, ' ') << "^\n";
942         OS << "error: Include directive within " << BlockIdentifierMessage
943            << ".\n";
944         OS << SourcePath << ":" << BlockStartLine << ":" << BlockStartColumn
945            << ":\n";
946         OS << getSourceLine(PP, BlockStartLoc) << "\n";
947         if (BlockStartColumn > 0)
948           OS << std::string(BlockStartColumn - 1, ' ') << "^\n";
949         OS << "The \"" << BlockIdentifierMessage << "\" block is here.\n";
950       }
951     }
952     return returnValue;
953   }
954 
955   // Handle entering a header source file.
956   void handleHeaderEntry(clang::Preprocessor &PP, llvm::StringRef HeaderPath) {
957     // Ignore <built-in> and <command-line> to reduce message clutter.
958     if (HeaderPath.startswith("<"))
959       return;
960     HeaderHandle H = addHeader(HeaderPath);
961     if (H != getCurrentHeaderHandle())
962       pushHeaderHandle(H);
963     // Check for nested header.
964     if (!InNestedHeader)
965       InNestedHeader = !HeadersInThisCompile.insert(H);
966   }
967   // Handle exiting a header source file.
968   void handleHeaderExit(llvm::StringRef HeaderPath) {
969     // Ignore <built-in> and <command-line> to reduce message clutter.
970     if (HeaderPath.startswith("<"))
971       return;
972     HeaderHandle H = findHeaderHandle(HeaderPath);
973     if (isHeaderHandleInStack(H)) {
974       while ((H != getCurrentHeaderHandle()) && (HeaderStack.size() != 0))
975         popHeaderHandle();
976     }
977     InNestedHeader = false;
978   }
979 
980   // Lookup/add string.
981   StringHandle addString(llvm::StringRef Str) { return Strings.intern(Str); }
982 
983   // Get the handle of a header file entry.
984   // Return HeaderHandleInvalid if not found.
985   HeaderHandle findHeaderHandle(llvm::StringRef HeaderPath) const {
986     std::string CanonicalPath(HeaderPath);
987     std::replace(CanonicalPath.begin(), CanonicalPath.end(), '\\', '/');
988     HeaderHandle H = 0;
989     for (std::vector<StringHandle>::const_iterator I = HeaderPaths.begin(),
990                                                    E = HeaderPaths.end();
991          I != E; ++I, ++H) {
992       if (**I == CanonicalPath)
993         return H;
994     }
995     return HeaderHandleInvalid;
996   }
997 
998   // Add a new header file entry, or return existing handle.
999   // Return the header handle.
1000   HeaderHandle addHeader(llvm::StringRef HeaderPath) {
1001     std::string CanonicalPath(HeaderPath);
1002     std::replace(CanonicalPath.begin(), CanonicalPath.end(), '\\', '/');
1003     HeaderHandle H = findHeaderHandle(CanonicalPath);
1004     if (H == HeaderHandleInvalid) {
1005       H = HeaderPaths.size();
1006       HeaderPaths.push_back(addString(CanonicalPath));
1007     }
1008     return H;
1009   }
1010 
1011   // Return a header file path string given its handle.
1012   StringHandle getHeaderFilePath(HeaderHandle H) const {
1013     if ((H >= 0) && (H < (HeaderHandle)HeaderPaths.size()))
1014       return HeaderPaths[H];
1015     return StringHandle();
1016   }
1017 
1018   // Returns a handle to the inclusion path.
1019   InclusionPathHandle pushHeaderHandle(HeaderHandle H) {
1020     HeaderStack.push_back(H);
1021     return CurrentInclusionPathHandle = addInclusionPathHandle(HeaderStack);
1022   }
1023   // Pops the last header handle from the stack;
1024   void popHeaderHandle() {
1025     // assert((HeaderStack.size() != 0) && "Header stack already empty.");
1026     if (HeaderStack.size() != 0) {
1027       HeaderStack.pop_back();
1028       CurrentInclusionPathHandle = addInclusionPathHandle(HeaderStack);
1029     }
1030   }
1031   // Get the top handle on the header stack.
1032   HeaderHandle getCurrentHeaderHandle() const {
1033     if (HeaderStack.size() != 0)
1034       return HeaderStack.back();
1035     return HeaderHandleInvalid;
1036   }
1037 
1038   // Check for presence of header handle in the header stack.
1039   bool isHeaderHandleInStack(HeaderHandle H) const {
1040     for (std::vector<HeaderHandle>::const_iterator I = HeaderStack.begin(),
1041                                                    E = HeaderStack.end();
1042          I != E; ++I) {
1043       if (*I == H)
1044         return true;
1045     }
1046     return false;
1047   }
1048 
1049   // Get the handle of a header inclusion path entry.
1050   // Return InclusionPathHandleInvalid if not found.
1051   InclusionPathHandle
1052   findInclusionPathHandle(const std::vector<HeaderHandle> &Path) const {
1053     InclusionPathHandle H = 0;
1054     for (std::vector<HeaderInclusionPath>::const_iterator
1055              I = InclusionPaths.begin(),
1056              E = InclusionPaths.end();
1057          I != E; ++I, ++H) {
1058       if (I->Path == Path)
1059         return H;
1060     }
1061     return HeaderHandleInvalid;
1062   }
1063   // Add a new header inclusion path entry, or return existing handle.
1064   // Return the header inclusion path entry handle.
1065   InclusionPathHandle
1066   addInclusionPathHandle(const std::vector<HeaderHandle> &Path) {
1067     InclusionPathHandle H = findInclusionPathHandle(Path);
1068     if (H == HeaderHandleInvalid) {
1069       H = InclusionPaths.size();
1070       InclusionPaths.push_back(HeaderInclusionPath(Path));
1071     }
1072     return H;
1073   }
1074   // Return the current inclusion path handle.
1075   InclusionPathHandle getCurrentInclusionPathHandle() const {
1076     return CurrentInclusionPathHandle;
1077   }
1078 
1079   // Return an inclusion path given its handle.
1080   const std::vector<HeaderHandle> &
1081   getInclusionPath(InclusionPathHandle H) const {
1082     if ((H >= 0) && (H <= (InclusionPathHandle)InclusionPaths.size()))
1083       return InclusionPaths[H].Path;
1084     static std::vector<HeaderHandle> Empty;
1085     return Empty;
1086   }
1087 
1088   // Add a macro expansion instance.
1089   void addMacroExpansionInstance(clang::Preprocessor &PP, HeaderHandle H,
1090                                  clang::SourceLocation InstanceLoc,
1091                                  clang::SourceLocation DefinitionLoc,
1092                                  clang::IdentifierInfo *II,
1093                                  llvm::StringRef MacroUnexpanded,
1094                                  llvm::StringRef MacroExpanded,
1095                                  InclusionPathHandle InclusionPathHandle) {
1096     if (InNestedHeader)
1097       return;
1098     StringHandle MacroName = addString(II->getName());
1099     PPItemKey InstanceKey(PP, MacroName, H, InstanceLoc);
1100     PPItemKey DefinitionKey(PP, MacroName, H, DefinitionLoc);
1101     MacroExpansionMapIter I = MacroExpansions.find(InstanceKey);
1102     // If existing instance of expansion not found, add one.
1103     if (I == MacroExpansions.end()) {
1104       std::string InstanceSourceLine =
1105           getSourceLocationString(PP, InstanceLoc) + ":\n" +
1106           getSourceLine(PP, InstanceLoc) + "\n";
1107       std::string DefinitionSourceLine =
1108           getSourceLocationString(PP, DefinitionLoc) + ":\n" +
1109           getSourceLine(PP, DefinitionLoc) + "\n";
1110       MacroExpansions[InstanceKey] = MacroExpansionTracker(
1111           addString(MacroUnexpanded), addString(MacroExpanded),
1112           addString(InstanceSourceLine), DefinitionKey,
1113           addString(DefinitionSourceLine), InclusionPathHandle);
1114     } else {
1115       // We've seen the macro before.  Get its tracker.
1116       MacroExpansionTracker &CondTracker = I->second;
1117       // Look up an existing instance value for the macro.
1118       MacroExpansionInstance *MacroInfo =
1119           CondTracker.findMacroExpansionInstance(addString(MacroExpanded),
1120                                                  DefinitionKey);
1121       // If found, just add the inclusion path to the instance.
1122       if (MacroInfo != NULL)
1123         MacroInfo->addInclusionPathHandle(InclusionPathHandle);
1124       else {
1125         // Otherwise add a new instance with the unique value.
1126         std::string DefinitionSourceLine =
1127             getSourceLocationString(PP, DefinitionLoc) + ":\n" +
1128             getSourceLine(PP, DefinitionLoc) + "\n";
1129         CondTracker.addMacroExpansionInstance(
1130             addString(MacroExpanded), DefinitionKey,
1131             addString(DefinitionSourceLine), InclusionPathHandle);
1132       }
1133     }
1134   }
1135 
1136   // Add a conditional expansion instance.
1137   void
1138   addConditionalExpansionInstance(clang::Preprocessor &PP, HeaderHandle H,
1139                                   clang::SourceLocation InstanceLoc,
1140                                   clang::tok::PPKeywordKind DirectiveKind,
1141                                   bool ConditionValue,
1142                                   llvm::StringRef ConditionUnexpanded,
1143                                   InclusionPathHandle InclusionPathHandle) {
1144     // Ignore header guards, assuming the header guard is the only conditional.
1145     if (InNestedHeader)
1146       return;
1147     StringHandle ConditionUnexpandedHandle(addString(ConditionUnexpanded));
1148     PPItemKey InstanceKey(PP, ConditionUnexpandedHandle, H, InstanceLoc);
1149     ConditionalExpansionMapIter I = ConditionalExpansions.find(InstanceKey);
1150     // If existing instance of condition not found, add one.
1151     if (I == ConditionalExpansions.end()) {
1152       std::string InstanceSourceLine =
1153           getSourceLocationString(PP, InstanceLoc) + ":\n" +
1154           getSourceLine(PP, InstanceLoc) + "\n";
1155       ConditionalExpansions[InstanceKey] =
1156           ConditionalTracker(DirectiveKind, ConditionValue,
1157                              ConditionUnexpandedHandle, InclusionPathHandle);
1158     } else {
1159       // We've seen the conditional before.  Get its tracker.
1160       ConditionalTracker &CondTracker = I->second;
1161       // Look up an existing instance value for the condition.
1162       ConditionalExpansionInstance *MacroInfo =
1163           CondTracker.findConditionalExpansionInstance(ConditionValue);
1164       // If found, just add the inclusion path to the instance.
1165       if (MacroInfo != NULL)
1166         MacroInfo->addInclusionPathHandle(InclusionPathHandle);
1167       else {
1168         // Otherwise add a new instance with the unique value.
1169         CondTracker.addConditionalExpansionInstance(ConditionValue,
1170                                                     InclusionPathHandle);
1171       }
1172     }
1173   }
1174 
1175   // Report on inconsistent macro instances.
1176   // Returns true if any mismatches.
1177   bool reportInconsistentMacros(llvm::raw_ostream &OS) {
1178     bool ReturnValue = false;
1179     // Walk all the macro expansion trackers in the map.
1180     for (MacroExpansionMapIter I = MacroExpansions.begin(),
1181                                E = MacroExpansions.end();
1182          I != E; ++I) {
1183       const PPItemKey &ItemKey = I->first;
1184       MacroExpansionTracker &MacroExpTracker = I->second;
1185       // If no mismatch (only one instance value) continue.
1186       if (!MacroExpTracker.hasMismatch())
1187         continue;
1188       // Tell caller we found one or more errors.
1189       ReturnValue = true;
1190       // Start the error message.
1191       OS << *MacroExpTracker.InstanceSourceLine;
1192       if (ItemKey.Column > 0)
1193         OS << std::string(ItemKey.Column - 1, ' ') << "^\n";
1194       OS << "error: Macro instance '" << *MacroExpTracker.MacroUnexpanded
1195          << "' has different values in this header, depending on how it was "
1196             "included.\n";
1197       // Walk all the instances.
1198       for (std::vector<MacroExpansionInstance>::iterator
1199                IMT = MacroExpTracker.MacroExpansionInstances.begin(),
1200                EMT = MacroExpTracker.MacroExpansionInstances.end();
1201            IMT != EMT; ++IMT) {
1202         MacroExpansionInstance &MacroInfo = *IMT;
1203         OS << "  '" << *MacroExpTracker.MacroUnexpanded << "' expanded to: '"
1204            << *MacroInfo.MacroExpanded
1205            << "' with respect to these inclusion paths:\n";
1206         // Walk all the inclusion path hierarchies.
1207         for (std::vector<InclusionPathHandle>::iterator
1208                  IIP = MacroInfo.InclusionPathHandles.begin(),
1209                  EIP = MacroInfo.InclusionPathHandles.end();
1210              IIP != EIP; ++IIP) {
1211           const std::vector<HeaderHandle> &ip = getInclusionPath(*IIP);
1212           int Count = (int)ip.size();
1213           for (int Index = 0; Index < Count; ++Index) {
1214             HeaderHandle H = ip[Index];
1215             OS << std::string((Index * 2) + 4, ' ') << *getHeaderFilePath(H)
1216                << "\n";
1217           }
1218         }
1219         // For a macro that wasn't defined, we flag it by using the
1220         // instance location.
1221         // If there is a definition...
1222         if (MacroInfo.DefinitionLocation.Line != ItemKey.Line) {
1223           OS << *MacroInfo.DefinitionSourceLine;
1224           if (MacroInfo.DefinitionLocation.Column > 0)
1225             OS << std::string(MacroInfo.DefinitionLocation.Column - 1, ' ')
1226                << "^\n";
1227           OS << "Macro defined here.\n";
1228         } else
1229           OS << "(no macro definition)"
1230              << "\n";
1231       }
1232     }
1233     return ReturnValue;
1234   }
1235 
1236   // Report on inconsistent conditional instances.
1237   // Returns true if any mismatches.
1238   bool reportInconsistentConditionals(llvm::raw_ostream &OS) {
1239     bool ReturnValue = false;
1240     // Walk all the conditional trackers in the map.
1241     for (ConditionalExpansionMapIter I = ConditionalExpansions.begin(),
1242                                      E = ConditionalExpansions.end();
1243          I != E; ++I) {
1244       const PPItemKey &ItemKey = I->first;
1245       ConditionalTracker &CondTracker = I->second;
1246       if (!CondTracker.hasMismatch())
1247         continue;
1248       // Tell caller we found one or more errors.
1249       ReturnValue = true;
1250       // Start the error message.
1251       OS << *HeaderPaths[ItemKey.File] << ":" << ItemKey.Line << ":"
1252          << ItemKey.Column << "\n";
1253       OS << "#" << getDirectiveSpelling(CondTracker.DirectiveKind) << " "
1254          << *CondTracker.ConditionUnexpanded << "\n";
1255       OS << "^\n";
1256       OS << "error: Conditional expression instance '"
1257          << *CondTracker.ConditionUnexpanded
1258          << "' has different values in this header, depending on how it was "
1259             "included.\n";
1260       // Walk all the instances.
1261       for (std::vector<ConditionalExpansionInstance>::iterator
1262                IMT = CondTracker.ConditionalExpansionInstances.begin(),
1263                EMT = CondTracker.ConditionalExpansionInstances.end();
1264            IMT != EMT; ++IMT) {
1265         ConditionalExpansionInstance &MacroInfo = *IMT;
1266         OS << "  '" << *CondTracker.ConditionUnexpanded << "' expanded to: '"
1267            << (MacroInfo.ConditionValue ? "true" : "false")
1268            << "' with respect to these inclusion paths:\n";
1269         // Walk all the inclusion path hierarchies.
1270         for (std::vector<InclusionPathHandle>::iterator
1271                  IIP = MacroInfo.InclusionPathHandles.begin(),
1272                  EIP = MacroInfo.InclusionPathHandles.end();
1273              IIP != EIP; ++IIP) {
1274           const std::vector<HeaderHandle> &ip = getInclusionPath(*IIP);
1275           int Count = (int)ip.size();
1276           for (int Index = 0; Index < Count; ++Index) {
1277             HeaderHandle H = ip[Index];
1278             OS << std::string((Index * 2) + 4, ' ') << *getHeaderFilePath(H)
1279                << "\n";
1280           }
1281         }
1282       }
1283     }
1284     return ReturnValue;
1285   }
1286 
1287   // Get directive spelling.
1288   static const char *getDirectiveSpelling(clang::tok::PPKeywordKind kind) {
1289     switch (kind) {
1290     case clang::tok::pp_if:
1291       return "if";
1292     case clang::tok::pp_elif:
1293       return "elif";
1294     case clang::tok::pp_ifdef:
1295       return "ifdef";
1296     case clang::tok::pp_ifndef:
1297       return "ifndef";
1298     default:
1299       return "(unknown)";
1300     }
1301   }
1302 
1303 private:
1304   llvm::StringPool Strings;
1305   std::vector<StringHandle> HeaderPaths;
1306   std::vector<HeaderHandle> HeaderStack;
1307   std::vector<HeaderInclusionPath> InclusionPaths;
1308   InclusionPathHandle CurrentInclusionPathHandle;
1309   llvm::SmallSet<HeaderHandle, 128> HeadersInThisCompile;
1310   std::vector<PPItemKey> IncludeDirectives;
1311   MacroExpansionMap MacroExpansions;
1312   ConditionalExpansionMap ConditionalExpansions;
1313   bool InNestedHeader;
1314 };
1315 
1316 // PreprocessorTracker functions.
1317 
1318 // PreprocessorTracker desctructor.
1319 PreprocessorTracker::~PreprocessorTracker() {}
1320 
1321 // Create instance of PreprocessorTracker.
1322 PreprocessorTracker *PreprocessorTracker::create() {
1323   return new PreprocessorTrackerImpl();
1324 }
1325 
1326 // Preprocessor callbacks for modularize.
1327 
1328 // Handle include directive.
1329 void PreprocessorCallbacks::InclusionDirective(
1330     clang::SourceLocation HashLoc, const clang::Token &IncludeTok,
1331     llvm::StringRef FileName, bool IsAngled,
1332     clang::CharSourceRange FilenameRange, const clang::FileEntry *File,
1333     llvm::StringRef SearchPath, llvm::StringRef RelativePath,
1334     const clang::Module *Imported) {
1335   int DirectiveLine, DirectiveColumn;
1336   std::string HeaderPath = getSourceLocationFile(PP, HashLoc);
1337   getSourceLocationLineAndColumn(PP, HashLoc, DirectiveLine, DirectiveColumn);
1338   PPTracker.handleIncludeDirective(HeaderPath, DirectiveLine, DirectiveColumn,
1339                                    FileName);
1340 }
1341 
1342 // Handle file entry/exit.
1343 void PreprocessorCallbacks::FileChanged(
1344     clang::SourceLocation Loc, clang::PPCallbacks::FileChangeReason Reason,
1345     clang::SrcMgr::CharacteristicKind FileType, clang::FileID PrevFID) {
1346   switch (Reason) {
1347   case EnterFile:
1348     PPTracker.handleHeaderEntry(PP, getSourceLocationFile(PP, Loc));
1349     break;
1350   case ExitFile: {
1351     const clang::FileEntry *F =
1352         PP.getSourceManager().getFileEntryForID(PrevFID);
1353     if (F != NULL)
1354       PPTracker.handleHeaderExit(F->getName());
1355   } break;
1356   case SystemHeaderPragma:
1357   case RenameFile:
1358     break;
1359   }
1360 }
1361 
1362 // Handle macro expansion.
1363 void PreprocessorCallbacks::MacroExpands(const clang::Token &MacroNameTok,
1364                                          const clang::MacroDirective *MD,
1365                                          clang::SourceRange Range,
1366                                          const clang::MacroArgs *Args) {
1367   clang::SourceLocation Loc = Range.getBegin();
1368   // Ignore macro argument expansions.
1369   if (!Loc.isFileID())
1370     return;
1371   clang::IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1372   const clang::MacroInfo *MI = PP.getMacroInfo(II);
1373   std::string MacroName = II->getName().str();
1374   std::string Unexpanded(getMacroUnexpandedString(Range, PP, MacroName, MI));
1375   std::string Expanded(getMacroExpandedString(PP, MacroName, MI, Args));
1376   PPTracker.addMacroExpansionInstance(
1377       PP, PPTracker.getCurrentHeaderHandle(), Loc, MI->getDefinitionLoc(), II,
1378       Unexpanded, Expanded, PPTracker.getCurrentInclusionPathHandle());
1379 }
1380 
1381 void PreprocessorCallbacks::Defined(const clang::Token &MacroNameTok,
1382                                     const clang::MacroDirective *MD,
1383                                     clang::SourceRange Range) {
1384   clang::SourceLocation Loc(Range.getBegin());
1385   clang::IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1386   const clang::MacroInfo *MI = PP.getMacroInfo(II);
1387   std::string MacroName = II->getName().str();
1388   std::string Unexpanded(getSourceString(PP, Range));
1389   PPTracker.addMacroExpansionInstance(
1390       PP, PPTracker.getCurrentHeaderHandle(), Loc,
1391       (MI ? MI->getDefinitionLoc() : Loc), II, Unexpanded,
1392       (MI ? "true" : "false"), PPTracker.getCurrentInclusionPathHandle());
1393 }
1394 
1395 void PreprocessorCallbacks::If(clang::SourceLocation Loc,
1396                                clang::SourceRange ConditionRange,
1397                                bool ConditionResult) {
1398   std::string Unexpanded(getSourceString(PP, ConditionRange));
1399   PPTracker.addConditionalExpansionInstance(
1400       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_if,
1401       ConditionResult, Unexpanded, PPTracker.getCurrentInclusionPathHandle());
1402 }
1403 
1404 void PreprocessorCallbacks::Elif(clang::SourceLocation Loc,
1405                                  clang::SourceRange ConditionRange,
1406                                  bool ConditionResult,
1407                                  clang::SourceLocation IfLoc) {
1408   std::string Unexpanded(getSourceString(PP, ConditionRange));
1409   PPTracker.addConditionalExpansionInstance(
1410       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_elif,
1411       ConditionResult, Unexpanded, PPTracker.getCurrentInclusionPathHandle());
1412 }
1413 
1414 void PreprocessorCallbacks::Ifdef(clang::SourceLocation Loc,
1415                                   const clang::Token &MacroNameTok,
1416                                   const clang::MacroDirective *MD) {
1417   bool IsDefined = (MD != 0);
1418   PPTracker.addConditionalExpansionInstance(
1419       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifdef,
1420       IsDefined, PP.getSpelling(MacroNameTok),
1421       PPTracker.getCurrentInclusionPathHandle());
1422 }
1423 
1424 void PreprocessorCallbacks::Ifndef(clang::SourceLocation Loc,
1425                                    const clang::Token &MacroNameTok,
1426                                    const clang::MacroDirective *MD) {
1427   bool IsNotDefined = (MD == 0);
1428   PPTracker.addConditionalExpansionInstance(
1429       PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifndef,
1430       IsNotDefined, PP.getSpelling(MacroNameTok),
1431       PPTracker.getCurrentInclusionPathHandle());
1432 }
1433 } // end namespace Modularize
1434