-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathFrontendTool.cpp
1916 lines (1672 loc) · 73.3 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 - 2018 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 "ImportedModules.h"
#include "ReferenceDependencies.h"
#include "TBD.h"
#include "swift/Subsystems.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExperimentalDependencies.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/AST/TypeRefinementContext.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/Edit.h"
#include "swift/Basic/FileSystem.h"
#include "swift/Basic/JSONSerialization.h"
#include "swift/Basic/LLVMContext.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/PrettyStackTrace.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/Timer.h"
#include "swift/Basic/UUID.h"
#include "swift/Frontend/DiagnosticVerifier.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/Frontend/SerializedDiagnosticConsumer.h"
#include "swift/Frontend/ParseableInterfaceModuleLoader.h"
#include "swift/Frontend/ParseableInterfaceSupport.h"
#include "swift/Immediate/Immediate.h"
#include "swift/Index/IndexRecord.h"
#include "swift/Option/Options.h"
#include "swift/Migrator/FixitFilter.h"
#include "swift/Migrator/Migrator.h"
#include "swift/PrintAsObjC/PrintAsObjC.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Syntax/Serialization/SyntaxSerialization.h"
#include "swift/Syntax/SyntaxNodes.h"
#include "swift/TBDGen/TBDGen.h"
#include "clang/AST/ASTContext.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Option/Option.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Target/TargetMachine.h"
#include <deque>
#include <memory>
#include <unordered_set>
#include <utility>
#if !defined(_MSC_VER) && !defined(__MINGW32__)
#include <unistd.h>
#else
#include <io.h>
#endif
using namespace swift;
static std::string displayName(StringRef MainExecutablePath) {
std::string Name = llvm::sys::path::stem(MainExecutablePath);
Name += " -frontend";
return Name;
}
StringRef
swift::frontend::utils::escapeForMake(StringRef raw,
llvm::SmallVectorImpl<char> &buffer) {
buffer.clear();
// The escaping rules for GNU make are complicated due to the various
// subsitutions and use of the tab in the leading position for recipes.
// Various symbols have significance in different contexts. It is not
// possible to correctly quote all characters in Make (as of 3.7). Match
// gcc and clang's behaviour for the escaping which covers only a subset of
// characters.
for (unsigned I = 0, E = raw.size(); I != E; ++I) {
switch (raw[I]) {
case '#': // Handle '#' the broken GCC way
buffer.push_back('\\');
break;
case ' ':
for (unsigned J = I; J && raw[J - 1] == '\\'; --J)
buffer.push_back('\\');
buffer.push_back('\\');
break;
case '$': // $ is escaped by $
buffer.push_back('$');
break;
}
buffer.push_back(raw[I]);
}
buffer.push_back('\0');
return buffer.data();
}
/// Emits a Make-style dependencies file.
static bool emitMakeDependenciesIfNeeded(DiagnosticEngine &diags,
DependencyTracker *depTracker,
const FrontendOptions &opts,
const InputFile &input) {
const std::string &dependenciesFilePath = input.dependenciesFilePath();
if (dependenciesFilePath.empty())
return false;
std::error_code EC;
llvm::raw_fd_ostream out(dependenciesFilePath, EC, llvm::sys::fs::F_None);
if (out.has_error() || EC) {
diags.diagnose(SourceLoc(), diag::error_opening_output,
dependenciesFilePath, EC.message());
out.clear_error();
return true;
}
llvm::SmallString<256> buffer;
// FIXME: Xcode can't currently handle multiple targets in a single
// dependency line.
opts.forAllOutputPaths(input, [&](const StringRef targetName) {
out << swift::frontend::utils::escapeForMake(targetName, buffer) << " :";
// First include all other files in the module. Make-style dependencies
// need to be conservative!
for (auto const &path :
reversePathSortedFilenames(opts.InputsAndOutputs.getInputFilenames()))
out << ' ' << swift::frontend::utils::escapeForMake(path, buffer);
// Then print dependencies we've picked up during compilation.
for (auto const &path :
reversePathSortedFilenames(depTracker->getDependencies()))
out << ' ' << swift::frontend::utils::escapeForMake(path, buffer);
out << '\n';
});
return false;
}
static bool emitMakeDependenciesIfNeeded(DiagnosticEngine &diags,
DependencyTracker *depTracker,
const FrontendOptions &opts) {
return opts.InputsAndOutputs.forEachInputProducingSupplementaryOutput(
[&](const InputFile &f) -> bool {
return emitMakeDependenciesIfNeeded(diags, depTracker, opts, f);
});
}
namespace {
struct SwiftModuleTraceInfo {
Identifier Name;
std::string Path;
bool IsImportedDirectly;
bool SupportsLibraryEvolution;
};
struct LoadedModuleTraceFormat {
static const unsigned CurrentVersion = 2;
unsigned Version;
Identifier Name;
std::string Arch;
std::vector<SwiftModuleTraceInfo> SwiftModules;
};
}
namespace swift {
namespace json {
template <> struct ObjectTraits<SwiftModuleTraceInfo> {
static void mapping(Output &out, SwiftModuleTraceInfo &contents) {
StringRef name = contents.Name.str();
out.mapRequired("name", name);
out.mapRequired("path", contents.Path);
out.mapRequired("isImportedDirectly", contents.IsImportedDirectly);
out.mapRequired("supportsLibraryEvolution",
contents.SupportsLibraryEvolution);
}
};
// Version notes:
// 1. Keys: name, arch, swiftmodules
// 2. New keys: version, swiftmodulesDetailedInfo
template <> struct ObjectTraits<LoadedModuleTraceFormat> {
static void mapping(Output &out, LoadedModuleTraceFormat &contents) {
out.mapRequired("version", contents.Version);
StringRef name = contents.Name.str();
out.mapRequired("name", name);
out.mapRequired("arch", contents.Arch);
// The 'swiftmodules' key is kept for backwards compatibility.
std::vector<std::string> moduleNames;
for (auto &m : contents.SwiftModules)
moduleNames.push_back(m.Path);
out.mapRequired("swiftmodules", moduleNames);
out.mapRequired("swiftmodulesDetailedInfo", contents.SwiftModules);
}
};
}
}
static bool emitLoadedModuleTraceIfNeeded(ModuleDecl *mainModule,
DependencyTracker *depTracker,
StringRef loadedModuleTracePath) {
if (loadedModuleTracePath.empty())
return false;
std::error_code EC;
llvm::raw_fd_ostream out(loadedModuleTracePath, EC, llvm::sys::fs::F_Append);
ASTContext &ctxt = mainModule->getASTContext();
if (out.has_error() || EC) {
ctxt.Diags.diagnose(SourceLoc(), diag::error_opening_output,
loadedModuleTracePath, EC.message());
out.clear_error();
return true;
}
ModuleDecl::ImportFilter filter = ModuleDecl::ImportFilterKind::Public;
filter |= ModuleDecl::ImportFilterKind::Private;
filter |= ModuleDecl::ImportFilterKind::ImplementationOnly;
SmallVector<ModuleDecl::ImportedModule, 8> imports;
mainModule->getImportedModules(imports, filter);
SmallPtrSet<ModuleDecl *, 8> importedModules;
for (std::pair<ModuleDecl::AccessPathTy, ModuleDecl *> &import : imports)
importedModules.insert(import.second);
llvm::DenseMap<StringRef, ModuleDecl *> pathToModuleDecl;
for (auto &module : ctxt.LoadedModules) {
ModuleDecl *loadedDecl = module.second;
assert(loadedDecl && "Expected loaded module to be non-null.");
assert(!loadedDecl->getModuleFilename().empty()
&& "Don't know how to handle modules with empty names.");
pathToModuleDecl.insert(
std::make_pair(loadedDecl->getModuleFilename(), loadedDecl));
}
std::vector<SwiftModuleTraceInfo> swiftModules;
SmallString<256> buffer;
for (auto &depPath : depTracker->getDependencies()) {
StringRef realDepPath;
// FIXME: appropriate error handling
if (llvm::sys::fs::real_path(depPath, buffer,/*expand_tilde=*/true))
// Couldn't find the canonical path, so let's just assume the old one was
// canonical (enough).
realDepPath = depPath;
else
realDepPath = buffer.str();
// Decide if this is a swiftmodule based on the extension of the raw
// dependency path, as the true file may have a different one.
// For example, this might happen when the canonicalized path points to
// a Content Addressed Storage (CAS) location.
auto moduleFileType =
file_types::lookupTypeForExtension(llvm::sys::path::extension(depPath));
if (moduleFileType == file_types::TY_SwiftModuleFile
|| moduleFileType == file_types::TY_SwiftParseableInterfaceFile) {
auto dep = pathToModuleDecl.find(depPath);
assert(dep != pathToModuleDecl.end()
&& "Dependency must've been loaded.");
ModuleDecl *depMod = dep->second;
swiftModules.push_back({
/*Name=*/
depMod->getName(),
/*Path=*/
realDepPath,
// TODO: There is an edge case which is not handled here.
// When we build a framework using -import-underlying-module, or an
// app/test using -import-objc-header, we should look at the direct
// imports of the bridging modules, and mark those as our direct
// imports.
/*IsImportedDirectly=*/
importedModules.find(depMod) != importedModules.end(),
/*SupportsLibraryEvolution=*/
depMod->isResilient()
});
}
}
// Almost a re-implementation of reversePathSortedFilenames :(.
std::sort(
swiftModules.begin(), swiftModules.end(),
[](const SwiftModuleTraceInfo &m1, const SwiftModuleTraceInfo &m2) -> bool {
return std::lexicographical_compare(
m1.Path.rbegin(), m1.Path.rend(),
m2.Path.rbegin(), m2.Path.rend());
});
LoadedModuleTraceFormat trace = {
/*version=*/LoadedModuleTraceFormat::CurrentVersion,
/*name=*/mainModule->getName(),
/*arch=*/ctxt.LangOpts.Target.getArchName(),
swiftModules
};
// raw_fd_ostream is unbuffered, and we may have multiple processes writing,
// so first write the whole thing into memory and dump out that buffer to the
// file.
std::string stringBuffer;
{
llvm::raw_string_ostream memoryBuffer(stringBuffer);
json::Output jsonOutput(memoryBuffer, /*UserInfo=*/{},
/*PrettyPrint=*/false);
json::jsonize(jsonOutput, trace, /*Required=*/true);
}
stringBuffer += "\n";
out << stringBuffer;
return true;
}
static bool
emitLoadedModuleTraceForAllPrimariesIfNeeded(ModuleDecl *mainModule,
DependencyTracker *depTracker,
const FrontendOptions &opts) {
return opts.InputsAndOutputs.forEachInputProducingSupplementaryOutput(
[&](const InputFile &input) -> bool {
return emitLoadedModuleTraceIfNeeded(
mainModule, depTracker, input.loadedModuleTracePath());
});
}
/// Gets an output stream for the provided output filename, or diagnoses to the
/// provided AST Context and returns null if there was an error getting the
/// stream.
static std::unique_ptr<llvm::raw_fd_ostream>
getFileOutputStream(StringRef OutputFilename, ASTContext &Ctx) {
std::error_code errorCode;
auto os = llvm::make_unique<llvm::raw_fd_ostream>(
OutputFilename, errorCode, llvm::sys::fs::F_None);
if (errorCode) {
Ctx.Diags.diagnose(SourceLoc(), diag::error_opening_output,
OutputFilename, errorCode.message());
return nullptr;
}
return os;
}
/// Writes the Syntax tree to the given file
static bool emitSyntax(SourceFile *SF, LangOptions &LangOpts,
SourceManager &SM, StringRef OutputFilename) {
auto bufferID = SF->getBufferID();
assert(bufferID && "frontend should have a buffer ID "
"for the main source file");
(void)bufferID;
auto os = getFileOutputStream(OutputFilename, SF->getASTContext());
if (!os) return true;
json::Output jsonOut(*os, /*UserInfo=*/{}, /*PrettyPrint=*/false);
auto Root = SF->getSyntaxRoot().getRaw();
jsonOut << *Root;
*os << "\n";
return false;
}
/// Writes SIL out to the given file.
static bool writeSIL(SILModule &SM, ModuleDecl *M, bool EmitVerboseSIL,
StringRef OutputFilename, bool SortSIL) {
auto OS = getFileOutputStream(OutputFilename, M->getASTContext());
if (!OS) return true;
SM.print(*OS, EmitVerboseSIL, M, SortSIL);
return false;
}
static bool writeSIL(SILModule &SM, const PrimarySpecificPaths &PSPs,
CompilerInstance &Instance,
CompilerInvocation &Invocation) {
const FrontendOptions &opts = Invocation.getFrontendOptions();
return writeSIL(SM, Instance.getMainModule(), opts.EmitVerboseSIL,
PSPs.OutputFilename, opts.EmitSortedSIL);
}
/// Prints the Objective-C "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::printAsObjC
static bool printAsObjCIfNeeded(StringRef outputPath, ModuleDecl *M,
StringRef bridgingHeader, bool moduleIsPublic) {
if (outputPath.empty())
return false;
return withOutputFile(M->getDiags(), outputPath,
[&](raw_ostream &out) -> bool {
auto requiredAccess = moduleIsPublic ? AccessLevel::Public
: AccessLevel::Internal;
return printAsObjC(out, M, bridgingHeader, requiredAccess);
});
}
/// Prints the stable parseable 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::emitParseableInterface
static bool
printParseableInterfaceIfNeeded(StringRef outputPath,
ParseableInterfaceOptions 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 withOutputFile(diags, outputPath,
[M, Opts](raw_ostream &out) -> bool {
return swift::emitParseableInterface(out, Opts, M);
});
}
/// Returns the OutputKind for the given Action.
static IRGenOutputKind getOutputKind(FrontendOptions::ActionType Action) {
switch (Action) {
case FrontendOptions::ActionType::EmitIR:
return IRGenOutputKind::LLVMAssembly;
case FrontendOptions::ActionType::EmitBC:
return IRGenOutputKind::LLVMBitcode;
case FrontendOptions::ActionType::EmitAssembly:
return IRGenOutputKind::NativeAssembly;
case FrontendOptions::ActionType::EmitObject:
return IRGenOutputKind::ObjectFile;
case FrontendOptions::ActionType::Immediate:
return IRGenOutputKind::Module;
default:
llvm_unreachable("Unknown ActionType which requires IRGen");
return IRGenOutputKind::ObjectFile;
}
}
namespace {
/// If there is an error with fixits it writes the fixits as edits in json
/// format.
class JSONFixitWriter
: public DiagnosticConsumer, public migrator::FixitFilter {
std::string FixitsOutputPath;
std::unique_ptr<llvm::raw_ostream> OSPtr;
bool FixitAll;
std::vector<SingleEdit> AllEdits;
public:
JSONFixitWriter(std::string fixitsOutputPath,
const DiagnosticOptions &DiagOpts)
: FixitsOutputPath(fixitsOutputPath),
FixitAll(DiagOpts.FixitCodeForAllDiagnostics) {}
private:
void
handleDiagnostic(SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef FormatString,
ArrayRef<DiagnosticArgument> FormatArgs,
const DiagnosticInfo &Info,
const SourceLoc bufferIndirectlyCausingDiagnostic) override {
if (!(FixitAll || shouldTakeFixit(Kind, Info)))
return;
for (const auto &Fix : Info.FixIts) {
AllEdits.push_back({SM, Fix.getRange(), Fix.getText()});
}
}
bool finishProcessing() override {
std::error_code EC;
std::unique_ptr<llvm::raw_fd_ostream> OS;
OS.reset(new llvm::raw_fd_ostream(FixitsOutputPath,
EC,
llvm::sys::fs::F_None));
if (EC) {
// Create a temporary diagnostics engine to print the error to stderr.
SourceManager dummyMgr;
DiagnosticEngine DE(dummyMgr);
PrintingDiagnosticConsumer PDC;
DE.addConsumer(PDC);
DE.diagnose(SourceLoc(), diag::cannot_open_file,
FixitsOutputPath, EC.message());
return true;
}
swift::writeEditsInJson(llvm::makeArrayRef(AllEdits), *OS);
return false;
}
};
} // anonymous namespace
// 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;
}
/// \return true on error.
static bool emitIndexDataIfNeeded(SourceFile *PrimarySourceFile,
const CompilerInvocation &Invocation,
CompilerInstance &Instance);
static void countStatsOfSourceFile(UnifiedStatsReporter &Stats,
CompilerInstance &Instance,
SourceFile *SF) {
auto &C = Stats.getFrontendCounters();
auto &SM = Instance.getSourceMgr();
C.NumDecls += SF->Decls.size();
C.NumLocalTypeDecls += SF->LocalTypeDecls.size();
C.NumObjCMethods += SF->ObjCMethods.size();
C.NumInfixOperators += SF->InfixOperators.size();
C.NumPostfixOperators += SF->PostfixOperators.size();
C.NumPrefixOperators += SF->PrefixOperators.size();
C.NumPrecedenceGroups += SF->PrecedenceGroups.size();
auto bufID = SF->getBufferID();
if (bufID.hasValue()) {
C.NumSourceLines +=
SM.getEntireTextForBuffer(bufID.getValue()).count('\n');
}
}
static void countStatsPostSema(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.LoadedModules.size();
if (auto *D = Instance.getDependencyTracker()) {
C.NumDependencies = D->getDependencies().size();
}
for (auto SF : Instance.getPrimarySourceFiles()) {
if (auto *R = SF->getReferencedNameTracker()) {
C.NumReferencedTopLevelNames += R->getTopLevelNames().size();
C.NumReferencedDynamicNames += R->getDynamicLookupNames().size();
C.NumReferencedMemberNames += R->getUsedMembers().size();
}
}
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.getVTableList().size();
C.NumSILGenWitnessTables += Module.getWitnessTableList().size();
C.NumSILGenDefaultWitnessTables += Module.getDefaultWitnessTableList().size();
C.NumSILGenGlobalVariables += Module.getSILGlobalList().size();
}
static std::unique_ptr<llvm::raw_fd_ostream>
createOptRecordFile(StringRef Filename, DiagnosticEngine &DE) {
if (Filename.empty())
return nullptr;
std::error_code EC;
auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC,
llvm::sys::fs::F_None);
if (EC) {
DE.diagnose(SourceLoc(), diag::cannot_open_file, Filename, EC.message());
return nullptr;
}
return File;
}
struct PostSILGenInputs {
std::unique_ptr<SILModule> TheSILModule;
bool ASTGuaranteedToCorrespondToSIL;
ModuleOrSourceFile ModuleOrPrimarySourceFile;
PrimarySpecificPaths PSPs;
};
static bool precompileBridgingHeader(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
auto clangImporter = static_cast<ClangImporter *>(
Instance.getASTContext().getClangModuleLoader());
auto &ImporterOpts = Invocation.getClangImporterOptions();
auto &PCHOutDir = ImporterOpts.PrecompiledHeaderOutputDir;
if (!PCHOutDir.empty()) {
ImporterOpts.BridgingHeader =
Invocation.getFrontendOptions()
.InputsAndOutputs.getFilenameOfFirstInput();
// Create or validate a persistent PCH.
auto SwiftPCHHash = Invocation.getPCHHash();
auto PCH = clangImporter->getOrCreatePCH(ImporterOpts, SwiftPCHHash);
return !PCH.hasValue();
}
return clangImporter->emitBridgingPCH(
Invocation.getFrontendOptions()
.InputsAndOutputs.getFilenameOfFirstInput(),
Invocation.getFrontendOptions()
.InputsAndOutputs.getSingleOutputFilename());
}
static bool buildModuleFromParseableInterface(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
const FrontendOptions &FEOpts = Invocation.getFrontendOptions();
assert(FEOpts.InputsAndOutputs.hasSingleInput());
StringRef InputPath = FEOpts.InputsAndOutputs.getFilenameOfFirstInput();
StringRef PrebuiltCachePath = FEOpts.PrebuiltModuleCachePath;
return ParseableInterfaceModuleLoader::buildSwiftModuleFromSwiftInterface(
Instance.getSourceMgr(), Instance.getDiags(),
Invocation.getSearchPathOptions(), Invocation.getLangOptions(),
Invocation.getClangModuleCachePath(),
PrebuiltCachePath, Invocation.getModuleName(), InputPath,
Invocation.getOutputFilename(),
FEOpts.SerializeModuleInterfaceDependencyHashes,
FEOpts.TrackSystemDeps, FEOpts.RemarkOnRebuildFromModuleInterface);
}
static bool compileLLVMIR(CompilerInvocation &Invocation,
CompilerInstance &Instance,
UnifiedStatsReporter *Stats) {
auto &LLVMContext = getGlobalLLVMContext();
// Load in bitcode file.
assert(Invocation.getFrontendOptions().InputsAndOutputs.hasSingleInput() &&
"We expect a single input for bitcode input!");
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
swift::vfs::getFileOrSTDIN(Instance.getFileSystem(),
Invocation.getFrontendOptions()
.InputsAndOutputs.getFilenameOfFirstInput());
if (!FileBufOrErr) {
Instance.getASTContext().Diags.diagnose(
SourceLoc(), diag::error_open_input_file,
Invocation.getFrontendOptions()
.InputsAndOutputs.getFilenameOfFirstInput(),
FileBufOrErr.getError().message());
return true;
}
llvm::MemoryBuffer *MainFile = FileBufOrErr.get().get();
llvm::SMDiagnostic Err;
std::unique_ptr<llvm::Module> Module =
llvm::parseIR(MainFile->getMemBufferRef(), Err, LLVMContext);
if (!Module) {
// TODO: Translate from the diagnostic info to the SourceManager location
// if available.
Instance.getASTContext().Diags.diagnose(
SourceLoc(), diag::error_parse_input_file,
Invocation.getFrontendOptions()
.InputsAndOutputs.getFilenameOfFirstInput(),
Err.getMessage());
return true;
}
IRGenOptions &IRGenOpts = Invocation.getIRGenOptions();
// TODO: remove once the frontend understands what action it should perform
IRGenOpts.OutputKind =
getOutputKind(Invocation.getFrontendOptions().RequestedAction);
return performLLVM(IRGenOpts, Instance.getASTContext(), Module.get(),
Invocation.getFrontendOptions()
.InputsAndOutputs.getSingleOutputFilename(),
Stats);
}
static void verifyGenericSignaturesIfNeeded(CompilerInvocation &Invocation,
ASTContext &Context) {
auto verifyGenericSignaturesInModule =
Invocation.getFrontendOptions().VerifyGenericSignaturesInModule;
if (verifyGenericSignaturesInModule.empty())
return;
if (auto module = Context.getModuleByName(verifyGenericSignaturesInModule))
GenericSignatureBuilder::verifyGenericSignaturesInModule(module);
}
static void dumpAndPrintScopeMap(CompilerInvocation &Invocation,
CompilerInstance &Instance, SourceFile *SF) {
const ASTScope &scope = SF->getScope();
if (Invocation.getFrontendOptions().DumpScopeMapLocations.empty()) {
llvm::errs() << "***Complete scope map***\n";
scope.print(llvm::errs());
return;
}
// Probe each of the locations, and dump what we find.
for (auto lineColumn :
Invocation.getFrontendOptions().DumpScopeMapLocations)
scope.dumpOneScopeMapLocation(lineColumn);
}
static SourceFile *getPrimaryOrMainSourceFile(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
SourceFile *SF = Instance.getPrimarySourceFile();
if (!SF) {
SourceFileKind Kind = Invocation.getSourceFileKind();
SF = &Instance.getMainModule()->getMainSourceFile(Kind);
}
return SF;
}
/// Dumps the AST of all available primary source files. If corresponding output
/// files were specified, use them; otherwise, dump the AST to stdout.
static void dumpAST(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
// FIXME: WMO doesn't use the notion of primary files, so this doesn't do the
// right thing. Perhaps it'd be best to ignore WMO when dumping the AST, just
// like WMO ignores `-incremental`.
auto primaryFiles = Instance.getPrimarySourceFiles();
if (!primaryFiles.empty()) {
for (SourceFile *sourceFile: primaryFiles) {
auto PSPs = Instance.getPrimarySpecificPathsForSourceFile(*sourceFile);
auto OutputFilename = PSPs.OutputFilename;
auto OS = getFileOutputStream(OutputFilename, Instance.getASTContext());
sourceFile->dump(*OS);
}
} else {
// Some invocations don't have primary files. In that case, we default to
// looking for the main file and dumping it to `stdout`.
getPrimaryOrMainSourceFile(Invocation, Instance)->dump(llvm::outs());
}
}
/// We may have been told to dump the AST (either after parsing or
/// type-checking, which is already differentiated in
/// CompilerInstance::performSema()), so dump or print the main source file and
/// return.
static Optional<bool> dumpASTIfNeeded(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
FrontendOptions &opts = Invocation.getFrontendOptions();
FrontendOptions::ActionType Action = opts.RequestedAction;
ASTContext &Context = Instance.getASTContext();
switch (Action) {
default:
return None;
case FrontendOptions::ActionType::PrintAST:
getPrimaryOrMainSourceFile(Invocation, Instance)
->print(llvm::outs(), PrintOptions::printEverything());
break;
case FrontendOptions::ActionType::DumpScopeMaps:
dumpAndPrintScopeMap(Invocation, Instance,
getPrimaryOrMainSourceFile(Invocation, Instance));
break;
case FrontendOptions::ActionType::DumpTypeRefinementContexts:
getPrimaryOrMainSourceFile(Invocation, Instance)
->getTypeRefinementContext()
->dump(llvm::errs(), Context.SourceMgr);
break;
case FrontendOptions::ActionType::DumpInterfaceHash:
getPrimaryOrMainSourceFile(Invocation, Instance)
->dumpInterfaceHash(llvm::errs());
break;
case FrontendOptions::ActionType::EmitSyntax:
emitSyntax(getPrimaryOrMainSourceFile(Invocation, Instance),
Invocation.getLangOptions(), Instance.getSourceMgr(),
opts.InputsAndOutputs.getSingleOutputFilename());
break;
case FrontendOptions::ActionType::DumpParse:
case FrontendOptions::ActionType::DumpAST:
dumpAST(Invocation, Instance);
break;
case FrontendOptions::ActionType::EmitImportedModules:
emitImportedModules(Context, Instance.getMainModule(), opts);
break;
}
return Context.hadError();
}
static void emitReferenceDependenciesForAllPrimaryInputsIfNeeded(
CompilerInvocation &Invocation, CompilerInstance &Instance) {
if (Invocation.getFrontendOptions()
.InputsAndOutputs.hasReferenceDependenciesPath() &&
Instance.getPrimarySourceFiles().empty()) {
Instance.getASTContext().Diags.diagnose(
SourceLoc(), diag::emit_reference_dependencies_without_primary_file);
return;
}
for (auto *SF : Instance.getPrimarySourceFiles()) {
const std::string &referenceDependenciesFilePath =
Invocation.getReferenceDependenciesFilePathForPrimary(
SF->getFilename());
if (!referenceDependenciesFilePath.empty()) {
if (Invocation.getLangOptions().EnableExperimentalDependencies)
(void)experimental_dependencies::emitReferenceDependencies(
Instance.getASTContext().Diags, SF,
*Instance.getDependencyTracker(), referenceDependenciesFilePath);
else
(void)emitReferenceDependencies(Instance.getASTContext().Diags, SF,
*Instance.getDependencyTracker(),
referenceDependenciesFilePath);
}
}
}
static bool writeTBDIfNeeded(CompilerInvocation &Invocation,
CompilerInstance &Instance) {
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;
}
const std::string &TBDPath = Invocation.getTBDPathForWholeModule();
return writeTBD(Instance.getMainModule(), TBDPath, tbdOpts);
}
static std::deque<PostSILGenInputs>
generateSILModules(CompilerInvocation &Invocation, CompilerInstance &Instance) {
auto mod = Instance.getMainModule();
if (auto SM = Instance.takeSILModule()) {
std::deque<PostSILGenInputs> PSGIs;
const PrimarySpecificPaths PSPs =
Instance.getPrimarySpecificPathsForAtMostOnePrimary();
PSGIs.push_back(PostSILGenInputs{std::move(SM), false, mod, PSPs});
return PSGIs;
}
SILOptions &SILOpts = Invocation.getSILOptions();
FrontendOptions &opts = Invocation.getFrontendOptions();
auto fileIsSIB = [](const FileUnit *File) -> bool {
auto SASTF = dyn_cast<SerializedASTFile>(File);
return SASTF && SASTF->isSIB();
};
if (!opts.InputsAndOutputs.hasPrimaryInputs()) {
// If there are no primary inputs the compiler is in WMO mode and builds one
// SILModule for the entire module.
auto SM = performSILGeneration(mod, SILOpts);
std::deque<PostSILGenInputs> PSGIs;
const PrimarySpecificPaths PSPs =
Instance.getPrimarySpecificPathsForWholeModuleOptimizationMode();
PSGIs.push_back(PostSILGenInputs{
std::move(SM), llvm::none_of(mod->getFiles(), fileIsSIB), mod, PSPs});
return PSGIs;
}
// 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.
std::deque<PostSILGenInputs> PSGIs;
for (auto *PrimaryFile : Instance.getPrimarySourceFiles()) {
auto SM = performSILGeneration(*PrimaryFile, SILOpts);
const PrimarySpecificPaths PSPs =
Instance.getPrimarySpecificPathsForSourceFile(*PrimaryFile);
PSGIs.push_back(PostSILGenInputs{std::move(SM), true, PrimaryFile, PSPs});
}
if (!PSGIs.empty())
return PSGIs;
// If there are primary inputs but no primary _source files_, there might be
// a primary serialized input.
for (FileUnit *fileUnit : mod->getFiles()) {
if (auto SASTF = dyn_cast<SerializedASTFile>(fileUnit))
if (Invocation.getFrontendOptions().InputsAndOutputs.isInputPrimary(
SASTF->getFilename())) {
assert(PSGIs.empty() && "Can only handle one primary AST input");
auto SM = performSILGeneration(*SASTF, SILOpts);
const PrimarySpecificPaths &PSPs =
Instance.getPrimarySpecificPathsForPrimary(SASTF->getFilename());
PSGIs.push_back(
PostSILGenInputs{std::move(SM), !fileIsSIB(SASTF), mod, PSPs});
}
}
return PSGIs;
}
/// Emits index data for all primary inputs, or the main module.
static bool
emitIndexData(CompilerInvocation &Invocation, CompilerInstance &Instance) {
bool hadEmitIndexDataError = false;
if (Instance.getPrimarySourceFiles().empty())
return emitIndexDataIfNeeded(nullptr, Invocation, Instance);
for (SourceFile *SF : Instance.getPrimarySourceFiles())
hadEmitIndexDataError = emitIndexDataIfNeeded(SF, Invocation, Instance) ||
hadEmitIndexDataError;
return hadEmitIndexDataError;
}
/// Emits all "one-per-module" supplementary outputs that don't depend on
/// anything past type-checking.
///
/// These are extracted out so that they can be invoked early when using
/// `-typecheck`, but skipped for any mode that runs SIL diagnostics if there's
/// an error found there (to get those diagnostics back to the user faster).
static bool emitAnyWholeModulePostTypeCheckSupplementaryOutputs(
CompilerInstance &Instance, CompilerInvocation &Invocation,
bool moduleIsPublic) {
const FrontendOptions &opts = Invocation.getFrontendOptions();
// 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 (opts.InputsAndOutputs.hasObjCHeaderOutputPath()) {
hadAnyError |= printAsObjCIfNeeded(
Invocation.getObjCHeaderOutputPathForAtMostOnePrimary(),
Instance.getMainModule(), opts.ImplicitObjCHeaderPath, moduleIsPublic);
}
if (opts.InputsAndOutputs.hasParseableInterfaceOutputPath()) {
hadAnyError |= printParseableInterfaceIfNeeded(
Invocation.getParseableInterfaceOutputPathForWholeModule(),
Invocation.getParseableInterfaceOptions(),
Invocation.getLangOptions(),
Instance.getMainModule());
}
{
hadAnyError |= writeTBDIfNeeded(Invocation, Instance);
}
return hadAnyError;
}
static bool performCompileStepsPostSILGen(
CompilerInstance &Instance, CompilerInvocation &Invocation,
std::unique_ptr<SILModule> SM, bool astGuaranteedToCorrespondToSIL,
ModuleOrSourceFile MSF, const PrimarySpecificPaths &PSPs,