blob: 915a041db9eef2d4185c42befe3623d45503d4ce [file] [log] [blame]
Rui Ueyama00762152015-02-05 20:05:33 +00001//===-- ReaderWriter/MachO/LayoutPass.cpp - Layout atoms ------------------===//
Shankar Easwaran34ab70f2013-02-07 20:16:12 +00002//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Shankar Easwaran34ab70f2013-02-07 20:16:12 +00009
Rui Ueyama00762152015-02-05 20:05:33 +000010#include "LayoutPass.h"
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +000011#include "lld/Core/Instrumentation.h"
Rui Ueyama87d10ef2015-01-26 20:18:37 +000012#include "lld/Core/Parallel.h"
Rui Ueyama00762152015-02-05 20:05:33 +000013#include "lld/Core/PassManager.h"
14#include "lld/ReaderWriter/MachOLinkingContext.h"
Benjamin Kramer06a42af2015-03-02 00:48:06 +000015#include "llvm/ADT/STLExtras.h"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000016#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000017#include "llvm/Support/Debug.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000018#include <algorithm>
19#include <set>
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000020
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000021using namespace lld;
22
Chandler Carruth9afe32d2014-04-22 03:21:31 +000023#define DEBUG_TYPE "LayoutPass"
24
Rui Ueyama00762152015-02-05 20:05:33 +000025namespace lld {
26namespace mach_o {
27
Rui Ueyama5af46222013-12-08 03:24:09 +000028static bool compareAtoms(const LayoutPass::SortKey &,
Nick Kledzik82d24bc2014-11-07 21:01:21 +000029 const LayoutPass::SortKey &,
Rui Ueyama540842c2015-02-05 20:08:04 +000030 LayoutPass::SortOverride customSorter);
Rui Ueyama5af46222013-12-08 03:24:09 +000031
Rui Ueyama2994f6f2013-12-08 03:37:58 +000032#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000033// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000034static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama2ea86392014-09-18 23:21:39 +000035 return (Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")")
36 .str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000037}
Rui Ueyama46bf8282013-10-19 03:18:18 +000038
39// Less-than relationship of two atoms must be transitive, which is, if a < b
40// and b < c, a < c must be true. This function checks the transitivity by
41// checking the sort results.
Rui Ueyama540842c2015-02-05 20:08:04 +000042static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec,
43 LayoutPass::SortOverride customSorter) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000044 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
45 for (auto j = i + 1; j != e; ++j) {
Rui Ueyama540842c2015-02-05 20:08:04 +000046 assert(compareAtoms(*i, *j, customSorter));
47 assert(!compareAtoms(*j, *i, customSorter));
Rui Ueyama46bf8282013-10-19 03:18:18 +000048 }
49 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000050}
Rui Ueyamaa930d122013-12-09 00:37:19 +000051
52// Helper functions to check follow-on graph.
53typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
54
55static std::string atomToDebugString(const Atom *atom) {
56 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
57 std::string str;
58 llvm::raw_string_ostream s(str);
59 if (definedAtom->name().empty())
60 s << "<anonymous " << definedAtom << ">";
61 else
62 s << definedAtom->name();
63 s << " in ";
64 if (definedAtom->customSectionName().empty())
65 s << "<anonymous>";
66 else
67 s << definedAtom->customSectionName();
68 s.flush();
69 return str;
70}
71
Nico Rieckb9d84f42014-02-24 21:14:37 +000072static void showCycleDetectedError(const Registry &registry,
73 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000074 const DefinedAtom *atom) {
75 const DefinedAtom *start = atom;
76 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
77 do {
78 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
79 for (const Reference *ref : *atom) {
Nico Rieckb9d84f42014-02-24 21:14:37 +000080 StringRef kindValStr;
81 if (!registry.referenceKindToString(ref->kindNamespace(), ref->kindArch(),
82 ref->kindValue(), kindValStr)) {
83 kindValStr = "<unknown>";
84 }
85 llvm::dbgs() << " " << kindValStr
86 << ": " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000087 }
88 atom = followOnNexts[atom];
89 } while (atom != start);
90 llvm::report_fatal_error("Cycle detected");
91}
92
93/// Exit if there's a cycle in a followon chain reachable from the
94/// given root atom. Uses the tortoise and hare algorithm to detect a
95/// cycle.
Nico Rieckb9d84f42014-02-24 21:14:37 +000096static void checkNoCycleInFollowonChain(const Registry &registry,
97 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000098 const DefinedAtom *root) {
99 const DefinedAtom *tortoise = root;
100 const DefinedAtom *hare = followOnNexts[root];
101 while (true) {
102 if (!tortoise || !hare)
103 return;
104 if (tortoise == hare)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000105 showCycleDetectedError(registry, followOnNexts, tortoise);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000106 tortoise = followOnNexts[tortoise];
107 hare = followOnNexts[followOnNexts[hare]];
108 }
109}
110
111static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
112 const DefinedAtom *atom) {
113 if (!atom) return;
114 auto i = followOnRoots.find(atom);
115 if (i == followOnRoots.end()) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000116 llvm_unreachable(((Twine("Atom <") + atomToDebugString(atom) +
117 "> has no follow-on root!"))
118 .str()
119 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000120 }
121 const DefinedAtom *ap = i->second;
122 while (true) {
123 const DefinedAtom *next = followOnRoots[ap];
124 if (!next) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000125 llvm_unreachable((Twine("Atom <" + atomToDebugString(atom) +
126 "> is not reachable from its root!"))
127 .str()
128 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000129 }
130 if (next == ap)
131 return;
132 ap = next;
133 }
134}
135
Rui Ueyama3c45cff2015-04-07 20:43:38 +0000136static void printDefinedAtoms(const SimpleFile::DefinedAtomRange &atomRange) {
Rui Ueyamaa930d122013-12-09 00:37:19 +0000137 for (const DefinedAtom *atom : atomRange) {
138 llvm::dbgs() << " file=" << atom->file().path()
139 << ", name=" << atom->name()
140 << ", size=" << atom->size()
141 << ", type=" << atom->contentType()
142 << ", ordinal=" << atom->ordinal()
143 << "\n";
144 }
145}
146
147/// Verify that the followon chain is sane. Should not be called in
148/// release binary.
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000149void LayoutPass::checkFollowonChain(const SimpleFile::DefinedAtomRange &range) {
Rui Ueyamaa930d122013-12-09 00:37:19 +0000150 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
151
152 // Verify that there's no cycle in follow-on chain.
153 std::set<const DefinedAtom *> roots;
154 for (const auto &ai : _followOnRoots)
155 roots.insert(ai.second);
156 for (const DefinedAtom *root : roots)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000157 checkNoCycleInFollowonChain(_registry, _followOnNexts, root);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000158
159 // Verify that all the atoms in followOnNexts have references to
160 // their roots.
161 for (const auto &ai : _followOnNexts) {
162 checkReachabilityFromRoot(_followOnRoots, ai.first);
163 checkReachabilityFromRoot(_followOnRoots, ai.second);
164 }
165}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000166#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000167
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000168/// The function compares atoms by sorting atoms in the following order
Rui Ueyama05366772015-03-08 01:01:40 +0000169/// a) Sorts atoms by their ordinal overrides (layout-after/ingroup)
170/// b) Sorts atoms by their permissions
171/// c) Sorts atoms by their content
172/// d) Sorts atoms by custom sorter
173/// e) Sorts atoms on how they appear using File Ordinality
174/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +0000175static bool compareAtomsSub(const LayoutPass::SortKey &lc,
176 const LayoutPass::SortKey &rc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000177 LayoutPass::SortOverride customSorter,
Rui Ueyama5af46222013-12-08 03:24:09 +0000178 std::string &reason) {
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000179 const DefinedAtom *left = lc._atom.get();
180 const DefinedAtom *right = rc._atom.get();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000181 if (left == right) {
182 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000183 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000184 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000185
Rui Ueyama46bf8282013-10-19 03:18:18 +0000186 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000187 const DefinedAtom *leftRoot = lc._root;
188 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000189
190 // Sort atoms by their ordinal overrides only if they fall in the same
191 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000192 if (leftRoot == rightRoot) {
193 DEBUG(reason = formatReason("override", lc._override, rc._override));
194 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000195 }
196
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000197 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000198 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
199 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000200
Rui Ueyama6a607b62013-10-18 02:56:31 +0000201 if (leftPerms != rightPerms) {
202 DEBUG(reason =
203 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000204 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000205 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000206
207 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000208 DefinedAtom::ContentType leftType = leftRoot->contentType();
209 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000210
Rui Ueyama6a607b62013-10-18 02:56:31 +0000211 if (leftType != rightType) {
212 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000213 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000214 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000215
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000216 // Use custom sorter if supplied.
217 if (customSorter) {
218 bool leftBeforeRight;
219 if (customSorter(leftRoot, rightRoot, leftBeforeRight))
220 return leftBeforeRight;
221 }
222
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000223 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000224 const File *leftFile = &leftRoot->file();
225 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000226
Rui Ueyama6a607b62013-10-18 02:56:31 +0000227 if (leftFile != rightFile) {
228 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
229 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000230 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000231 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000232
233 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000234 uint64_t leftOrdinal = leftRoot->ordinal();
235 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000236
Rui Ueyama6a607b62013-10-18 02:56:31 +0000237 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000238 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
239 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000240 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000241 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000242
Rui Ueyamacd480752013-11-27 01:33:42 +0000243 llvm::errs() << "Unordered: <" << left->name() << "> <"
244 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000245 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000246}
247
Rui Ueyama5af46222013-12-08 03:24:09 +0000248static bool compareAtoms(const LayoutPass::SortKey &lc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000249 const LayoutPass::SortKey &rc,
250 LayoutPass::SortOverride customSorter) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000251 std::string reason;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000252 bool result = compareAtomsSub(lc, rc, customSorter, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000253 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000254 StringRef comp = result ? "<" : ">=";
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000255 llvm::dbgs() << "Layout: '" << lc._atom.get()->name()
256 << "' " << comp << " '"
257 << rc._atom.get()->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000258 });
259 return result;
260}
261
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000262LayoutPass::LayoutPass(const Registry &registry, SortOverride sorter)
263 : _registry(registry), _customSorter(sorter) {}
Nico Rieckb9d84f42014-02-24 21:14:37 +0000264
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000265// Returns the atom immediately followed by the given atom in the followon
266// chain.
267const DefinedAtom *LayoutPass::findAtomFollowedBy(
268 const DefinedAtom *targetAtom) {
269 // Start from the beginning of the chain and follow the chain until
270 // we find the targetChain.
271 const DefinedAtom *atom = _followOnRoots[targetAtom];
272 while (true) {
273 const DefinedAtom *prevAtom = atom;
274 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
275 // The target atom must be in the chain of its root.
276 assert(targetFollowOnAtomsIter != _followOnNexts.end());
277 atom = targetFollowOnAtomsIter->second;
278 if (atom == targetAtom)
279 return prevAtom;
280 }
281}
282
283// Check if all the atoms followed by the given target atom are of size zero.
284// When this method is called, an atom being added is not of size zero and
285// will be added to the head of the followon chain. All the atoms between the
286// atom and the targetAtom (specified by layout-after) need to be of size zero
287// in this case. Otherwise the desired layout is impossible.
288bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
289 const DefinedAtom *atom = _followOnRoots[targetAtom];
290 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000291 if (atom == targetAtom)
292 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000293 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000294 // TODO: print warning that an impossible layout is being desired by the
295 // user.
296 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000297 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
298 // The target atom must be in the chain of its root.
299 assert(targetFollowOnAtomsIter != _followOnNexts.end());
300 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000301 }
302}
303
304// Set the root of all atoms in targetAtom's chain to the given root.
305void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
306 const DefinedAtom *root) {
307 // Walk through the followon chain and override each node's root.
308 while (true) {
309 _followOnRoots[targetAtom] = root;
310 AtomToAtomT::iterator targetFollowOnAtomsIter =
311 _followOnNexts.find(targetAtom);
312 if (targetFollowOnAtomsIter == _followOnNexts.end())
313 return;
314 targetAtom = targetFollowOnAtomsIter->second;
315 }
316}
317
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000318/// This pass builds the followon tables described by two DenseMaps
319/// followOnRoots and followonNexts.
320/// The followOnRoots map contains a mapping of a DefinedAtom to its root
321/// The followOnNexts map contains a mapping of what DefinedAtom follows the
322/// current Atom
323/// The algorithm follows a very simple approach
324/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000325/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000326/// root of the current atom
327/// c) If the targetAtom is part of a different tree and the root of the
328/// targetAtom is itself, Chain all the atoms that are contained in the tree
329/// to the current Tree
330/// d) If the targetAtom is part of a different chain and the root of the
331/// targetAtom until the targetAtom has all atoms of size 0, then chain the
332/// targetAtoms and its tree to the current chain
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000333void LayoutPass::buildFollowOnTable(const SimpleFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000334 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000335 // Set the initial size of the followon and the followonNext hash to the
336 // number of atoms that we have.
Mehdi Aminid595b082016-03-22 07:31:35 +0000337 _followOnRoots.reserve(range.size());
338 _followOnNexts.reserve(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000339 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000340 for (const Reference *r : *ai) {
Rui Ueyamac9411c32014-03-21 21:46:49 +0000341 if (r->kindNamespace() != lld::Reference::KindNamespace::all ||
342 r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000343 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000344 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000345 _followOnNexts[ai] = targetAtom;
346
Alp Toker22593762013-12-02 01:28:14 +0000347 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000348 // root atom.
349 if (_followOnRoots.count(ai) == 0)
350 _followOnRoots[ai] = ai;
351
352 auto iter = _followOnRoots.find(targetAtom);
353 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000354 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000355 // the targetAtom to the root of the current chain.
Rui Ueyamaa821d322014-07-25 19:46:31 +0000356
357 // The expression m[i] = m[j] where m is a DenseMap and i != j is not
358 // safe. m[j] returns a reference, which would be invalidated when a
359 // rehashing occurs. If rehashing occurs to make room for m[i], m[j]
360 // becomes invalid, and that invalid reference would be used as the RHS
361 // value of the expression.
362 // Copy the value to workaround.
363 const DefinedAtom *tmp = _followOnRoots[ai];
364 _followOnRoots[targetAtom] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000365 continue;
366 }
367 if (iter->second == targetAtom) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000368 // If the targetAtom is the root of a chain, the chain becomes part of
369 // the current chain. Rewrite the subchain's root to the current
370 // chain's root.
371 setChainRoot(targetAtom, _followOnRoots[ai]);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000372 continue;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000373 }
Rui Ueyamac9411c32014-03-21 21:46:49 +0000374 // The targetAtom is already a part of a chain. If the current atom is
375 // of size zero, we can insert it in the middle of the chain just
376 // before the target atom, while not breaking other atom's followon
377 // relationships. If it's not, we can only insert the current atom at
378 // the beginning of the chain. All the atoms followed by the target
379 // atom must be of size zero in that case to satisfy the followon
380 // relationships.
381 size_t currentAtomSize = ai->size();
382 if (currentAtomSize == 0) {
383 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
384 _followOnNexts[targetPrevAtom] = ai;
Rui Ueyamaa821d322014-07-25 19:46:31 +0000385 const DefinedAtom *tmp = _followOnRoots[targetPrevAtom];
386 _followOnRoots[ai] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000387 continue;
388 }
389 if (!checkAllPrevAtomsZeroSize(targetAtom))
390 break;
391 _followOnNexts[ai] = _followOnRoots[targetAtom];
392 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000393 }
394 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000395}
396
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000397/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000398/// assigning ordinals to each atom, if the atoms have their ordinals
399/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000400/// main map thats used to sort the atoms while comparing two atoms together
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000401void
402LayoutPass::buildOrdinalOverrideMap(const SimpleFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000403 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000404 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000405 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000406 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000407 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
408 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000409 AtomToAtomT::iterator start = _followOnRoots.find(atom);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000410 if (start == _followOnRoots.end())
411 continue;
Rui Ueyama43155d02015-10-02 00:36:00 +0000412 for (const DefinedAtom *nextAtom = start->second; nextAtom;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000413 nextAtom = _followOnNexts[nextAtom]) {
414 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
415 if (pos == _ordinalOverrideMap.end())
416 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000417 }
418 }
419}
420
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000421std::vector<LayoutPass::SortKey>
Rui Ueyama3c45cff2015-04-07 20:43:38 +0000422LayoutPass::decorate(SimpleFile::DefinedAtomRange &atomRange) const {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000423 std::vector<SortKey> ret;
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000424 for (OwningAtomPtr<DefinedAtom> &atom : atomRange.owning_ptrs()) {
425 auto ri = _followOnRoots.find(atom.get());
426 auto oi = _ordinalOverrideMap.find(atom.get());
427 const auto *root = (ri == _followOnRoots.end()) ? atom.get() : ri->second;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000428 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000429 ret.push_back(SortKey(std::move(atom), root, override));
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000430 }
431 return ret;
432}
433
Rui Ueyama3c45cff2015-04-07 20:43:38 +0000434void LayoutPass::undecorate(SimpleFile::DefinedAtomRange &atomRange,
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000435 std::vector<SortKey> &keys) const {
436 size_t i = 0;
437 for (SortKey &k : keys)
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000438 atomRange[i++] = std::move(k._atom);
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000439}
440
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000441/// Perform the actual pass
Pete Cooperc73c9d22016-03-30 20:36:31 +0000442llvm::Error LayoutPass::perform(SimpleFile &mergedFile) {
Pete Cooper3e8f5652015-12-16 19:12:49 +0000443 DEBUG(llvm::dbgs() << "******** Laying out atoms:\n");
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000444 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000445 ScopedTask task(getDefaultDomain(), "LayoutPass");
David Blaikie25ddcb42015-06-19 19:43:43 +0000446 SimpleFile::DefinedAtomRange atomRange = mergedFile.definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000447
448 // Build follow on tables
449 buildFollowOnTable(atomRange);
450
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000451 // Check the structure of followon graph if running in debug mode.
452 DEBUG(checkFollowonChain(atomRange));
453
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000454 // Build override maps
455 buildOrdinalOverrideMap(atomRange);
456
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000457 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000458 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000459 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000460 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000461
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000462 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
Rui Ueyama87d10ef2015-01-26 20:18:37 +0000463 parallel_sort(vec.begin(), vec.end(),
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000464 [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool {
465 return compareAtoms(l, r, _customSorter);
466 });
Rui Ueyama540842c2015-02-05 20:08:04 +0000467 DEBUG(checkTransitivity(vec, _customSorter));
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000468 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000469
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000470 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000471 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000472 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000473 });
Lang Hamesb09c2c62015-06-19 17:51:46 +0000474
Pete Cooper3e8f5652015-12-16 19:12:49 +0000475 DEBUG(llvm::dbgs() << "******** Finished laying out atoms\n");
Pete Cooperc73c9d22016-03-30 20:36:31 +0000476 return llvm::Error();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000477}
Rui Ueyama00762152015-02-05 20:05:33 +0000478
479void addLayoutPass(PassManager &pm, const MachOLinkingContext &ctx) {
Rui Ueyama92634be2015-02-06 22:44:16 +0000480 pm.add(llvm::make_unique<LayoutPass>(
Rui Ueyama00762152015-02-05 20:05:33 +0000481 ctx.registry(), [&](const DefinedAtom * left, const DefinedAtom * right,
Rui Ueyama540842c2015-02-05 20:08:04 +0000482 bool & leftBeforeRight) ->bool {
Rui Ueyama00762152015-02-05 20:05:33 +0000483 return ctx.customAtomOrderer(left, right, leftBeforeRight);
Rui Ueyama92634be2015-02-06 22:44:16 +0000484 }));
Rui Ueyama00762152015-02-05 20:05:33 +0000485}
486
487} // namespace mach_o
488} // namespace lld