blob: e754c3157edbb945ce65ad931ad6e58ea145a5f1 [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"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000015#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000016#include "llvm/Support/Debug.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000017#include <algorithm>
18#include <set>
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000019
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000020using namespace lld;
21
Chandler Carruth9afe32d2014-04-22 03:21:31 +000022#define DEBUG_TYPE "LayoutPass"
23
Rui Ueyama00762152015-02-05 20:05:33 +000024namespace lld {
25namespace mach_o {
26
Rui Ueyama5af46222013-12-08 03:24:09 +000027static bool compareAtoms(const LayoutPass::SortKey &,
Nick Kledzik82d24bc2014-11-07 21:01:21 +000028 const LayoutPass::SortKey &,
Rui Ueyama540842c2015-02-05 20:08:04 +000029 LayoutPass::SortOverride customSorter);
Rui Ueyama5af46222013-12-08 03:24:09 +000030
Rui Ueyama2994f6f2013-12-08 03:37:58 +000031#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000032// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000033static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama2ea86392014-09-18 23:21:39 +000034 return (Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")")
35 .str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000036}
Rui Ueyama46bf8282013-10-19 03:18:18 +000037
38// Less-than relationship of two atoms must be transitive, which is, if a < b
39// and b < c, a < c must be true. This function checks the transitivity by
40// checking the sort results.
Rui Ueyama540842c2015-02-05 20:08:04 +000041static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec,
42 LayoutPass::SortOverride customSorter) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000043 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
44 for (auto j = i + 1; j != e; ++j) {
Rui Ueyama540842c2015-02-05 20:08:04 +000045 assert(compareAtoms(*i, *j, customSorter));
46 assert(!compareAtoms(*j, *i, customSorter));
Rui Ueyama46bf8282013-10-19 03:18:18 +000047 }
48 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000049}
Rui Ueyamaa930d122013-12-09 00:37:19 +000050
51// Helper functions to check follow-on graph.
52typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
53
54static std::string atomToDebugString(const Atom *atom) {
55 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
56 std::string str;
57 llvm::raw_string_ostream s(str);
58 if (definedAtom->name().empty())
59 s << "<anonymous " << definedAtom << ">";
60 else
61 s << definedAtom->name();
62 s << " in ";
63 if (definedAtom->customSectionName().empty())
64 s << "<anonymous>";
65 else
66 s << definedAtom->customSectionName();
67 s.flush();
68 return str;
69}
70
Nico Rieckb9d84f42014-02-24 21:14:37 +000071static void showCycleDetectedError(const Registry &registry,
72 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000073 const DefinedAtom *atom) {
74 const DefinedAtom *start = atom;
75 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
76 do {
77 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
78 for (const Reference *ref : *atom) {
Nico Rieckb9d84f42014-02-24 21:14:37 +000079 StringRef kindValStr;
80 if (!registry.referenceKindToString(ref->kindNamespace(), ref->kindArch(),
81 ref->kindValue(), kindValStr)) {
82 kindValStr = "<unknown>";
83 }
84 llvm::dbgs() << " " << kindValStr
85 << ": " << atomToDebugString(ref->target()) << "\n";
Rui Ueyamaa930d122013-12-09 00:37:19 +000086 }
87 atom = followOnNexts[atom];
88 } while (atom != start);
89 llvm::report_fatal_error("Cycle detected");
90}
91
92/// Exit if there's a cycle in a followon chain reachable from the
93/// given root atom. Uses the tortoise and hare algorithm to detect a
94/// cycle.
Nico Rieckb9d84f42014-02-24 21:14:37 +000095static void checkNoCycleInFollowonChain(const Registry &registry,
96 AtomToAtomT &followOnNexts,
Rui Ueyamaa930d122013-12-09 00:37:19 +000097 const DefinedAtom *root) {
98 const DefinedAtom *tortoise = root;
99 const DefinedAtom *hare = followOnNexts[root];
100 while (true) {
101 if (!tortoise || !hare)
102 return;
103 if (tortoise == hare)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000104 showCycleDetectedError(registry, followOnNexts, tortoise);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000105 tortoise = followOnNexts[tortoise];
106 hare = followOnNexts[followOnNexts[hare]];
107 }
108}
109
110static void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
111 const DefinedAtom *atom) {
112 if (!atom) return;
113 auto i = followOnRoots.find(atom);
114 if (i == followOnRoots.end()) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000115 llvm_unreachable(((Twine("Atom <") + atomToDebugString(atom) +
116 "> has no follow-on root!"))
117 .str()
118 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000119 }
120 const DefinedAtom *ap = i->second;
121 while (true) {
122 const DefinedAtom *next = followOnRoots[ap];
123 if (!next) {
Rui Ueyama2ea86392014-09-18 23:21:39 +0000124 llvm_unreachable((Twine("Atom <" + atomToDebugString(atom) +
125 "> is not reachable from its root!"))
126 .str()
127 .c_str());
Rui Ueyamaa930d122013-12-09 00:37:19 +0000128 }
129 if (next == ap)
130 return;
131 ap = next;
132 }
133}
134
135static void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
136 for (const DefinedAtom *atom : atomRange) {
137 llvm::dbgs() << " file=" << atom->file().path()
138 << ", name=" << atom->name()
139 << ", size=" << atom->size()
140 << ", type=" << atom->contentType()
141 << ", ordinal=" << atom->ordinal()
142 << "\n";
143 }
144}
145
146/// Verify that the followon chain is sane. Should not be called in
147/// release binary.
148void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
149 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
150
151 // Verify that there's no cycle in follow-on chain.
152 std::set<const DefinedAtom *> roots;
153 for (const auto &ai : _followOnRoots)
154 roots.insert(ai.second);
155 for (const DefinedAtom *root : roots)
Nico Rieckb9d84f42014-02-24 21:14:37 +0000156 checkNoCycleInFollowonChain(_registry, _followOnNexts, root);
Rui Ueyamaa930d122013-12-09 00:37:19 +0000157
158 // Verify that all the atoms in followOnNexts have references to
159 // their roots.
160 for (const auto &ai : _followOnNexts) {
161 checkReachabilityFromRoot(_followOnRoots, ai.first);
162 checkReachabilityFromRoot(_followOnRoots, ai.second);
163 }
164}
Rui Ueyama2994f6f2013-12-08 03:37:58 +0000165#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000166
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000167/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000168/// a) Sorts atoms by Section position preference
Rui Ueyama8be4ce22014-03-27 22:08:26 +0000169/// b) Sorts atoms by their ordinal overrides (layout-after/ingroup)
Shankar Easwarand6d1b522013-09-12 15:59:34 +0000170/// c) Sorts atoms by their permissions
171/// d) Sorts atoms by their content
Rui Ueyama540842c2015-02-05 20:08:04 +0000172/// e) Sorts atoms by custom sorter
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000173/// f) Sorts atoms on how they appear using File Ordinality
174/// g) 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) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000179 const DefinedAtom *left = lc._atom;
180 const DefinedAtom *right = rc._atom;
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
Shankar Easwarand8da9892013-05-22 17:41:04 +0000186 // Sort by section position preference.
187 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
188 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
189
Shankar Easwarand8da9892013-05-22 17:41:04 +0000190 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
191 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
192 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000193 if (leftPos != rightPos) {
194 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +0000195 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000196 }
Shankar Easwarand8da9892013-05-22 17:41:04 +0000197 }
198
Rui Ueyama46bf8282013-10-19 03:18:18 +0000199 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000200 const DefinedAtom *leftRoot = lc._root;
201 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +0000202
203 // Sort atoms by their ordinal overrides only if they fall in the same
204 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000205 if (leftRoot == rightRoot) {
206 DEBUG(reason = formatReason("override", lc._override, rc._override));
207 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +0000208 }
209
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000210 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000211 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
212 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000213
Rui Ueyama6a607b62013-10-18 02:56:31 +0000214 if (leftPerms != rightPerms) {
215 DEBUG(reason =
216 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000217 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000218 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000219
220 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000221 DefinedAtom::ContentType leftType = leftRoot->contentType();
222 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000223
Rui Ueyama6a607b62013-10-18 02:56:31 +0000224 if (leftType != rightType) {
225 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000226 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000227 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000228
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000229 // Use custom sorter if supplied.
230 if (customSorter) {
231 bool leftBeforeRight;
232 if (customSorter(leftRoot, rightRoot, leftBeforeRight))
233 return leftBeforeRight;
234 }
235
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000236 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000237 const File *leftFile = &leftRoot->file();
238 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000239
Rui Ueyama6a607b62013-10-18 02:56:31 +0000240 if (leftFile != rightFile) {
241 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
242 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000243 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000244 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000245
246 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000247 uint64_t leftOrdinal = leftRoot->ordinal();
248 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000249
Rui Ueyama6a607b62013-10-18 02:56:31 +0000250 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000251 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
252 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000253 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000254 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000255
Rui Ueyamacd480752013-11-27 01:33:42 +0000256 llvm::errs() << "Unordered: <" << left->name() << "> <"
257 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000258 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000259}
260
Rui Ueyama5af46222013-12-08 03:24:09 +0000261static bool compareAtoms(const LayoutPass::SortKey &lc,
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000262 const LayoutPass::SortKey &rc,
263 LayoutPass::SortOverride customSorter) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000264 std::string reason;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000265 bool result = compareAtomsSub(lc, rc, customSorter, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000266 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000267 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000268 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
269 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000270 });
271 return result;
272}
273
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000274LayoutPass::LayoutPass(const Registry &registry, SortOverride sorter)
275 : _registry(registry), _customSorter(sorter) {}
Nico Rieckb9d84f42014-02-24 21:14:37 +0000276
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000277// Returns the atom immediately followed by the given atom in the followon
278// chain.
279const DefinedAtom *LayoutPass::findAtomFollowedBy(
280 const DefinedAtom *targetAtom) {
281 // Start from the beginning of the chain and follow the chain until
282 // we find the targetChain.
283 const DefinedAtom *atom = _followOnRoots[targetAtom];
284 while (true) {
285 const DefinedAtom *prevAtom = atom;
286 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
287 // The target atom must be in the chain of its root.
288 assert(targetFollowOnAtomsIter != _followOnNexts.end());
289 atom = targetFollowOnAtomsIter->second;
290 if (atom == targetAtom)
291 return prevAtom;
292 }
293}
294
295// Check if all the atoms followed by the given target atom are of size zero.
296// When this method is called, an atom being added is not of size zero and
297// will be added to the head of the followon chain. All the atoms between the
298// atom and the targetAtom (specified by layout-after) need to be of size zero
299// in this case. Otherwise the desired layout is impossible.
300bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
301 const DefinedAtom *atom = _followOnRoots[targetAtom];
302 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000303 if (atom == targetAtom)
304 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000305 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000306 // TODO: print warning that an impossible layout is being desired by the
307 // user.
308 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000309 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
310 // The target atom must be in the chain of its root.
311 assert(targetFollowOnAtomsIter != _followOnNexts.end());
312 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000313 }
314}
315
316// Set the root of all atoms in targetAtom's chain to the given root.
317void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
318 const DefinedAtom *root) {
319 // Walk through the followon chain and override each node's root.
320 while (true) {
321 _followOnRoots[targetAtom] = root;
322 AtomToAtomT::iterator targetFollowOnAtomsIter =
323 _followOnNexts.find(targetAtom);
324 if (targetFollowOnAtomsIter == _followOnNexts.end())
325 return;
326 targetAtom = targetFollowOnAtomsIter->second;
327 }
328}
329
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000330/// This pass builds the followon tables described by two DenseMaps
331/// followOnRoots and followonNexts.
332/// The followOnRoots map contains a mapping of a DefinedAtom to its root
333/// The followOnNexts map contains a mapping of what DefinedAtom follows the
334/// current Atom
335/// The algorithm follows a very simple approach
336/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000337/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000338/// root of the current atom
339/// c) If the targetAtom is part of a different tree and the root of the
340/// targetAtom is itself, Chain all the atoms that are contained in the tree
341/// to the current Tree
342/// d) If the targetAtom is part of a different chain and the root of the
343/// targetAtom until the targetAtom has all atoms of size 0, then chain the
344/// targetAtoms and its tree to the current chain
345void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000346 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000347 // Set the initial size of the followon and the followonNext hash to the
348 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000349 _followOnRoots.resize(range.size());
350 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000351 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000352 for (const Reference *r : *ai) {
Rui Ueyamac9411c32014-03-21 21:46:49 +0000353 if (r->kindNamespace() != lld::Reference::KindNamespace::all ||
354 r->kindValue() != lld::Reference::kindLayoutAfter)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000355 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000356 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000357 _followOnNexts[ai] = targetAtom;
358
Alp Toker22593762013-12-02 01:28:14 +0000359 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000360 // root atom.
361 if (_followOnRoots.count(ai) == 0)
362 _followOnRoots[ai] = ai;
363
364 auto iter = _followOnRoots.find(targetAtom);
365 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000366 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000367 // the targetAtom to the root of the current chain.
Rui Ueyamaa821d322014-07-25 19:46:31 +0000368
369 // The expression m[i] = m[j] where m is a DenseMap and i != j is not
370 // safe. m[j] returns a reference, which would be invalidated when a
371 // rehashing occurs. If rehashing occurs to make room for m[i], m[j]
372 // becomes invalid, and that invalid reference would be used as the RHS
373 // value of the expression.
374 // Copy the value to workaround.
375 const DefinedAtom *tmp = _followOnRoots[ai];
376 _followOnRoots[targetAtom] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000377 continue;
378 }
379 if (iter->second == targetAtom) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000380 // If the targetAtom is the root of a chain, the chain becomes part of
381 // the current chain. Rewrite the subchain's root to the current
382 // chain's root.
383 setChainRoot(targetAtom, _followOnRoots[ai]);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000384 continue;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000385 }
Rui Ueyamac9411c32014-03-21 21:46:49 +0000386 // The targetAtom is already a part of a chain. If the current atom is
387 // of size zero, we can insert it in the middle of the chain just
388 // before the target atom, while not breaking other atom's followon
389 // relationships. If it's not, we can only insert the current atom at
390 // the beginning of the chain. All the atoms followed by the target
391 // atom must be of size zero in that case to satisfy the followon
392 // relationships.
393 size_t currentAtomSize = ai->size();
394 if (currentAtomSize == 0) {
395 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
396 _followOnNexts[targetPrevAtom] = ai;
Rui Ueyamaa821d322014-07-25 19:46:31 +0000397 const DefinedAtom *tmp = _followOnRoots[targetPrevAtom];
398 _followOnRoots[ai] = tmp;
Rui Ueyamac9411c32014-03-21 21:46:49 +0000399 continue;
400 }
401 if (!checkAllPrevAtomsZeroSize(targetAtom))
402 break;
403 _followOnNexts[ai] = _followOnRoots[targetAtom];
404 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000405 }
406 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000407}
408
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000409/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000410/// assigning ordinals to each atom, if the atoms have their ordinals
411/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000412/// main map thats used to sort the atoms while comparing two atoms together
413void LayoutPass::buildOrdinalOverrideMap(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000414 ScopedTask task(getDefaultDomain(), "LayoutPass::buildOrdinalOverrideMap");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000415 uint64_t index = 0;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000416 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000417 const DefinedAtom *atom = ai;
Michael J. Spencer1ecf8902013-03-12 00:10:00 +0000418 if (_ordinalOverrideMap.find(atom) != _ordinalOverrideMap.end())
419 continue;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000420 AtomToAtomT::iterator start = _followOnRoots.find(atom);
Rui Ueyamac9411c32014-03-21 21:46:49 +0000421 if (start == _followOnRoots.end())
422 continue;
423 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
424 nextAtom = _followOnNexts[nextAtom]) {
425 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
426 if (pos == _ordinalOverrideMap.end())
427 _ordinalOverrideMap[nextAtom] = index++;
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000428 }
429 }
430}
431
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000432std::vector<LayoutPass::SortKey>
433LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
434 std::vector<SortKey> ret;
435 for (const DefinedAtom *atom : atomRange) {
436 auto ri = _followOnRoots.find(atom);
437 auto oi = _ordinalOverrideMap.find(atom);
438 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
439 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
440 ret.push_back(SortKey(atom, root, override));
441 }
442 return ret;
443}
444
445void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
446 std::vector<SortKey> &keys) const {
447 size_t i = 0;
448 for (SortKey &k : keys)
449 atomRange[i++] = k._atom;
450}
451
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000452/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000453void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000454 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000455 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000456 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000457
458 // Build follow on tables
459 buildFollowOnTable(atomRange);
460
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000461 // Check the structure of followon graph if running in debug mode.
462 DEBUG(checkFollowonChain(atomRange));
463
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000464 // Build override maps
465 buildOrdinalOverrideMap(atomRange);
466
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000467 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000468 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000469 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000470 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000471
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000472 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
Rui Ueyama87d10ef2015-01-26 20:18:37 +0000473 parallel_sort(vec.begin(), vec.end(),
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000474 [&](const LayoutPass::SortKey &l, const LayoutPass::SortKey &r) -> bool {
475 return compareAtoms(l, r, _customSorter);
476 });
Rui Ueyama540842c2015-02-05 20:08:04 +0000477 DEBUG(checkTransitivity(vec, _customSorter));
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000478 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000479
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000480 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000481 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000482 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000483 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000484}
Rui Ueyama00762152015-02-05 20:05:33 +0000485
486void addLayoutPass(PassManager &pm, const MachOLinkingContext &ctx) {
487 pm.add(std::unique_ptr<Pass>(new LayoutPass(
488 ctx.registry(), [&](const DefinedAtom * left, const DefinedAtom * right,
Rui Ueyama540842c2015-02-05 20:08:04 +0000489 bool & leftBeforeRight) ->bool {
Rui Ueyama00762152015-02-05 20:05:33 +0000490 return ctx.customAtomOrderer(left, right, leftBeforeRight);
491 })));
492}
493
494} // namespace mach_o
495} // namespace lld