Module.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. //===--- Module.cpp - Describe a module -----------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the Module class, which describes a module in the source
  11. // code.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Basic/Module.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/LangOptions.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/ADT/ArrayRef.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
  25. bool IsFramework, bool IsExplicit, unsigned VisibilityID)
  26. : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
  27. Umbrella(), ASTFile(nullptr), VisibilityID(VisibilityID),
  28. IsMissingRequirement(false), HasIncompatibleModuleFile(false),
  29. IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
  30. IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
  31. IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
  32. InferExportWildcard(false), ConfigMacrosExhaustive(false),
  33. NoUndeclaredIncludes(false), NameVisibility(Hidden) {
  34. if (Parent) {
  35. if (!Parent->isAvailable())
  36. IsAvailable = false;
  37. if (Parent->IsSystem)
  38. IsSystem = true;
  39. if (Parent->IsExternC)
  40. IsExternC = true;
  41. if (Parent->NoUndeclaredIncludes)
  42. NoUndeclaredIncludes = true;
  43. IsMissingRequirement = Parent->IsMissingRequirement;
  44. Parent->SubModuleIndex[Name] = Parent->SubModules.size();
  45. Parent->SubModules.push_back(this);
  46. }
  47. }
  48. Module::~Module() {
  49. for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
  50. I != IEnd; ++I) {
  51. delete *I;
  52. }
  53. }
  54. /// \brief Determine whether a translation unit built using the current
  55. /// language options has the given feature.
  56. static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
  57. const TargetInfo &Target) {
  58. bool HasFeature = llvm::StringSwitch<bool>(Feature)
  59. .Case("altivec", LangOpts.AltiVec)
  60. .Case("blocks", LangOpts.Blocks)
  61. .Case("coroutines", LangOpts.CoroutinesTS)
  62. .Case("cplusplus", LangOpts.CPlusPlus)
  63. .Case("cplusplus11", LangOpts.CPlusPlus11)
  64. .Case("freestanding", LangOpts.Freestanding)
  65. .Case("gnuinlineasm", LangOpts.GNUAsm)
  66. .Case("objc", LangOpts.ObjC1)
  67. .Case("objc_arc", LangOpts.ObjCAutoRefCount)
  68. .Case("opencl", LangOpts.OpenCL)
  69. .Case("tls", Target.isTLSSupported())
  70. .Case("zvector", LangOpts.ZVector)
  71. .Default(Target.hasFeature(Feature));
  72. if (!HasFeature)
  73. HasFeature = std::find(LangOpts.ModuleFeatures.begin(),
  74. LangOpts.ModuleFeatures.end(),
  75. Feature) != LangOpts.ModuleFeatures.end();
  76. return HasFeature;
  77. }
  78. bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
  79. Requirement &Req,
  80. UnresolvedHeaderDirective &MissingHeader) const {
  81. if (IsAvailable)
  82. return true;
  83. for (const Module *Current = this; Current; Current = Current->Parent) {
  84. for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
  85. if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
  86. Current->Requirements[I].second) {
  87. Req = Current->Requirements[I];
  88. return false;
  89. }
  90. }
  91. if (!Current->MissingHeaders.empty()) {
  92. MissingHeader = Current->MissingHeaders.front();
  93. return false;
  94. }
  95. }
  96. llvm_unreachable("could not find a reason why module is unavailable");
  97. }
  98. bool Module::isSubModuleOf(const Module *Other) const {
  99. const Module *This = this;
  100. do {
  101. if (This == Other)
  102. return true;
  103. This = This->Parent;
  104. } while (This);
  105. return false;
  106. }
  107. const Module *Module::getTopLevelModule() const {
  108. const Module *Result = this;
  109. while (Result->Parent)
  110. Result = Result->Parent;
  111. return Result;
  112. }
  113. std::string Module::getFullModuleName() const {
  114. SmallVector<StringRef, 2> Names;
  115. // Build up the set of module names (from innermost to outermost).
  116. for (const Module *M = this; M; M = M->Parent)
  117. Names.push_back(M->Name);
  118. std::string Result;
  119. for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
  120. IEnd = Names.rend();
  121. I != IEnd; ++I) {
  122. if (!Result.empty())
  123. Result += '.';
  124. Result += *I;
  125. }
  126. return Result;
  127. }
  128. bool Module::fullModuleNameIs(ArrayRef<StringRef> nameParts) const {
  129. for (const Module *M = this; M; M = M->Parent) {
  130. if (nameParts.empty() || M->Name != nameParts.back())
  131. return false;
  132. nameParts = nameParts.drop_back();
  133. }
  134. return nameParts.empty();
  135. }
  136. Module::DirectoryName Module::getUmbrellaDir() const {
  137. if (Header U = getUmbrellaHeader())
  138. return {"", U.Entry->getDir()};
  139. return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()};
  140. }
  141. ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
  142. if (!TopHeaderNames.empty()) {
  143. for (std::vector<std::string>::iterator
  144. I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
  145. if (const FileEntry *FE = FileMgr.getFile(*I))
  146. TopHeaders.insert(FE);
  147. }
  148. TopHeaderNames.clear();
  149. }
  150. return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
  151. }
  152. bool Module::directlyUses(const Module *Requested) const {
  153. auto *Top = getTopLevelModule();
  154. // A top-level module implicitly uses itself.
  155. if (Requested->isSubModuleOf(Top))
  156. return true;
  157. for (auto *Use : Top->DirectUses)
  158. if (Requested->isSubModuleOf(Use))
  159. return true;
  160. // Anyone is allowed to use our builtin stddef.h and its accompanying module.
  161. if (!Requested->Parent && Requested->Name == "_Builtin_stddef_max_align_t")
  162. return true;
  163. return false;
  164. }
  165. void Module::addRequirement(StringRef Feature, bool RequiredState,
  166. const LangOptions &LangOpts,
  167. const TargetInfo &Target) {
  168. Requirements.push_back(Requirement(Feature, RequiredState));
  169. // If this feature is currently available, we're done.
  170. if (hasFeature(Feature, LangOpts, Target) == RequiredState)
  171. return;
  172. markUnavailable(/*MissingRequirement*/true);
  173. }
  174. void Module::markUnavailable(bool MissingRequirement) {
  175. auto needUpdate = [MissingRequirement](Module *M) {
  176. return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement);
  177. };
  178. if (!needUpdate(this))
  179. return;
  180. SmallVector<Module *, 2> Stack;
  181. Stack.push_back(this);
  182. while (!Stack.empty()) {
  183. Module *Current = Stack.back();
  184. Stack.pop_back();
  185. if (!needUpdate(Current))
  186. continue;
  187. Current->IsAvailable = false;
  188. Current->IsMissingRequirement |= MissingRequirement;
  189. for (submodule_iterator Sub = Current->submodule_begin(),
  190. SubEnd = Current->submodule_end();
  191. Sub != SubEnd; ++Sub) {
  192. if (needUpdate(*Sub))
  193. Stack.push_back(*Sub);
  194. }
  195. }
  196. }
  197. Module *Module::findSubmodule(StringRef Name) const {
  198. llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
  199. if (Pos == SubModuleIndex.end())
  200. return nullptr;
  201. return SubModules[Pos->getValue()];
  202. }
  203. static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
  204. for (unsigned I = 0, N = Id.size(); I != N; ++I) {
  205. if (I)
  206. OS << ".";
  207. OS << Id[I].first;
  208. }
  209. }
  210. void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
  211. // All non-explicit submodules are exported.
  212. for (std::vector<Module *>::const_iterator I = SubModules.begin(),
  213. E = SubModules.end();
  214. I != E; ++I) {
  215. Module *Mod = *I;
  216. if (!Mod->IsExplicit)
  217. Exported.push_back(Mod);
  218. }
  219. // Find re-exported modules by filtering the list of imported modules.
  220. bool AnyWildcard = false;
  221. bool UnrestrictedWildcard = false;
  222. SmallVector<Module *, 4> WildcardRestrictions;
  223. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  224. Module *Mod = Exports[I].getPointer();
  225. if (!Exports[I].getInt()) {
  226. // Export a named module directly; no wildcards involved.
  227. Exported.push_back(Mod);
  228. continue;
  229. }
  230. // Wildcard export: export all of the imported modules that match
  231. // the given pattern.
  232. AnyWildcard = true;
  233. if (UnrestrictedWildcard)
  234. continue;
  235. if (Module *Restriction = Exports[I].getPointer())
  236. WildcardRestrictions.push_back(Restriction);
  237. else {
  238. WildcardRestrictions.clear();
  239. UnrestrictedWildcard = true;
  240. }
  241. }
  242. // If there were any wildcards, push any imported modules that were
  243. // re-exported by the wildcard restriction.
  244. if (!AnyWildcard)
  245. return;
  246. for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
  247. Module *Mod = Imports[I];
  248. bool Acceptable = UnrestrictedWildcard;
  249. if (!Acceptable) {
  250. // Check whether this module meets one of the restrictions.
  251. for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
  252. Module *Restriction = WildcardRestrictions[R];
  253. if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
  254. Acceptable = true;
  255. break;
  256. }
  257. }
  258. }
  259. if (!Acceptable)
  260. continue;
  261. Exported.push_back(Mod);
  262. }
  263. }
  264. void Module::buildVisibleModulesCache() const {
  265. assert(VisibleModulesCache.empty() && "cache does not need building");
  266. // This module is visible to itself.
  267. VisibleModulesCache.insert(this);
  268. // Every imported module is visible.
  269. SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
  270. while (!Stack.empty()) {
  271. Module *CurrModule = Stack.pop_back_val();
  272. // Every module transitively exported by an imported module is visible.
  273. if (VisibleModulesCache.insert(CurrModule).second)
  274. CurrModule->getExportedModules(Stack);
  275. }
  276. }
  277. void Module::print(raw_ostream &OS, unsigned Indent) const {
  278. OS.indent(Indent);
  279. if (IsFramework)
  280. OS << "framework ";
  281. if (IsExplicit)
  282. OS << "explicit ";
  283. OS << "module " << Name;
  284. if (IsSystem || IsExternC) {
  285. OS.indent(Indent + 2);
  286. if (IsSystem)
  287. OS << " [system]";
  288. if (IsExternC)
  289. OS << " [extern_c]";
  290. }
  291. OS << " {\n";
  292. if (!Requirements.empty()) {
  293. OS.indent(Indent + 2);
  294. OS << "requires ";
  295. for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
  296. if (I)
  297. OS << ", ";
  298. if (!Requirements[I].second)
  299. OS << "!";
  300. OS << Requirements[I].first;
  301. }
  302. OS << "\n";
  303. }
  304. if (Header H = getUmbrellaHeader()) {
  305. OS.indent(Indent + 2);
  306. OS << "umbrella header \"";
  307. OS.write_escaped(H.NameAsWritten);
  308. OS << "\"\n";
  309. } else if (DirectoryName D = getUmbrellaDir()) {
  310. OS.indent(Indent + 2);
  311. OS << "umbrella \"";
  312. OS.write_escaped(D.NameAsWritten);
  313. OS << "\"\n";
  314. }
  315. if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
  316. OS.indent(Indent + 2);
  317. OS << "config_macros ";
  318. if (ConfigMacrosExhaustive)
  319. OS << "[exhaustive]";
  320. for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
  321. if (I)
  322. OS << ", ";
  323. OS << ConfigMacros[I];
  324. }
  325. OS << "\n";
  326. }
  327. struct {
  328. StringRef Prefix;
  329. HeaderKind Kind;
  330. } Kinds[] = {{"", HK_Normal},
  331. {"textual ", HK_Textual},
  332. {"private ", HK_Private},
  333. {"private textual ", HK_PrivateTextual},
  334. {"exclude ", HK_Excluded}};
  335. for (auto &K : Kinds) {
  336. for (auto &H : Headers[K.Kind]) {
  337. OS.indent(Indent + 2);
  338. OS << K.Prefix << "header \"";
  339. OS.write_escaped(H.NameAsWritten);
  340. OS << "\"\n";
  341. }
  342. }
  343. for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
  344. MI != MIEnd; ++MI)
  345. // Print inferred subframework modules so that we don't need to re-infer
  346. // them (requires expensive directory iteration + stat calls) when we build
  347. // the module. Regular inferred submodules are OK, as we need to look at all
  348. // those header files anyway.
  349. if (!(*MI)->IsInferred || (*MI)->IsFramework)
  350. (*MI)->print(OS, Indent + 2);
  351. for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
  352. OS.indent(Indent + 2);
  353. OS << "export ";
  354. if (Module *Restriction = Exports[I].getPointer()) {
  355. OS << Restriction->getFullModuleName();
  356. if (Exports[I].getInt())
  357. OS << ".*";
  358. } else {
  359. OS << "*";
  360. }
  361. OS << "\n";
  362. }
  363. for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
  364. OS.indent(Indent + 2);
  365. OS << "export ";
  366. printModuleId(OS, UnresolvedExports[I].Id);
  367. if (UnresolvedExports[I].Wildcard)
  368. OS << (UnresolvedExports[I].Id.empty() ? "*" : ".*");
  369. OS << "\n";
  370. }
  371. for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
  372. OS.indent(Indent + 2);
  373. OS << "use ";
  374. OS << DirectUses[I]->getFullModuleName();
  375. OS << "\n";
  376. }
  377. for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
  378. OS.indent(Indent + 2);
  379. OS << "use ";
  380. printModuleId(OS, UnresolvedDirectUses[I]);
  381. OS << "\n";
  382. }
  383. for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
  384. OS.indent(Indent + 2);
  385. OS << "link ";
  386. if (LinkLibraries[I].IsFramework)
  387. OS << "framework ";
  388. OS << "\"";
  389. OS.write_escaped(LinkLibraries[I].Library);
  390. OS << "\"";
  391. }
  392. for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
  393. OS.indent(Indent + 2);
  394. OS << "conflict ";
  395. printModuleId(OS, UnresolvedConflicts[I].Id);
  396. OS << ", \"";
  397. OS.write_escaped(UnresolvedConflicts[I].Message);
  398. OS << "\"\n";
  399. }
  400. for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
  401. OS.indent(Indent + 2);
  402. OS << "conflict ";
  403. OS << Conflicts[I].Other->getFullModuleName();
  404. OS << ", \"";
  405. OS.write_escaped(Conflicts[I].Message);
  406. OS << "\"\n";
  407. }
  408. if (InferSubmodules) {
  409. OS.indent(Indent + 2);
  410. if (InferExplicitSubmodules)
  411. OS << "explicit ";
  412. OS << "module * {\n";
  413. if (InferExportWildcard) {
  414. OS.indent(Indent + 4);
  415. OS << "export *\n";
  416. }
  417. OS.indent(Indent + 2);
  418. OS << "}\n";
  419. }
  420. OS.indent(Indent);
  421. OS << "}\n";
  422. }
  423. LLVM_DUMP_METHOD void Module::dump() const {
  424. print(llvm::errs());
  425. }
  426. void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc,
  427. VisibleCallback Vis, ConflictCallback Cb) {
  428. assert(Loc.isValid() && "setVisible expects a valid import location");
  429. if (isVisible(M))
  430. return;
  431. ++Generation;
  432. struct Visiting {
  433. Module *M;
  434. Visiting *ExportedBy;
  435. };
  436. std::function<void(Visiting)> VisitModule = [&](Visiting V) {
  437. // Modules that aren't available cannot be made visible.
  438. if (!V.M->isAvailable())
  439. return;
  440. // Nothing to do for a module that's already visible.
  441. unsigned ID = V.M->getVisibilityID();
  442. if (ImportLocs.size() <= ID)
  443. ImportLocs.resize(ID + 1);
  444. else if (ImportLocs[ID].isValid())
  445. return;
  446. ImportLocs[ID] = Loc;
  447. Vis(M);
  448. // Make any exported modules visible.
  449. SmallVector<Module *, 16> Exports;
  450. V.M->getExportedModules(Exports);
  451. for (Module *E : Exports)
  452. VisitModule({E, &V});
  453. for (auto &C : V.M->Conflicts) {
  454. if (isVisible(C.Other)) {
  455. llvm::SmallVector<Module*, 8> Path;
  456. for (Visiting *I = &V; I; I = I->ExportedBy)
  457. Path.push_back(I->M);
  458. Cb(Path, C.Other, C.Message);
  459. }
  460. }
  461. };
  462. VisitModule({M, nullptr});
  463. }