cmComputeLinkDepends.cxx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmComputeLinkDepends.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmComputeComponentGraph.h"
  6. #include "cmGeneratorTarget.h"
  7. #include "cmGlobalGenerator.h"
  8. #include "cmListFileCache.h"
  9. #include "cmLocalGenerator.h"
  10. #include "cmMakefile.h"
  11. #include "cmRange.h"
  12. #include "cmStateTypes.h"
  13. #include "cmStringAlgorithms.h"
  14. #include "cmTarget.h"
  15. #include "cmake.h"
  16. #include <algorithm>
  17. #include <assert.h>
  18. #include <iterator>
  19. #include <sstream>
  20. #include <stdio.h>
  21. #include <string.h>
  22. #include <utility>
  23. #include "cm_memory.hxx"
  24. /*
  25. This file computes an ordered list of link items to use when linking a
  26. single target in one configuration. Each link item is identified by
  27. the string naming it. A graph of dependencies is created in which
  28. each node corresponds to one item and directed edges lead from nodes to
  29. those which must *follow* them on the link line. For example, the
  30. graph
  31. A -> B -> C
  32. will lead to the link line order
  33. A B C
  34. The set of items placed in the graph is formed with a breadth-first
  35. search of the link dependencies starting from the main target.
  36. There are two types of items: those with known direct dependencies and
  37. those without known dependencies. We will call the two types "known
  38. items" and "unknown items", respectively. Known items are those whose
  39. names correspond to targets (built or imported) and those for which an
  40. old-style <item>_LIB_DEPENDS variable is defined. All other items are
  41. unknown and we must infer dependencies for them. For items that look
  42. like flags (beginning with '-') we trivially infer no dependencies,
  43. and do not include them in the dependencies of other items.
  44. Known items have dependency lists ordered based on how the user
  45. specified them. We can use this order to infer potential dependencies
  46. of unknown items. For example, if link items A and B are unknown and
  47. items X and Y are known, then we might have the following dependency
  48. lists:
  49. X: Y A B
  50. Y: A B
  51. The explicitly known dependencies form graph edges
  52. X -> Y , X -> A , X -> B , Y -> A , Y -> B
  53. We can also infer the edge
  54. A -> B
  55. because *every* time A appears B is seen on its right. We do not know
  56. whether A really needs symbols from B to link, but it *might* so we
  57. must preserve their order. This is the case also for the following
  58. explicit lists:
  59. X: A B Y
  60. Y: A B
  61. Here, A is followed by the set {B,Y} in one list, and {B} in the other
  62. list. The intersection of these sets is {B}, so we can infer that A
  63. depends on at most B. Meanwhile B is followed by the set {Y} in one
  64. list and {} in the other. The intersection is {} so we can infer that
  65. B has no dependencies.
  66. Let's make a more complex example by adding unknown item C and
  67. considering these dependency lists:
  68. X: A B Y C
  69. Y: A C B
  70. The explicit edges are
  71. X -> Y , X -> A , X -> B , X -> C , Y -> A , Y -> B , Y -> C
  72. For the unknown items, we infer dependencies by looking at the
  73. "follow" sets:
  74. A: intersect( {B,Y,C} , {C,B} ) = {B,C} ; infer edges A -> B , A -> C
  75. B: intersect( {Y,C} , {} ) = {} ; infer no edges
  76. C: intersect( {} , {B} ) = {} ; infer no edges
  77. Note that targets are never inferred as dependees because outside
  78. libraries should not depend on them.
  79. ------------------------------------------------------------------------------
  80. The initial exploration of dependencies using a BFS associates an
  81. integer index with each link item. When the graph is built outgoing
  82. edges are sorted by this index.
  83. After the initial exploration of the link interface tree, any
  84. transitive (dependent) shared libraries that were encountered and not
  85. included in the interface are processed in their own BFS. This BFS
  86. follows only the dependent library lists and not the link interfaces.
  87. They are added to the link items with a mark indicating that the are
  88. transitive dependencies. Then cmComputeLinkInformation deals with
  89. them on a per-platform basis.
  90. The complete graph formed from all known and inferred dependencies may
  91. not be acyclic, so an acyclic version must be created.
  92. The original graph is converted to a directed acyclic graph in which
  93. each node corresponds to a strongly connected component of the
  94. original graph. For example, the dependency graph
  95. X -> A -> B -> C -> A -> Y
  96. contains strongly connected components {X}, {A,B,C}, and {Y}. The
  97. implied directed acyclic graph (DAG) is
  98. {X} -> {A,B,C} -> {Y}
  99. We then compute a topological order for the DAG nodes to serve as a
  100. reference for satisfying dependencies efficiently. We perform the DFS
  101. in reverse order and assign topological order indices counting down so
  102. that the result is as close to the original BFS order as possible
  103. without violating dependencies.
  104. ------------------------------------------------------------------------------
  105. The final link entry order is constructed as follows. We first walk
  106. through and emit the *original* link line as specified by the user.
  107. As each item is emitted, a set of pending nodes in the component DAG
  108. is maintained. When a pending component has been completely seen, it
  109. is removed from the pending set and its dependencies (following edges
  110. of the DAG) are added. A trivial component (those with one item) is
  111. complete as soon as its item is seen. A non-trivial component (one
  112. with more than one item; assumed to be static libraries) is complete
  113. when *all* its entries have been seen *twice* (all entries seen once,
  114. then all entries seen again, not just each entry twice). A pending
  115. component tracks which items have been seen and a count of how many
  116. times the component needs to be seen (once for trivial components,
  117. twice for non-trivial). If at any time another component finishes and
  118. re-adds an already pending component, the pending component is reset
  119. so that it needs to be seen in its entirety again. This ensures that
  120. all dependencies of a component are satisfied no matter where it
  121. appears.
  122. After the original link line has been completed, we append to it the
  123. remaining pending components and their dependencies. This is done by
  124. repeatedly emitting the first item from the first pending component
  125. and following the same update rules as when traversing the original
  126. link line. Since the pending components are kept in topological order
  127. they are emitted with minimal repeats (we do not want to emit a
  128. component just to have it added again when another component is
  129. completed later). This process continues until no pending components
  130. remain. We know it will terminate because the component graph is
  131. guaranteed to be acyclic.
  132. The final list of items produced by this procedure consists of the
  133. original user link line followed by minimal additional items needed to
  134. satisfy dependencies. The final list is then filtered to de-duplicate
  135. items that we know the linker will re-use automatically (shared libs).
  136. */
  137. cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target,
  138. const std::string& config)
  139. {
  140. // Store context information.
  141. this->Target = target;
  142. this->Makefile = this->Target->Target->GetMakefile();
  143. this->GlobalGenerator =
  144. this->Target->GetLocalGenerator()->GetGlobalGenerator();
  145. this->CMakeInstance = this->GlobalGenerator->GetCMakeInstance();
  146. // The configuration being linked.
  147. this->HasConfig = !config.empty();
  148. this->Config = (this->HasConfig) ? config : std::string();
  149. std::vector<std::string> debugConfigs =
  150. this->Makefile->GetCMakeInstance()->GetDebugConfigs();
  151. this->LinkType = CMP0003_ComputeLinkType(this->Config, debugConfigs);
  152. // Enable debug mode if requested.
  153. this->DebugMode = this->Makefile->IsOn("CMAKE_LINK_DEPENDS_DEBUG_MODE");
  154. // Assume no compatibility until set.
  155. this->OldLinkDirMode = false;
  156. // No computation has been done.
  157. this->CCG = nullptr;
  158. }
  159. cmComputeLinkDepends::~cmComputeLinkDepends()
  160. {
  161. cmDeleteAll(this->InferredDependSets);
  162. }
  163. void cmComputeLinkDepends::SetOldLinkDirMode(bool b)
  164. {
  165. this->OldLinkDirMode = b;
  166. }
  167. std::vector<cmComputeLinkDepends::LinkEntry> const&
  168. cmComputeLinkDepends::Compute()
  169. {
  170. // Follow the link dependencies of the target to be linked.
  171. this->AddDirectLinkEntries();
  172. // Complete the breadth-first search of dependencies.
  173. while (!this->BFSQueue.empty()) {
  174. // Get the next entry.
  175. BFSEntry qe = this->BFSQueue.front();
  176. this->BFSQueue.pop();
  177. // Follow the entry's dependencies.
  178. this->FollowLinkEntry(qe);
  179. }
  180. // Complete the search of shared library dependencies.
  181. while (!this->SharedDepQueue.empty()) {
  182. // Handle the next entry.
  183. this->HandleSharedDependency(this->SharedDepQueue.front());
  184. this->SharedDepQueue.pop();
  185. }
  186. // Infer dependencies of targets for which they were not known.
  187. this->InferDependencies();
  188. // Cleanup the constraint graph.
  189. this->CleanConstraintGraph();
  190. // Display the constraint graph.
  191. if (this->DebugMode) {
  192. fprintf(stderr,
  193. "---------------------------------------"
  194. "---------------------------------------\n");
  195. fprintf(stderr, "Link dependency analysis for target %s, config %s\n",
  196. this->Target->GetName().c_str(),
  197. this->HasConfig ? this->Config.c_str() : "noconfig");
  198. this->DisplayConstraintGraph();
  199. }
  200. // Compute the final ordering.
  201. this->OrderLinkEntires();
  202. // Compute the final set of link entries.
  203. // Iterate in reverse order so we can keep only the last occurrence
  204. // of a shared library.
  205. std::set<int> emmitted;
  206. for (int i : cmReverseRange(this->FinalLinkOrder)) {
  207. LinkEntry const& e = this->EntryList[i];
  208. cmGeneratorTarget const* t = e.Target;
  209. // Entries that we know the linker will re-use do not need to be repeated.
  210. bool uniquify = t && t->GetType() == cmStateEnums::SHARED_LIBRARY;
  211. if (!uniquify || emmitted.insert(i).second) {
  212. this->FinalLinkEntries.push_back(e);
  213. }
  214. }
  215. // Reverse the resulting order since we iterated in reverse.
  216. std::reverse(this->FinalLinkEntries.begin(), this->FinalLinkEntries.end());
  217. // Display the final set.
  218. if (this->DebugMode) {
  219. this->DisplayFinalEntries();
  220. }
  221. return this->FinalLinkEntries;
  222. }
  223. std::map<cmLinkItem, int>::iterator cmComputeLinkDepends::AllocateLinkEntry(
  224. cmLinkItem const& item)
  225. {
  226. std::map<cmLinkItem, int>::value_type index_entry(
  227. item, static_cast<int>(this->EntryList.size()));
  228. std::map<cmLinkItem, int>::iterator lei =
  229. this->LinkEntryIndex.insert(index_entry).first;
  230. this->EntryList.emplace_back();
  231. this->InferredDependSets.push_back(nullptr);
  232. this->EntryConstraintGraph.emplace_back();
  233. return lei;
  234. }
  235. int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item)
  236. {
  237. // Check if the item entry has already been added.
  238. std::map<cmLinkItem, int>::iterator lei = this->LinkEntryIndex.find(item);
  239. if (lei != this->LinkEntryIndex.end()) {
  240. // Yes. We do not need to follow the item's dependencies again.
  241. return lei->second;
  242. }
  243. // Allocate a spot for the item entry.
  244. lei = this->AllocateLinkEntry(item);
  245. // Initialize the item entry.
  246. int index = lei->second;
  247. LinkEntry& entry = this->EntryList[index];
  248. entry.Item = item.AsStr();
  249. entry.Target = item.Target;
  250. entry.IsFlag =
  251. (!entry.Target && entry.Item[0] == '-' && entry.Item[1] != 'l' &&
  252. entry.Item.substr(0, 10) != "-framework");
  253. // If the item has dependencies queue it to follow them.
  254. if (entry.Target) {
  255. // Target dependencies are always known. Follow them.
  256. BFSEntry qe = { index, nullptr };
  257. this->BFSQueue.push(qe);
  258. } else {
  259. // Look for an old-style <item>_LIB_DEPENDS variable.
  260. std::string var = entry.Item;
  261. var += "_LIB_DEPENDS";
  262. if (const char* val = this->Makefile->GetDefinition(var)) {
  263. // The item dependencies are known. Follow them.
  264. BFSEntry qe = { index, val };
  265. this->BFSQueue.push(qe);
  266. } else if (!entry.IsFlag) {
  267. // The item dependencies are not known. We need to infer them.
  268. this->InferredDependSets[index] = new DependSetList;
  269. }
  270. }
  271. return index;
  272. }
  273. void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
  274. {
  275. // Get this entry representation.
  276. int depender_index = qe.Index;
  277. LinkEntry const& entry = this->EntryList[depender_index];
  278. // Follow the item's dependencies.
  279. if (entry.Target) {
  280. // Follow the target dependencies.
  281. if (cmLinkInterface const* iface =
  282. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  283. const bool isIface =
  284. entry.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY;
  285. // This target provides its own link interface information.
  286. this->AddLinkEntries(depender_index, iface->Libraries);
  287. if (isIface) {
  288. return;
  289. }
  290. // Handle dependent shared libraries.
  291. this->FollowSharedDeps(depender_index, iface);
  292. // Support for CMP0003.
  293. for (cmLinkItem const& oi : iface->WrongConfigLibraries) {
  294. this->CheckWrongConfigItem(oi);
  295. }
  296. }
  297. } else {
  298. // Follow the old-style dependency list.
  299. this->AddVarLinkEntries(depender_index, qe.LibDepends);
  300. }
  301. }
  302. void cmComputeLinkDepends::FollowSharedDeps(int depender_index,
  303. cmLinkInterface const* iface,
  304. bool follow_interface)
  305. {
  306. // Follow dependencies if we have not followed them already.
  307. if (this->SharedDepFollowed.insert(depender_index).second) {
  308. if (follow_interface) {
  309. this->QueueSharedDependencies(depender_index, iface->Libraries);
  310. }
  311. this->QueueSharedDependencies(depender_index, iface->SharedDeps);
  312. }
  313. }
  314. void cmComputeLinkDepends::QueueSharedDependencies(
  315. int depender_index, std::vector<cmLinkItem> const& deps)
  316. {
  317. for (cmLinkItem const& li : deps) {
  318. SharedDepEntry qe;
  319. qe.Item = li;
  320. qe.DependerIndex = depender_index;
  321. this->SharedDepQueue.push(qe);
  322. }
  323. }
  324. void cmComputeLinkDepends::HandleSharedDependency(SharedDepEntry const& dep)
  325. {
  326. // Check if the target already has an entry.
  327. std::map<cmLinkItem, int>::iterator lei =
  328. this->LinkEntryIndex.find(dep.Item);
  329. if (lei == this->LinkEntryIndex.end()) {
  330. // Allocate a spot for the item entry.
  331. lei = this->AllocateLinkEntry(dep.Item);
  332. // Initialize the item entry.
  333. LinkEntry& entry = this->EntryList[lei->second];
  334. entry.Item = dep.Item.AsStr();
  335. entry.Target = dep.Item.Target;
  336. // This item was added specifically because it is a dependent
  337. // shared library. It may get special treatment
  338. // in cmComputeLinkInformation.
  339. entry.IsSharedDep = true;
  340. }
  341. // Get the link entry for this target.
  342. int index = lei->second;
  343. LinkEntry& entry = this->EntryList[index];
  344. // This shared library dependency must follow the item that listed
  345. // it.
  346. this->EntryConstraintGraph[dep.DependerIndex].emplace_back(
  347. index, true, cmListFileBacktrace());
  348. // Target items may have their own dependencies.
  349. if (entry.Target) {
  350. if (cmLinkInterface const* iface =
  351. entry.Target->GetLinkInterface(this->Config, this->Target)) {
  352. // Follow public and private dependencies transitively.
  353. this->FollowSharedDeps(index, iface, true);
  354. }
  355. }
  356. }
  357. void cmComputeLinkDepends::AddVarLinkEntries(int depender_index,
  358. const char* value)
  359. {
  360. // This is called to add the dependencies named by
  361. // <item>_LIB_DEPENDS. The variable contains a semicolon-separated
  362. // list. The list contains link-type;item pairs and just items.
  363. std::vector<std::string> deplist;
  364. cmExpandList(value, deplist);
  365. // Look for entries meant for this configuration.
  366. std::vector<cmLinkItem> actual_libs;
  367. cmTargetLinkLibraryType llt = GENERAL_LibraryType;
  368. bool haveLLT = false;
  369. for (std::string const& d : deplist) {
  370. if (d == "debug") {
  371. llt = DEBUG_LibraryType;
  372. haveLLT = true;
  373. } else if (d == "optimized") {
  374. llt = OPTIMIZED_LibraryType;
  375. haveLLT = true;
  376. } else if (d == "general") {
  377. llt = GENERAL_LibraryType;
  378. haveLLT = true;
  379. } else if (!d.empty()) {
  380. // If no explicit link type was given prior to this entry then
  381. // check if the entry has its own link type variable. This is
  382. // needed for compatibility with dependency files generated by
  383. // the export_library_dependencies command from CMake 2.4 and
  384. // lower.
  385. if (!haveLLT) {
  386. std::string var = d;
  387. var += "_LINK_TYPE";
  388. if (const char* val = this->Makefile->GetDefinition(var)) {
  389. if (strcmp(val, "debug") == 0) {
  390. llt = DEBUG_LibraryType;
  391. } else if (strcmp(val, "optimized") == 0) {
  392. llt = OPTIMIZED_LibraryType;
  393. }
  394. }
  395. }
  396. // If the library is meant for this link type then use it.
  397. if (llt == GENERAL_LibraryType || llt == this->LinkType) {
  398. actual_libs.emplace_back(this->ResolveLinkItem(depender_index, d));
  399. } else if (this->OldLinkDirMode) {
  400. cmLinkItem item = this->ResolveLinkItem(depender_index, d);
  401. this->CheckWrongConfigItem(item);
  402. }
  403. // Reset the link type until another explicit type is given.
  404. llt = GENERAL_LibraryType;
  405. haveLLT = false;
  406. }
  407. }
  408. // Add the entries from this list.
  409. this->AddLinkEntries(depender_index, actual_libs);
  410. }
  411. void cmComputeLinkDepends::AddDirectLinkEntries()
  412. {
  413. // Add direct link dependencies in this configuration.
  414. cmLinkImplementation const* impl =
  415. this->Target->GetLinkImplementation(this->Config);
  416. this->AddLinkEntries(-1, impl->Libraries);
  417. for (cmLinkItem const& wi : impl->WrongConfigLibraries) {
  418. this->CheckWrongConfigItem(wi);
  419. }
  420. }
  421. template <typename T>
  422. void cmComputeLinkDepends::AddLinkEntries(int depender_index,
  423. std::vector<T> const& libs)
  424. {
  425. // Track inferred dependency sets implied by this list.
  426. std::map<int, DependSet> dependSets;
  427. // Loop over the libraries linked directly by the depender.
  428. for (T const& l : libs) {
  429. // Skip entries that will resolve to the target getting linked or
  430. // are empty.
  431. cmLinkItem const& item = l;
  432. if (item.AsStr() == this->Target->GetName() || item.AsStr().empty()) {
  433. continue;
  434. }
  435. // Add a link entry for this item.
  436. int dependee_index = this->AddLinkEntry(l);
  437. // The dependee must come after the depender.
  438. if (depender_index >= 0) {
  439. this->EntryConstraintGraph[depender_index].emplace_back(
  440. dependee_index, false, cmListFileBacktrace());
  441. } else {
  442. // This is a direct dependency of the target being linked.
  443. this->OriginalEntries.push_back(dependee_index);
  444. }
  445. // Update the inferred dependencies for earlier items.
  446. for (auto& dependSet : dependSets) {
  447. // Add this item to the inferred dependencies of other items.
  448. // Target items are never inferred dependees because unknown
  449. // items are outside libraries that should not be depending on
  450. // targets.
  451. if (!this->EntryList[dependee_index].Target &&
  452. !this->EntryList[dependee_index].IsFlag &&
  453. dependee_index != dependSet.first) {
  454. dependSet.second.insert(dependee_index);
  455. }
  456. }
  457. // If this item needs to have dependencies inferred, do so.
  458. if (this->InferredDependSets[dependee_index]) {
  459. // Make sure an entry exists to hold the set for the item.
  460. dependSets[dependee_index];
  461. }
  462. }
  463. // Store the inferred dependency sets discovered for this list.
  464. for (auto const& dependSet : dependSets) {
  465. this->InferredDependSets[dependSet.first]->push_back(dependSet.second);
  466. }
  467. }
  468. cmLinkItem cmComputeLinkDepends::ResolveLinkItem(int depender_index,
  469. const std::string& name)
  470. {
  471. // Look for a target in the scope of the depender.
  472. cmGeneratorTarget const* from = this->Target;
  473. if (depender_index >= 0) {
  474. if (cmGeneratorTarget const* depender =
  475. this->EntryList[depender_index].Target) {
  476. from = depender;
  477. }
  478. }
  479. return from->ResolveLinkItem(name, cmListFileBacktrace());
  480. }
  481. void cmComputeLinkDepends::InferDependencies()
  482. {
  483. // The inferred dependency sets for each item list the possible
  484. // dependencies. The intersection of the sets for one item form its
  485. // inferred dependencies.
  486. for (unsigned int depender_index = 0;
  487. depender_index < this->InferredDependSets.size(); ++depender_index) {
  488. // Skip items for which dependencies do not need to be inferred or
  489. // for which the inferred dependency sets are empty.
  490. DependSetList* sets = this->InferredDependSets[depender_index];
  491. if (!sets || sets->empty()) {
  492. continue;
  493. }
  494. // Intersect the sets for this item.
  495. DependSet common = sets->front();
  496. for (DependSet const& i : cmMakeRange(*sets).advance(1)) {
  497. DependSet intersection;
  498. std::set_intersection(common.begin(), common.end(), i.begin(), i.end(),
  499. std::inserter(intersection, intersection.begin()));
  500. common = intersection;
  501. }
  502. // Add the inferred dependencies to the graph.
  503. cmGraphEdgeList& edges = this->EntryConstraintGraph[depender_index];
  504. edges.reserve(edges.size() + common.size());
  505. for (auto const& c : common) {
  506. edges.emplace_back(c, true, cmListFileBacktrace());
  507. }
  508. }
  509. }
  510. void cmComputeLinkDepends::CleanConstraintGraph()
  511. {
  512. for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
  513. // Sort the outgoing edges for each graph node so that the
  514. // original order will be preserved as much as possible.
  515. std::sort(edgeList.begin(), edgeList.end());
  516. // Make the edge list unique.
  517. edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
  518. edgeList.end());
  519. }
  520. }
  521. void cmComputeLinkDepends::DisplayConstraintGraph()
  522. {
  523. // Display the graph nodes and their edges.
  524. std::ostringstream e;
  525. for (unsigned int i = 0; i < this->EntryConstraintGraph.size(); ++i) {
  526. EdgeList const& nl = this->EntryConstraintGraph[i];
  527. e << "item " << i << " is [" << this->EntryList[i].Item << "]\n";
  528. e << cmWrap(" item ", nl, " must follow it", "\n") << "\n";
  529. }
  530. fprintf(stderr, "%s\n", e.str().c_str());
  531. }
  532. void cmComputeLinkDepends::OrderLinkEntires()
  533. {
  534. // Compute the DAG of strongly connected components. The algorithm
  535. // used by cmComputeComponentGraph should identify the components in
  536. // the same order in which the items were originally discovered in
  537. // the BFS. This should preserve the original order when no
  538. // constraints disallow it.
  539. this->CCG =
  540. cm::make_unique<cmComputeComponentGraph>(this->EntryConstraintGraph);
  541. // The component graph is guaranteed to be acyclic. Start a DFS
  542. // from every entry to compute a topological order for the
  543. // components.
  544. Graph const& cgraph = this->CCG->GetComponentGraph();
  545. int n = static_cast<int>(cgraph.size());
  546. this->ComponentVisited.resize(cgraph.size(), 0);
  547. this->ComponentOrder.resize(cgraph.size(), n);
  548. this->ComponentOrderId = n;
  549. // Run in reverse order so the topological order will preserve the
  550. // original order where there are no constraints.
  551. for (int c = n - 1; c >= 0; --c) {
  552. this->VisitComponent(c);
  553. }
  554. // Display the component graph.
  555. if (this->DebugMode) {
  556. this->DisplayComponents();
  557. }
  558. // Start with the original link line.
  559. for (int originalEntry : this->OriginalEntries) {
  560. this->VisitEntry(originalEntry);
  561. }
  562. // Now explore anything left pending. Since the component graph is
  563. // guaranteed to be acyclic we know this will terminate.
  564. while (!this->PendingComponents.empty()) {
  565. // Visit one entry from the first pending component. The visit
  566. // logic will update the pending components accordingly. Since
  567. // the pending components are kept in topological order this will
  568. // not repeat one.
  569. int e = *this->PendingComponents.begin()->second.Entries.begin();
  570. this->VisitEntry(e);
  571. }
  572. }
  573. void cmComputeLinkDepends::DisplayComponents()
  574. {
  575. fprintf(stderr, "The strongly connected components are:\n");
  576. std::vector<NodeList> const& components = this->CCG->GetComponents();
  577. for (unsigned int c = 0; c < components.size(); ++c) {
  578. fprintf(stderr, "Component (%u):\n", c);
  579. NodeList const& nl = components[c];
  580. for (int i : nl) {
  581. fprintf(stderr, " item %d [%s]\n", i, this->EntryList[i].Item.c_str());
  582. }
  583. EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
  584. for (cmGraphEdge const& oi : ol) {
  585. int i = oi;
  586. fprintf(stderr, " followed by Component (%d)\n", i);
  587. }
  588. fprintf(stderr, " topo order index %d\n", this->ComponentOrder[c]);
  589. }
  590. fprintf(stderr, "\n");
  591. }
  592. void cmComputeLinkDepends::VisitComponent(unsigned int c)
  593. {
  594. // Check if the node has already been visited.
  595. if (this->ComponentVisited[c]) {
  596. return;
  597. }
  598. // We are now visiting this component so mark it.
  599. this->ComponentVisited[c] = 1;
  600. // Visit the neighbors of the component first.
  601. // Run in reverse order so the topological order will preserve the
  602. // original order where there are no constraints.
  603. EdgeList const& nl = this->CCG->GetComponentGraphEdges(c);
  604. for (cmGraphEdge const& edge : cmReverseRange(nl)) {
  605. this->VisitComponent(edge);
  606. }
  607. // Assign an ordering id to this component.
  608. this->ComponentOrder[c] = --this->ComponentOrderId;
  609. }
  610. void cmComputeLinkDepends::VisitEntry(int index)
  611. {
  612. // Include this entry on the link line.
  613. this->FinalLinkOrder.push_back(index);
  614. // This entry has now been seen. Update its component.
  615. bool completed = false;
  616. int component = this->CCG->GetComponentMap()[index];
  617. std::map<int, PendingComponent>::iterator mi =
  618. this->PendingComponents.find(this->ComponentOrder[component]);
  619. if (mi != this->PendingComponents.end()) {
  620. // The entry is in an already pending component.
  621. PendingComponent& pc = mi->second;
  622. // Remove the entry from those pending in its component.
  623. pc.Entries.erase(index);
  624. if (pc.Entries.empty()) {
  625. // The complete component has been seen since it was last needed.
  626. --pc.Count;
  627. if (pc.Count == 0) {
  628. // The component has been completed.
  629. this->PendingComponents.erase(mi);
  630. completed = true;
  631. } else {
  632. // The whole component needs to be seen again.
  633. NodeList const& nl = this->CCG->GetComponent(component);
  634. assert(nl.size() > 1);
  635. pc.Entries.insert(nl.begin(), nl.end());
  636. }
  637. }
  638. } else {
  639. // The entry is not in an already pending component.
  640. NodeList const& nl = this->CCG->GetComponent(component);
  641. if (nl.size() > 1) {
  642. // This is a non-trivial component. It is now pending.
  643. PendingComponent& pc = this->MakePendingComponent(component);
  644. // The starting entry has already been seen.
  645. pc.Entries.erase(index);
  646. } else {
  647. // This is a trivial component, so it is already complete.
  648. completed = true;
  649. }
  650. }
  651. // If the entry completed a component, the component's dependencies
  652. // are now pending.
  653. if (completed) {
  654. EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
  655. for (cmGraphEdge const& oi : ol) {
  656. // This entire component is now pending no matter whether it has
  657. // been partially seen already.
  658. this->MakePendingComponent(oi);
  659. }
  660. }
  661. }
  662. cmComputeLinkDepends::PendingComponent&
  663. cmComputeLinkDepends::MakePendingComponent(unsigned int component)
  664. {
  665. // Create an entry (in topological order) for the component.
  666. PendingComponent& pc =
  667. this->PendingComponents[this->ComponentOrder[component]];
  668. pc.Id = component;
  669. NodeList const& nl = this->CCG->GetComponent(component);
  670. if (nl.size() == 1) {
  671. // Trivial components need be seen only once.
  672. pc.Count = 1;
  673. } else {
  674. // This is a non-trivial strongly connected component of the
  675. // original graph. It consists of two or more libraries
  676. // (archives) that mutually require objects from one another. In
  677. // the worst case we may have to repeat the list of libraries as
  678. // many times as there are object files in the biggest archive.
  679. // For now we just list them twice.
  680. //
  681. // The list of items in the component has been sorted by the order
  682. // of discovery in the original BFS of dependencies. This has the
  683. // advantage that the item directly linked by a target requiring
  684. // this component will come first which minimizes the number of
  685. // repeats needed.
  686. pc.Count = this->ComputeComponentCount(nl);
  687. }
  688. // Store the entries to be seen.
  689. pc.Entries.insert(nl.begin(), nl.end());
  690. return pc;
  691. }
  692. int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
  693. {
  694. unsigned int count = 2;
  695. for (int ni : nl) {
  696. if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
  697. if (cmLinkInterface const* iface =
  698. target->GetLinkInterface(this->Config, this->Target)) {
  699. if (iface->Multiplicity > count) {
  700. count = iface->Multiplicity;
  701. }
  702. }
  703. }
  704. }
  705. return count;
  706. }
  707. void cmComputeLinkDepends::DisplayFinalEntries()
  708. {
  709. fprintf(stderr, "target [%s] links to:\n", this->Target->GetName().c_str());
  710. for (LinkEntry const& lei : this->FinalLinkEntries) {
  711. if (lei.Target) {
  712. fprintf(stderr, " target [%s]\n", lei.Target->GetName().c_str());
  713. } else {
  714. fprintf(stderr, " item [%s]\n", lei.Item.c_str());
  715. }
  716. }
  717. fprintf(stderr, "\n");
  718. }
  719. void cmComputeLinkDepends::CheckWrongConfigItem(cmLinkItem const& item)
  720. {
  721. if (!this->OldLinkDirMode) {
  722. return;
  723. }
  724. // For CMake 2.4 bug-compatibility we need to consider the output
  725. // directories of targets linked in another configuration as link
  726. // directories.
  727. if (item.Target && !item.Target->IsImported()) {
  728. this->OldWrongConfigItems.insert(item.Target);
  729. }
  730. }