Skip to content

Commit e7095cb

Browse files
authored
Merge pull request #10726 from bitjammer/upstream-index-while-building-swift-4.0-branch
[index/build] Upstream indexing while building changes
2 parents 73128fc + 12b2c4f commit e7095cb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1634
-4
lines changed

include/swift/AST/DiagnosticsFrontend.def

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,17 @@ ERROR(verify_encountered_fatal,none,
167167
ERROR(error_parse_input_file,none,
168168
"error parsing input file '%0' (%1)", (StringRef, StringRef))
169169

170+
ERROR(error_write_index_unit,none,
171+
"writing index unit file: %0", (StringRef))
172+
ERROR(error_create_index_dir,none,
173+
"creating index directory: %0", (StringRef))
174+
ERROR(error_write_index_record,none,
175+
"writing index record file: %0", (StringRef))
176+
ERROR(error_index_failed_status_check,none,
177+
"failed file status check: %0", (StringRef))
178+
ERROR(error_index_inputs_more_than_outputs,none,
179+
"index output filenames do not match input source files", ())
180+
170181
ERROR(error_formatting_multiple_file_ranges,none,
171182
"file ranges don't support multiple input files", ())
172183

include/swift/ClangImporter/ClangImporterOptions.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ class ClangImporterOptions {
3737
/// Equivalent to Clang's -mcpu=.
3838
std::string TargetCPU;
3939

40+
/// The path to which we should store indexing data, if any.
41+
std::string IndexStorePath;
42+
4043
/// The bridging header or PCH that will be imported.
4144
std::string BridgingHeader;
4245

include/swift/Driver/Types.def

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ TYPE("imported-modules", ImportedModules, "importedmodules", "")
6161
TYPE("tbd", TBD, "tbd", "")
6262
TYPE("module-trace", ModuleTrace, "trace.json", "")
6363

64+
// BEGIN APPLE-ONLY OUTPUT TYPES
65+
TYPE("index-data", IndexData, "", "")
66+
// END APPLE-ONLY OUTPUT TYPES
67+
6468
// Misc types
6569
TYPE("pcm", ClangModuleFile, "pcm", "")
6670
TYPE("pch", PCH, "pch", "")

include/swift/Frontend/FrontendOptions.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,12 @@ class FrontendOptions {
132132
/// The path to collect the group information for the compiled source files.
133133
std::string GroupInfoPath;
134134

135+
/// The path to which we should store indexing data, if any.
136+
std::string IndexStorePath;
137+
138+
/// Emit index data for imported serialized swift system modules.
139+
bool IndexSystemModules = false;
140+
135141
/// If non-zero, warn when a function body takes longer than this many
136142
/// milliseconds to type-check.
137143
///

include/swift/Index/IndexRecord.h

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
//===--- IndexRecord.h - Entry point for recording index data ---*- C++ -*-===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See http://swift.org/LICENSE.txt for license information
9+
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
#ifndef SWIFT_INDEX_INDEXRECORD_H
14+
#define SWIFT_INDEX_INDEXRECORD_H
15+
16+
#include "swift/Basic/LLVM.h"
17+
#include "llvm/ADT/ArrayRef.h"
18+
#include "llvm/ADT/StringRef.h"
19+
20+
namespace swift {
21+
class DependencyTracker;
22+
class ModuleDecl;
23+
class SourceFile;
24+
25+
namespace index {
26+
27+
/// Index the given source file and store the results to \p indexStorePath.
28+
///
29+
/// \param primarySourceFile The source file to index.
30+
///
31+
/// \param indexUnitToken A unique identifier for this translation unit in the
32+
/// form of a file path.
33+
///
34+
/// \param indexStorePath The location to write the indexing data to.
35+
///
36+
/// \param indexSystemModules If true, emit index data for imported serialized
37+
/// swift system modules.
38+
///
39+
/// \param isDebugCompilation true for non-optimized compiler invocation.
40+
///
41+
/// \param targetTriple The target for this compilation.
42+
///
43+
/// \param dependencyTracker The set of dependencies seen while building.
44+
bool indexAndRecord(SourceFile *primarySourceFile, StringRef indexUnitToken,
45+
StringRef indexStorePath, bool indexSystemModules,
46+
bool isDebugCompilation, StringRef targetTriple,
47+
const DependencyTracker &dependencyTracker);
48+
49+
/// Index the given module and store the results to \p indexStorePath.
50+
///
51+
/// \param module The module to index.
52+
///
53+
/// \param indexUnitTokens A list of unique identifiers for the index units to
54+
/// be written. This may either be one unit per source file of \p module, or it
55+
/// may be a single unit, in which case all the index information will be
56+
/// combined into a single unit.
57+
///
58+
/// \param moduleUnitToken A unique identifier for this module unit in the form
59+
/// of a file path. Only used if \p indexUnitTokens are specified for each
60+
/// source file, otherwise the single \p indexUnitTokens value is used instead.
61+
///
62+
/// \param indexStorePath The location to write the indexing data to.
63+
///
64+
/// \param indexSystemModules If true, emit index data for imported serialized
65+
/// swift system modules.
66+
///
67+
/// \param isDebugCompilation true for non-optimized compiler invocation.
68+
///
69+
/// \param targetTriple The target for this compilation.
70+
///
71+
/// \param dependencyTracker The set of dependencies seen while building.
72+
bool indexAndRecord(ModuleDecl *module, ArrayRef<std::string> indexUnitTokens,
73+
StringRef moduleUnitToken, StringRef indexStorePath,
74+
bool indexSystemModules, bool isDebugCompilation,
75+
StringRef targetTriple,
76+
const DependencyTracker &dependencyTracker);
77+
// FIXME: indexUnitTokens could be StringRef, but that creates an impedance
78+
// mismatch in the caller.
79+
80+
} // end namespace index
81+
} // end namespace swift
82+
83+
#endif // SWIFT_INDEX_INDEXRECORD_H

include/swift/Option/FrontendOptions.td

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,9 @@ def external_pass_pipeline_filename : Separate<["-"], "external-pass-pipeline-fi
414414
HelpText<"Use the pass pipeline defined by <pass_pipeline_file>">,
415415
MetaVarName<"<pass_pipeline_file>">;
416416

417+
def index_system_modules : Flag<["-"], "index-system-modules">,
418+
HelpText<"Emit index data for imported serialized swift system modules">;
419+
417420
def dump_interface_hash : Flag<["-"], "dump-interface-hash">,
418421
HelpText<"Parse input file(s) and dump interface token hash(es)">,
419422
ModeOpt;

include/swift/Option/Options.td

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,18 @@ def sanitize_coverage_EQ : CommaJoined<["-"], "sanitize-coverage=">,
646646
HelpText<"Specify the type of coverage instrumentation for Sanitizers and"
647647
" additional options separated by commas">;
648648

649+
def index_file : Flag<["-"], "index-file">,
650+
HelpText<"Produce index data for a source file">, ModeOpt,
651+
Flags<[NoInteractiveOption, DoesNotAffectIncrementalBuild]>;
652+
def index_file_path : Separate<["-"], "index-file-path">,
653+
Flags<[NoInteractiveOption, DoesNotAffectIncrementalBuild]>,
654+
HelpText<"Produce index data for file <path>">,
655+
MetaVarName<"<path>">;
656+
657+
def index_store_path : Separate<["-"], "index-store-path">,
658+
Flags<[FrontendOption]>, MetaVarName<"<path>">,
659+
HelpText<"Store indexing data to <path>">;
660+
649661
def enforce_exclusivity_EQ : Joined<["-"], "enforce-exclusivity=">,
650662
Flags<[FrontendOption]>, MetaVarName<"<enforcement>">,
651663
HelpText<"Enforce law of exclusivity">;

lib/ClangImporter/ClangImporter.cpp

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
4747
#include "clang/Frontend/FrontendActions.h"
4848
#include "clang/Frontend/Utils.h"
49+
#include "clang/Index/IndexingAction.h"
4950
#include "clang/Serialization/ASTReader.h"
5051
#include "clang/Serialization/ASTWriter.h"
5152
#include "clang/Lex/Preprocessor.h"
@@ -705,6 +706,11 @@ addCommonInvocationArguments(std::vector<std::string> &invocationArgStrs,
705706
invocationArgStrs.push_back(overrideResourceDir);
706707
}
707708

709+
if (!importerOpts.IndexStorePath.empty()) {
710+
invocationArgStrs.push_back("-index-store-path");
711+
invocationArgStrs.push_back(importerOpts.IndexStorePath);
712+
}
713+
708714
for (auto extraArg : importerOpts.ExtraArgs) {
709715
invocationArgStrs.push_back(extraArg);
710716
}
@@ -1306,6 +1312,7 @@ ClangImporter::emitBridgingPCH(StringRef headerPath,
13061312
invocation->getFrontendOpts().Inputs.push_back(
13071313
clang::FrontendInputFile(headerPath, clang::IK_ObjC));
13081314
invocation->getFrontendOpts().OutputFile = outputPCHPath;
1315+
invocation->getFrontendOpts().ProgramAction = clang::frontend::GeneratePCH;
13091316
invocation->getPreprocessorOpts().resetNonModularOptions();
13101317

13111318
clang::CompilerInstance emitInstance(
@@ -1319,8 +1326,15 @@ ClangImporter::emitBridgingPCH(StringRef headerPath,
13191326
emitInstance.createSourceManager(fileManager);
13201327
emitInstance.setTarget(&Impl.Instance->getTarget());
13211328

1322-
clang::GeneratePCHAction action;
1323-
emitInstance.ExecuteAction(action);
1329+
std::unique_ptr<clang::FrontendAction> action;
1330+
action.reset(new clang::GeneratePCHAction());
1331+
if (!emitInstance.getFrontendOpts().IndexStorePath.empty()) {
1332+
action = clang::index::
1333+
createIndexDataRecordingAction(emitInstance.getFrontendOpts(),
1334+
std::move(action));
1335+
}
1336+
emitInstance.ExecuteAction(*action);
1337+
13241338
if (emitInstance.getDiagnostics().hasErrorOccurred()) {
13251339
Impl.SwiftContext.Diags.diagnose({},
13261340
diag::bridging_header_pch_error,
@@ -1407,6 +1421,17 @@ ModuleDecl *ClangImporter::loadModule(
14071421
auto importRAII = diagClient.handleImport(clangPath.front().first,
14081422
importLoc);
14091423

1424+
std::string preservedIndexStorePathOption;
1425+
auto &clangFEOpts = Impl.Instance->getFrontendOpts();
1426+
if (!clangFEOpts.IndexStorePath.empty()) {
1427+
StringRef moduleName = path[0].first->getName();
1428+
// Ignore the SwiftShims module for the index data.
1429+
if (moduleName == Impl.SwiftContext.SwiftShimsModuleName.str()) {
1430+
preservedIndexStorePathOption = clangFEOpts.IndexStorePath;
1431+
clangFEOpts.IndexStorePath.clear();
1432+
}
1433+
}
1434+
14101435
// FIXME: The source location here is completely bogus. It can't be
14111436
// invalid, it can't be the same thing twice in a row, and it has to come
14121437
// from an actual buffer, so we make a fake buffer and just use a counter.
@@ -1427,6 +1452,12 @@ ModuleDecl *ClangImporter::loadModule(
14271452
clang::ModuleLoadResult result =
14281453
Impl.Instance->loadModule(clangImportLoc, path, visibility,
14291454
/*IsInclusionDirective=*/false);
1455+
1456+
if (!preservedIndexStorePathOption.empty()) {
1457+
// Restore the -index-store-path option.
1458+
clangFEOpts.IndexStorePath = preservedIndexStorePathOption;
1459+
}
1460+
14301461
if (result && makeVisible)
14311462
Impl.getClangPreprocessor().makeModuleVisible(result, clangImportLoc);
14321463
return result;

lib/Driver/Driver.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1128,6 +1128,17 @@ void Driver::buildOutputInfo(const ToolChain &TC, const DerivedArgList &Args,
11281128
OI.CompilerMode = OutputInfo::Mode::SingleCompile;
11291129
break;
11301130

1131+
// BEGIN APPLE-ONLY OUTPUT ACTIONS
1132+
case options::OPT_index_file:
1133+
OI.CompilerMode = OutputInfo::Mode::SingleCompile;
1134+
OI.CompilerOutputType = types::TY_IndexData;
1135+
break;
1136+
// END APPLE-ONLY OUTPUT ACTIONS
1137+
1138+
case options::OPT_update_code:
1139+
OI.CompilerOutputType = types::TY_Remapping;
1140+
OI.LinkAction = LinkKind::None;
1141+
break;
11311142
case options::OPT_parse:
11321143
case options::OPT_typecheck:
11331144
case options::OPT_dump_parse:
@@ -1420,6 +1431,7 @@ void Driver::buildActions(const ToolChain &TC,
14201431
case types::TY_ClangModuleFile:
14211432
case types::TY_SwiftDeps:
14221433
case types::TY_Remapping:
1434+
case types::TY_IndexData:
14231435
case types::TY_PCH:
14241436
case types::TY_ImportedModules:
14251437
case types::TY_TBD:

lib/Driver/ToolChains.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,13 @@ ToolChain::constructInvocation(const CompileJobAction &job,
231231
case types::TY_TBD:
232232
FrontendModeOption = "-emit-tbd";
233233
break;
234+
235+
// BEGIN APPLE-ONLY OUTPUT TYPES
236+
case types::TY_IndexData:
237+
FrontendModeOption = "-typecheck";
238+
break;
239+
// END APPLE-ONLY OUTPUT TYPES
240+
234241
case types::TY_Remapping:
235242
FrontendModeOption = "-update-code";
236243
break;
@@ -311,6 +318,12 @@ ToolChain::constructInvocation(const CompileJobAction &job,
311318
break;
312319
}
313320
case OutputInfo::Mode::SingleCompile: {
321+
if (context.Output.getPrimaryOutputType() == types::TY_IndexData) {
322+
if (Arg *A = context.Args.getLastArg(options::OPT_index_file_path)) {
323+
Arguments.push_back("-primary-file");
324+
Arguments.push_back(A->getValue());
325+
}
326+
}
314327
if (context.Args.hasArg(options::OPT_driver_use_filelists) ||
315328
context.InputActions.size() > TOO_MANY_FILES) {
316329
Arguments.push_back("-filelist");
@@ -456,6 +469,11 @@ ToolChain::constructInvocation(const CompileJobAction &job,
456469
if (context.Args.hasArg(options::OPT_embed_bitcode_marker))
457470
Arguments.push_back("-embed-bitcode-marker");
458471

472+
if (context.Args.hasArg(options::OPT_index_store_path)) {
473+
context.Args.AddLastArg(Arguments, options::OPT_index_store_path);
474+
Arguments.push_back("-index-system-modules");
475+
}
476+
459477
return II;
460478
}
461479

@@ -541,6 +559,7 @@ ToolChain::constructInvocation(const BackendJobAction &job,
541559
case types::TY_SIL:
542560
case types::TY_SIB:
543561
case types::TY_PCH:
562+
case types::TY_IndexData:
544563
llvm_unreachable("Cannot be output from backend job");
545564
case types::TY_Swift:
546565
case types::TY_dSYM:
@@ -824,6 +843,7 @@ ToolChain::constructInvocation(const GeneratePCHJobAction &job,
824843
Arguments);
825844

826845
addInputsOfType(Arguments, context.InputActions, types::TY_ObjCHeader);
846+
context.Args.AddLastArg(Arguments, options::OPT_index_store_path);
827847

828848
if (job.isPersistentPCH()) {
829849
Arguments.push_back("-emit-pch");

lib/Driver/Types.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ bool types::isTextual(ID Id) {
9292
case types::TY_SwiftDeps:
9393
case types::TY_Nothing:
9494
case types::TY_Remapping:
95+
case types::TY_IndexData:
9596
return false;
9697
case types::TY_INVALID:
9798
llvm_unreachable("Invalid type ID.");
@@ -128,6 +129,7 @@ bool types::isAfterLLVM(ID Id) {
128129
case types::TY_SwiftDeps:
129130
case types::TY_Nothing:
130131
case types::TY_Remapping:
132+
case types::TY_IndexData:
131133
case types::TY_ModuleTrace:
132134
return false;
133135
case types::TY_INVALID:
@@ -165,6 +167,7 @@ bool types::isPartOfSwiftCompilation(ID Id) {
165167
case types::TY_SwiftDeps:
166168
case types::TY_Nothing:
167169
case types::TY_Remapping:
170+
case types::TY_IndexData:
168171
case types::TY_ModuleTrace:
169172
return false;
170173
case types::TY_INVALID:

lib/Frontend/CompilerInvocation.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,11 @@ static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
169169
Opts.GroupInfoPath = A->getValue();
170170
}
171171

172+
if (const Arg *A = Args.getLastArg(OPT_index_store_path)) {
173+
Opts.IndexStorePath = A->getValue();
174+
}
175+
Opts.IndexSystemModules |= Args.hasArg(OPT_index_system_modules);
176+
172177
Opts.EmitVerboseSIL |= Args.hasArg(OPT_emit_verbose_sil);
173178
Opts.EmitSortedSIL |= Args.hasArg(OPT_emit_sorted_sil);
174179

@@ -1143,6 +1148,9 @@ static bool ParseClangImporterArgs(ClangImporterOptions &Opts,
11431148
if (const Arg *A = Args.getLastArg(OPT_target_cpu))
11441149
Opts.TargetCPU = A->getValue();
11451150

1151+
if (const Arg *A = Args.getLastArg(OPT_index_store_path))
1152+
Opts.IndexStorePath = A->getValue();
1153+
11461154
for (const Arg *A : make_range(Args.filtered_begin(OPT_Xcc),
11471155
Args.filtered_end())) {
11481156
Opts.ExtraArgs.push_back(A->getValue());

lib/Frontend/Frontend.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,12 @@ bool CompilerInstance::setup(const CompilerInvocation &Invok) {
9797
if (!Invocation.getFrontendOptions().ModuleDocOutputPath.empty())
9898
Invocation.getLangOptions().AttachCommentsToDecls = true;
9999

100+
// If we are doing index-while-building, configure lexing and parsing to
101+
// remember comments.
102+
if (!Invocation.getFrontendOptions().IndexStorePath.empty()) {
103+
Invocation.getLangOptions().AttachCommentsToDecls = true;
104+
}
105+
100106
Context.reset(new ASTContext(Invocation.getLangOptions(),
101107
Invocation.getSearchPathOptions(),
102108
SourceMgr, Diagnostics));

lib/FrontendTool/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ add_swift_library(swiftFrontendTool STATIC
55
TBD.cpp
66
DEPENDS SwiftOptions
77
LINK_LIBRARIES
8+
swiftIndex
89
swiftIDE
910
swiftTBDGen swiftIRGen swiftSIL swiftSILGen swiftSILOptimizer
1011
swiftDemangling

0 commit comments

Comments
 (0)