blob: 61135da7c9e8c369571a863df67ad66f31c26556 [file] [log] [blame]
Shankar Easwaran2bc24922013-10-29 05:12:14 +00001//===--Passes/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
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000010#define DEBUG_TYPE "LayoutPass"
11
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000012#include <algorithm>
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000013#include <set>
14
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000015#include "lld/Passes/LayoutPass.h"
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +000016#include "lld/Core/Instrumentation.h"
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +000017
18#include "llvm/ADT/Twine.h"
Michael J. Spencer7f09a3d2013-02-26 01:35:30 +000019#include "llvm/Support/Debug.h"
20
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000021using namespace lld;
22
Rui Ueyama5af46222013-12-08 03:24:09 +000023static bool compareAtoms(const LayoutPass::SortKey &,
24 const LayoutPass::SortKey &);
25
Rui Ueyama2994f6f2013-12-08 03:37:58 +000026#ifndef NDEBUG
Rui Ueyama6a607b62013-10-18 02:56:31 +000027// Return "reason (leftval, rightval)"
Rui Ueyama5af46222013-12-08 03:24:09 +000028static std::string formatReason(StringRef reason, int leftVal, int rightVal) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000029 Twine msg =
30 Twine(reason) + " (" + Twine(leftVal) + ", " + Twine(rightVal) + ")";
Rui Ueyamac74157c2013-11-01 20:40:33 +000031 return msg.str();
Rui Ueyama6a607b62013-10-18 02:56:31 +000032}
Rui Ueyama46bf8282013-10-19 03:18:18 +000033
34// Less-than relationship of two atoms must be transitive, which is, if a < b
35// and b < c, a < c must be true. This function checks the transitivity by
36// checking the sort results.
Rui Ueyama5af46222013-12-08 03:24:09 +000037static void checkTransitivity(std::vector<LayoutPass::SortKey> &vec) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000038 for (auto i = vec.begin(), e = vec.end(); (i + 1) != e; ++i) {
39 for (auto j = i + 1; j != e; ++j) {
40 assert(compareAtoms(*i, *j));
41 assert(!compareAtoms(*j, *i));
Rui Ueyama46bf8282013-10-19 03:18:18 +000042 }
43 }
Rui Ueyama6a607b62013-10-18 02:56:31 +000044}
Rui Ueyama2994f6f2013-12-08 03:37:58 +000045#endif // #ifndef NDEBUG
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000046
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000047/// The function compares atoms by sorting atoms in the following order
Shankar Easwarand6d1b522013-09-12 15:59:34 +000048/// a) Sorts atoms by Section position preference
49/// b) Sorts atoms by their ordinal overrides
50/// (layout-after/layout-before/ingroup)
51/// c) Sorts atoms by their permissions
52/// d) Sorts atoms by their content
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000053/// e) Sorts atoms on how they appear using File Ordinality
54/// f) Sorts atoms on how they appear within the File
Rui Ueyama5af46222013-12-08 03:24:09 +000055static bool compareAtomsSub(const LayoutPass::SortKey &lc,
56 const LayoutPass::SortKey &rc,
57 std::string &reason) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000058 const DefinedAtom *left = lc._atom;
59 const DefinedAtom *right = rc._atom;
Rui Ueyama6a607b62013-10-18 02:56:31 +000060 if (left == right) {
61 reason = "same";
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000062 return false;
Rui Ueyama6a607b62013-10-18 02:56:31 +000063 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000064
Shankar Easwarand8da9892013-05-22 17:41:04 +000065 // Sort by section position preference.
66 DefinedAtom::SectionPosition leftPos = left->sectionPosition();
67 DefinedAtom::SectionPosition rightPos = right->sectionPosition();
68
Shankar Easwarand8da9892013-05-22 17:41:04 +000069 bool leftSpecialPos = (leftPos != DefinedAtom::sectionPositionAny);
70 bool rightSpecialPos = (rightPos != DefinedAtom::sectionPositionAny);
71 if (leftSpecialPos || rightSpecialPos) {
Rui Ueyama6a607b62013-10-18 02:56:31 +000072 if (leftPos != rightPos) {
73 DEBUG(reason = formatReason("sectionPos", (int)leftPos, (int)rightPos));
Shankar Easwarand8da9892013-05-22 17:41:04 +000074 return leftPos < rightPos;
Rui Ueyama6a607b62013-10-18 02:56:31 +000075 }
Shankar Easwarand8da9892013-05-22 17:41:04 +000076 }
77
Rui Ueyama46bf8282013-10-19 03:18:18 +000078 // Find the root of the chain if it is a part of a follow-on chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000079 const DefinedAtom *leftRoot = lc._root;
80 const DefinedAtom *rightRoot = rc._root;
Shankar Easwaranf1b341c2013-09-12 15:43:09 +000081
82 // Sort atoms by their ordinal overrides only if they fall in the same
83 // chain.
Rui Ueyama37c43e9f2013-12-08 03:12:08 +000084 if (leftRoot == rightRoot) {
85 DEBUG(reason = formatReason("override", lc._override, rc._override));
86 return lc._override < rc._override;
Shankar Easwaran3c5d2c82013-05-10 16:44:02 +000087 }
88
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000089 // Sort same permissions together.
Rui Ueyama46bf8282013-10-19 03:18:18 +000090 DefinedAtom::ContentPermissions leftPerms = leftRoot->permissions();
91 DefinedAtom::ContentPermissions rightPerms = rightRoot->permissions();
Shankar Easwaran8c256852013-03-13 04:05:38 +000092
Rui Ueyama6a607b62013-10-18 02:56:31 +000093 if (leftPerms != rightPerms) {
94 DEBUG(reason =
95 formatReason("contentPerms", (int)leftPerms, (int)rightPerms));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000096 return leftPerms < rightPerms;
Rui Ueyama6a607b62013-10-18 02:56:31 +000097 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +000098
99 // Sort same content types together.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000100 DefinedAtom::ContentType leftType = leftRoot->contentType();
101 DefinedAtom::ContentType rightType = rightRoot->contentType();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000102
Rui Ueyama6a607b62013-10-18 02:56:31 +0000103 if (leftType != rightType) {
104 DEBUG(reason = formatReason("contentType", (int)leftType, (int)rightType));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000105 return leftType < rightType;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000106 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000107
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000108 // Sort by .o order.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000109 const File *leftFile = &leftRoot->file();
110 const File *rightFile = &rightRoot->file();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000111
Rui Ueyama6a607b62013-10-18 02:56:31 +0000112 if (leftFile != rightFile) {
113 DEBUG(reason = formatReason(".o order", (int)leftFile->ordinal(),
114 (int)rightFile->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000115 return leftFile->ordinal() < rightFile->ordinal();
Rui Ueyama6a607b62013-10-18 02:56:31 +0000116 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000117
118 // Sort by atom order with .o file.
Rui Ueyama46bf8282013-10-19 03:18:18 +0000119 uint64_t leftOrdinal = leftRoot->ordinal();
120 uint64_t rightOrdinal = rightRoot->ordinal();
Shankar Easwaran8c256852013-03-13 04:05:38 +0000121
Rui Ueyama6a607b62013-10-18 02:56:31 +0000122 if (leftOrdinal != rightOrdinal) {
Rui Ueyama46bf8282013-10-19 03:18:18 +0000123 DEBUG(reason = formatReason("ordinal", (int)leftRoot->ordinal(),
124 (int)rightRoot->ordinal()));
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000125 return leftOrdinal < rightOrdinal;
Rui Ueyama6a607b62013-10-18 02:56:31 +0000126 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000127
Rui Ueyamacd480752013-11-27 01:33:42 +0000128 llvm::errs() << "Unordered: <" << left->name() << "> <"
129 << right->name() << ">\n";
Shankar Easwaranbcf36562013-10-11 01:50:04 +0000130 llvm_unreachable("Atoms with Same Ordinal!");
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000131}
132
Rui Ueyama5af46222013-12-08 03:24:09 +0000133static bool compareAtoms(const LayoutPass::SortKey &lc,
134 const LayoutPass::SortKey &rc) {
Rui Ueyama6a607b62013-10-18 02:56:31 +0000135 std::string reason;
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000136 bool result = compareAtomsSub(lc, rc, reason);
Rui Ueyama6a607b62013-10-18 02:56:31 +0000137 DEBUG({
Rui Ueyama4050b202013-10-18 03:18:52 +0000138 StringRef comp = result ? "<" : ">=";
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000139 llvm::dbgs() << "Layout: '" << lc._atom->name() << "' " << comp << " '"
140 << rc._atom->name() << "' (" << reason << ")\n";
Rui Ueyama6a607b62013-10-18 02:56:31 +0000141 });
142 return result;
143}
144
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000145// Returns the atom immediately followed by the given atom in the followon
146// chain.
147const DefinedAtom *LayoutPass::findAtomFollowedBy(
148 const DefinedAtom *targetAtom) {
149 // Start from the beginning of the chain and follow the chain until
150 // we find the targetChain.
151 const DefinedAtom *atom = _followOnRoots[targetAtom];
152 while (true) {
153 const DefinedAtom *prevAtom = atom;
154 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
155 // The target atom must be in the chain of its root.
156 assert(targetFollowOnAtomsIter != _followOnNexts.end());
157 atom = targetFollowOnAtomsIter->second;
158 if (atom == targetAtom)
159 return prevAtom;
160 }
161}
162
163// Check if all the atoms followed by the given target atom are of size zero.
164// When this method is called, an atom being added is not of size zero and
165// will be added to the head of the followon chain. All the atoms between the
166// atom and the targetAtom (specified by layout-after) need to be of size zero
167// in this case. Otherwise the desired layout is impossible.
168bool LayoutPass::checkAllPrevAtomsZeroSize(const DefinedAtom *targetAtom) {
169 const DefinedAtom *atom = _followOnRoots[targetAtom];
170 while (true) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000171 if (atom == targetAtom)
172 return true;
Rui Ueyama0196d1062013-05-14 16:53:59 +0000173 if (atom->size() != 0)
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000174 // TODO: print warning that an impossible layout is being desired by the
175 // user.
176 return false;
Rui Ueyama5ec6d1a2013-05-14 01:51:56 +0000177 AtomToAtomT::iterator targetFollowOnAtomsIter = _followOnNexts.find(atom);
178 // The target atom must be in the chain of its root.
179 assert(targetFollowOnAtomsIter != _followOnNexts.end());
180 atom = targetFollowOnAtomsIter->second;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000181 }
182}
183
184// Set the root of all atoms in targetAtom's chain to the given root.
185void LayoutPass::setChainRoot(const DefinedAtom *targetAtom,
186 const DefinedAtom *root) {
187 // Walk through the followon chain and override each node's root.
188 while (true) {
189 _followOnRoots[targetAtom] = root;
190 AtomToAtomT::iterator targetFollowOnAtomsIter =
191 _followOnNexts.find(targetAtom);
192 if (targetFollowOnAtomsIter == _followOnNexts.end())
193 return;
194 targetAtom = targetFollowOnAtomsIter->second;
195 }
196}
197
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000198/// This pass builds the followon tables described by two DenseMaps
199/// followOnRoots and followonNexts.
200/// The followOnRoots map contains a mapping of a DefinedAtom to its root
201/// The followOnNexts map contains a mapping of what DefinedAtom follows the
202/// current Atom
203/// The algorithm follows a very simple approach
204/// a) If the atom is first seen, then make that as the root atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000205/// b) The targetAtom which this Atom contains, has the root thats set to the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000206/// root of the current atom
207/// c) If the targetAtom is part of a different tree and the root of the
208/// targetAtom is itself, Chain all the atoms that are contained in the tree
209/// to the current Tree
210/// d) If the targetAtom is part of a different chain and the root of the
211/// targetAtom until the targetAtom has all atoms of size 0, then chain the
212/// targetAtoms and its tree to the current chain
213void LayoutPass::buildFollowOnTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000214 ScopedTask task(getDefaultDomain(), "LayoutPass::buildFollowOnTable");
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000215 // Set the initial size of the followon and the followonNext hash to the
216 // number of atoms that we have.
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000217 _followOnRoots.resize(range.size());
218 _followOnNexts.resize(range.size());
Rui Ueyama0196d1062013-05-14 16:53:59 +0000219 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000220 for (const Reference *r : *ai) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000221 if (r->kind() != lld::Reference::kindLayoutAfter)
222 continue;
Rui Ueyamac1800be2013-11-05 01:37:40 +0000223 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000224 _followOnNexts[ai] = targetAtom;
225
Alp Toker22593762013-12-02 01:28:14 +0000226 // If we find a followon for the first time, let's make that atom as the
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000227 // root atom.
228 if (_followOnRoots.count(ai) == 0)
229 _followOnRoots[ai] = ai;
230
231 auto iter = _followOnRoots.find(targetAtom);
232 if (iter == _followOnRoots.end()) {
Alp Toker22593762013-12-02 01:28:14 +0000233 // If the targetAtom is not a root of any chain, let's make the root of
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000234 // the targetAtom to the root of the current chain.
235 _followOnRoots[targetAtom] = _followOnRoots[ai];
236 } else if (iter->second == targetAtom) {
237 // If the targetAtom is the root of a chain, the chain becomes part of
238 // the current chain. Rewrite the subchain's root to the current
239 // chain's root.
240 setChainRoot(targetAtom, _followOnRoots[ai]);
241 } else {
242 // The targetAtom is already a part of a chain. If the current atom is
243 // of size zero, we can insert it in the middle of the chain just
244 // before the target atom, while not breaking other atom's followon
245 // relationships. If it's not, we can only insert the current atom at
246 // the beginning of the chain. All the atoms followed by the target
247 // atom must be of size zero in that case to satisfy the followon
248 // relationships.
Rui Ueyama0196d1062013-05-14 16:53:59 +0000249 size_t currentAtomSize = ai->size();
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000250 if (currentAtomSize == 0) {
251 const DefinedAtom *targetPrevAtom = findAtomFollowedBy(targetAtom);
252 _followOnNexts[targetPrevAtom] = ai;
253 _followOnRoots[ai] = _followOnRoots[targetPrevAtom];
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000254 } else {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000255 if (!checkAllPrevAtomsZeroSize(targetAtom))
256 break;
257 _followOnNexts[ai] = _followOnRoots[targetAtom];
258 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
259 }
260 }
261 }
262 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000263}
264
265/// This pass builds the followon tables using InGroup relationships
266/// The algorithm follows a very simple approach
267/// a) If the rootAtom is not part of any root, create a new root with the
268/// as the head
269/// b) If the current Atom root is not found, then make the current atoms root
270/// point to the rootAtom
271/// c) If the root of the current Atom is itself a root of some other tree
272/// make all the atoms in the chain point to the ingroup reference
273/// d) Check to see if the current atom is part of the chain from the rootAtom
274/// if not add the atom to the chain, so that the current atom is part of the
275/// the chain where the rootAtom is in
276void LayoutPass::buildInGroupTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000277 ScopedTask task(getDefaultDomain(), "LayoutPass::buildInGroupTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000278 // This table would convert precededby references to follow on
279 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000280 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000281 for (const Reference *r : *ai) {
282 if (r->kind() == lld::Reference::kindInGroup) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000283 const DefinedAtom *rootAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000284 // If the root atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000285 // create a new root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000286 if (_followOnRoots.count(rootAtom) == 0) {
287 _followOnRoots[rootAtom] = rootAtom;
288 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000289 // If the current Atom has not been seen yet and there is no root
290 // that has been set, set the root of the atom to the targetAtom
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000291 // as the targetAtom points to the ingroup root
292 auto iter = _followOnRoots.find(ai);
293 if (iter == _followOnRoots.end()) {
294 _followOnRoots[ai] = rootAtom;
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000295 } else if (iter->second == ai) {
296 if (iter->second != rootAtom)
297 setChainRoot(iter->second, rootAtom);
298 } else {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000299 // TODO : Flag an error that the root of the tree
300 // is different, Here is an example
301 // Say there are atoms
302 // chain 1 : a->b->c
303 // chain 2 : d->e->f
304 // and e,f have their ingroup reference as a
305 // this could happen only if the root of e,f that is d
306 // has root as 'a'
307 continue;
308 }
309
310 // Check if the current atom is part of the chain
311 bool isAtomInChain = false;
312 const DefinedAtom *lastAtom = rootAtom;
313 while (true) {
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000314 AtomToAtomT::iterator followOnAtomsIter =
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000315 _followOnNexts.find(lastAtom);
316 if (followOnAtomsIter != _followOnNexts.end()) {
317 lastAtom = followOnAtomsIter->second;
318 if (lastAtom == ai) {
319 isAtomInChain = true;
320 break;
321 }
322 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000323 else
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000324 break;
325 } // findAtomInChain
326
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000327 if (!isAtomInChain)
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000328 _followOnNexts[lastAtom] = ai;
329 }
330 }
331 }
332}
333
334/// This pass builds the followon tables using Preceded By relationships
335/// The algorithm follows a very simple approach
336/// a) If the targetAtom is not part of any root and the current atom is not
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000337/// part of any root, create a chain with the current atom as root and
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000338/// the targetAtom as following the current atom
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000339/// b) Chain the targetAtom to the current Atom if the targetAtom is not part
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000340/// of any chain and the currentAtom has no followOn's
341/// c) If the targetAtom is part of a different tree and the root of the
342/// targetAtom is itself, and if the current atom is not part of any root
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000343/// chain all the atoms together
344/// d) If the current atom has no followon and the root of the targetAtom is
345/// not equal to the root of the current atom(the targetAtom is not in the
346/// same chain), chain all the atoms that are lead by the targetAtom into
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000347/// the current chain
348void LayoutPass::buildPrecededByTable(MutableFile::DefinedAtomRange &range) {
Michael J. Spencerd4eb47c2013-04-06 00:56:40 +0000349 ScopedTask task(getDefaultDomain(), "LayoutPass::buildPrecededByTable");
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000350 // This table would convert precededby references to follow on
351 // references so that we have only one table
Rui Ueyama0196d1062013-05-14 16:53:59 +0000352 for (const DefinedAtom *ai : range) {
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000353 for (const Reference *r : *ai) {
354 if (r->kind() == lld::Reference::kindLayoutBefore) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000355 const DefinedAtom *targetAtom = dyn_cast<DefinedAtom>(r->target());
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000356 // Is the targetAtom not chained
357 if (_followOnRoots.count(targetAtom) == 0) {
358 // Is the current atom not part of any root ?
359 if (_followOnRoots.count(ai) == 0) {
360 _followOnRoots[ai] = ai;
361 _followOnNexts[ai] = targetAtom;
362 _followOnRoots[targetAtom] = _followOnRoots[ai];
363 } else if (_followOnNexts.count(ai) == 0) {
364 // Chain the targetAtom to the current Atom
365 // if the currentAtom has no followon references
366 _followOnNexts[ai] = targetAtom;
367 _followOnRoots[targetAtom] = _followOnRoots[ai];
368 }
369 } else if (_followOnRoots.find(targetAtom)->second == targetAtom) {
370 // Is the targetAtom in chain with the targetAtom as the root ?
371 bool changeRoots = false;
372 if (_followOnRoots.count(ai) == 0) {
373 _followOnRoots[ai] = ai;
374 _followOnNexts[ai] = targetAtom;
375 _followOnRoots[targetAtom] = _followOnRoots[ai];
376 changeRoots = true;
377 } else if (_followOnNexts.count(ai) == 0) {
378 // Chain the targetAtom to the current Atom
379 // if the currentAtom has no followon references
380 if (_followOnRoots[ai] != _followOnRoots[targetAtom]) {
381 _followOnNexts[ai] = targetAtom;
382 _followOnRoots[targetAtom] = _followOnRoots[ai];
383 changeRoots = true;
384 }
385 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000386 // Change the roots of the targetAtom and its chain to
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000387 // the current atoms root
388 if (changeRoots) {
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000389 setChainRoot(_followOnRoots[targetAtom], _followOnRoots[ai]);
390 }
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000391 } // Is targetAtom root
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000392 } // kindLayoutBefore
Rui Ueyamaca8ca552013-05-14 00:41:52 +0000393 } // Reference
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000394 } // atom iteration
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000395} // end function
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000396
397
398/// Build an ordinal override map by traversing the followon chain, and
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000399/// assigning ordinals to each atom, if the atoms have their ordinals
400/// already assigned skip the atom and move to the next. This is the
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000401/// main map thats used to sort the atoms while comparing two atoms together
402void LayoutPass::buildOrdinalOverrideMap(MutableFile::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);
410 if (start != _followOnRoots.end()) {
411 for (const DefinedAtom *nextAtom = start->second; nextAtom != NULL;
412 nextAtom = _followOnNexts[nextAtom]) {
413 AtomToOrdinalT::iterator pos = _ordinalOverrideMap.find(nextAtom);
414 if (pos == _ordinalOverrideMap.end()) {
415 _ordinalOverrideMap[nextAtom] = index++;
416 }
417 }
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000418 }
419 }
420}
421
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000422// Helper functions to check follow-on graph.
423#ifndef NDEBUG
424namespace {
425typedef llvm::DenseMap<const DefinedAtom *, const DefinedAtom *> AtomToAtomT;
426
427std::string atomToDebugString(const Atom *atom) {
Rui Ueyamac1800be2013-11-05 01:37:40 +0000428 const DefinedAtom *definedAtom = dyn_cast<DefinedAtom>(atom);
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000429 std::string str;
430 llvm::raw_string_ostream s(str);
431 if (definedAtom->name().empty())
432 s << "<anonymous " << definedAtom << ">";
433 else
434 s << definedAtom->name();
435 s << " in ";
436 if (definedAtom->customSectionName().empty())
437 s << "<anonymous>";
438 else
439 s << definedAtom->customSectionName();
440 s.flush();
441 return str;
442}
443
444void showCycleDetectedError(AtomToAtomT &followOnNexts,
445 const DefinedAtom *atom) {
446 const DefinedAtom *start = atom;
447 llvm::dbgs() << "There's a cycle in a follow-on chain!\n";
448 do {
449 llvm::dbgs() << " " << atomToDebugString(atom) << "\n";
450 for (const Reference *ref : *atom) {
451 llvm::dbgs() << " " << ref->kindToString()
452 << ": " << atomToDebugString(ref->target()) << "\n";
453 }
454 atom = followOnNexts[atom];
455 } while (atom != start);
Rui Ueyama5b274f32013-07-29 21:50:33 +0000456 llvm::report_fatal_error("Cycle detected");
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000457}
458
459/// Exit if there's a cycle in a followon chain reachable from the
460/// given root atom. Uses the tortoise and hare algorithm to detect a
461/// cycle.
462void checkNoCycleInFollowonChain(AtomToAtomT &followOnNexts,
463 const DefinedAtom *root) {
464 const DefinedAtom *tortoise = root;
465 const DefinedAtom *hare = followOnNexts[root];
466 while (true) {
467 if (!tortoise || !hare)
468 return;
469 if (tortoise == hare)
470 showCycleDetectedError(followOnNexts, tortoise);
471 tortoise = followOnNexts[tortoise];
472 hare = followOnNexts[followOnNexts[hare]];
473 }
474}
475
476void checkReachabilityFromRoot(AtomToAtomT &followOnRoots,
477 const DefinedAtom *atom) {
478 if (!atom) return;
479 auto i = followOnRoots.find(atom);
480 if (i == followOnRoots.end()) {
481 Twine msg(Twine("Atom <") + atomToDebugString(atom)
482 + "> has no follow-on root!");
483 llvm_unreachable(msg.str().c_str());
484 }
485 const DefinedAtom *ap = i->second;
486 while (true) {
487 const DefinedAtom *next = followOnRoots[ap];
488 if (!next) {
489 Twine msg(Twine("Atom <" + atomToDebugString(atom)
490 + "> is not reachable from its root!"));
491 llvm_unreachable(msg.str().c_str());
492 }
493 if (next == ap)
494 return;
495 ap = next;
496 }
497}
498
499void printDefinedAtoms(const MutableFile::DefinedAtomRange &atomRange) {
500 for (const DefinedAtom *atom : atomRange) {
501 llvm::dbgs() << " file=" << atom->file().path()
502 << ", name=" << atom->name()
503 << ", size=" << atom->size()
504 << ", type=" << atom->contentType()
505 << ", ordinal=" << atom->ordinal()
506 << "\n";
507 }
508}
509} // end anonymous namespace
510
511/// Verify that the followon chain is sane. Should not be called in
512/// release binary.
513void LayoutPass::checkFollowonChain(MutableFile::DefinedAtomRange &range) {
514 ScopedTask task(getDefaultDomain(), "LayoutPass::checkFollowonChain");
515
516 // Verify that there's no cycle in follow-on chain.
517 std::set<const DefinedAtom *> roots;
518 for (const auto &ai : _followOnRoots)
519 roots.insert(ai.second);
520 for (const DefinedAtom *root : roots)
521 checkNoCycleInFollowonChain(_followOnNexts, root);
522
523 // Verify that all the atoms in followOnNexts have references to
524 // their roots.
525 for (const auto &ai : _followOnNexts) {
526 checkReachabilityFromRoot(_followOnRoots, ai.first);
527 checkReachabilityFromRoot(_followOnRoots, ai.second);
528 }
529}
530#endif // #ifndef NDEBUG
531
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000532std::vector<LayoutPass::SortKey>
533LayoutPass::decorate(MutableFile::DefinedAtomRange &atomRange) const {
534 std::vector<SortKey> ret;
535 for (const DefinedAtom *atom : atomRange) {
536 auto ri = _followOnRoots.find(atom);
537 auto oi = _ordinalOverrideMap.find(atom);
538 const DefinedAtom *root = (ri == _followOnRoots.end()) ? atom : ri->second;
539 uint64_t override = (oi == _ordinalOverrideMap.end()) ? 0 : oi->second;
540 ret.push_back(SortKey(atom, root, override));
541 }
542 return ret;
543}
544
545void LayoutPass::undecorate(MutableFile::DefinedAtomRange &atomRange,
546 std::vector<SortKey> &keys) const {
547 size_t i = 0;
548 for (SortKey &k : keys)
549 atomRange[i++] = k._atom;
550}
551
Shankar Easwaran8962feb2013-03-14 16:09:49 +0000552/// Perform the actual pass
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000553void LayoutPass::perform(std::unique_ptr<MutableFile> &mergedFile) {
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000554 // sort the atoms
Michael J. Spencerbd66d042013-05-28 18:55:39 +0000555 ScopedTask task(getDefaultDomain(), "LayoutPass");
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000556 MutableFile::DefinedAtomRange atomRange = mergedFile->definedAtoms();
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000557
558 // Build follow on tables
559 buildFollowOnTable(atomRange);
560
561 // Build Ingroup reference table
562 buildInGroupTable(atomRange);
563
564 // Build preceded by tables
565 buildPrecededByTable(atomRange);
566
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000567 // Check the structure of followon graph if running in debug mode.
568 DEBUG(checkFollowonChain(atomRange));
569
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000570 // Build override maps
571 buildOrdinalOverrideMap(atomRange);
572
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000573 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000574 llvm::dbgs() << "unsorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000575 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000576 });
Shankar Easwaran45a5f932013-04-29 03:27:57 +0000577
Rui Ueyama37c43e9f2013-12-08 03:12:08 +0000578 std::vector<LayoutPass::SortKey> vec = decorate(atomRange);
579 std::sort(vec.begin(), vec.end(), compareAtoms);
580 DEBUG(checkTransitivity(vec));
581 undecorate(atomRange, vec);
Rui Ueyama46bf8282013-10-19 03:18:18 +0000582
Rui Ueyama9c4f89a2013-05-23 01:31:25 +0000583 DEBUG({
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000584 llvm::dbgs() << "sorted atoms:\n";
Rui Ueyamaa6b71ca2013-06-07 20:18:39 +0000585 printDefinedAtoms(atomRange);
Nick Kledzikf4fa8c02013-04-04 20:32:18 +0000586 });
Shankar Easwaran34ab70f2013-02-07 20:16:12 +0000587}