-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathFrontendTool.cpp
2143 lines (1875 loc) · 84.6 KB
/
FrontendTool.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- FrontendTool.cpp - Swift Compiler Frontend -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This is the entry point to the swift -frontend functionality, which
/// implements the core compiler functionality along with a number of additional
/// tools for demonstration and testing purposes.
///
/// This is separate from the rest of libFrontend to reduce the dependencies
/// required by that library.
///
//===----------------------------------------------------------------------===//
#include "swift/FrontendTool/FrontendTool.h"
#include "Dependencies.h"
#include "TBD.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/AvailabilityScope.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/FineGrainedDependencies.h"
#include "swift/AST/FineGrainedDependencyFormat.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/IRGenRequests.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/TBDGenRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Edit.h"
#include "swift/Basic/FileSystem.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/PrettyStackTrace.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/TargetInfo.h"
#include "swift/Basic/UUID.h"
#include "swift/Basic/Version.h"
#include "swift/ConstExtract/ConstExtract.h"
#include "swift/DependencyScan/ScanDependencies.h"
#include "swift/Frontend/CachedDiagnostics.h"
#include "swift/Frontend/CachingUtils.h"
#include "swift/Frontend/CompileJobCacheKey.h"
#include "swift/Frontend/DiagnosticHelper.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/MakeStyleDependencies.h"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "swift/Frontend/ModuleInterfaceSupport.h"
#include "swift/IRGen/TBDGen.h"
#include "swift/Immediate/Immediate.h"
#include "swift/Index/IndexRecord.h"
#include "swift/Migrator/FixitFilter.h"
#include "swift/Migrator/Migrator.h"
#include "swift/Option/Options.h"
#include "swift/PrintAsClang/PrintAsClang.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Subsystems.h"
#include "swift/SymbolGraphGen/SymbolGraphOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualOutputBackend.h"
#include "llvm/Support/VirtualOutputBackends.h"
#include "llvm/Support/raw_ostream.h"
#if __has_include(<unistd.h>)
#include <unistd.h>
#elif defined(_WIN32)
#include <process.h>
#endif
#include <algorithm>
#include <memory>
#include <unordered_set>
#include <utility>
using namespace swift;
static std::string displayName(StringRef MainExecutablePath) {
std::string Name = llvm::sys::path::stem(MainExecutablePath).str();
Name += " -frontend";
return Name;
}
static void emitMakeDependenciesIfNeeded(CompilerInstance &instance) {
instance.getInvocation()
.getFrontendOptions()
.InputsAndOutputs.forEachInputProducingSupplementaryOutput(
[&](const InputFile &f) -> bool {
return swift::emitMakeDependenciesIfNeeded(instance, f);
});
}
static void
emitLoadedModuleTraceForAllPrimariesIfNeeded(ModuleDecl *mainModule,
DependencyTracker *depTracker,
const FrontendOptions &opts) {
opts.InputsAndOutputs.forEachInputProducingSupplementaryOutput(
[&](const InputFile &input) -> bool {
return swift::emitLoadedModuleTraceIfNeeded(mainModule, depTracker,
opts, input);
});
}
/// Writes SIL out to the given file.
static bool writeSIL(SILModule &SM, ModuleDecl *M, const SILOptions &Opts,
StringRef OutputFilename,
llvm::vfs::OutputBackend &Backend) {
return withOutputPath(M->getDiags(), Backend, OutputFilename,
[&](raw_ostream &out) -> bool {
SM.print(out, M, Opts);
return M->getASTContext().hadError();
});
}
static bool writeSIL(SILModule &SM, const PrimarySpecificPaths &PSPs,
CompilerInstance &Instance,
const SILOptions &Opts) {
return writeSIL(SM, Instance.getMainModule(), Opts,
PSPs.OutputFilename, Instance.getOutputBackend());
}
/// Prints the Objective-C "generated header" interface for \p M to \p
/// outputPath.
/// Print the exposed "generated header" interface for \p M to \p
/// outputPath.
///
/// ...unless \p outputPath is empty, in which case it does nothing.
///
/// \returns true if there were any errors
///
/// \see swift::printAsClangHeader
static bool printAsClangHeaderIfNeeded(llvm::vfs::OutputBackend &outputBackend,
StringRef outputPath, ModuleDecl *M, StringRef bridgingHeader,
const FrontendOptions &frontendOpts, const IRGenOptions &irGenOpts,
clang::HeaderSearch &clangHeaderSearchInfo) {
if (outputPath.empty())
return false;
return withOutputPath(
M->getDiags(), outputBackend, outputPath, [&](raw_ostream &out) -> bool {
return printAsClangHeader(out, M, bridgingHeader, frontendOpts,
irGenOpts, clangHeaderSearchInfo);
});
}
/// Prints the stable module interface for \p M to \p outputPath.
///
/// ...unless \p outputPath is empty, in which case it does nothing.
///
/// \returns true if there were any errors
///
/// \see swift::emitSwiftInterface
static bool
printModuleInterfaceIfNeeded(llvm::vfs::OutputBackend &outputBackend,
StringRef outputPath,
ModuleInterfaceOptions const &Opts,
LangOptions const &LangOpts,
ModuleDecl *M) {
if (outputPath.empty())
return false;
DiagnosticEngine &diags = M->getDiags();
if (!LangOpts.isSwiftVersionAtLeast(5)) {
assert(LangOpts.isSwiftVersionAtLeast(4));
diags.diagnose(SourceLoc(),
diag::warn_unsupported_module_interface_swift_version,
LangOpts.isSwiftVersionAtLeast(4, 2) ? "4.2" : "4");
}
if (M->getResilienceStrategy() != ResilienceStrategy::Resilient) {
diags.diagnose(SourceLoc(),
diag::warn_unsupported_module_interface_library_evolution);
}
return withOutputPath(diags, outputBackend, outputPath,
[M, Opts](raw_ostream &out) -> bool {
return swift::emitSwiftInterface(out, Opts, M);
});
}
// This is a separate function so that it shows up in stack traces.
LLVM_ATTRIBUTE_NOINLINE
static void debugFailWithAssertion() {
// Per the user's request, this assertion should always fail in
// builds with assertions enabled.
// This should not be converted to llvm_unreachable, as those are
// treated as optimization hints in builds where they turn into
// __builtin_unreachable().
assert((0) && "This is an assertion!");
}
// This is a separate function so that it shows up in stack traces.
LLVM_ATTRIBUTE_NOINLINE
static void debugFailWithCrash() {
LLVM_BUILTIN_TRAP;
}
static void countStatsOfSourceFile(UnifiedStatsReporter &Stats,
const CompilerInstance &Instance,
SourceFile *SF) {
auto &C = Stats.getFrontendCounters();
auto &SM = Instance.getSourceMgr();
C.NumDecls += SF->getTopLevelDecls().size();
C.NumLocalTypeDecls += SF->getLocalTypeDecls().size();
C.NumObjCMethods += SF->ObjCMethods.size();
SmallVector<OperatorDecl *, 2> operators;
SF->getOperatorDecls(operators);
C.NumOperators += operators.size();
SmallVector<PrecedenceGroupDecl *, 2> groups;
SF->getPrecedenceGroups(groups);
C.NumPrecedenceGroups += groups.size();
C.NumSourceLines +=
SM.getEntireTextForBuffer(SF->getBufferID()).count('\n');
}
static void countASTStats(UnifiedStatsReporter &Stats,
CompilerInstance& Instance) {
auto &C = Stats.getFrontendCounters();
auto &SM = Instance.getSourceMgr();
C.NumSourceBuffers = SM.getLLVMSourceMgr().getNumBuffers();
C.NumLinkLibraries = Instance.getLinkLibraries().size();
auto const &AST = Instance.getASTContext();
C.NumLoadedModules = AST.getNumLoadedModules();
if (auto *D = Instance.getDependencyTracker()) {
C.NumDependencies = D->getDependencies().size();
C.NumIncrementalDependencies = D->getIncrementalDependencies().size();
C.NumMacroPluginDependencies = D->getMacroPluginDependencies().size();
}
for (auto SF : Instance.getPrimarySourceFiles()) {
auto &Ctx = SF->getASTContext();
Ctx.evaluator.enumerateReferencesInFile(SF, [&C](const auto &ref) {
using NodeKind = evaluator::DependencyCollector::Reference::Kind;
switch (ref.kind) {
case NodeKind::Empty:
case NodeKind::Tombstone:
llvm_unreachable("Cannot enumerate dead dependency!");
case NodeKind::TopLevel:
C.NumReferencedTopLevelNames += 1;
return;
case NodeKind::Dynamic:
C.NumReferencedDynamicNames += 1;
return;
case NodeKind::PotentialMember:
case NodeKind::UsedMember:
C.NumReferencedMemberNames += 1;
return;
}
});
}
if (!Instance.getPrimarySourceFiles().empty()) {
for (auto SF : Instance.getPrimarySourceFiles())
countStatsOfSourceFile(Stats, Instance, SF);
} else if (auto *M = Instance.getMainModule()) {
// No primary source file, but a main module; this is WMO-mode
for (auto *F : M->getFiles()) {
if (auto *SF = dyn_cast<SourceFile>(F)) {
countStatsOfSourceFile(Stats, Instance, SF);
}
}
}
}
static void countStatsPostSILGen(UnifiedStatsReporter &Stats,
const SILModule& Module) {
auto &C = Stats.getFrontendCounters();
// FIXME: calculate these in constant time, via the dense maps.
C.NumSILGenFunctions += Module.getFunctionList().size();
C.NumSILGenVtables += Module.getVTables().size();
C.NumSILGenWitnessTables += Module.getWitnessTableList().size();
C.NumSILGenDefaultWitnessTables += Module.getDefaultWitnessTableList().size();
C.NumSILGenGlobalVariables += Module.getSILGlobalList().size();
}
static bool precompileBridgingHeader(const CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &opts = Invocation.getFrontendOptions();
auto clangImporter = static_cast<ClangImporter *>(
Instance.getASTContext().getClangModuleLoader());
auto &ImporterOpts = Invocation.getClangImporterOptions();
auto &PCHOutDir = ImporterOpts.PrecompiledHeaderOutputDir;
auto OutputBackend = Instance.getOutputBackend().clone();
if (!PCHOutDir.empty()) {
// Create or validate a persistent PCH.
auto SwiftPCHHash = Invocation.getPCHHash();
auto PCH = clangImporter->getOrCreatePCH(ImporterOpts, SwiftPCHHash,
/*cached=*/false);
return !PCH.has_value();
}
return clangImporter->emitBridgingPCH(
opts.InputsAndOutputs.getFilenameOfFirstInput(),
opts.InputsAndOutputs.getSingleOutputFilename(), /*cached=*/false);
}
static bool precompileClangModule(const CompilerInstance &Instance) {
const auto &opts = Instance.getInvocation().getFrontendOptions();
auto clangImporter = static_cast<ClangImporter *>(
Instance.getASTContext().getClangModuleLoader());
return clangImporter->emitPrecompiledModule(
opts.InputsAndOutputs.getFilenameOfFirstInput(), opts.ModuleName,
opts.InputsAndOutputs.getSingleOutputFilename());
}
static bool dumpPrecompiledClangModule(const CompilerInstance &Instance) {
const auto &opts = Instance.getInvocation().getFrontendOptions();
auto clangImporter = static_cast<ClangImporter *>(
Instance.getASTContext().getClangModuleLoader());
return clangImporter->dumpPrecompiledModule(
opts.InputsAndOutputs.getFilenameOfFirstInput(),
opts.InputsAndOutputs.getSingleOutputFilename());
}
static bool buildModuleFromInterface(CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const FrontendOptions &FEOpts = Invocation.getFrontendOptions();
assert(FEOpts.InputsAndOutputs.hasSingleInput());
StringRef InputPath = FEOpts.InputsAndOutputs.getFilenameOfFirstInput();
StringRef PrebuiltCachePath = FEOpts.PrebuiltModuleCachePath;
ModuleInterfaceLoaderOptions LoaderOpts(FEOpts);
StringRef ABIPath = Instance.getPrimarySpecificPathsForAtMostOnePrimary()
.SupplementaryOutputs.ABIDescriptorOutputPath;
bool IgnoreAdjacentModules = Instance.hasASTContext() &&
Instance.getASTContext().IgnoreAdjacentModules;
// When building explicit module dependencies, they are
// discovered by dependency scanner and the swiftmodule is already rebuilt
// ignoring candidate module. There is no need to serialized dependencies for
// validation purpose because the build system (swift-driver) is then
// responsible for checking whether inputs are up-to-date.
bool ShouldSerializeDeps = !FEOpts.ExplicitInterfaceBuild;
// If an explicit interface build was requested, bypass the creation of a new
// sub-instance from the interface which will build it in a separate thread,
// and isntead directly use the current \c Instance for compilation.
//
// FIXME: -typecheck-module-from-interface is the exception here because
// currently we need to ensure it still reads the flags written out
// in the .swiftinterface file itself. Instead, creation of that
// job should incorporate those flags.
if (FEOpts.ExplicitInterfaceBuild && !(FEOpts.isTypeCheckAction()))
return ModuleInterfaceLoader::buildExplicitSwiftModuleFromSwiftInterface(
Instance, Invocation.getClangModuleCachePath(),
FEOpts.BackupModuleInterfaceDir, PrebuiltCachePath, ABIPath, InputPath,
Invocation.getOutputFilename(), ShouldSerializeDeps,
Invocation.getSearchPathOptions().CandidateCompiledModules);
return ModuleInterfaceLoader::buildSwiftModuleFromSwiftInterface(
Instance.getSourceMgr(), Instance.getDiags(),
Invocation.getSearchPathOptions(), Invocation.getLangOptions(),
Invocation.getClangImporterOptions(), Invocation.getCASOptions(),
Invocation.getClangModuleCachePath(), PrebuiltCachePath,
FEOpts.BackupModuleInterfaceDir, Invocation.getModuleName(), InputPath,
Invocation.getOutputFilename(), ABIPath,
FEOpts.SerializeModuleInterfaceDependencyHashes,
FEOpts.shouldTrackSystemDependencies(), LoaderOpts,
RequireOSSAModules_t(Invocation.getSILOptions()),
IgnoreAdjacentModules);
}
static bool compileLLVMIR(CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &inputsAndOutputs =
Invocation.getFrontendOptions().InputsAndOutputs;
// Load in bitcode file.
assert(inputsAndOutputs.hasSingleInput() &&
"We expect a single input for bitcode input!");
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
swift::vfs::getFileOrSTDIN(Instance.getFileSystem(),
inputsAndOutputs.getFilenameOfFirstInput());
if (!FileBufOrErr) {
Instance.getDiags().diagnose(SourceLoc(), diag::error_open_input_file,
inputsAndOutputs.getFilenameOfFirstInput(),
FileBufOrErr.getError().message());
return true;
}
llvm::MemoryBuffer *MainFile = FileBufOrErr.get().get();
llvm::SMDiagnostic Err;
auto LLVMContext = std::make_unique<llvm::LLVMContext>();
std::unique_ptr<llvm::Module> Module =
llvm::parseIR(MainFile->getMemBufferRef(), Err, *LLVMContext.get());
if (!Module) {
// TODO: Translate from the diagnostic info to the SourceManager location
// if available.
Instance.getDiags().diagnose(SourceLoc(), diag::error_parse_input_file,
inputsAndOutputs.getFilenameOfFirstInput(),
Err.getMessage());
return true;
}
return performLLVM(Invocation.getIRGenOptions(), Instance.getASTContext(),
Module.get(), inputsAndOutputs.getSingleOutputFilename());
}
static void verifyGenericSignaturesIfNeeded(const FrontendOptions &opts,
ASTContext &Context) {
auto verifyGenericSignaturesInModule = opts.VerifyGenericSignaturesInModule;
if (verifyGenericSignaturesInModule.empty())
return;
if (auto module = Context.getModuleByName(verifyGenericSignaturesInModule))
swift::validateGenericSignaturesInModule(module);
}
static bool dumpAndPrintScopeMap(const CompilerInstance &Instance,
SourceFile &SF) {
// Not const because may require reexpansion
ASTScope &scope = SF.getScope();
const auto &opts = Instance.getInvocation().getFrontendOptions();
if (opts.DumpScopeMapLocations.empty()) {
llvm::errs() << "***Complete scope map***\n";
scope.buildFullyExpandedTree();
scope.print(llvm::errs());
return Instance.getASTContext().hadError();
}
// Probe each of the locations, and dump what we find.
for (auto lineColumn : opts.DumpScopeMapLocations) {
scope.buildFullyExpandedTree();
scope.dumpOneScopeMapLocation(lineColumn);
}
return Instance.getASTContext().hadError();
}
static SourceFile &
getPrimaryOrMainSourceFile(const CompilerInstance &Instance) {
if (SourceFile *SF = Instance.getPrimarySourceFile()) {
return *SF;
}
return Instance.getMainModule()->getMainSourceFile();
}
/// Dumps the AST of all available primary source files. If corresponding output
/// files were specified, use them; otherwise, dump the AST to stdout.
static bool dumpAST(CompilerInstance &Instance) {
auto primaryFiles = Instance.getPrimarySourceFiles();
if (!primaryFiles.empty()) {
for (SourceFile *sourceFile: primaryFiles) {
auto PSPs = Instance.getPrimarySpecificPathsForSourceFile(*sourceFile);
auto OutputFilename = PSPs.OutputFilename;
if (withOutputPath(Instance.getASTContext().Diags,
Instance.getOutputBackend(), OutputFilename,
[&](raw_ostream &out) -> bool {
sourceFile->dump(out, /*parseIfNeeded*/ true);
return false;
}))
return true;
}
} else {
// Some invocations don't have primary files. In that case, we default to
// looking for the main file and dumping it to `stdout`.
auto &SF = getPrimaryOrMainSourceFile(Instance);
SF.dump(llvm::outs(), /*parseIfNeeded*/ true);
}
return Instance.getASTContext().hadError();
}
static bool emitReferenceDependencies(CompilerInstance &Instance,
SourceFile *const SF,
StringRef outputPath) {
const auto alsoEmitDotFile = Instance.getInvocation()
.getLangOptions()
.EmitFineGrainedDependencySourcefileDotFiles;
// Before writing to the dependencies file path, preserve any previous file
// that may have been there. No error handling -- this is just a nicety, it
// doesn't matter if it fails.
llvm::sys::fs::rename(outputPath, outputPath + "~");
using SourceFileDepGraph = fine_grained_dependencies::SourceFileDepGraph;
return fine_grained_dependencies::withReferenceDependencies(
SF, *Instance.getDependencyTracker(), Instance.getOutputBackend(),
outputPath, alsoEmitDotFile, [&](SourceFileDepGraph &&g) -> bool {
const bool hadError =
fine_grained_dependencies::writeFineGrainedDependencyGraphToPath(
Instance.getDiags(), Instance.getOutputBackend(), outputPath,
g);
// If path is stdout, cannot read it back, so check for "-"
assert(outputPath == "-" || g.verifyReadsWhatIsWritten(outputPath));
if (alsoEmitDotFile)
g.emitDotFile(Instance.getOutputBackend(), outputPath,
Instance.getDiags());
return hadError;
});
}
static void emitSwiftdepsForAllPrimaryInputsIfNeeded(
CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
if (Invocation.getFrontendOptions()
.InputsAndOutputs.hasReferenceDependenciesFilePath() &&
Instance.getPrimarySourceFiles().empty()) {
Instance.getDiags().diagnose(
SourceLoc(), diag::emit_reference_dependencies_without_primary_file);
return;
}
// Do not write out swiftdeps for any primaries if we've encountered an
// error. Without this, the driver will attempt to integrate swiftdeps
// from broken swift files. One way this could go wrong is if a primary that
// fails to build in an early wave has dependents in a later wave. The
// driver will not schedule those later dependents after this batch exits,
// so they will have no opportunity to bring their swiftdeps files up to
// date. With this early exit, the driver sees the same priors in the
// swiftdeps files from before errors were introduced into the batch, and
// integration therefore always hops from "known good" to "known good" states.
//
// FIXME: It seems more appropriate for the driver to notice the early-exit
// and react by always enqueuing the jobs it dropped in the other waves.
//
// We will output a module if allowing errors, so ignore that case.
if (Instance.getDiags().hadAnyError() &&
!Invocation.getFrontendOptions().AllowModuleWithCompilerErrors)
return;
for (auto *SF : Instance.getPrimarySourceFiles()) {
const std::string &referenceDependenciesFilePath =
Invocation.getReferenceDependenciesFilePathForPrimary(
SF->getFilename());
if (referenceDependenciesFilePath.empty()) {
continue;
}
emitReferenceDependencies(Instance, SF, referenceDependenciesFilePath);
}
}
static bool emitConstValuesForWholeModuleIfNeeded(
CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &frontendOpts = Invocation.getFrontendOptions();
auto constExtractProtocolListPath =
Instance.getASTContext().SearchPathOpts.ConstGatherProtocolListFilePath;
if (constExtractProtocolListPath.empty())
return false;
if (!frontendOpts.InputsAndOutputs.hasConstValuesOutputPath())
return false;
assert(frontendOpts.InputsAndOutputs.isWholeModule() &&
"'emitConstValuesForWholeModule' only makes sense when the whole module can be seen");
auto ConstValuesFilePath = frontendOpts.InputsAndOutputs
.getPrimarySpecificPathsForAtMostOnePrimary().SupplementaryOutputs
.ConstValuesOutputPath;
// List of protocols whose conforming nominal types
// we should extract compile-time-known values from
std::unordered_set<std::string> Protocols;
bool inputParseSuccess = parseProtocolListFromFile(constExtractProtocolListPath,
Instance.getDiags(), Protocols);
if (!inputParseSuccess)
return true;
auto ConstValues = gatherConstValuesForModule(Protocols,
Instance.getMainModule());
return withOutputPath(Instance.getDiags(), Instance.getOutputBackend(),
ConstValuesFilePath, [&](llvm::raw_ostream &OS) {
writeAsJSONToFile(ConstValues, OS);
return false;
});
}
static void emitConstValuesForAllPrimaryInputsIfNeeded(
CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
auto constExtractProtocolListPath =
Instance.getASTContext().SearchPathOpts.ConstGatherProtocolListFilePath;
if (constExtractProtocolListPath.empty())
return;
// List of protocols whose conforming nominal types
// we should extract compile-time-known values from
std::unordered_set<std::string> Protocols;
bool inputParseSuccess = parseProtocolListFromFile(constExtractProtocolListPath,
Instance.getDiags(), Protocols);
if (!inputParseSuccess)
return;
for (auto *SF : Instance.getPrimarySourceFiles()) {
const std::string &ConstValuesFilePath =
Invocation.getConstValuesFilePathForPrimary(
SF->getFilename());
if (ConstValuesFilePath.empty())
continue;
auto ConstValues = gatherConstValuesForPrimary(Protocols, SF);
withOutputPath(Instance.getDiags(), Instance.getOutputBackend(),
ConstValuesFilePath, [&](llvm::raw_ostream &OS) {
writeAsJSONToFile(ConstValues, OS);
return false;
});
}
}
static bool writeModuleSemanticInfoIfNeeded(CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &frontendOpts = Invocation.getFrontendOptions();
if (!frontendOpts.InputsAndOutputs.hasModuleSemanticInfoOutputPath())
return false;
std::error_code EC;
assert(frontendOpts.InputsAndOutputs.isWholeModule() &&
"TBDPath only makes sense when the whole module can be seen");
auto ModuleSemanticPath = frontendOpts.InputsAndOutputs
.getPrimarySpecificPathsForAtMostOnePrimary().SupplementaryOutputs
.ModuleSemanticInfoOutputPath;
return withOutputPath(Instance.getDiags(), Instance.getOutputBackend(),
ModuleSemanticPath, [&](llvm::raw_ostream &OS) {
OS << "{}\n";
return false;
});
}
static bool writeTBDIfNeeded(CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &frontendOpts = Invocation.getFrontendOptions();
const auto &tbdOpts = Invocation.getTBDGenOptions();
if (!frontendOpts.InputsAndOutputs.hasTBDPath())
return false;
if (!frontendOpts.InputsAndOutputs.isWholeModule()) {
Instance.getDiags().diagnose(SourceLoc(),
diag::tbd_only_supported_in_whole_module);
return false;
}
if (Invocation.getSILOptions().CMOMode ==
CrossModuleOptimizationMode::Aggressive) {
Instance.getDiags().diagnose(SourceLoc(),
diag::tbd_not_supported_with_cmo);
return false;
}
const std::string &TBDPath = Invocation.getTBDPathForWholeModule();
return writeTBD(Instance.getMainModule(), TBDPath,
Instance.getOutputBackend(), tbdOpts);
}
static bool writeAPIDescriptor(ModuleDecl *M, StringRef OutputPath,
llvm::vfs::OutputBackend &Backend) {
return withOutputPath(M->getDiags(), Backend, OutputPath,
[&](raw_ostream &OS) -> bool {
writeAPIJSONFile(M, OS, /*PrettyPrinted=*/false);
return false;
});
}
static bool writeAPIDescriptorIfNeeded(CompilerInstance &Instance) {
const auto &Invocation = Instance.getInvocation();
const auto &frontendOpts = Invocation.getFrontendOptions();
if (!frontendOpts.InputsAndOutputs.hasAPIDescriptorOutputPath())
return false;
if (!frontendOpts.InputsAndOutputs.isWholeModule()) {
Instance.getDiags().diagnose(
SourceLoc(), diag::api_descriptor_only_supported_in_whole_module);
return false;
}
const std::string &APIDescriptorPath =
Invocation.getAPIDescriptorPathForWholeModule();
return writeAPIDescriptor(Instance.getMainModule(), APIDescriptorPath,
Instance.getOutputBackend());
}
static bool performCompileStepsPostSILGen(CompilerInstance &Instance,
std::unique_ptr<SILModule> SM,
ModuleOrSourceFile MSF,
const PrimarySpecificPaths &PSPs,
int &ReturnValue,
FrontendObserver *observer);
bool swift::performCompileStepsPostSema(CompilerInstance &Instance,
int &ReturnValue,
FrontendObserver *observer) {
const auto &Invocation = Instance.getInvocation();
const FrontendOptions &opts = Invocation.getFrontendOptions();
auto getSILOptions = [&](const PrimarySpecificPaths &PSPs) -> SILOptions {
SILOptions SILOpts = Invocation.getSILOptions();
if (SILOpts.OptRecordFile.empty()) {
// Check if the record file path was passed via supplemental outputs.
SILOpts.OptRecordFile = SILOpts.OptRecordFormat ==
llvm::remarks::Format::YAML ?
PSPs.SupplementaryOutputs.YAMLOptRecordPath :
PSPs.SupplementaryOutputs.BitstreamOptRecordPath;
}
return SILOpts;
};
auto *mod = Instance.getMainModule();
if (!opts.InputsAndOutputs.hasPrimaryInputs()) {
// If there are no primary inputs the compiler is in WMO mode and builds one
// SILModule for the entire module.
const PrimarySpecificPaths PSPs =
Instance.getPrimarySpecificPathsForWholeModuleOptimizationMode();
SILOptions SILOpts = getSILOptions(PSPs);
IRGenOptions irgenOpts = Invocation.getIRGenOptions();
auto SM = performASTLowering(mod, Instance.getSILTypes(), SILOpts,
&irgenOpts);
return performCompileStepsPostSILGen(Instance, std::move(SM), mod, PSPs,
ReturnValue, observer);
}
// If there are primary source files, build a separate SILModule for
// each source file, and run the remaining SILOpt-Serialize-IRGen-LLVM
// once for each such input.
if (!Instance.getPrimarySourceFiles().empty()) {
bool result = false;
for (auto *PrimaryFile : Instance.getPrimarySourceFiles()) {
const PrimarySpecificPaths PSPs =
Instance.getPrimarySpecificPathsForSourceFile(*PrimaryFile);
SILOptions SILOpts = getSILOptions(PSPs);
IRGenOptions irgenOpts = Invocation.getIRGenOptions();
auto SM = performASTLowering(*PrimaryFile, Instance.getSILTypes(),
SILOpts, &irgenOpts);
result |= performCompileStepsPostSILGen(Instance, std::move(SM),
PrimaryFile, PSPs, ReturnValue,
observer);
}
return result;
}
// If there are primary inputs but no primary _source files_, there might be
// a primary serialized input.
bool result = false;
for (FileUnit *fileUnit : mod->getFiles()) {
if (auto SASTF = dyn_cast<SerializedASTFile>(fileUnit))
if (opts.InputsAndOutputs.isInputPrimary(SASTF->getFilename())) {
const PrimarySpecificPaths &PSPs =
Instance.getPrimarySpecificPathsForPrimary(SASTF->getFilename());
SILOptions SILOpts = getSILOptions(PSPs);
auto SM = performASTLowering(*SASTF, Instance.getSILTypes(), SILOpts);
result |= performCompileStepsPostSILGen(Instance, std::move(SM), mod,
PSPs, ReturnValue, observer);
}
}
return result;
}
static void emitIndexDataForSourceFile(SourceFile *PrimarySourceFile,
const CompilerInstance &Instance);
/// Emits index data for all primary inputs, or the main module.
static void emitIndexData(const CompilerInstance &Instance) {
if (Instance.getPrimarySourceFiles().empty()) {
emitIndexDataForSourceFile(nullptr, Instance);
} else {
for (SourceFile *SF : Instance.getPrimarySourceFiles())
emitIndexDataForSourceFile(SF, Instance);
}
}
/// Emits all "one-per-module" supplementary outputs that don't depend on
/// anything past type-checking.
static bool emitAnyWholeModulePostTypeCheckSupplementaryOutputs(
CompilerInstance &Instance) {
const auto &Context = Instance.getASTContext();
const auto &Invocation = Instance.getInvocation();
const FrontendOptions &opts = Invocation.getFrontendOptions();
// FIXME: Whole-module outputs with a non-whole-module action ought to
// be disallowed, but the driver implements -index-file mode by generating a
// regular whole-module frontend command line and modifying it to index just
// one file (by making it a primary) instead of all of them. If that
// invocation also has flags to emit whole-module supplementary outputs, the
// compiler can crash trying to access information for non-type-checked
// declarations in the non-primary files. For now, prevent those crashes by
// guarding the emission of whole-module supplementary outputs.
if (!opts.InputsAndOutputs.isWholeModule())
return false;
// Record whether we failed to emit any of these outputs, but keep going; one
// failure does not mean skipping the rest.
bool hadAnyError = false;
if ((!Context.hadError() || opts.AllowModuleWithCompilerErrors) &&
opts.InputsAndOutputs.hasClangHeaderOutputPath()) {
std::string BridgingHeaderPathForPrint = Instance.getBridgingHeaderPath();
if (!BridgingHeaderPathForPrint.empty()) {
if (opts.BridgingHeaderDirForPrint.has_value()) {
// User specified preferred directory for including, use that dir.
llvm::SmallString<32> Buffer(*opts.BridgingHeaderDirForPrint);
llvm::sys::path::append(Buffer,
llvm::sys::path::filename(BridgingHeaderPathForPrint));
BridgingHeaderPathForPrint = (std::string)Buffer;
}
}
hadAnyError |= printAsClangHeaderIfNeeded(
Instance.getOutputBackend(),
Invocation.getClangHeaderOutputPathForAtMostOnePrimary(),
Instance.getMainModule(), BridgingHeaderPathForPrint, opts,
Invocation.getIRGenOptions(),
Context.getClangModuleLoader()
->getClangPreprocessor()
.getHeaderSearchInfo());
}
// Only want the header if there's been any errors, ie. there's not much
// point outputting a swiftinterface for an invalid module
if (Context.hadError())
return hadAnyError;
if (opts.InputsAndOutputs.hasModuleInterfaceOutputPath()) {
hadAnyError |= printModuleInterfaceIfNeeded(
Instance.getOutputBackend(),
Invocation.getModuleInterfaceOutputPathForWholeModule(),
Invocation.getModuleInterfaceOptions(),
Invocation.getLangOptions(),
Instance.getMainModule());
}
if (opts.InputsAndOutputs.hasPrivateModuleInterfaceOutputPath()) {
// Copy the settings from the module interface to add SPI printing.
ModuleInterfaceOptions privOpts = Invocation.getModuleInterfaceOptions();
privOpts.setInterfaceMode(PrintOptions::InterfaceMode::Private);
privOpts.ModulesToSkipInPublicInterface.clear();
hadAnyError |= printModuleInterfaceIfNeeded(
Instance.getOutputBackend(),
Invocation.getPrivateModuleInterfaceOutputPathForWholeModule(),
privOpts,
Invocation.getLangOptions(),
Instance.getMainModule());
}
if (opts.InputsAndOutputs.hasPackageModuleInterfaceOutputPath()) {
// Copy the settings from the module interface to add package decl printing.
ModuleInterfaceOptions pkgOpts = Invocation.getModuleInterfaceOptions();
pkgOpts.setInterfaceMode(PrintOptions::InterfaceMode::Package);
pkgOpts.ModulesToSkipInPublicInterface.clear();
hadAnyError |= printModuleInterfaceIfNeeded(
Instance.getOutputBackend(),
Invocation.getPackageModuleInterfaceOutputPathForWholeModule(),
pkgOpts,
Invocation.getLangOptions(),
Instance.getMainModule());
}
{
hadAnyError |= writeTBDIfNeeded(Instance);
}
{
hadAnyError |= writeAPIDescriptorIfNeeded(Instance);
}
{
hadAnyError |= writeModuleSemanticInfoIfNeeded(Instance);
}
{
hadAnyError |= emitConstValuesForWholeModuleIfNeeded(Instance);
}
return hadAnyError;
}
static void dumpAPIIfNeeded(const CompilerInstance &Instance) {
using namespace llvm::sys;
const auto &Invocation = Instance.getInvocation();
StringRef OutDir = Invocation.getFrontendOptions().DumpAPIPath;
if (OutDir.empty())
return;
auto getOutPath = [&](SourceFile *SF) -> std::string {
SmallString<256> Path = OutDir;
StringRef Filename = SF->getFilename();
path::append(Path, path::filename(Filename));
return std::string(Path.str());
};
std::unordered_set<std::string> Filenames;
auto dumpFile = [&](SourceFile *SF) -> bool {
SmallString<512> TempBuf;
llvm::raw_svector_ostream TempOS(TempBuf);
PrintOptions PO = PrintOptions::printInterface(
Invocation.getFrontendOptions().PrintFullConvention);
PO.PrintOriginalSourceText = true;
PO.Indent = 2;
PO.PrintAccess = false;
PO.SkipUnderscoredSystemProtocols = true;
SF->print(TempOS, PO);
if (TempOS.str().trim().empty())
return false; // nothing to show.
std::string OutPath = getOutPath(SF);
bool WasInserted = Filenames.insert(OutPath).second;
if (!WasInserted) {
llvm::errs() << "multiple source files ended up with the same dump API "
"filename to write to: " << OutPath << '\n';
return true;
}
std::error_code EC;
llvm::raw_fd_ostream OS(OutPath, EC, fs::FA_Read | fs::FA_Write);
if (EC) {
llvm::errs() << "error opening file '" << OutPath << "': "
<< EC.message() << '\n';
return true;
}
OS << TempOS.str();
return false;
};
std::error_code EC = fs::create_directories(OutDir);
if (EC) {
llvm::errs() << "error creating directory '" << OutDir << "': "
<< EC.message() << '\n';
return;
}
for (auto *FU : Instance.getMainModule()->getFiles()) {
if (auto *SF = dyn_cast<SourceFile>(FU))
if (dumpFile(SF))
return;
}
}
/// Perform any actions that must have access to the ASTContext, and need to be
/// delayed until the Swift compile pipeline has finished. This may be called
/// before or after LLVM depending on when the ASTContext gets freed.
static void performEndOfPipelineActions(CompilerInstance &Instance) {
assert(Instance.hasASTContext());
auto &ctx = Instance.getASTContext();
const auto &Invocation = Instance.getInvocation();
const auto &opts = Invocation.getFrontendOptions();
// If we were asked to print Clang stats, do so.
if (opts.PrintClangStats && ctx.getClangModuleLoader())
ctx.getClangModuleLoader()->printStatistics();
// Report AST stats if needed.
if (auto *stats = ctx.Stats)
countASTStats(*stats, Instance);
if (opts.DumpClangLookupTables && ctx.getClangModuleLoader())
ctx.getClangModuleLoader()->dumpSwiftLookupTables();
// Report mangling stats if there was no error.
if (!ctx.hadError())
Mangle::printManglingStats();
// Make sure we didn't load a module during a parse-only invocation, unless
// it's -emit-imported-modules, which can load modules.
auto action = opts.RequestedAction;
if (FrontendOptions::shouldActionOnlyParse(action) &&
!ctx.getLoadedModules().empty() &&
action != FrontendOptions::ActionType::EmitImportedModules) {
assert(ctx.getNumLoadedModules() == 1 &&
"Loaded a module during parse-only");
assert(ctx.getLoadedModules().begin()->second == Instance.getMainModule());
}
if (!opts.AllowModuleWithCompilerErrors) {
// Verify the AST for all the modules we've loaded.
ctx.verifyAllLoadedModules();
// Verify generic signatures if we've been asked to.
verifyGenericSignaturesIfNeeded(Invocation.getFrontendOptions(), ctx);
}
// Emit any additional outputs that we only need for a successful compilation.
// We don't want to unnecessarily delay getting any errors back to the user.
if (!ctx.hadError()) {
emitLoadedModuleTraceForAllPrimariesIfNeeded(