-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCompilerInstance.cpp
1958 lines (1709 loc) · 74.4 KB
/
CompilerInstance.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
//===--- CompilerInstance.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/CompilerInstance.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/MemoryBufferCache.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/Config/config.h"
#include "clang/Frontend/ChainedDiagnosticConsumer.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/LogDiagnosticPrinter.h"
#include "clang/Frontend/SerializedDiagnosticPrinter.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/Utils.h"
#include "clang/Frontend/VerifyDiagnosticConsumer.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/PTHManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/GlobalModuleIndex.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/LockFileManager.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <sys/stat.h>
#include <system_error>
#include <time.h>
#include <utility>
using namespace clang;
CompilerInstance::CompilerInstance(
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
MemoryBufferCache *SharedPCMCache)
: ModuleLoader(/* BuildingModule = */ SharedPCMCache),
Invocation(new CompilerInvocation()),
PCMCache(SharedPCMCache ? SharedPCMCache : new MemoryBufferCache),
ThePCHContainerOperations(std::move(PCHContainerOps)) {
// Don't allow this to invalidate buffers in use by others.
if (SharedPCMCache)
getPCMCache().finalizeCurrentBuffers();
}
CompilerInstance::~CompilerInstance() {
assert(OutputFiles.empty() && "Still output files in flight?");
}
void CompilerInstance::setInvocation(
std::shared_ptr<CompilerInvocation> Value) {
Invocation = std::move(Value);
}
bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
return (BuildGlobalModuleIndex ||
(ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
getFrontendOpts().GenerateGlobalModuleIndex)) &&
!ModuleBuildFailed;
}
void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
Diagnostics = Value;
}
void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
void CompilerInstance::setFileManager(FileManager *Value) {
FileMgr = Value;
if (Value)
VirtualFileSystem = Value->getVirtualFileSystem();
else
VirtualFileSystem.reset();
}
void CompilerInstance::setSourceManager(SourceManager *Value) {
SourceMgr = Value;
}
void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
PP = std::move(Value);
}
void CompilerInstance::setASTContext(ASTContext *Value) {
Context = Value;
if (Context && Consumer)
getASTConsumer().Initialize(getASTContext());
}
void CompilerInstance::setSema(Sema *S) {
TheSema.reset(S);
}
void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
Consumer = std::move(Value);
if (Context && Consumer)
getASTConsumer().Initialize(getASTContext());
}
void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
CompletionConsumer.reset(Value);
}
std::unique_ptr<Sema> CompilerInstance::takeSema() {
return std::move(TheSema);
}
IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
return ModuleManager;
}
void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
assert(PCMCache.get() == &Reader->getModuleManager().getPCMCache() &&
"Expected ASTReader to use the same PCM cache");
ModuleManager = std::move(Reader);
}
std::shared_ptr<ModuleDependencyCollector>
CompilerInstance::getModuleDepCollector() const {
return ModuleDepCollector;
}
void CompilerInstance::setModuleDepCollector(
std::shared_ptr<ModuleDependencyCollector> Collector) {
ModuleDepCollector = std::move(Collector);
}
static void collectHeaderMaps(const HeaderSearch &HS,
std::shared_ptr<ModuleDependencyCollector> MDC) {
SmallVector<std::string, 4> HeaderMapFileNames;
HS.getHeaderMapFileNames(HeaderMapFileNames);
for (auto &Name : HeaderMapFileNames)
MDC->addFile(Name);
}
static void collectIncludePCH(CompilerInstance &CI,
std::shared_ptr<ModuleDependencyCollector> MDC) {
const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
if (PPOpts.ImplicitPCHInclude.empty())
return;
StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
FileManager &FileMgr = CI.getFileManager();
const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude);
if (!PCHDir) {
MDC->addFile(PCHInclude);
return;
}
std::error_code EC;
SmallString<128> DirNative;
llvm::sys::path::native(PCHDir->getName(), DirNative);
vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
SimpleASTReaderListener Validator(CI.getPreprocessor());
for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
Dir != DirEnd && !EC; Dir.increment(EC)) {
// Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
// used here since we're not interested in validating the PCH at this time,
// but only to check whether this is a file containing an AST.
if (!ASTReader::readASTFileControlBlock(
Dir->getName(), FileMgr, CI.getPCHContainerReader(),
/*FindModuleFileExtensions=*/false, Validator,
/*ValidateDiagnosticOptions=*/false))
MDC->addFile(Dir->getName());
}
}
static void collectVFSEntries(CompilerInstance &CI,
std::shared_ptr<ModuleDependencyCollector> MDC) {
if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
return;
// Collect all VFS found.
SmallVector<vfs::YAMLVFSEntry, 16> VFSEntries;
for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
llvm::MemoryBuffer::getFile(VFSFile);
if (!Buffer)
return;
vfs::collectVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr,
VFSFile, VFSEntries);
}
for (auto &E : VFSEntries)
MDC->addFile(E.VPath, E.RPath);
}
// Diagnostics
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
const CodeGenOptions *CodeGenOpts,
DiagnosticsEngine &Diags) {
std::error_code EC;
std::unique_ptr<raw_ostream> StreamOwner;
raw_ostream *OS = &llvm::errs();
if (DiagOpts->DiagnosticLogFile != "-") {
// Create the output stream.
auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
DiagOpts->DiagnosticLogFile, EC,
llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
if (EC) {
Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
<< DiagOpts->DiagnosticLogFile << EC.message();
} else {
FileOS->SetUnbuffered();
OS = FileOS.get();
StreamOwner = std::move(FileOS);
}
}
// Chain in the diagnostic client which will log the diagnostics.
auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
std::move(StreamOwner));
if (CodeGenOpts)
Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
assert(Diags.ownsClient());
Diags.setClient(
new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
}
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
DiagnosticsEngine &Diags,
StringRef OutputFile) {
auto SerializedConsumer =
clang::serialized_diags::create(OutputFile, DiagOpts);
if (Diags.ownsClient()) {
Diags.setClient(new ChainedDiagnosticConsumer(
Diags.takeClient(), std::move(SerializedConsumer)));
} else {
Diags.setClient(new ChainedDiagnosticConsumer(
Diags.getClient(), std::move(SerializedConsumer)));
}
}
void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
bool ShouldOwnClient) {
Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
ShouldOwnClient, &getCodeGenOpts());
}
IntrusiveRefCntPtr<DiagnosticsEngine>
CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
DiagnosticConsumer *Client,
bool ShouldOwnClient,
const CodeGenOptions *CodeGenOpts) {
IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine>
Diags(new DiagnosticsEngine(DiagID, Opts));
// Create the diagnostic client for reporting errors or for
// implementing -verify.
if (Client) {
Diags->setClient(Client, ShouldOwnClient);
} else
Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
// Chain in -verify checker, if requested.
if (Opts->VerifyDiagnostics)
Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
// Chain in -diagnostic-log-file dumper, if requested.
if (!Opts->DiagnosticLogFile.empty())
SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
if (!Opts->DiagnosticSerializationFile.empty())
SetupSerializedDiagnostics(Opts, *Diags,
Opts->DiagnosticSerializationFile);
// Configure our handling of diagnostics.
ProcessWarningOptions(*Diags, *Opts);
return Diags;
}
// File Manager
void CompilerInstance::createFileManager() {
if (!hasVirtualFileSystem()) {
// TODO: choose the virtual file system based on the CompilerInvocation.
setVirtualFileSystem(vfs::getRealFileSystem());
}
FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
}
// Source Manager
void CompilerInstance::createSourceManager(FileManager &FileMgr) {
SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
}
// Initialize the remapping of files to alternative contents, e.g.,
// those specified through other files.
static void InitializeFileRemapping(DiagnosticsEngine &Diags,
SourceManager &SourceMgr,
FileManager &FileMgr,
const PreprocessorOptions &InitOpts) {
// Remap files in the source manager (with buffers).
for (const auto &RB : InitOpts.RemappedFileBuffers) {
// Create the file entry for the file that we're mapping from.
const FileEntry *FromFile =
FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
if (!InitOpts.RetainRemappedFileBuffers)
delete RB.second;
continue;
}
// Override the contents of the "from" file with the contents of
// the "to" file.
SourceMgr.overrideFileContents(FromFile, RB.second,
InitOpts.RetainRemappedFileBuffers);
}
// Remap files in the source manager (with other files).
for (const auto &RF : InitOpts.RemappedFiles) {
// Find the file that we're mapping to.
const FileEntry *ToFile = FileMgr.getFile(RF.second);
if (!ToFile) {
Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
continue;
}
// Create the file entry for the file that we're mapping from.
const FileEntry *FromFile =
FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
if (!FromFile) {
Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
continue;
}
// Override the contents of the "from" file with the contents of
// the "to" file.
SourceMgr.overrideFileContents(FromFile, ToFile);
}
SourceMgr.setOverridenFilesKeepOriginalName(
InitOpts.RemappedFilesKeepOriginalName);
}
// Preprocessor
void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
const PreprocessorOptions &PPOpts = getPreprocessorOpts();
// Create a PTH manager if we are using some form of a token cache.
PTHManager *PTHMgr = nullptr;
if (!PPOpts.TokenCache.empty())
PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
// Create the Preprocessor.
HeaderSearch *HeaderInfo =
new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(),
getDiagnostics(), getLangOpts(), &getTarget());
PP = std::make_shared<Preprocessor>(
Invocation->getPreprocessorOptsPtr(), getDiagnostics(), getLangOpts(),
getSourceManager(), getPCMCache(), *HeaderInfo, *this, PTHMgr,
/*OwnsHeaderSearch=*/true, TUKind);
PP->Initialize(getTarget(), getAuxTarget());
// Note that this is different then passing PTHMgr to Preprocessor's ctor.
// That argument is used as the IdentifierInfoLookup argument to
// IdentifierTable's ctor.
if (PTHMgr) {
PTHMgr->setPreprocessor(&*PP);
PP->setPTHManager(PTHMgr);
}
if (PPOpts.DetailedRecord)
PP->createPreprocessingRecord();
// Apply remappings to the source manager.
InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
PP->getFileManager(), PPOpts);
// Predefine macros and configure the preprocessor.
InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
getFrontendOpts());
// Initialize the header search object. In CUDA compilations, we use the aux
// triple (the host triple) to initialize our header search, since we need to
// find the host headers in order to compile the CUDA code.
const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
PP->getAuxTargetInfo())
HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
PP->getLangOpts(), *HeaderSearchTriple);
PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
// Handle generating dependencies, if requested.
const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
if (!DepOpts.OutputFile.empty())
TheDependencyFileGenerator.reset(
DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
if (!DepOpts.DOTOutputFile.empty())
AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
getHeaderSearchOpts().Sysroot);
// If we don't have a collector, but we are collecting module dependencies,
// then we're the top level compiler instance and need to create one.
if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
DepOpts.ModuleDependencyOutputDir);
}
// If there is a module dep collector, register with other dep collectors
// and also (a) collect header maps and (b) TODO: input vfs overlay files.
if (ModuleDepCollector) {
addDependencyCollector(ModuleDepCollector);
collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector);
collectIncludePCH(*this, ModuleDepCollector);
collectVFSEntries(*this, ModuleDepCollector);
}
for (auto &Listener : DependencyCollectors)
Listener->attachToPreprocessor(*PP);
// Handle generating header include information, if requested.
if (DepOpts.ShowHeaderIncludes)
AttachHeaderIncludeGen(*PP, DepOpts);
if (!DepOpts.HeaderIncludeOutputFile.empty()) {
StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
if (OutputPath == "-")
OutputPath = "";
AttachHeaderIncludeGen(*PP, DepOpts,
/*ShowAllHeaders=*/true, OutputPath,
/*ShowDepth=*/false);
}
if (DepOpts.PrintShowIncludes) {
AttachHeaderIncludeGen(*PP, DepOpts,
/*ShowAllHeaders=*/true, /*OutputPath=*/"",
/*ShowDepth=*/true, /*MSStyle=*/true);
}
}
std::string CompilerInstance::getSpecificModuleCachePath() {
// Set up the module path, including the hash for the
// module-creation options.
SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
llvm::sys::path::append(SpecificModuleCache,
getInvocation().getModuleHash());
return SpecificModuleCache.str();
}
// ASTContext
void CompilerInstance::createASTContext() {
Preprocessor &PP = getPreprocessor();
auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
PP.getIdentifierTable(), PP.getSelectorTable(),
PP.getBuiltinInfo());
Context->InitBuiltinTypes(getTarget(), getAuxTarget());
setASTContext(Context);
}
// ExternalASTSource
void CompilerInstance::createPCHExternalASTSource(
StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
void *DeserializationListener, bool OwnDeserializationListener) {
bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
ModuleManager = createPCHExternalASTSource(
Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
getPCHContainerReader(),
getFrontendOpts().ModuleFileExtensions,
TheDependencyFileGenerator.get(),
DependencyCollectors,
DeserializationListener,
OwnDeserializationListener, Preamble,
getFrontendOpts().UseGlobalModuleIndex);
}
IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
const PCHContainerReader &PCHContainerRdr,
ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
DependencyFileGenerator *DependencyFile,
ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
void *DeserializationListener, bool OwnDeserializationListener,
bool Preamble, bool UseGlobalModuleIndex) {
HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
PP, Context, PCHContainerRdr, Extensions,
Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
// We need the external source to be set up before we read the AST, because
// eagerly-deserialized declarations may use it.
Context.setExternalSource(Reader.get());
Reader->setDeserializationListener(
static_cast<ASTDeserializationListener *>(DeserializationListener),
/*TakeOwnership=*/OwnDeserializationListener);
if (DependencyFile)
DependencyFile->AttachToASTReader(*Reader);
for (auto &Listener : DependencyCollectors)
Listener->attachToASTReader(*Reader);
switch (Reader->ReadAST(Path,
Preamble ? serialization::MK_Preamble
: serialization::MK_PCH,
SourceLocation(),
ASTReader::ARR_None)) {
case ASTReader::Success:
// Set the predefines buffer as suggested by the PCH reader. Typically, the
// predefines buffer will be empty.
PP.setPredefines(Reader->getSuggestedPredefines());
return Reader;
case ASTReader::Failure:
// Unrecoverable failure: don't even try to process the input file.
break;
case ASTReader::Missing:
case ASTReader::OutOfDate:
case ASTReader::VersionMismatch:
case ASTReader::ConfigurationMismatch:
case ASTReader::HadErrors:
// No suitable PCH file could be found. Return an error.
break;
}
Context.setExternalSource(nullptr);
return nullptr;
}
// Code Completion
static bool EnableCodeCompletion(Preprocessor &PP,
StringRef Filename,
unsigned Line,
unsigned Column) {
// Tell the source manager to chop off the given file at a specific
// line and column.
const FileEntry *Entry = PP.getFileManager().getFile(Filename);
if (!Entry) {
PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
<< Filename;
return true;
}
// Truncate the named file at the given line/column.
PP.SetCodeCompletionPoint(Entry, Line, Column);
return false;
}
void CompilerInstance::createCodeCompletionConsumer() {
const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
if (!CompletionConsumer) {
setCodeCompletionConsumer(
createCodeCompletionConsumer(getPreprocessor(),
Loc.FileName, Loc.Line, Loc.Column,
getFrontendOpts().CodeCompleteOpts,
llvm::outs()));
if (!CompletionConsumer)
return;
} else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
Loc.Line, Loc.Column)) {
setCodeCompletionConsumer(nullptr);
return;
}
if (CompletionConsumer->isOutputBinary() &&
llvm::sys::ChangeStdoutToBinary()) {
getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
setCodeCompletionConsumer(nullptr);
}
}
void CompilerInstance::createFrontendTimer() {
FrontendTimerGroup.reset(
new llvm::TimerGroup("frontend", "Clang front-end time report"));
FrontendTimer.reset(
new llvm::Timer("frontend", "Clang front-end timer",
*FrontendTimerGroup));
}
CodeCompleteConsumer *
CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
StringRef Filename,
unsigned Line,
unsigned Column,
const CodeCompleteOptions &Opts,
raw_ostream &OS) {
if (EnableCodeCompletion(PP, Filename, Line, Column))
return nullptr;
// Set up the creation routine for code-completion.
return new PrintingCodeCompleteConsumer(Opts, OS);
}
void CompilerInstance::createSema(TranslationUnitKind TUKind,
CodeCompleteConsumer *CompletionConsumer) {
TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
TUKind, CompletionConsumer));
// Attach the external sema source if there is any.
if (ExternalSemaSrc) {
TheSema->addExternalSource(ExternalSemaSrc.get());
ExternalSemaSrc->InitializeSema(*TheSema);
}
}
// Output Files
void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
OutputFiles.push_back(std::move(OutFile));
}
void CompilerInstance::clearOutputFiles(bool EraseFiles) {
for (OutputFile &OF : OutputFiles) {
if (!OF.TempFilename.empty()) {
if (EraseFiles) {
llvm::sys::fs::remove(OF.TempFilename);
} else {
SmallString<128> NewOutFile(OF.Filename);
// If '-working-directory' was passed, the output filename should be
// relative to that.
FileMgr->FixupRelativePath(NewOutFile);
if (std::error_code ec =
llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
getDiagnostics().Report(diag::err_unable_to_rename_temp)
<< OF.TempFilename << OF.Filename << ec.message();
llvm::sys::fs::remove(OF.TempFilename);
}
}
} else if (!OF.Filename.empty() && EraseFiles)
llvm::sys::fs::remove(OF.Filename);
}
OutputFiles.clear();
NonSeekStream.reset();
}
std::unique_ptr<raw_pwrite_stream>
CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
StringRef Extension) {
return createOutputFile(getFrontendOpts().OutputFile, Binary,
/*RemoveFileOnSignal=*/true, InFile, Extension,
/*UseTemporary=*/true);
}
std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
return llvm::make_unique<llvm::raw_null_ostream>();
}
std::unique_ptr<raw_pwrite_stream>
CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
bool RemoveFileOnSignal, StringRef InFile,
StringRef Extension, bool UseTemporary,
bool CreateMissingDirectories) {
std::string OutputPathName, TempPathName;
std::error_code EC;
std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
if (!OS) {
getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
<< EC.message();
return nullptr;
}
// Add the output file -- but don't try to remove "-", since this means we are
// using stdin.
addOutputFile(
OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
return OS;
}
std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
StringRef OutputPath, std::error_code &Error, bool Binary,
bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
bool UseTemporary, bool CreateMissingDirectories,
std::string *ResultPathName, std::string *TempPathName) {
assert((!CreateMissingDirectories || UseTemporary) &&
"CreateMissingDirectories is only allowed when using temporary files");
std::string OutFile, TempFile;
if (!OutputPath.empty()) {
OutFile = OutputPath;
} else if (InFile == "-") {
OutFile = "-";
} else if (!Extension.empty()) {
SmallString<128> Path(InFile);
llvm::sys::path::replace_extension(Path, Extension);
OutFile = Path.str();
} else {
OutFile = "-";
}
std::unique_ptr<llvm::raw_fd_ostream> OS;
std::string OSFile;
if (UseTemporary) {
if (OutFile == "-")
UseTemporary = false;
else {
llvm::sys::fs::file_status Status;
llvm::sys::fs::status(OutputPath, Status);
if (llvm::sys::fs::exists(Status)) {
// Fail early if we can't write to the final destination.
if (!llvm::sys::fs::can_write(OutputPath)) {
Error = make_error_code(llvm::errc::operation_not_permitted);
return nullptr;
}
// Don't use a temporary if the output is a special file. This handles
// things like '-o /dev/null'
if (!llvm::sys::fs::is_regular_file(Status))
UseTemporary = false;
}
}
}
if (UseTemporary) {
// Create a temporary file.
SmallString<128> TempPath;
TempPath = OutFile;
TempPath += "-%%%%%%%%";
int fd;
std::error_code EC =
llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
if (CreateMissingDirectories &&
EC == llvm::errc::no_such_file_or_directory) {
StringRef Parent = llvm::sys::path::parent_path(OutputPath);
EC = llvm::sys::fs::create_directories(Parent);
if (!EC) {
EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
}
}
if (!EC) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempFile = TempPath.str();
}
// If we failed to create the temporary, fallback to writing to the file
// directly. This handles the corner case where we cannot write to the
// directory, but can write to the file.
}
if (!OS) {
OSFile = OutFile;
OS.reset(new llvm::raw_fd_ostream(
OSFile, Error,
(Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
if (Error)
return nullptr;
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (ResultPathName)
*ResultPathName = OutFile;
if (TempPathName)
*TempPathName = TempFile;
if (!Binary || OS->supportsSeeking())
return std::move(OS);
auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
assert(!NonSeekStream);
NonSeekStream = std::move(OS);
return std::move(B);
}
// Initialization Utilities
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
return InitializeSourceManager(
Input, getDiagnostics(), getFileManager(), getSourceManager(),
hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
getDependencyOutputOpts(), getFrontendOpts());
}
// static
bool CompilerInstance::InitializeSourceManager(
const FrontendInputFile &Input, DiagnosticsEngine &Diags,
FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
SrcMgr::CharacteristicKind
Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
if (Input.isBuffer()) {
SourceMgr.setMainFileID(SourceMgr.createFileID(
std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
assert(SourceMgr.getMainFileID().isValid() &&
"Couldn't establish MainFileID!");
return true;
}
StringRef InputFile = Input.getFile();
// Figure out where to get and map in the main file.
if (InputFile != "-") {
const FileEntry *File;
if (Opts.FindPchSource.empty()) {
File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
} else {
// When building a pch file in clang-cl mode, the .h file is built as if
// it was included by a cc file. Since the driver doesn't know about
// all include search directories, the frontend must search the input
// file through HeaderSearch here, as if it had been included by the
// cc file at Opts.FindPchSource.
const FileEntry *FindFile = FileMgr.getFile(Opts.FindPchSource);
if (!FindFile) {
Diags.Report(diag::err_fe_error_reading) << Opts.FindPchSource;
return false;
}
const DirectoryLookup *UnusedCurDir;
SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
Includers;
Includers.push_back(std::make_pair(FindFile, FindFile->getDir()));
File = HS->LookupFile(InputFile, SourceLocation(), /*isAngled=*/false,
/*FromDir=*/nullptr,
/*CurDir=*/UnusedCurDir, Includers,
/*SearchPath=*/nullptr,
/*RelativePath=*/nullptr,
/*RequestingModule=*/nullptr,
/*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
/*SkipCache=*/true);
// Also add the header to /showIncludes output.
if (File)
DepOpts.ShowIncludesPretendHeader = File->getName();
}
if (!File) {
Diags.Report(diag::err_fe_error_reading) << InputFile;
return false;
}
// The natural SourceManager infrastructure can't currently handle named
// pipes, but we would at least like to accept them for the main
// file. Detect them here, read them with the volatile flag so FileMgr will
// pick up the correct size, and simply override their contents as we do for
// STDIN.
if (File->isNamedPipe()) {
auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
if (MB) {
// Create a new virtual file that will have the correct size.
File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
SourceMgr.overrideFileContents(File, std::move(*MB));
} else {
Diags.Report(diag::err_cannot_open_file) << InputFile
<< MB.getError().message();
return false;
}
}
SourceMgr.setMainFileID(
SourceMgr.createFileID(File, SourceLocation(), Kind));
} else {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
llvm::MemoryBuffer::getSTDIN();
if (std::error_code EC = SBOrErr.getError()) {
Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
return false;
}
std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
SB->getBufferSize(), 0);
SourceMgr.setMainFileID(
SourceMgr.createFileID(File, SourceLocation(), Kind));
SourceMgr.overrideFileContents(File, std::move(SB));
}
assert(SourceMgr.getMainFileID().isValid() &&
"Couldn't establish MainFileID!");
return true;
}
// High-Level Operations
bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
// FIXME: Take this as an argument, once all the APIs we used have moved to
// taking it as an input instead of hard-coding llvm::errs.
raw_ostream &OS = llvm::errs();
// Create the target instance.
setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
getInvocation().TargetOpts));
if (!hasTarget())
return false;
// Create TargetInfo for the other side of CUDA compilation.
if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) {
auto TO = std::make_shared<TargetOptions>();
TO->Triple = getFrontendOpts().AuxTriple;
TO->HostTriple = getTarget().getTriple().str();
setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
}
// Inform the target of the language options.
//
// FIXME: We shouldn't need to do this, the target should be immutable once
// created. This complexity should be lifted elsewhere.
getTarget().adjust(getLangOpts());
// Adjust target options based on codegen options.
getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts());
// rewriter project will change target built-in bool type from its default.
if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
getTarget().noSignedCharForObjCBool();
// Validate/process some options.
if (getHeaderSearchOpts().Verbose)
OS << "clang -cc1 version " CLANG_VERSION_STRING
<< " based upon " << BACKEND_PACKAGE_STRING
<< " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
if (getFrontendOpts().ShowTimers)
createFrontendTimer();
if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
llvm::EnableStatistics(false);
for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
// Reset the ID tables if we are reusing the SourceManager and parsing
// regular files.
if (hasSourceManager() && !Act.isModelParsingAction())
getSourceManager().clearIDTables();
if (Act.BeginSourceFile(*this, FIF)) {
Act.Execute();
Act.EndSourceFile();
}
}
// Notify the diagnostic client that all files were processed.
getDiagnostics().getClient()->finish();
if (getDiagnosticOpts().ShowCarets) {
// We can have multiple diagnostics sharing one diagnostic client.
// Get the total number of warnings/errors from the client.
unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
if (NumWarnings)
OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
if (NumWarnings && NumErrors)
OS << " and ";
if (NumErrors)
OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
if (NumWarnings || NumErrors)
OS << " generated.\n";
}
if (getFrontendOpts().ShowStats) {
if (hasFileManager()) {
getFileManager().PrintStats();
OS << '\n';
}
llvm::PrintStatistics(OS);
}