forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClangImporter.cpp
3115 lines (2644 loc) · 110 KB
/
ClangImporter.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
//===--- ClangImporter.cpp - Import Clang Modules -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// This file implements support for loading Clang modules into Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "IAMInference.h"
#include "ImporterImpl.h"
#include "ClangDiagnosticConsumer.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsClangImporter.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/LinkLibrary.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporterOptions.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Config.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Mangle.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/ASTWriter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Parse/Parser.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/Rewrite/Frontend/Rewriters.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Memory.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#include <memory>
using namespace swift;
using namespace importer;
// Commonly-used Clang classes.
using clang::CompilerInstance;
using clang::CompilerInvocation;
#pragma mark Internal data structures
namespace {
class HeaderImportCallbacks : public clang::PPCallbacks {
ClangImporter::Implementation &Impl;
public:
HeaderImportCallbacks(ClangImporter::Implementation &impl)
: Impl(impl) {}
void handleImport(const clang::Module *imported) {
if (!imported)
return;
Impl.DeferredHeaderImports.push_back(imported);
}
void InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
StringRef SearchPath,
StringRef RelativePath,
const clang::Module *Imported) override {
handleImport(Imported);
}
void moduleImport(clang::SourceLocation ImportLoc,
clang::ModuleIdPath Path,
const clang::Module *Imported) override {
handleImport(Imported);
}
};
class PCHDeserializationCallbacks : public clang::ASTDeserializationListener {
ClangImporter::Implementation &Impl;
public:
explicit PCHDeserializationCallbacks(ClangImporter::Implementation &impl)
: Impl(impl) {}
void ModuleImportRead(clang::serialization::SubmoduleID ID,
clang::SourceLocation ImportLoc) {
if (Impl.IsReadingBridgingPCH) {
Impl.PCHImportedSubmodules.push_back(ID);
}
}
};
class HeaderParsingASTConsumer : public clang::ASTConsumer {
SmallVector<clang::DeclGroupRef, 4> DeclGroups;
PCHDeserializationCallbacks PCHCallbacks;
public:
explicit HeaderParsingASTConsumer(ClangImporter::Implementation &impl)
: PCHCallbacks(impl) {}
void
HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef decls) override {
DeclGroups.push_back(decls);
}
ArrayRef<clang::DeclGroupRef> getAdditionalParsedDecls() {
return DeclGroups;
}
clang::ASTDeserializationListener *GetASTDeserializationListener() override {
return &PCHCallbacks;
}
void reset() {
DeclGroups.clear();
}
};
class ParsingAction : public clang::ASTFrontendAction {
ASTContext &Ctx;
ClangImporter &Importer;
ClangImporter::Implementation &Impl;
const ClangImporterOptions &ImporterOpts;
std::string SwiftPCHHash;
public:
explicit ParsingAction(ASTContext &ctx,
ClangImporter &importer,
ClangImporter::Implementation &impl,
const ClangImporterOptions &importerOpts,
std::string swiftPCHHash)
: Ctx(ctx), Importer(importer), Impl(impl), ImporterOpts(importerOpts),
SwiftPCHHash(swiftPCHHash) {}
std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
return llvm::make_unique<HeaderParsingASTConsumer>(Impl);
}
bool BeginSourceFileAction(clang::CompilerInstance &CI,
StringRef Filename) override {
// Prefer frameworks over plain headers.
// We add search paths here instead of when building the initial invocation
// so that (a) we use the same code as search paths for imported modules,
// and (b) search paths are always added after -Xcc options.
SearchPathOptions &searchPathOpts = Ctx.SearchPathOpts;
for (const auto &framepath : searchPathOpts.FrameworkSearchPaths) {
Importer.addSearchPath(framepath.Path, /*isFramework*/true,
framepath.IsSystem);
}
for (auto path : searchPathOpts.ImportSearchPaths) {
Importer.addSearchPath(path, /*isFramework*/false, /*isSystem=*/false);
}
auto PCH = Importer.getOrCreatePCH(ImporterOpts, SwiftPCHHash);
if (PCH.hasValue()) {
Impl.getClangInstance()->getPreprocessorOpts().ImplicitPCHInclude =
PCH.getValue();
Impl.IsReadingBridgingPCH = true;
Impl.setSinglePCHImport(PCH.getValue());
}
return true;
}
};
class StdStringMemBuffer : public llvm::MemoryBuffer {
const std::string storage;
const std::string name;
public:
StdStringMemBuffer(std::string &&source, StringRef name)
: storage(std::move(source)), name(name.str()) {
init(storage.data(), storage.data() + storage.size(),
/*null-terminated=*/true);
}
StringRef getBufferIdentifier() const override {
return name;
}
BufferKind getBufferKind() const override {
return MemoryBuffer_Malloc;
}
};
class ZeroFilledMemoryBuffer : public llvm::MemoryBuffer {
const std::string name;
public:
explicit ZeroFilledMemoryBuffer(size_t size, StringRef name)
: name(name.str()) {
assert(size > 0);
std::error_code error;
llvm::sys::MemoryBlock memory =
llvm::sys::Memory::allocateMappedMemory(size, nullptr,
llvm::sys::Memory::MF_READ,
error);
assert(!error && "failed to allocated read-only zero-filled memory");
init(static_cast<char *>(memory.base()),
static_cast<char *>(memory.base()) + memory.size() - 1,
/*null-terminated*/true);
}
~ZeroFilledMemoryBuffer() {
llvm::sys::MemoryBlock memory{const_cast<char *>(getBufferStart()),
getBufferSize()};
std::error_code error = llvm::sys::Memory::releaseMappedMemory(memory);
assert(!error && "failed to deallocate read-only zero-filled memory");
(void)error;
}
ZeroFilledMemoryBuffer(const ZeroFilledMemoryBuffer &) = delete;
ZeroFilledMemoryBuffer(ZeroFilledMemoryBuffer &&) = delete;
void operator=(const ZeroFilledMemoryBuffer &) = delete;
void operator=(ZeroFilledMemoryBuffer &&) = delete;
StringRef getBufferIdentifier() const override {
return name;
}
BufferKind getBufferKind() const override {
return MemoryBuffer_MMap;
}
};
} // end anonymous namespace
namespace {
class BridgingPPTracker : public clang::PPCallbacks {
ClangImporter::Implementation &Impl;
public:
BridgingPPTracker(ClangImporter::Implementation &Impl)
: Impl(Impl) {}
private:
static unsigned getNumModuleIdentifiers(const clang::Module *Mod) {
unsigned Result = 1;
while (Mod->Parent) {
Mod = Mod->Parent;
++Result;
}
return Result;
}
void InclusionDirective(clang::SourceLocation HashLoc,
const clang::Token &IncludeTok,
StringRef FileName,
bool IsAngled,
clang::CharSourceRange FilenameRange,
const clang::FileEntry *File,
StringRef SearchPath,
StringRef RelativePath,
const clang::Module *Imported) override {
if (!Imported) {
if (File)
Impl.BridgeHeaderFiles.insert(File);
return;
}
// Synthesize identifier locations.
SmallVector<clang::SourceLocation, 4> IdLocs;
for (unsigned I = 0, E = getNumModuleIdentifiers(Imported); I != E; ++I)
IdLocs.push_back(HashLoc);
handleImport(HashLoc, IdLocs, Imported);
}
void moduleImport(clang::SourceLocation ImportLoc,
clang::ModuleIdPath Path,
const clang::Module *Imported) override {
if (!Imported)
return;
SmallVector<clang::SourceLocation, 4> IdLocs;
for (auto &P : Path)
IdLocs.push_back(P.second);
handleImport(ImportLoc, IdLocs, Imported);
}
void handleImport(clang::SourceLocation ImportLoc,
ArrayRef<clang::SourceLocation> IdLocs,
const clang::Module *Imported) {
clang::ASTContext &ClangCtx = Impl.getClangASTContext();
clang::ImportDecl *ClangImport = clang::ImportDecl::Create(ClangCtx,
ClangCtx.getTranslationUnitDecl(),
ImportLoc,
const_cast<clang::Module*>(Imported),
IdLocs);
Impl.BridgeHeaderTopLevelImports.push_back(ClangImport);
}
void MacroDefined(const clang::Token &MacroNameTok,
const clang::MacroDirective *MD) override {
Impl.BridgeHeaderMacros.push_back(MacroNameTok.getIdentifierInfo());
}
};
class ClangImporterDependencyCollector : public clang::DependencyCollector
{
llvm::StringSet<> ExcludedPaths;
public:
ClangImporterDependencyCollector() = default;
void excludePath(StringRef filename) {
ExcludedPaths.insert(filename);
}
bool isClangImporterSpecialName(StringRef Filename) {
using ImporterImpl = ClangImporter::Implementation;
return (Filename == ImporterImpl::moduleImportBufferName
|| Filename == ImporterImpl::bridgingHeaderBufferName);
}
// Currently preserving older ClangImporter behaviour of ignoring system
// dependencies, but possibly revisit?
bool needSystemDependencies() override { return false; }
bool sawDependency(StringRef Filename, bool FromClangModule,
bool IsSystem, bool IsClangModuleFile,
bool IsMissing) override {
if (!clang::DependencyCollector::sawDependency(Filename, FromClangModule,
IsSystem, IsClangModuleFile,
IsMissing))
return false;
// Currently preserving older ClangImporter behaviour of ignoring .pcm
// file dependencies, but possibly revisit?
if (IsClangModuleFile
|| isClangImporterSpecialName(Filename)
|| ExcludedPaths.count(Filename))
return false;
return true;
}
};
} // end anonymous namespace
std::shared_ptr<clang::DependencyCollector>
ClangImporter::createDependencyCollector()
{
return std::make_shared<ClangImporterDependencyCollector>();
}
void ClangImporter::Implementation::addBridgeHeaderTopLevelDecls(
clang::Decl *D) {
if (shouldIgnoreBridgeHeaderTopLevelDecl(D))
return;
BridgeHeaderTopLevelDecls.push_back(D);
}
bool ClangImporter::Implementation::shouldIgnoreBridgeHeaderTopLevelDecl(
clang::Decl *D) {
// Ignore forward references;
if (auto *ID = dyn_cast<clang::ObjCInterfaceDecl>(D)) {
if (!ID->isThisDeclarationADefinition())
return true;
} else if (auto PD = dyn_cast<clang::ObjCProtocolDecl>(D)) {
if (!PD->isThisDeclarationADefinition())
return true;
} else if (auto TD = dyn_cast<clang::TagDecl>(D)) {
if (!TD->isThisDeclarationADefinition())
return true;
}
return false;
}
ClangImporter::ClangImporter(ASTContext &ctx,
const ClangImporterOptions &clangImporterOpts,
DependencyTracker *tracker)
: ClangModuleLoader(tracker),
Impl(*new Implementation(ctx, clangImporterOpts))
{
}
ClangImporter::~ClangImporter() {
delete &Impl;
}
void ClangImporter::setTypeResolver(LazyResolver &resolver) {
Impl.setTypeResolver(&resolver);
}
void ClangImporter::clearTypeResolver() {
Impl.setTypeResolver(nullptr);
}
#pragma mark Module loading
#define SHIMS_INCLUDE_FLAG "-isystem"
static StringRef
getMinVersionOptNameForDarwinTriple(const llvm::Triple &triple) {
switch(getDarwinPlatformKind(triple)) {
case DarwinPlatformKind::MacOS:
return "-mmacosx-version-min=";
case DarwinPlatformKind::IPhoneOS:
return "-mios-version-min=";
case DarwinPlatformKind::IPhoneOSSimulator:
return "-mios-simulator-version-min=";
case DarwinPlatformKind::TvOS:
return "-mtvos-version-min=";
case DarwinPlatformKind::TvOSSimulator:
return "-mtvos-simulator-version-min=";
case DarwinPlatformKind::WatchOS:
return "-mwatchos-version-min=";
case DarwinPlatformKind::WatchOSSimulator:
return "-mwatchos-simulator-version-min=";
}
llvm_unreachable("Unsupported Darwin platform");
}
static void
getNormalInvocationArguments(std::vector<std::string> &invocationArgStrs,
ASTContext &ctx,
const ClangImporterOptions &importerOpts) {
const llvm::Triple &triple = ctx.LangOpts.Target;
SearchPathOptions &searchPathOpts = ctx.SearchPathOpts;
auto languageVersion = ctx.LangOpts.EffectiveLanguageVersion;
if (llvm::sys::path::extension(importerOpts.BridgingHeader).endswith(
PCH_EXTENSION)) {
invocationArgStrs.insert(
invocationArgStrs.end(),
{ "-include-pch", importerOpts.BridgingHeader }
);
}
// Construct the invocation arguments for the current target.
// Add target-independent options first.
invocationArgStrs.insert(
invocationArgStrs.end(),
{
// Enable modules
"-fmodules",
"-Werror=non-modular-include-in-framework-module",
"-Xclang", "-fmodule-feature", "-Xclang", "swift",
// Don't emit LLVM IR.
"-fsyntax-only",
// Enable block support.
"-fblocks",
languageVersion.preprocessorDefinition("__swift__", {10000, 100, 1}),
"-fretain-comments-from-system-headers",
SHIMS_INCLUDE_FLAG, searchPathOpts.RuntimeResourcePath,
});
// Set C language options.
if (triple.isOSDarwin()) {
invocationArgStrs.insert(invocationArgStrs.end(), {
// Darwin uses Objective-C ARC.
"-x", "objective-c", "-std=gnu11", "-fobjc-arc",
// Define macros that Swift bridging headers use.
"-DSWIFT_CLASS_EXTRA=__attribute__((annotate(\""
SWIFT_NATIVE_ANNOTATION_STRING "\")))",
"-DSWIFT_PROTOCOL_EXTRA=__attribute__((annotate(\""
SWIFT_NATIVE_ANNOTATION_STRING "\")))",
"-DSWIFT_EXTENSION_EXTRA=__attribute__((annotate(\""
SWIFT_NATIVE_ANNOTATION_STRING "\")))",
"-DSWIFT_ENUM_EXTRA=__attribute__((annotate(\""
SWIFT_NATIVE_ANNOTATION_STRING "\")))",
// Avoid including the iso646.h header because some headers from OS X
// frameworks are broken by it.
"-D_ISO646_H_", "-D__ISO646_H",
// Request new APIs from AppKit.
"-DSWIFT_SDK_OVERLAY_APPKIT_EPOCH=2",
// Request new APIs from Foundation.
"-DSWIFT_SDK_OVERLAY_FOUNDATION_EPOCH=8",
// Request new APIs from SceneKit.
"-DSWIFT_SDK_OVERLAY2_SCENEKIT_EPOCH=3",
// Request new APIs from GameplayKit.
"-DSWIFT_SDK_OVERLAY_GAMEPLAYKIT_EPOCH=1",
// Request new APIs from SpriteKit.
"-DSWIFT_SDK_OVERLAY_SPRITEKIT_EPOCH=1",
// Request new APIs from CoreImage.
"-DSWIFT_SDK_OVERLAY_COREIMAGE_EPOCH=2",
// Request new APIs from libdispatch.
"-DSWIFT_SDK_OVERLAY_DISPATCH_EPOCH=2",
// Request new APIs from libpthread
"-DSWIFT_SDK_OVERLAY_PTHREAD_EPOCH=1",
// Request new APIs from CoreGraphics.
"-DSWIFT_SDK_OVERLAY_COREGRAPHICS_EPOCH=0",
// Request new APIs from UIKit.
"-DSWIFT_SDK_OVERLAY_UIKIT_EPOCH=2",
});
// Get the version of this compiler and pass it to
// C/Objective-C declarations.
auto V = version::Version::getCurrentCompilerVersion();
if (!V.empty()) {
invocationArgStrs.insert(invocationArgStrs.end(), {
V.preprocessorDefinition("__SWIFT_COMPILER_VERSION",
{1000000000, /*ignored*/0, 1000000, 1000, 1}),
});
}
} else {
invocationArgStrs.insert(invocationArgStrs.end(), {
// Non-Darwin platforms don't use the Objective-C runtime, so they can
// not import Objective-C modules.
//
// Just use the most feature-rich C language mode.
"-x", "c", "-std=gnu11",
});
// The module map used for Glibc depends on the target we're compiling for,
// and is not included in the resource directory with the other implicit
// module maps. It's at {freebsd|linux}/{arch}/glibc.modulemap.
SmallString<128> GlibcModuleMapPath;
GlibcModuleMapPath = searchPathOpts.RuntimeResourcePath;
// Running without a resource directory is not a supported configuration.
assert(!GlibcModuleMapPath.empty());
llvm::sys::path::append(
GlibcModuleMapPath,
swift::getPlatformNameForTriple(triple),
swift::getMajorArchitectureName(triple),
"glibc.modulemap");
// Only specify the module map if that file actually exists.
// It may not--for example in the case that
// `swiftc -target x86_64-unknown-linux-gnu -emit-ir` is invoked using
// a Swift compiler not built for Linux targets.
if (llvm::sys::fs::exists(GlibcModuleMapPath)) {
invocationArgStrs.push_back(
(Twine("-fmodule-map-file=") + GlibcModuleMapPath).str());
} else {
// FIXME: Emit a warning of some kind.
}
}
if (triple.isOSDarwin()) {
std::string minVersionBuf;
llvm::raw_string_ostream minVersionOpt{minVersionBuf};
minVersionOpt << getMinVersionOptNameForDarwinTriple(triple);
unsigned major, minor, micro;
if (triple.isiOS()) {
triple.getiOSVersion(major, minor, micro);
} else if (triple.isWatchOS()) {
triple.getWatchOSVersion(major, minor, micro);
} else {
assert(triple.isMacOSX());
triple.getMacOSXVersion(major, minor, micro);
}
minVersionOpt << clang::VersionTuple(major, minor, micro);
invocationArgStrs.push_back(std::move(minVersionOpt.str()));
}
if (searchPathOpts.SDKPath.empty()) {
invocationArgStrs.push_back("-Xclang");
invocationArgStrs.push_back("-nostdsysteminc");
} else {
// On Darwin, Clang uses -isysroot to specify the include
// system root. On other targets, it seems to use --sysroot.
if (triple.isOSDarwin()) {
invocationArgStrs.push_back("-isysroot");
} else {
invocationArgStrs.push_back("--sysroot");
}
invocationArgStrs.push_back(searchPathOpts.SDKPath);
}
const std::string &moduleCachePath = importerOpts.ModuleCachePath;
// Set the module and API notes cache paths to the same location.
if (!moduleCachePath.empty()) {
invocationArgStrs.push_back("-fmodules-cache-path=");
invocationArgStrs.back().append(moduleCachePath);
invocationArgStrs.push_back("-fapinotes-cache-path=");
invocationArgStrs.back().append(moduleCachePath);
}
if (!importerOpts.DisableModulesValidateSystemHeaders) {
invocationArgStrs.push_back("-fmodules-validate-system-headers");
}
if (importerOpts.DetailedPreprocessingRecord) {
invocationArgStrs.insert(invocationArgStrs.end(), {
"-Xclang", "-detailed-preprocessing-record",
"-Xclang", "-fmodule-format=raw",
});
} else {
invocationArgStrs.insert(invocationArgStrs.end(), {
"-Xclang", "-fmodule-format=obj",
});
}
}
static void
getEmbedBitcodeInvocationArguments(std::vector<std::string> &invocationArgStrs,
ASTContext &ctx,
const ClangImporterOptions &importerOpts) {
invocationArgStrs.insert(invocationArgStrs.end(), {
// Backend mode.
"-fembed-bitcode",
// ...but Clang isn't doing the emission.
"-fsyntax-only",
"-x", "ir",
});
}
static void
addCommonInvocationArguments(std::vector<std::string> &invocationArgStrs,
ASTContext &ctx,
const ClangImporterOptions &importerOpts) {
using ImporterImpl = ClangImporter::Implementation;
const llvm::Triple &triple = ctx.LangOpts.Target;
SearchPathOptions &searchPathOpts = ctx.SearchPathOpts;
invocationArgStrs.push_back("-target");
invocationArgStrs.push_back(triple.str());
invocationArgStrs.push_back(ImporterImpl::moduleImportBufferName);
if (ctx.LangOpts.EnableAppExtensionRestrictions) {
invocationArgStrs.push_back("-fapplication-extension");
}
if (!importerOpts.TargetCPU.empty()) {
invocationArgStrs.push_back("-mcpu=" + importerOpts.TargetCPU);
} else if (triple.isOSDarwin()) {
// Special case: arm64 defaults to the "cyclone" CPU for Darwin,
// but Clang only detects this if we use -arch.
if (triple.getArch() == llvm::Triple::aarch64 ||
triple.getArch() == llvm::Triple::aarch64_be) {
invocationArgStrs.push_back("-mcpu=cyclone");
}
}
const std::string &overrideResourceDir = importerOpts.OverrideResourceDir;
if (overrideResourceDir.empty()) {
llvm::SmallString<128> resourceDir(searchPathOpts.RuntimeResourcePath);
// Adjust the path to refer to our copy of the Clang resource directory
// under 'lib/swift/clang', which is either a real resource directory or a
// symlink to one inside of a full Clang installation.
//
// The rationale for looking under the Swift resource directory and not
// assuming that the Clang resource directory is located next to it is that
// Swift, when installed separately, should not need to install files in
// directories that are not "owned" by it.
llvm::sys::path::append(resourceDir, "clang");
// Set the Clang resource directory to the path we computed.
invocationArgStrs.push_back("-resource-dir");
invocationArgStrs.push_back(resourceDir.str());
} else {
invocationArgStrs.push_back("-resource-dir");
invocationArgStrs.push_back(overrideResourceDir);
}
for (auto extraArg : importerOpts.ExtraArgs) {
invocationArgStrs.push_back(extraArg);
}
// Enable API notes alongside headers/in frameworks.
invocationArgStrs.push_back("-fapinotes-modules");
// Add API notes paths.
for (const auto &searchPath : searchPathOpts.ImportSearchPaths) {
invocationArgStrs.push_back("-iapinotes-modules");
invocationArgStrs.push_back(searchPath);
}
invocationArgStrs.push_back("-iapinotes-modules");
invocationArgStrs.push_back(searchPathOpts.RuntimeLibraryImportPath);
// Map the Swift major version into the API notes version for Swift. This
// has the effect of allowing API notes to effect changes only on Swift
// major versions, not minor versions.
invocationArgStrs.push_back("-fapinotes-swift-version=" +
llvm::itostr(ctx.LangOpts.EffectiveLanguageVersion[0]));
}
bool ClangImporter::canReadPCH(StringRef PCHFilename) {
return clang::ASTReader::isAcceptableASTFile(PCHFilename,
Impl.Instance->getFileManager(),
Impl.Instance->getPCHContainerReader(),
Impl.Instance->getLangOpts(),
Impl.Instance->getTargetOpts(),
Impl.Instance->getPreprocessorOpts(),
Impl.Instance->getSpecificModuleCachePath());
}
Optional<std::string>
ClangImporter::getPCHFilename(const ClangImporterOptions &ImporterOptions,
const std::string &SwiftPCHHash) {
if (llvm::sys::path::extension(ImporterOptions.BridgingHeader)
.endswith(PCH_EXTENSION)) {
return ImporterOptions.BridgingHeader;
}
const auto &BridgingHeader = ImporterOptions.BridgingHeader;
const auto &PCHOutputDir = ImporterOptions.PrecompiledHeaderOutputDir;
if (SwiftPCHHash.empty() || BridgingHeader.empty() || PCHOutputDir.empty()) {
return None;
}
SmallString<256> PCHBasename { llvm::sys::path::filename(BridgingHeader) };
llvm::sys::path::replace_extension(PCHBasename, "");
PCHBasename.append("-swift_");
PCHBasename.append(SwiftPCHHash);
PCHBasename.append("-clang_");
PCHBasename.append(getClangModuleHash());
llvm::sys::path::replace_extension(PCHBasename, ".pch");
SmallString<256> PCHFilename { PCHOutputDir };
llvm::sys::path::append(PCHFilename, PCHBasename);
return PCHFilename.str().str();
}
Optional<std::string>
ClangImporter::getOrCreatePCH(const ClangImporterOptions &ImporterOptions,
const std::string &SwiftPCHHash) {
auto PCHFilename = getPCHFilename(ImporterOptions, SwiftPCHHash);
if (!PCHFilename.hasValue()) {
return None;
}
if (!canReadPCH(PCHFilename.getValue())) {
SmallString<256> Message;
llvm::raw_svector_ostream OS(Message);
auto Diags = new clang::TextDiagnosticPrinter {
llvm::errs(),
&Impl.Instance->getDiagnosticOpts()
};
auto FailedToEmit = emitBridgingPCH(ImporterOptions.BridgingHeader,
PCHFilename.getValue(),
Diags);
if (FailedToEmit) {
return None;
}
}
return PCHFilename.getValue();
}
std::unique_ptr<ClangImporter>
ClangImporter::create(ASTContext &ctx,
const ClangImporterOptions &importerOpts,
std::string swiftPCHHash,
DependencyTracker *tracker) {
std::unique_ptr<ClangImporter> importer{
new ClangImporter(ctx, importerOpts, tracker)
};
std::vector<std::string> invocationArgStrs;
// Clang expects this to be like an actual command line. So we need to pass in
// "clang" for argv[0]
invocationArgStrs.push_back("clang");
switch (importerOpts.Mode) {
case ClangImporterOptions::Modes::Normal:
getNormalInvocationArguments(invocationArgStrs, ctx, importerOpts);
break;
case ClangImporterOptions::Modes::EmbedBitcode:
getEmbedBitcodeInvocationArguments(invocationArgStrs, ctx, importerOpts);
break;
}
addCommonInvocationArguments(invocationArgStrs, ctx, importerOpts);
if (importerOpts.DumpClangDiagnostics) {
llvm::errs() << "'";
interleave(invocationArgStrs,
[](StringRef arg) { llvm::errs() << arg; },
[] { llvm::errs() << "' '"; });
llvm::errs() << "'\n";
}
std::vector<const char *> invocationArgs;
for (auto &argStr : invocationArgStrs)
invocationArgs.push_back(argStr.c_str());
if (llvm::sys::path::extension(importerOpts.BridgingHeader).endswith(
PCH_EXTENSION)) {
importer->Impl.setSinglePCHImport(importerOpts.BridgingHeader);
importer->Impl.IsReadingBridgingPCH = true;
if (tracker) {
// Currently ignoring dependency on bridging .pch files because they are
// temporaries; if and when they are no longer temporaries, this condition
// should be removed.
auto &coll = static_cast<ClangImporterDependencyCollector &>(
*tracker->getClangCollector());
coll.excludePath(importerOpts.BridgingHeader);
}
}
// FIXME: These can't be controlled from the command line.
llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnosticOpts{
new clang::DiagnosticOptions
};
std::unique_ptr<ClangDiagnosticConsumer> diagClient{
new ClangDiagnosticConsumer(importer->Impl, *diagnosticOpts,
importerOpts.DumpClangDiagnostics)
};
auto clangDiags =
clang::CompilerInstance::createDiagnostics(diagnosticOpts.get(),
diagClient.release());
// Create a new Clang compiler invocation.
importer->Impl.Invocation =
clang::createInvocationFromCommandLine(invocationArgs, clangDiags);
if (!importer->Impl.Invocation)
return nullptr;
// Don't stop emitting messages if we ever can't load a module.
// FIXME: This is actually a general problem: any "fatal" error could mess up
// the CompilerInvocation.
clangDiags->setSeverity(clang::diag::err_module_not_found,
clang::diag::Severity::Error,
clang::SourceLocation());
clangDiags->setSeverity(clang::diag::err_module_not_built,
clang::diag::Severity::Error,
clang::SourceLocation());
// Create an almost-empty memory buffer.
auto sourceBuffer = llvm::MemoryBuffer::getMemBuffer(
"extern int __swift __attribute__((unavailable));",
Implementation::moduleImportBufferName);
clang::PreprocessorOptions &ppOpts =
importer->Impl.Invocation->getPreprocessorOpts();
ppOpts.addRemappedFile(Implementation::moduleImportBufferName,
sourceBuffer.release());
// Install a Clang module file extension to build Swift name lookup tables.
importer->Impl.Invocation->getFrontendOpts().ModuleFileExtensions.push_back(
std::make_shared<SwiftNameLookupExtension>(
importer->Impl.BridgingHeaderLookupTable,
importer->Impl.LookupTables, importer->Impl.SwiftContext,
importer->Impl.platformAvailability,
importer->Impl.InferImportAsMember));
// Create a compiler instance.
auto PCHContainerOperations =
std::make_shared<clang::PCHContainerOperations>();
PCHContainerOperations->registerWriter(
llvm::make_unique<clang::ObjectFilePCHContainerWriter>());
PCHContainerOperations->registerReader(
llvm::make_unique<clang::ObjectFilePCHContainerReader>());
importer->Impl.Instance.reset(
new clang::CompilerInstance(PCHContainerOperations));
auto &instance = *importer->Impl.Instance;
if (tracker)
instance.addDependencyCollector(tracker->getClangCollector());
instance.setDiagnostics(&*clangDiags);
instance.setInvocation(importer->Impl.Invocation);
// Create the associated action.
importer->Impl.Action.reset(new ParsingAction(ctx, *importer,
importer->Impl,
importerOpts,
swiftPCHHash));
auto *action = importer->Impl.Action.get();
// Execute the action. We effectively inline most of
// CompilerInstance::ExecuteAction here, because we need to leave the AST
// open for future module loading.
// FIXME: This has to be cleaned up on the Clang side before we can improve
// things here.
// Create the target instance.
instance.setTarget(
clang::TargetInfo::CreateTargetInfo(*clangDiags,
instance.getInvocation().TargetOpts));
if (!instance.hasTarget())
return nullptr;
// 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.
instance.getTarget().adjust(instance.getLangOpts());
if (importerOpts.Mode == ClangImporterOptions::Modes::EmbedBitcode)
return importer;
bool canBegin = action->BeginSourceFile(instance,
instance.getFrontendOpts().Inputs[0]);
if (!canBegin)
return nullptr; // there was an error related to the compiler arguments.
clang::Preprocessor &clangPP = instance.getPreprocessor();
clangPP.enableIncrementalProcessing();
// Setup Preprocessor callbacks before initialing the parser to make sure
// we catch implicit includes.
auto ppTracker = llvm::make_unique<BridgingPPTracker>(importer->Impl);
clangPP.addPPCallbacks(std::move(ppTracker));
instance.createModuleManager();
// Manually run the action, so that the TU stays open for additional parsing.
instance.createSema(action->getTranslationUnitKind(), nullptr);
importer->Impl.Parser.reset(new clang::Parser(clangPP, instance.getSema(),
/*SkipFunctionBodies=*/false));
clangPP.EnterMainSourceFile();
importer->Impl.Parser->Initialize();
importer->Impl.nameImporter.reset(new NameImporter(
importer->Impl.SwiftContext, importer->Impl.platformAvailability,
importer->Impl.getClangSema(), importer->Impl.InferImportAsMember));
// FIXME: These decls are not being parsed correctly since (a) some of the
// callbacks are still being added, and (b) the logic to parse them has
// changed.
clang::Parser::DeclGroupPtrTy parsed;
while (!importer->Impl.Parser->ParseTopLevelDecl(parsed)) {
for (auto *D : parsed.get()) {
importer->Impl.addBridgeHeaderTopLevelDecls(D);
if (auto named = dyn_cast<clang::NamedDecl>(D)) {
addEntryToLookupTable(*importer->Impl.BridgingHeaderLookupTable, named,
*importer->Impl.nameImporter);
}
}
}
// FIXME: This is missing implicit includes.
auto *CB = new HeaderImportCallbacks(importer->Impl);
clangPP.addPPCallbacks(std::unique_ptr<clang::PPCallbacks>(CB));
// Create the selectors we'll be looking for.
auto &clangContext = importer->Impl.Instance->getASTContext();
importer->Impl.objectAtIndexedSubscript
= clangContext.Selectors.getUnarySelector(
&clangContext.Idents.get("objectAtIndexedSubscript"));
clang::IdentifierInfo *setObjectAtIndexedSubscriptIdents[2] = {
&clangContext.Idents.get("setObject"),
&clangContext.Idents.get("atIndexedSubscript")
};
importer->Impl.setObjectAtIndexedSubscript
= clangContext.Selectors.getSelector(2, setObjectAtIndexedSubscriptIdents);
importer->Impl.objectForKeyedSubscript
= clangContext.Selectors.getUnarySelector(
&clangContext.Idents.get("objectForKeyedSubscript"));
clang::IdentifierInfo *setObjectForKeyedSubscriptIdents[2] = {
&clangContext.Idents.get("setObject"),
&clangContext.Idents.get("forKeyedSubscript")
};
importer->Impl.setObjectForKeyedSubscript
= clangContext.Selectors.getSelector(2, setObjectForKeyedSubscriptIdents);
// Set up the imported header module.
auto *importedHeaderModule = ModuleDecl::create(ctx.getIdentifier("__ObjC"), ctx);
importer->Impl.ImportedHeaderUnit =
new (ctx) ClangModuleUnit(*importedHeaderModule, importer->Impl, nullptr);
importedHeaderModule->addFile(*importer->Impl.ImportedHeaderUnit);
importer->Impl.IsReadingBridgingPCH = false;
return importer;
}
bool ClangImporter::addSearchPath(StringRef newSearchPath, bool isFramework,
bool isSystem) {
clang::FileManager &fileMgr = Impl.Instance->getFileManager();
const clang::DirectoryEntry *entry = fileMgr.getDirectory(newSearchPath);
if (!entry)
return true;