1 //===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InterpolatingCompilationDatabase wraps another CompilationDatabase and
11 // attempts to heuristically determine appropriate compile commands for files
12 // that are not included, such as headers or newly created files.
14 // Motivating cases include:
15 // Header files that live next to their implementation files. These typically
16 // share a base filename. (libclang/CXString.h, libclang/CXString.cpp).
17 // Some projects separate headers from includes. Filenames still typically
18 // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc).
19 // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes
20 // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp).
21 // Even if we can't find a "right" compile command, even a random one from
22 // the project will tend to get important flags like -I and -x right.
24 // We "borrow" the compile command for the closest available file:
25 // - points are awarded if the filename matches (ignoring extension)
26 // - points are awarded if the directory structure matches
27 // - ties are broken by length of path prefix match
29 // The compile command is adjusted, replacing the filename and removing output
30 // file arguments. The -x and -std flags may be affected too.
32 // Source language is a tricky issue: is it OK to use a .c file's command
33 // for building a .cc file? What language is a .h file in?
34 // - We only consider compile commands for c-family languages as candidates.
35 // - For files whose language is implied by the filename (e.g. .m, .hpp)
36 // we prefer candidates from the same language.
37 // If we must cross languages, we drop any -x and -std flags.
38 // - For .h files, candidates from any c-family language are acceptable.
39 // We use the candidate's language, inserting e.g. -x c++-header.
41 // This class is only useful when wrapping databases that can enumerate all
42 // their compile commands. If getAllFilenames() is empty, no inference occurs.
44 //===----------------------------------------------------------------------===//
46 #include "clang/Driver/Options.h"
47 #include "clang/Driver/Types.h"
48 #include "clang/Frontend/LangStandard.h"
49 #include "clang/Tooling/CompilationDatabase.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/StringExtras.h"
53 #include "llvm/ADT/StringSwitch.h"
54 #include "llvm/Option/ArgList.h"
55 #include "llvm/Option/OptTable.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/Path.h"
58 #include "llvm/Support/StringSaver.h"
59 #include "llvm/Support/raw_ostream.h"
66 namespace types = clang::driver::types;
67 namespace path = llvm::sys::path;
69 // The length of the prefix these two strings have in common.
70 size_t matchingPrefix(StringRef L, StringRef R) {
71 size_t Limit = std::min(L.size(), R.size());
72 for (size_t I = 0; I < Limit; ++I)
78 // A comparator for searching SubstringWithIndexes with std::equal_range etc.
79 // Optionaly prefix semantics: compares equal if the key is a prefix.
80 template <bool Prefix> struct Less {
81 bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const {
82 StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
85 bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const {
86 StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first;
91 // Infer type from filename. If we might have gotten it wrong, set *Certain.
92 // *.h will be inferred as a C header, but not certain.
93 types::ID guessType(StringRef Filename, bool *Certain = nullptr) {
94 // path::extension is ".cpp", lookupTypeForExtension wants "cpp".
96 types::lookupTypeForExtension(path::extension(Filename).substr(1));
98 *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID;
102 // Return Lang as one of the canonical supported types.
103 // e.g. c-header --> c; fortran --> TY_INVALID
104 static types::ID foldType(types::ID Lang) {
107 case types::TY_CHeader:
110 case types::TY_ObjCHeader:
111 return types::TY_ObjC;
113 case types::TY_CXXHeader:
114 return types::TY_CXX;
115 case types::TY_ObjCXX:
116 case types::TY_ObjCXXHeader:
117 return types::TY_ObjCXX;
119 return types::TY_INVALID;
123 // A CompileCommand that can be applied to another file.
124 struct TransferableCommand {
125 // Flags that should not apply to all files are stripped from CommandLine.
127 // Language detected from -x or the filename. Never TY_INVALID.
128 Optional<types::ID> Type;
129 // Standard specified by -std.
130 LangStandard::Kind Std = LangStandard::lang_unspecified;
131 // Whether the command line is for the cl-compatible driver.
134 TransferableCommand(CompileCommand C)
135 : Cmd(std::move(C)), Type(guessType(Cmd.Filename)),
136 ClangCLMode(checkIsCLMode(Cmd.CommandLine)) {
137 std::vector<std::string> OldArgs = std::move(Cmd.CommandLine);
138 Cmd.CommandLine.clear();
140 // Wrap the old arguments in an InputArgList.
141 llvm::opt::InputArgList ArgList;
143 SmallVector<const char *, 16> TmpArgv;
144 for (const std::string &S : OldArgs)
145 TmpArgv.push_back(S.c_str());
146 ArgList = {TmpArgv.begin(), TmpArgv.end()};
149 // Parse the old args in order to strip out and record unwanted flags.
150 // We parse each argument individually so that we can retain the exact
151 // spelling of each argument; re-rendering is lossy for aliased flags.
152 // E.g. in CL mode, /W4 maps to -Wall.
153 auto OptTable = clang::driver::createDriverOptTable();
154 Cmd.CommandLine.emplace_back(OldArgs.front());
155 for (unsigned Pos = 1; Pos < OldArgs.size();) {
156 using namespace driver::options;
158 const unsigned OldPos = Pos;
159 std::unique_ptr<llvm::opt::Arg> Arg(OptTable->ParseOneArg(
161 /* Include */ClangCLMode ? CoreOption | CLOption : 0,
162 /* Exclude */ClangCLMode ? 0 : CLOption));
167 const llvm::opt::Option &Opt = Arg->getOption();
169 // Strip input and output files.
170 if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) ||
171 (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) ||
172 Opt.matches(OPT__SLASH_Fe) ||
173 Opt.matches(OPT__SLASH_Fi) ||
174 Opt.matches(OPT__SLASH_Fo))))
177 // Strip -x, but record the overridden language.
178 if (const auto GivenType = tryParseTypeArg(*Arg)) {
183 // Strip -std, but record the value.
184 if (const auto GivenStd = tryParseStdArg(*Arg)) {
185 if (*GivenStd != LangStandard::lang_unspecified)
190 Cmd.CommandLine.insert(Cmd.CommandLine.end(),
191 OldArgs.data() + OldPos, OldArgs.data() + Pos);
194 if (Std != LangStandard::lang_unspecified) // -std take precedence over -x
195 Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage());
196 Type = foldType(*Type);
197 // The contract is to store None instead of TY_INVALID.
198 if (Type == types::TY_INVALID)
202 // Produce a CompileCommand for \p filename, based on this one.
203 CompileCommand transferTo(StringRef Filename) const {
204 CompileCommand Result = Cmd;
205 Result.Filename = Filename;
207 auto TargetType = guessType(Filename, &TypeCertain);
208 // If the filename doesn't determine the language (.h), transfer with -x.
209 if (TargetType != types::TY_INVALID && !TypeCertain && Type) {
210 TargetType = types::onlyPrecompileType(TargetType) // header?
211 ? types::lookupHeaderTypeForSourceType(*Type)
214 const StringRef Flag = toCLFlag(TargetType);
216 Result.CommandLine.push_back(Flag);
218 Result.CommandLine.push_back("-x");
219 Result.CommandLine.push_back(types::getTypeName(TargetType));
222 // --std flag may only be transferred if the language is the same.
223 // We may consider "translating" these, e.g. c++11 -> c11.
224 if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) {
225 Result.CommandLine.emplace_back((
226 llvm::Twine(ClangCLMode ? "/std:" : "-std=") +
227 LangStandard::getLangStandardForKind(Std).getName()).str());
229 Result.CommandLine.push_back(Filename);
234 // Determine whether the given command line is intended for the CL driver.
235 static bool checkIsCLMode(ArrayRef<std::string> CmdLine) {
236 // First look for --driver-mode.
237 for (StringRef S : llvm::reverse(CmdLine)) {
238 if (S.consume_front("--driver-mode="))
242 // Otherwise just check the clang executable file name.
243 return llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl");
246 // Map the language from the --std flag to that of the -x flag.
247 static types::ID toType(InputKind::Language Lang) {
252 return types::TY_CXX;
253 case InputKind::ObjC:
254 return types::TY_ObjC;
255 case InputKind::ObjCXX:
256 return types::TY_ObjCXX;
258 return types::TY_INVALID;
262 // Convert a file type to the matching CL-style type flag.
263 static StringRef toCLFlag(types::ID Type) {
266 case types::TY_CHeader:
269 case types::TY_CXXHeader:
276 // Try to interpret the argument as a type specifier, e.g. '-x'.
277 Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) {
278 const llvm::opt::Option &Opt = Arg.getOption();
279 using namespace driver::options;
281 if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc))
283 if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp))
284 return types::TY_CXX;
286 if (Opt.matches(driver::options::OPT_x))
287 return types::lookupTypeForTypeSpecifier(Arg.getValue());
292 // Try to interpret the argument as '-std='.
293 Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) {
294 using namespace driver::options;
295 if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) {
296 return llvm::StringSwitch<LangStandard::Kind>(Arg.getValue())
297 #define LANGSTANDARD(id, name, lang, ...) .Case(name, LangStandard::lang_##id)
298 #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id)
299 #include "clang/Frontend/LangStandards.def"
300 #undef LANGSTANDARD_ALIAS
302 .Default(LangStandard::lang_unspecified);
308 // Given a filename, FileIndex picks the best matching file from the underlying
309 // DB. This is the proxy file whose CompileCommand will be reused. The
310 // heuristics incorporate file name, extension, and directory structure.
312 // - Build indexes of each of the substrings we want to look up by.
313 // These indexes are just sorted lists of the substrings.
314 // - Each criterion corresponds to a range lookup into the index, so we only
315 // need O(log N) string comparisons to determine scores.
317 // Apart from path proximity signals, also takes file extensions into account
318 // when scoring the candidates.
321 FileIndex(std::vector<std::string> Files)
322 : OriginalPaths(std::move(Files)), Strings(Arena) {
323 // Sort commands by filename for determinism (index is a tiebreaker later).
324 llvm::sort(OriginalPaths);
325 Paths.reserve(OriginalPaths.size());
326 Types.reserve(OriginalPaths.size());
327 Stems.reserve(OriginalPaths.size());
328 for (size_t I = 0; I < OriginalPaths.size(); ++I) {
329 StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower());
331 Paths.emplace_back(Path, I);
332 Types.push_back(foldType(guessType(Path)));
333 Stems.emplace_back(sys::path::stem(Path), I);
334 auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path);
335 for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir)
336 if (Dir->size() > ShortDirectorySegment) // not trivial ones
337 Components.emplace_back(*Dir, I);
341 llvm::sort(Components);
344 bool empty() const { return Paths.empty(); }
346 // Returns the path for the file that best fits OriginalFilename.
347 // Candidates with extensions matching PreferLanguage will be chosen over
348 // others (unless it's TY_INVALID, or all candidates are bad).
349 StringRef chooseProxy(StringRef OriginalFilename,
350 types::ID PreferLanguage) const {
351 assert(!empty() && "need at least one candidate!");
352 std::string Filename = OriginalFilename.lower();
353 auto Candidates = scoreCandidates(Filename);
354 std::pair<size_t, int> Best =
355 pickWinner(Candidates, Filename, PreferLanguage);
359 llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first]
360 << " as proxy for " << OriginalFilename << " preferring "
361 << (PreferLanguage == types::TY_INVALID
363 : types::getTypeName(PreferLanguage))
364 << " score=" << Best.second << "\n");
365 return OriginalPaths[Best.first];
369 using SubstringAndIndex = std::pair<StringRef, size_t>;
370 // Directory matching parameters: we look at the last two segments of the
371 // parent directory (usually the semantically significant ones in practice).
372 // We search only the last four of each candidate (for efficiency).
373 constexpr static int DirectorySegmentsIndexed = 4;
374 constexpr static int DirectorySegmentsQueried = 2;
375 constexpr static int ShortDirectorySegment = 1; // Only look at longer names.
377 // Award points to candidate entries that should be considered for the file.
378 // Returned keys are indexes into paths, and the values are (nonzero) scores.
379 DenseMap<size_t, int> scoreCandidates(StringRef Filename) const {
380 // Decompose Filename into the parts we care about.
381 // /some/path/complicated/project/Interesting.h
382 // [-prefix--][---dir---] [-dir-] [--stem---]
383 StringRef Stem = sys::path::stem(Filename);
384 llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs;
385 llvm::StringRef Prefix;
386 auto Dir = ++sys::path::rbegin(Filename),
387 DirEnd = sys::path::rend(Filename);
388 for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) {
389 if (Dir->size() > ShortDirectorySegment)
390 Dirs.push_back(*Dir);
391 Prefix = Filename.substr(0, Dir - DirEnd);
394 // Now award points based on lookups into our various indexes.
395 DenseMap<size_t, int> Candidates; // Index -> score.
396 auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) {
397 for (const auto &Entry : Range)
398 Candidates[Entry.second] += Points;
400 // Award one point if the file's basename is a prefix of the candidate,
401 // and another if it's an exact match (so exact matches get two points).
402 Award(1, indexLookup</*Prefix=*/true>(Stem, Stems));
403 Award(1, indexLookup</*Prefix=*/false>(Stem, Stems));
404 // For each of the last few directories in the Filename, award a point
405 // if it's present in the candidate.
406 for (StringRef Dir : Dirs)
407 Award(1, indexLookup</*Prefix=*/false>(Dir, Components));
408 // Award one more point if the whole rest of the path matches.
409 if (sys::path::root_directory(Prefix) != Prefix)
410 Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths));
414 // Pick a single winner from the set of scored candidates.
415 // Returns (index, score).
416 std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates,
418 types::ID PreferredLanguage) const {
419 struct ScoredCandidate {
425 // Choose the best candidate by (preferred, points, prefix length, alpha).
426 ScoredCandidate Best = {size_t(-1), false, 0, 0};
427 for (const auto &Candidate : Candidates) {
429 S.Index = Candidate.first;
430 S.Preferred = PreferredLanguage == types::TY_INVALID ||
431 PreferredLanguage == Types[S.Index];
432 S.Points = Candidate.second;
433 if (!S.Preferred && Best.Preferred)
435 if (S.Preferred == Best.Preferred) {
436 if (S.Points < Best.Points)
438 if (S.Points == Best.Points) {
439 S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
440 if (S.PrefixLength < Best.PrefixLength)
442 // hidden heuristics should at least be deterministic!
443 if (S.PrefixLength == Best.PrefixLength)
444 if (S.Index > Best.Index)
448 // PrefixLength was only set above if actually needed for a tiebreak.
449 // But it definitely needs to be set to break ties in the future.
450 S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first);
453 // Edge case: no candidate got any points.
454 // We ignore PreferredLanguage at this point (not ideal).
455 if (Best.Index == size_t(-1))
456 return {longestMatch(Filename, Paths).second, 0};
457 return {Best.Index, Best.Points};
460 // Returns the range within a sorted index that compares equal to Key.
461 // If Prefix is true, it's instead the range starting with Key.
462 template <bool Prefix>
463 ArrayRef<SubstringAndIndex>
464 indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const {
465 // Use pointers as iteratiors to ease conversion of result to ArrayRef.
466 auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key,
468 return {Range.first, Range.second};
471 // Performs a point lookup into a nonempty index, returning a longest match.
472 SubstringAndIndex longestMatch(StringRef Key,
473 ArrayRef<SubstringAndIndex> Idx) const {
474 assert(!Idx.empty());
475 // Longest substring match will be adjacent to a direct lookup.
477 std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0});
478 if (It == Idx.begin())
482 // Have to choose between It and It-1
483 size_t Prefix = matchingPrefix(Key, It->first);
484 size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first);
485 return Prefix > PrevPrefix ? *It : *--It;
488 // Original paths, everything else is in lowercase.
489 std::vector<std::string> OriginalPaths;
490 BumpPtrAllocator Arena;
492 // Indexes of candidates by certain substrings.
493 // String is lowercase and sorted, index points into OriginalPaths.
494 std::vector<SubstringAndIndex> Paths; // Full path.
495 // Lang types obtained by guessing on the corresponding path. I-th element is
496 // a type for the I-th path.
497 std::vector<types::ID> Types;
498 std::vector<SubstringAndIndex> Stems; // Basename, without extension.
499 std::vector<SubstringAndIndex> Components; // Last path components.
502 // The actual CompilationDatabase wrapper delegates to its inner database.
503 // If no match, looks up a proxy file in FileIndex and transfers its
504 // command to the requested file.
505 class InterpolatingCompilationDatabase : public CompilationDatabase {
507 InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner)
508 : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {}
510 std::vector<CompileCommand>
511 getCompileCommands(StringRef Filename) const override {
512 auto Known = Inner->getCompileCommands(Filename);
513 if (Index.empty() || !Known.empty())
516 auto Lang = guessType(Filename, &TypeCertain);
518 Lang = types::TY_INVALID;
520 Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang)));
521 if (ProxyCommands.empty())
523 return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)};
526 std::vector<std::string> getAllFiles() const override {
527 return Inner->getAllFiles();
530 std::vector<CompileCommand> getAllCompileCommands() const override {
531 return Inner->getAllCompileCommands();
535 std::unique_ptr<CompilationDatabase> Inner;
541 std::unique_ptr<CompilationDatabase>
542 inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) {
543 return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner));
546 } // namespace tooling