StackColoring.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. //===- StackColoring.cpp --------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass implements the stack-coloring optimization that looks for
  11. // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
  12. // which represent the possible lifetime of stack slots. It attempts to
  13. // merge disjoint stack slots and reduce the used stack space.
  14. // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
  15. //
  16. // TODO: In the future we plan to improve stack coloring in the following ways:
  17. // 1. Allow merging multiple small slots into a single larger slot at different
  18. // offsets.
  19. // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
  20. // spill slots.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/ADT/BitVector.h"
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/DepthFirstIterator.h"
  26. #include "llvm/ADT/SmallPtrSet.h"
  27. #include "llvm/ADT/SmallVector.h"
  28. #include "llvm/ADT/Statistic.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/CodeGen/LiveInterval.h"
  31. #include "llvm/CodeGen/MachineBasicBlock.h"
  32. #include "llvm/CodeGen/MachineFrameInfo.h"
  33. #include "llvm/CodeGen/MachineFunction.h"
  34. #include "llvm/CodeGen/MachineFunctionPass.h"
  35. #include "llvm/CodeGen/MachineInstr.h"
  36. #include "llvm/CodeGen/MachineMemOperand.h"
  37. #include "llvm/CodeGen/MachineOperand.h"
  38. #include "llvm/CodeGen/Passes.h"
  39. #include "llvm/CodeGen/SelectionDAGNodes.h"
  40. #include "llvm/CodeGen/SlotIndexes.h"
  41. #include "llvm/CodeGen/StackProtector.h"
  42. #include "llvm/CodeGen/TargetOpcodes.h"
  43. #include "llvm/CodeGen/WinEHFuncInfo.h"
  44. #include "llvm/Config/llvm-config.h"
  45. #include "llvm/IR/Constants.h"
  46. #include "llvm/IR/DebugInfoMetadata.h"
  47. #include "llvm/IR/Function.h"
  48. #include "llvm/IR/Instructions.h"
  49. #include "llvm/IR/Metadata.h"
  50. #include "llvm/IR/Use.h"
  51. #include "llvm/IR/Value.h"
  52. #include "llvm/Pass.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/CommandLine.h"
  55. #include "llvm/Support/Compiler.h"
  56. #include "llvm/Support/Debug.h"
  57. #include "llvm/Support/raw_ostream.h"
  58. #include <algorithm>
  59. #include <cassert>
  60. #include <limits>
  61. #include <memory>
  62. #include <utility>
  63. using namespace llvm;
  64. #define DEBUG_TYPE "stack-coloring"
  65. static cl::opt<bool>
  66. DisableColoring("no-stack-coloring",
  67. cl::init(false), cl::Hidden,
  68. cl::desc("Disable stack coloring"));
  69. /// The user may write code that uses allocas outside of the declared lifetime
  70. /// zone. This can happen when the user returns a reference to a local
  71. /// data-structure. We can detect these cases and decide not to optimize the
  72. /// code. If this flag is enabled, we try to save the user. This option
  73. /// is treated as overriding LifetimeStartOnFirstUse below.
  74. static cl::opt<bool>
  75. ProtectFromEscapedAllocas("protect-from-escaped-allocas",
  76. cl::init(false), cl::Hidden,
  77. cl::desc("Do not optimize lifetime zones that "
  78. "are broken"));
  79. /// Enable enhanced dataflow scheme for lifetime analysis (treat first
  80. /// use of stack slot as start of slot lifetime, as opposed to looking
  81. /// for LIFETIME_START marker). See "Implementation notes" below for
  82. /// more info.
  83. static cl::opt<bool>
  84. LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use",
  85. cl::init(true), cl::Hidden,
  86. cl::desc("Treat stack lifetimes as starting on first use, not on START marker."));
  87. STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
  88. STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
  89. STATISTIC(StackSlotMerged, "Number of stack slot merged.");
  90. STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region");
  91. //===----------------------------------------------------------------------===//
  92. // StackColoring Pass
  93. //===----------------------------------------------------------------------===//
  94. //
  95. // Stack Coloring reduces stack usage by merging stack slots when they
  96. // can't be used together. For example, consider the following C program:
  97. //
  98. // void bar(char *, int);
  99. // void foo(bool var) {
  100. // A: {
  101. // char z[4096];
  102. // bar(z, 0);
  103. // }
  104. //
  105. // char *p;
  106. // char x[4096];
  107. // char y[4096];
  108. // if (var) {
  109. // p = x;
  110. // } else {
  111. // bar(y, 1);
  112. // p = y + 1024;
  113. // }
  114. // B:
  115. // bar(p, 2);
  116. // }
  117. //
  118. // Naively-compiled, this program would use 12k of stack space. However, the
  119. // stack slot corresponding to `z` is always destroyed before either of the
  120. // stack slots for `x` or `y` are used, and then `x` is only used if `var`
  121. // is true, while `y` is only used if `var` is false. So in no time are 2
  122. // of the stack slots used together, and therefore we can merge them,
  123. // compiling the function using only a single 4k alloca:
  124. //
  125. // void foo(bool var) { // equivalent
  126. // char x[4096];
  127. // char *p;
  128. // bar(x, 0);
  129. // if (var) {
  130. // p = x;
  131. // } else {
  132. // bar(x, 1);
  133. // p = x + 1024;
  134. // }
  135. // bar(p, 2);
  136. // }
  137. //
  138. // This is an important optimization if we want stack space to be under
  139. // control in large functions, both open-coded ones and ones created by
  140. // inlining.
  141. //
  142. // Implementation Notes:
  143. // ---------------------
  144. //
  145. // An important part of the above reasoning is that `z` can't be accessed
  146. // while the latter 2 calls to `bar` are running. This is justified because
  147. // `z`'s lifetime is over after we exit from block `A:`, so any further
  148. // accesses to it would be UB. The way we represent this information
  149. // in LLVM is by having frontends delimit blocks with `lifetime.start`
  150. // and `lifetime.end` intrinsics.
  151. //
  152. // The effect of these intrinsics seems to be as follows (maybe I should
  153. // specify this in the reference?):
  154. //
  155. // L1) at start, each stack-slot is marked as *out-of-scope*, unless no
  156. // lifetime intrinsic refers to that stack slot, in which case
  157. // it is marked as *in-scope*.
  158. // L2) on a `lifetime.start`, a stack slot is marked as *in-scope* and
  159. // the stack slot is overwritten with `undef`.
  160. // L3) on a `lifetime.end`, a stack slot is marked as *out-of-scope*.
  161. // L4) on function exit, all stack slots are marked as *out-of-scope*.
  162. // L5) `lifetime.end` is a no-op when called on a slot that is already
  163. // *out-of-scope*.
  164. // L6) memory accesses to *out-of-scope* stack slots are UB.
  165. // L7) when a stack-slot is marked as *out-of-scope*, all pointers to it
  166. // are invalidated, unless the slot is "degenerate". This is used to
  167. // justify not marking slots as in-use until the pointer to them is
  168. // used, but feels a bit hacky in the presence of things like LICM. See
  169. // the "Degenerate Slots" section for more details.
  170. //
  171. // Now, let's ground stack coloring on these rules. We'll define a slot
  172. // as *in-use* at a (dynamic) point in execution if it either can be
  173. // written to at that point, or if it has a live and non-undef content
  174. // at that point.
  175. //
  176. // Obviously, slots that are never *in-use* together can be merged, and
  177. // in our example `foo`, the slots for `x`, `y` and `z` are never
  178. // in-use together (of course, sometimes slots that *are* in-use together
  179. // might still be mergable, but we don't care about that here).
  180. //
  181. // In this implementation, we successively merge pairs of slots that are
  182. // not *in-use* together. We could be smarter - for example, we could merge
  183. // a single large slot with 2 small slots, or we could construct the
  184. // interference graph and run a "smart" graph coloring algorithm, but with
  185. // that aside, how do we find out whether a pair of slots might be *in-use*
  186. // together?
  187. //
  188. // From our rules, we see that *out-of-scope* slots are never *in-use*,
  189. // and from (L7) we see that "non-degenerate" slots remain non-*in-use*
  190. // until their address is taken. Therefore, we can approximate slot activity
  191. // using dataflow.
  192. //
  193. // A subtle point: naively, we might try to figure out which pairs of
  194. // stack-slots interfere by propagating `S in-use` through the CFG for every
  195. // stack-slot `S`, and having `S` and `T` interfere if there is a CFG point in
  196. // which they are both *in-use*.
  197. //
  198. // That is sound, but overly conservative in some cases: in our (artificial)
  199. // example `foo`, either `x` or `y` might be in use at the label `B:`, but
  200. // as `x` is only in use if we came in from the `var` edge and `y` only
  201. // if we came from the `!var` edge, they still can't be in use together.
  202. // See PR32488 for an important real-life case.
  203. //
  204. // If we wanted to find all points of interference precisely, we could
  205. // propagate `S in-use` and `S&T in-use` predicates through the CFG. That
  206. // would be precise, but requires propagating `O(n^2)` dataflow facts.
  207. //
  208. // However, we aren't interested in the *set* of points of interference
  209. // between 2 stack slots, only *whether* there *is* such a point. So we
  210. // can rely on a little trick: for `S` and `T` to be in-use together,
  211. // one of them needs to become in-use while the other is in-use (or
  212. // they might both become in use simultaneously). We can check this
  213. // by also keeping track of the points at which a stack slot might *start*
  214. // being in-use.
  215. //
  216. // Exact first use:
  217. // ----------------
  218. //
  219. // Consider the following motivating example:
  220. //
  221. // int foo() {
  222. // char b1[1024], b2[1024];
  223. // if (...) {
  224. // char b3[1024];
  225. // <uses of b1, b3>;
  226. // return x;
  227. // } else {
  228. // char b4[1024], b5[1024];
  229. // <uses of b2, b4, b5>;
  230. // return y;
  231. // }
  232. // }
  233. //
  234. // In the code above, "b3" and "b4" are declared in distinct lexical
  235. // scopes, meaning that it is easy to prove that they can share the
  236. // same stack slot. Variables "b1" and "b2" are declared in the same
  237. // scope, meaning that from a lexical point of view, their lifetimes
  238. // overlap. From a control flow pointer of view, however, the two
  239. // variables are accessed in disjoint regions of the CFG, thus it
  240. // should be possible for them to share the same stack slot. An ideal
  241. // stack allocation for the function above would look like:
  242. //
  243. // slot 0: b1, b2
  244. // slot 1: b3, b4
  245. // slot 2: b5
  246. //
  247. // Achieving this allocation is tricky, however, due to the way
  248. // lifetime markers are inserted. Here is a simplified view of the
  249. // control flow graph for the code above:
  250. //
  251. // +------ block 0 -------+
  252. // 0| LIFETIME_START b1, b2 |
  253. // 1| <test 'if' condition> |
  254. // +-----------------------+
  255. // ./ \.
  256. // +------ block 1 -------+ +------ block 2 -------+
  257. // 2| LIFETIME_START b3 | 5| LIFETIME_START b4, b5 |
  258. // 3| <uses of b1, b3> | 6| <uses of b2, b4, b5> |
  259. // 4| LIFETIME_END b3 | 7| LIFETIME_END b4, b5 |
  260. // +-----------------------+ +-----------------------+
  261. // \. /.
  262. // +------ block 3 -------+
  263. // 8| <cleanupcode> |
  264. // 9| LIFETIME_END b1, b2 |
  265. // 10| return |
  266. // +-----------------------+
  267. //
  268. // If we create live intervals for the variables above strictly based
  269. // on the lifetime markers, we'll get the set of intervals on the
  270. // left. If we ignore the lifetime start markers and instead treat a
  271. // variable's lifetime as beginning with the first reference to the
  272. // var, then we get the intervals on the right.
  273. //
  274. // LIFETIME_START First Use
  275. // b1: [0,9] [3,4] [8,9]
  276. // b2: [0,9] [6,9]
  277. // b3: [2,4] [3,4]
  278. // b4: [5,7] [6,7]
  279. // b5: [5,7] [6,7]
  280. //
  281. // For the intervals on the left, the best we can do is overlap two
  282. // variables (b3 and b4, for example); this gives us a stack size of
  283. // 4*1024 bytes, not ideal. When treating first-use as the start of a
  284. // lifetime, we can additionally overlap b1 and b5, giving us a 3*1024
  285. // byte stack (better).
  286. //
  287. // Degenerate Slots:
  288. // -----------------
  289. //
  290. // Relying entirely on first-use of stack slots is problematic,
  291. // however, due to the fact that optimizations can sometimes migrate
  292. // uses of a variable outside of its lifetime start/end region. Here
  293. // is an example:
  294. //
  295. // int bar() {
  296. // char b1[1024], b2[1024];
  297. // if (...) {
  298. // <uses of b2>
  299. // return y;
  300. // } else {
  301. // <uses of b1>
  302. // while (...) {
  303. // char b3[1024];
  304. // <uses of b3>
  305. // }
  306. // }
  307. // }
  308. //
  309. // Before optimization, the control flow graph for the code above
  310. // might look like the following:
  311. //
  312. // +------ block 0 -------+
  313. // 0| LIFETIME_START b1, b2 |
  314. // 1| <test 'if' condition> |
  315. // +-----------------------+
  316. // ./ \.
  317. // +------ block 1 -------+ +------- block 2 -------+
  318. // 2| <uses of b2> | 3| <uses of b1> |
  319. // +-----------------------+ +-----------------------+
  320. // | |
  321. // | +------- block 3 -------+ <-\.
  322. // | 4| <while condition> | |
  323. // | +-----------------------+ |
  324. // | / | |
  325. // | / +------- block 4 -------+
  326. // \ / 5| LIFETIME_START b3 | |
  327. // \ / 6| <uses of b3> | |
  328. // \ / 7| LIFETIME_END b3 | |
  329. // \ | +------------------------+ |
  330. // \ | \ /
  331. // +------ block 5 -----+ \---------------
  332. // 8| <cleanupcode> |
  333. // 9| LIFETIME_END b1, b2 |
  334. // 10| return |
  335. // +---------------------+
  336. //
  337. // During optimization, however, it can happen that an instruction
  338. // computing an address in "b3" (for example, a loop-invariant GEP) is
  339. // hoisted up out of the loop from block 4 to block 2. [Note that
  340. // this is not an actual load from the stack, only an instruction that
  341. // computes the address to be loaded]. If this happens, there is now a
  342. // path leading from the first use of b3 to the return instruction
  343. // that does not encounter the b3 LIFETIME_END, hence b3's lifetime is
  344. // now larger than if we were computing live intervals strictly based
  345. // on lifetime markers. In the example above, this lengthened lifetime
  346. // would mean that it would appear illegal to overlap b3 with b2.
  347. //
  348. // To deal with this such cases, the code in ::collectMarkers() below
  349. // tries to identify "degenerate" slots -- those slots where on a single
  350. // forward pass through the CFG we encounter a first reference to slot
  351. // K before we hit the slot K lifetime start marker. For such slots,
  352. // we fall back on using the lifetime start marker as the beginning of
  353. // the variable's lifetime. NB: with this implementation, slots can
  354. // appear degenerate in cases where there is unstructured control flow:
  355. //
  356. // if (q) goto mid;
  357. // if (x > 9) {
  358. // int b[100];
  359. // memcpy(&b[0], ...);
  360. // mid: b[k] = ...;
  361. // abc(&b);
  362. // }
  363. //
  364. // If in RPO ordering chosen to walk the CFG we happen to visit the b[k]
  365. // before visiting the memcpy block (which will contain the lifetime start
  366. // for "b" then it will appear that 'b' has a degenerate lifetime.
  367. //
  368. namespace {
  369. /// StackColoring - A machine pass for merging disjoint stack allocations,
  370. /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
  371. class StackColoring : public MachineFunctionPass {
  372. MachineFrameInfo *MFI;
  373. MachineFunction *MF;
  374. /// A class representing liveness information for a single basic block.
  375. /// Each bit in the BitVector represents the liveness property
  376. /// for a different stack slot.
  377. struct BlockLifetimeInfo {
  378. /// Which slots BEGINs in each basic block.
  379. BitVector Begin;
  380. /// Which slots ENDs in each basic block.
  381. BitVector End;
  382. /// Which slots are marked as LIVE_IN, coming into each basic block.
  383. BitVector LiveIn;
  384. /// Which slots are marked as LIVE_OUT, coming out of each basic block.
  385. BitVector LiveOut;
  386. };
  387. /// Maps active slots (per bit) for each basic block.
  388. using LivenessMap = DenseMap<const MachineBasicBlock *, BlockLifetimeInfo>;
  389. LivenessMap BlockLiveness;
  390. /// Maps serial numbers to basic blocks.
  391. DenseMap<const MachineBasicBlock *, int> BasicBlocks;
  392. /// Maps basic blocks to a serial number.
  393. SmallVector<const MachineBasicBlock *, 8> BasicBlockNumbering;
  394. /// Maps slots to their use interval. Outside of this interval, slots
  395. /// values are either dead or `undef` and they will not be written to.
  396. SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals;
  397. /// Maps slots to the points where they can become in-use.
  398. SmallVector<SmallVector<SlotIndex, 4>, 16> LiveStarts;
  399. /// VNInfo is used for the construction of LiveIntervals.
  400. VNInfo::Allocator VNInfoAllocator;
  401. /// SlotIndex analysis object.
  402. SlotIndexes *Indexes;
  403. /// The stack protector object.
  404. StackProtector *SP;
  405. /// The list of lifetime markers found. These markers are to be removed
  406. /// once the coloring is done.
  407. SmallVector<MachineInstr*, 8> Markers;
  408. /// Record the FI slots for which we have seen some sort of
  409. /// lifetime marker (either start or end).
  410. BitVector InterestingSlots;
  411. /// FI slots that need to be handled conservatively (for these
  412. /// slots lifetime-start-on-first-use is disabled).
  413. BitVector ConservativeSlots;
  414. /// Number of iterations taken during data flow analysis.
  415. unsigned NumIterations;
  416. public:
  417. static char ID;
  418. StackColoring() : MachineFunctionPass(ID) {
  419. initializeStackColoringPass(*PassRegistry::getPassRegistry());
  420. }
  421. void getAnalysisUsage(AnalysisUsage &AU) const override;
  422. bool runOnMachineFunction(MachineFunction &MF) override;
  423. private:
  424. /// Used in collectMarkers
  425. using BlockBitVecMap = DenseMap<const MachineBasicBlock *, BitVector>;
  426. /// Debug.
  427. void dump() const;
  428. void dumpIntervals() const;
  429. void dumpBB(MachineBasicBlock *MBB) const;
  430. void dumpBV(const char *tag, const BitVector &BV) const;
  431. /// Removes all of the lifetime marker instructions from the function.
  432. /// \returns true if any markers were removed.
  433. bool removeAllMarkers();
  434. /// Scan the machine function and find all of the lifetime markers.
  435. /// Record the findings in the BEGIN and END vectors.
  436. /// \returns the number of markers found.
  437. unsigned collectMarkers(unsigned NumSlot);
  438. /// Perform the dataflow calculation and calculate the lifetime for each of
  439. /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
  440. /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
  441. /// in and out blocks.
  442. void calculateLocalLiveness();
  443. /// Returns TRUE if we're using the first-use-begins-lifetime method for
  444. /// this slot (if FALSE, then the start marker is treated as start of lifetime).
  445. bool applyFirstUse(int Slot) {
  446. if (!LifetimeStartOnFirstUse || ProtectFromEscapedAllocas)
  447. return false;
  448. if (ConservativeSlots.test(Slot))
  449. return false;
  450. return true;
  451. }
  452. /// Examines the specified instruction and returns TRUE if the instruction
  453. /// represents the start or end of an interesting lifetime. The slot or slots
  454. /// starting or ending are added to the vector "slots" and "isStart" is set
  455. /// accordingly.
  456. /// \returns True if inst contains a lifetime start or end
  457. bool isLifetimeStartOrEnd(const MachineInstr &MI,
  458. SmallVector<int, 4> &slots,
  459. bool &isStart);
  460. /// Construct the LiveIntervals for the slots.
  461. void calculateLiveIntervals(unsigned NumSlots);
  462. /// Go over the machine function and change instructions which use stack
  463. /// slots to use the joint slots.
  464. void remapInstructions(DenseMap<int, int> &SlotRemap);
  465. /// The input program may contain instructions which are not inside lifetime
  466. /// markers. This can happen due to a bug in the compiler or due to a bug in
  467. /// user code (for example, returning a reference to a local variable).
  468. /// This procedure checks all of the instructions in the function and
  469. /// invalidates lifetime ranges which do not contain all of the instructions
  470. /// which access that frame slot.
  471. void removeInvalidSlotRanges();
  472. /// Map entries which point to other entries to their destination.
  473. /// A->B->C becomes A->C.
  474. void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
  475. };
  476. } // end anonymous namespace
  477. char StackColoring::ID = 0;
  478. char &llvm::StackColoringID = StackColoring::ID;
  479. INITIALIZE_PASS_BEGIN(StackColoring, DEBUG_TYPE,
  480. "Merge disjoint stack slots", false, false)
  481. INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
  482. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  483. INITIALIZE_PASS_END(StackColoring, DEBUG_TYPE,
  484. "Merge disjoint stack slots", false, false)
  485. void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
  486. AU.addRequired<SlotIndexes>();
  487. AU.addRequired<StackProtector>();
  488. MachineFunctionPass::getAnalysisUsage(AU);
  489. }
  490. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  491. LLVM_DUMP_METHOD void StackColoring::dumpBV(const char *tag,
  492. const BitVector &BV) const {
  493. dbgs() << tag << " : { ";
  494. for (unsigned I = 0, E = BV.size(); I != E; ++I)
  495. dbgs() << BV.test(I) << " ";
  496. dbgs() << "}\n";
  497. }
  498. LLVM_DUMP_METHOD void StackColoring::dumpBB(MachineBasicBlock *MBB) const {
  499. LivenessMap::const_iterator BI = BlockLiveness.find(MBB);
  500. assert(BI != BlockLiveness.end() && "Block not found");
  501. const BlockLifetimeInfo &BlockInfo = BI->second;
  502. dumpBV("BEGIN", BlockInfo.Begin);
  503. dumpBV("END", BlockInfo.End);
  504. dumpBV("LIVE_IN", BlockInfo.LiveIn);
  505. dumpBV("LIVE_OUT", BlockInfo.LiveOut);
  506. }
  507. LLVM_DUMP_METHOD void StackColoring::dump() const {
  508. for (MachineBasicBlock *MBB : depth_first(MF)) {
  509. dbgs() << "Inspecting block #" << MBB->getNumber() << " ["
  510. << MBB->getName() << "]\n";
  511. dumpBB(MBB);
  512. }
  513. }
  514. LLVM_DUMP_METHOD void StackColoring::dumpIntervals() const {
  515. for (unsigned I = 0, E = Intervals.size(); I != E; ++I) {
  516. dbgs() << "Interval[" << I << "]:\n";
  517. Intervals[I]->dump();
  518. }
  519. }
  520. #endif
  521. static inline int getStartOrEndSlot(const MachineInstr &MI)
  522. {
  523. assert((MI.getOpcode() == TargetOpcode::LIFETIME_START ||
  524. MI.getOpcode() == TargetOpcode::LIFETIME_END) &&
  525. "Expected LIFETIME_START or LIFETIME_END op");
  526. const MachineOperand &MO = MI.getOperand(0);
  527. int Slot = MO.getIndex();
  528. if (Slot >= 0)
  529. return Slot;
  530. return -1;
  531. }
  532. // At the moment the only way to end a variable lifetime is with
  533. // a VARIABLE_LIFETIME op (which can't contain a start). If things
  534. // change and the IR allows for a single inst that both begins
  535. // and ends lifetime(s), this interface will need to be reworked.
  536. bool StackColoring::isLifetimeStartOrEnd(const MachineInstr &MI,
  537. SmallVector<int, 4> &slots,
  538. bool &isStart) {
  539. if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
  540. MI.getOpcode() == TargetOpcode::LIFETIME_END) {
  541. int Slot = getStartOrEndSlot(MI);
  542. if (Slot < 0)
  543. return false;
  544. if (!InterestingSlots.test(Slot))
  545. return false;
  546. slots.push_back(Slot);
  547. if (MI.getOpcode() == TargetOpcode::LIFETIME_END) {
  548. isStart = false;
  549. return true;
  550. }
  551. if (!applyFirstUse(Slot)) {
  552. isStart = true;
  553. return true;
  554. }
  555. } else if (LifetimeStartOnFirstUse && !ProtectFromEscapedAllocas) {
  556. if (!MI.isDebugInstr()) {
  557. bool found = false;
  558. for (const MachineOperand &MO : MI.operands()) {
  559. if (!MO.isFI())
  560. continue;
  561. int Slot = MO.getIndex();
  562. if (Slot<0)
  563. continue;
  564. if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) {
  565. slots.push_back(Slot);
  566. found = true;
  567. }
  568. }
  569. if (found) {
  570. isStart = true;
  571. return true;
  572. }
  573. }
  574. }
  575. return false;
  576. }
  577. unsigned StackColoring::collectMarkers(unsigned NumSlot) {
  578. unsigned MarkersFound = 0;
  579. BlockBitVecMap SeenStartMap;
  580. InterestingSlots.clear();
  581. InterestingSlots.resize(NumSlot);
  582. ConservativeSlots.clear();
  583. ConservativeSlots.resize(NumSlot);
  584. // number of start and end lifetime ops for each slot
  585. SmallVector<int, 8> NumStartLifetimes(NumSlot, 0);
  586. SmallVector<int, 8> NumEndLifetimes(NumSlot, 0);
  587. // Step 1: collect markers and populate the "InterestingSlots"
  588. // and "ConservativeSlots" sets.
  589. for (MachineBasicBlock *MBB : depth_first(MF)) {
  590. // Compute the set of slots for which we've seen a START marker but have
  591. // not yet seen an END marker at this point in the walk (e.g. on entry
  592. // to this bb).
  593. BitVector BetweenStartEnd;
  594. BetweenStartEnd.resize(NumSlot);
  595. for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
  596. PE = MBB->pred_end(); PI != PE; ++PI) {
  597. BlockBitVecMap::const_iterator I = SeenStartMap.find(*PI);
  598. if (I != SeenStartMap.end()) {
  599. BetweenStartEnd |= I->second;
  600. }
  601. }
  602. // Walk the instructions in the block to look for start/end ops.
  603. for (MachineInstr &MI : *MBB) {
  604. if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
  605. MI.getOpcode() == TargetOpcode::LIFETIME_END) {
  606. int Slot = getStartOrEndSlot(MI);
  607. if (Slot < 0)
  608. continue;
  609. InterestingSlots.set(Slot);
  610. if (MI.getOpcode() == TargetOpcode::LIFETIME_START) {
  611. BetweenStartEnd.set(Slot);
  612. NumStartLifetimes[Slot] += 1;
  613. } else {
  614. BetweenStartEnd.reset(Slot);
  615. NumEndLifetimes[Slot] += 1;
  616. }
  617. const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
  618. if (Allocation) {
  619. DEBUG(dbgs() << "Found a lifetime ");
  620. DEBUG(dbgs() << (MI.getOpcode() == TargetOpcode::LIFETIME_START
  621. ? "start"
  622. : "end"));
  623. DEBUG(dbgs() << " marker for slot #" << Slot);
  624. DEBUG(dbgs() << " with allocation: " << Allocation->getName()
  625. << "\n");
  626. }
  627. Markers.push_back(&MI);
  628. MarkersFound += 1;
  629. } else {
  630. for (const MachineOperand &MO : MI.operands()) {
  631. if (!MO.isFI())
  632. continue;
  633. int Slot = MO.getIndex();
  634. if (Slot < 0)
  635. continue;
  636. if (! BetweenStartEnd.test(Slot)) {
  637. ConservativeSlots.set(Slot);
  638. }
  639. }
  640. }
  641. }
  642. BitVector &SeenStart = SeenStartMap[MBB];
  643. SeenStart |= BetweenStartEnd;
  644. }
  645. if (!MarkersFound) {
  646. return 0;
  647. }
  648. // PR27903: slots with multiple start or end lifetime ops are not
  649. // safe to enable for "lifetime-start-on-first-use".
  650. for (unsigned slot = 0; slot < NumSlot; ++slot)
  651. if (NumStartLifetimes[slot] > 1 || NumEndLifetimes[slot] > 1)
  652. ConservativeSlots.set(slot);
  653. DEBUG(dumpBV("Conservative slots", ConservativeSlots));
  654. // Step 2: compute begin/end sets for each block
  655. // NOTE: We use a depth-first iteration to ensure that we obtain a
  656. // deterministic numbering.
  657. for (MachineBasicBlock *MBB : depth_first(MF)) {
  658. // Assign a serial number to this basic block.
  659. BasicBlocks[MBB] = BasicBlockNumbering.size();
  660. BasicBlockNumbering.push_back(MBB);
  661. // Keep a reference to avoid repeated lookups.
  662. BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB];
  663. BlockInfo.Begin.resize(NumSlot);
  664. BlockInfo.End.resize(NumSlot);
  665. SmallVector<int, 4> slots;
  666. for (MachineInstr &MI : *MBB) {
  667. bool isStart = false;
  668. slots.clear();
  669. if (isLifetimeStartOrEnd(MI, slots, isStart)) {
  670. if (!isStart) {
  671. assert(slots.size() == 1 && "unexpected: MI ends multiple slots");
  672. int Slot = slots[0];
  673. if (BlockInfo.Begin.test(Slot)) {
  674. BlockInfo.Begin.reset(Slot);
  675. }
  676. BlockInfo.End.set(Slot);
  677. } else {
  678. for (auto Slot : slots) {
  679. DEBUG(dbgs() << "Found a use of slot #" << Slot);
  680. DEBUG(dbgs() << " at " << printMBBReference(*MBB) << " index ");
  681. DEBUG(Indexes->getInstructionIndex(MI).print(dbgs()));
  682. const AllocaInst *Allocation = MFI->getObjectAllocation(Slot);
  683. if (Allocation) {
  684. DEBUG(dbgs() << " with allocation: "<< Allocation->getName());
  685. }
  686. DEBUG(dbgs() << "\n");
  687. if (BlockInfo.End.test(Slot)) {
  688. BlockInfo.End.reset(Slot);
  689. }
  690. BlockInfo.Begin.set(Slot);
  691. }
  692. }
  693. }
  694. }
  695. }
  696. // Update statistics.
  697. NumMarkerSeen += MarkersFound;
  698. return MarkersFound;
  699. }
  700. void StackColoring::calculateLocalLiveness() {
  701. unsigned NumIters = 0;
  702. bool changed = true;
  703. while (changed) {
  704. changed = false;
  705. ++NumIters;
  706. for (const MachineBasicBlock *BB : BasicBlockNumbering) {
  707. // Use an iterator to avoid repeated lookups.
  708. LivenessMap::iterator BI = BlockLiveness.find(BB);
  709. assert(BI != BlockLiveness.end() && "Block not found");
  710. BlockLifetimeInfo &BlockInfo = BI->second;
  711. // Compute LiveIn by unioning together the LiveOut sets of all preds.
  712. BitVector LocalLiveIn;
  713. for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(),
  714. PE = BB->pred_end(); PI != PE; ++PI) {
  715. LivenessMap::const_iterator I = BlockLiveness.find(*PI);
  716. assert(I != BlockLiveness.end() && "Predecessor not found");
  717. LocalLiveIn |= I->second.LiveOut;
  718. }
  719. // Compute LiveOut by subtracting out lifetimes that end in this
  720. // block, then adding in lifetimes that begin in this block. If
  721. // we have both BEGIN and END markers in the same basic block
  722. // then we know that the BEGIN marker comes after the END,
  723. // because we already handle the case where the BEGIN comes
  724. // before the END when collecting the markers (and building the
  725. // BEGIN/END vectors).
  726. BitVector LocalLiveOut = LocalLiveIn;
  727. LocalLiveOut.reset(BlockInfo.End);
  728. LocalLiveOut |= BlockInfo.Begin;
  729. // Update block LiveIn set, noting whether it has changed.
  730. if (LocalLiveIn.test(BlockInfo.LiveIn)) {
  731. changed = true;
  732. BlockInfo.LiveIn |= LocalLiveIn;
  733. }
  734. // Update block LiveOut set, noting whether it has changed.
  735. if (LocalLiveOut.test(BlockInfo.LiveOut)) {
  736. changed = true;
  737. BlockInfo.LiveOut |= LocalLiveOut;
  738. }
  739. }
  740. } // while changed.
  741. NumIterations = NumIters;
  742. }
  743. void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
  744. SmallVector<SlotIndex, 16> Starts;
  745. SmallVector<bool, 16> DefinitelyInUse;
  746. // For each block, find which slots are active within this block
  747. // and update the live intervals.
  748. for (const MachineBasicBlock &MBB : *MF) {
  749. Starts.clear();
  750. Starts.resize(NumSlots);
  751. DefinitelyInUse.clear();
  752. DefinitelyInUse.resize(NumSlots);
  753. // Start the interval of the slots that we previously found to be 'in-use'.
  754. BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB];
  755. for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1;
  756. pos = MBBLiveness.LiveIn.find_next(pos)) {
  757. Starts[pos] = Indexes->getMBBStartIdx(&MBB);
  758. }
  759. // Create the interval for the basic blocks containing lifetime begin/end.
  760. for (const MachineInstr &MI : MBB) {
  761. SmallVector<int, 4> slots;
  762. bool IsStart = false;
  763. if (!isLifetimeStartOrEnd(MI, slots, IsStart))
  764. continue;
  765. SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
  766. for (auto Slot : slots) {
  767. if (IsStart) {
  768. // If a slot is already definitely in use, we don't have to emit
  769. // a new start marker because there is already a pre-existing
  770. // one.
  771. if (!DefinitelyInUse[Slot]) {
  772. LiveStarts[Slot].push_back(ThisIndex);
  773. DefinitelyInUse[Slot] = true;
  774. }
  775. if (!Starts[Slot].isValid())
  776. Starts[Slot] = ThisIndex;
  777. } else {
  778. if (Starts[Slot].isValid()) {
  779. VNInfo *VNI = Intervals[Slot]->getValNumInfo(0);
  780. Intervals[Slot]->addSegment(
  781. LiveInterval::Segment(Starts[Slot], ThisIndex, VNI));
  782. Starts[Slot] = SlotIndex(); // Invalidate the start index
  783. DefinitelyInUse[Slot] = false;
  784. }
  785. }
  786. }
  787. }
  788. // Finish up started segments
  789. for (unsigned i = 0; i < NumSlots; ++i) {
  790. if (!Starts[i].isValid())
  791. continue;
  792. SlotIndex EndIdx = Indexes->getMBBEndIdx(&MBB);
  793. VNInfo *VNI = Intervals[i]->getValNumInfo(0);
  794. Intervals[i]->addSegment(LiveInterval::Segment(Starts[i], EndIdx, VNI));
  795. }
  796. }
  797. }
  798. bool StackColoring::removeAllMarkers() {
  799. unsigned Count = 0;
  800. for (MachineInstr *MI : Markers) {
  801. MI->eraseFromParent();
  802. Count++;
  803. }
  804. Markers.clear();
  805. DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
  806. return Count;
  807. }
  808. void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
  809. unsigned FixedInstr = 0;
  810. unsigned FixedMemOp = 0;
  811. unsigned FixedDbg = 0;
  812. // Remap debug information that refers to stack slots.
  813. for (auto &VI : MF->getVariableDbgInfo()) {
  814. if (!VI.Var)
  815. continue;
  816. if (SlotRemap.count(VI.Slot)) {
  817. DEBUG(dbgs() << "Remapping debug info for ["
  818. << cast<DILocalVariable>(VI.Var)->getName() << "].\n");
  819. VI.Slot = SlotRemap[VI.Slot];
  820. FixedDbg++;
  821. }
  822. }
  823. // Keep a list of *allocas* which need to be remapped.
  824. DenseMap<const AllocaInst*, const AllocaInst*> Allocas;
  825. // Keep a list of allocas which has been affected by the remap.
  826. SmallPtrSet<const AllocaInst*, 32> MergedAllocas;
  827. for (const std::pair<int, int> &SI : SlotRemap) {
  828. const AllocaInst *From = MFI->getObjectAllocation(SI.first);
  829. const AllocaInst *To = MFI->getObjectAllocation(SI.second);
  830. assert(To && From && "Invalid allocation object");
  831. Allocas[From] = To;
  832. // AA might be used later for instruction scheduling, and we need it to be
  833. // able to deduce the correct aliasing releationships between pointers
  834. // derived from the alloca being remapped and the target of that remapping.
  835. // The only safe way, without directly informing AA about the remapping
  836. // somehow, is to directly update the IR to reflect the change being made
  837. // here.
  838. Instruction *Inst = const_cast<AllocaInst *>(To);
  839. if (From->getType() != To->getType()) {
  840. BitCastInst *Cast = new BitCastInst(Inst, From->getType());
  841. Cast->insertAfter(Inst);
  842. Inst = Cast;
  843. }
  844. // We keep both slots to maintain AliasAnalysis metadata later.
  845. MergedAllocas.insert(From);
  846. MergedAllocas.insert(To);
  847. // Allow the stack protector to adjust its value map to account for the
  848. // upcoming replacement.
  849. SP->adjustForColoring(From, To);
  850. // The new alloca might not be valid in a llvm.dbg.declare for this
  851. // variable, so undef out the use to make the verifier happy.
  852. AllocaInst *FromAI = const_cast<AllocaInst *>(From);
  853. if (FromAI->isUsedByMetadata())
  854. ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType()));
  855. for (auto &Use : FromAI->uses()) {
  856. if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get()))
  857. if (BCI->isUsedByMetadata())
  858. ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType()));
  859. }
  860. // Note that this will not replace uses in MMOs (which we'll update below),
  861. // or anywhere else (which is why we won't delete the original
  862. // instruction).
  863. FromAI->replaceAllUsesWith(Inst);
  864. }
  865. // Remap all instructions to the new stack slots.
  866. for (MachineBasicBlock &BB : *MF)
  867. for (MachineInstr &I : BB) {
  868. // Skip lifetime markers. We'll remove them soon.
  869. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  870. I.getOpcode() == TargetOpcode::LIFETIME_END)
  871. continue;
  872. // Update the MachineMemOperand to use the new alloca.
  873. for (MachineMemOperand *MMO : I.memoperands()) {
  874. // We've replaced IR-level uses of the remapped allocas, so we only
  875. // need to replace direct uses here.
  876. const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue());
  877. if (!AI)
  878. continue;
  879. if (!Allocas.count(AI))
  880. continue;
  881. MMO->setValue(Allocas[AI]);
  882. FixedMemOp++;
  883. }
  884. // Update all of the machine instruction operands.
  885. for (MachineOperand &MO : I.operands()) {
  886. if (!MO.isFI())
  887. continue;
  888. int FromSlot = MO.getIndex();
  889. // Don't touch arguments.
  890. if (FromSlot<0)
  891. continue;
  892. // Only look at mapped slots.
  893. if (!SlotRemap.count(FromSlot))
  894. continue;
  895. // In a debug build, check that the instruction that we are modifying is
  896. // inside the expected live range. If the instruction is not inside
  897. // the calculated range then it means that the alloca usage moved
  898. // outside of the lifetime markers, or that the user has a bug.
  899. // NOTE: Alloca address calculations which happen outside the lifetime
  900. // zone are okay, despite the fact that we don't have a good way
  901. // for validating all of the usages of the calculation.
  902. #ifndef NDEBUG
  903. bool TouchesMemory = I.mayLoad() || I.mayStore();
  904. // If we *don't* protect the user from escaped allocas, don't bother
  905. // validating the instructions.
  906. if (!I.isDebugInstr() && TouchesMemory && ProtectFromEscapedAllocas) {
  907. SlotIndex Index = Indexes->getInstructionIndex(I);
  908. const LiveInterval *Interval = &*Intervals[FromSlot];
  909. assert(Interval->find(Index) != Interval->end() &&
  910. "Found instruction usage outside of live range.");
  911. }
  912. #endif
  913. // Fix the machine instructions.
  914. int ToSlot = SlotRemap[FromSlot];
  915. MO.setIndex(ToSlot);
  916. FixedInstr++;
  917. }
  918. // We adjust AliasAnalysis information for merged stack slots.
  919. MachineSDNode::mmo_iterator NewMemOps =
  920. MF->allocateMemRefsArray(I.getNumMemOperands());
  921. unsigned MemOpIdx = 0;
  922. bool ReplaceMemOps = false;
  923. for (MachineMemOperand *MMO : I.memoperands()) {
  924. // If this memory location can be a slot remapped here,
  925. // we remove AA information.
  926. bool MayHaveConflictingAAMD = false;
  927. if (MMO->getAAInfo()) {
  928. if (const Value *MMOV = MMO->getValue()) {
  929. SmallVector<Value *, 4> Objs;
  930. getUnderlyingObjectsForCodeGen(MMOV, Objs, MF->getDataLayout());
  931. if (Objs.empty())
  932. MayHaveConflictingAAMD = true;
  933. else
  934. for (Value *V : Objs) {
  935. // If this memory location comes from a known stack slot
  936. // that is not remapped, we continue checking.
  937. // Otherwise, we need to invalidate AA infomation.
  938. const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(V);
  939. if (AI && MergedAllocas.count(AI)) {
  940. MayHaveConflictingAAMD = true;
  941. break;
  942. }
  943. }
  944. }
  945. }
  946. if (MayHaveConflictingAAMD) {
  947. NewMemOps[MemOpIdx++] = MF->getMachineMemOperand(MMO, AAMDNodes());
  948. ReplaceMemOps = true;
  949. }
  950. else
  951. NewMemOps[MemOpIdx++] = MMO;
  952. }
  953. // If any memory operand is updated, set memory references of
  954. // this instruction.
  955. if (ReplaceMemOps)
  956. I.setMemRefs(std::make_pair(NewMemOps, I.getNumMemOperands()));
  957. }
  958. // Update the location of C++ catch objects for the MSVC personality routine.
  959. if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo())
  960. for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap)
  961. for (WinEHHandlerType &H : TBME.HandlerArray)
  962. if (H.CatchObj.FrameIndex != std::numeric_limits<int>::max() &&
  963. SlotRemap.count(H.CatchObj.FrameIndex))
  964. H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex];
  965. DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
  966. DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
  967. DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
  968. }
  969. void StackColoring::removeInvalidSlotRanges() {
  970. for (MachineBasicBlock &BB : *MF)
  971. for (MachineInstr &I : BB) {
  972. if (I.getOpcode() == TargetOpcode::LIFETIME_START ||
  973. I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugInstr())
  974. continue;
  975. // Some intervals are suspicious! In some cases we find address
  976. // calculations outside of the lifetime zone, but not actual memory
  977. // read or write. Memory accesses outside of the lifetime zone are a clear
  978. // violation, but address calculations are okay. This can happen when
  979. // GEPs are hoisted outside of the lifetime zone.
  980. // So, in here we only check instructions which can read or write memory.
  981. if (!I.mayLoad() && !I.mayStore())
  982. continue;
  983. // Check all of the machine operands.
  984. for (const MachineOperand &MO : I.operands()) {
  985. if (!MO.isFI())
  986. continue;
  987. int Slot = MO.getIndex();
  988. if (Slot<0)
  989. continue;
  990. if (Intervals[Slot]->empty())
  991. continue;
  992. // Check that the used slot is inside the calculated lifetime range.
  993. // If it is not, warn about it and invalidate the range.
  994. LiveInterval *Interval = &*Intervals[Slot];
  995. SlotIndex Index = Indexes->getInstructionIndex(I);
  996. if (Interval->find(Index) == Interval->end()) {
  997. Interval->clear();
  998. DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
  999. EscapedAllocas++;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
  1005. unsigned NumSlots) {
  1006. // Expunge slot remap map.
  1007. for (unsigned i=0; i < NumSlots; ++i) {
  1008. // If we are remapping i
  1009. if (SlotRemap.count(i)) {
  1010. int Target = SlotRemap[i];
  1011. // As long as our target is mapped to something else, follow it.
  1012. while (SlotRemap.count(Target)) {
  1013. Target = SlotRemap[Target];
  1014. SlotRemap[i] = Target;
  1015. }
  1016. }
  1017. }
  1018. }
  1019. bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
  1020. DEBUG(dbgs() << "********** Stack Coloring **********\n"
  1021. << "********** Function: " << Func.getName() << '\n');
  1022. MF = &Func;
  1023. MFI = &MF->getFrameInfo();
  1024. Indexes = &getAnalysis<SlotIndexes>();
  1025. SP = &getAnalysis<StackProtector>();
  1026. BlockLiveness.clear();
  1027. BasicBlocks.clear();
  1028. BasicBlockNumbering.clear();
  1029. Markers.clear();
  1030. Intervals.clear();
  1031. LiveStarts.clear();
  1032. VNInfoAllocator.Reset();
  1033. unsigned NumSlots = MFI->getObjectIndexEnd();
  1034. // If there are no stack slots then there are no markers to remove.
  1035. if (!NumSlots)
  1036. return false;
  1037. SmallVector<int, 8> SortedSlots;
  1038. SortedSlots.reserve(NumSlots);
  1039. Intervals.reserve(NumSlots);
  1040. LiveStarts.resize(NumSlots);
  1041. unsigned NumMarkers = collectMarkers(NumSlots);
  1042. unsigned TotalSize = 0;
  1043. DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
  1044. DEBUG(dbgs()<<"Slot structure:\n");
  1045. for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
  1046. DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
  1047. TotalSize += MFI->getObjectSize(i);
  1048. }
  1049. DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
  1050. // Don't continue because there are not enough lifetime markers, or the
  1051. // stack is too small, or we are told not to optimize the slots.
  1052. if (NumMarkers < 2 || TotalSize < 16 || DisableColoring ||
  1053. skipFunction(Func.getFunction())) {
  1054. DEBUG(dbgs()<<"Will not try to merge slots.\n");
  1055. return removeAllMarkers();
  1056. }
  1057. for (unsigned i=0; i < NumSlots; ++i) {
  1058. std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0));
  1059. LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
  1060. Intervals.push_back(std::move(LI));
  1061. SortedSlots.push_back(i);
  1062. }
  1063. // Calculate the liveness of each block.
  1064. calculateLocalLiveness();
  1065. DEBUG(dbgs() << "Dataflow iterations: " << NumIterations << "\n");
  1066. DEBUG(dump());
  1067. // Propagate the liveness information.
  1068. calculateLiveIntervals(NumSlots);
  1069. DEBUG(dumpIntervals());
  1070. // Search for allocas which are used outside of the declared lifetime
  1071. // markers.
  1072. if (ProtectFromEscapedAllocas)
  1073. removeInvalidSlotRanges();
  1074. // Maps old slots to new slots.
  1075. DenseMap<int, int> SlotRemap;
  1076. unsigned RemovedSlots = 0;
  1077. unsigned ReducedSize = 0;
  1078. // Do not bother looking at empty intervals.
  1079. for (unsigned I = 0; I < NumSlots; ++I) {
  1080. if (Intervals[SortedSlots[I]]->empty())
  1081. SortedSlots[I] = -1;
  1082. }
  1083. // This is a simple greedy algorithm for merging allocas. First, sort the
  1084. // slots, placing the largest slots first. Next, perform an n^2 scan and look
  1085. // for disjoint slots. When you find disjoint slots, merge the samller one
  1086. // into the bigger one and update the live interval. Remove the small alloca
  1087. // and continue.
  1088. // Sort the slots according to their size. Place unused slots at the end.
  1089. // Use stable sort to guarantee deterministic code generation.
  1090. std::stable_sort(SortedSlots.begin(), SortedSlots.end(),
  1091. [this](int LHS, int RHS) {
  1092. // We use -1 to denote a uninteresting slot. Place these slots at the end.
  1093. if (LHS == -1) return false;
  1094. if (RHS == -1) return true;
  1095. // Sort according to size.
  1096. return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
  1097. });
  1098. for (auto &s : LiveStarts)
  1099. llvm::sort(s.begin(), s.end());
  1100. bool Changed = true;
  1101. while (Changed) {
  1102. Changed = false;
  1103. for (unsigned I = 0; I < NumSlots; ++I) {
  1104. if (SortedSlots[I] == -1)
  1105. continue;
  1106. for (unsigned J=I+1; J < NumSlots; ++J) {
  1107. if (SortedSlots[J] == -1)
  1108. continue;
  1109. int FirstSlot = SortedSlots[I];
  1110. int SecondSlot = SortedSlots[J];
  1111. LiveInterval *First = &*Intervals[FirstSlot];
  1112. LiveInterval *Second = &*Intervals[SecondSlot];
  1113. auto &FirstS = LiveStarts[FirstSlot];
  1114. auto &SecondS = LiveStarts[SecondSlot];
  1115. assert(!First->empty() && !Second->empty() && "Found an empty range");
  1116. // Merge disjoint slots. This is a little bit tricky - see the
  1117. // Implementation Notes section for an explanation.
  1118. if (!First->isLiveAtIndexes(SecondS) &&
  1119. !Second->isLiveAtIndexes(FirstS)) {
  1120. Changed = true;
  1121. First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0));
  1122. int OldSize = FirstS.size();
  1123. FirstS.append(SecondS.begin(), SecondS.end());
  1124. auto Mid = FirstS.begin() + OldSize;
  1125. std::inplace_merge(FirstS.begin(), Mid, FirstS.end());
  1126. SlotRemap[SecondSlot] = FirstSlot;
  1127. SortedSlots[J] = -1;
  1128. DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
  1129. SecondSlot<<" together.\n");
  1130. unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
  1131. MFI->getObjectAlignment(SecondSlot));
  1132. assert(MFI->getObjectSize(FirstSlot) >=
  1133. MFI->getObjectSize(SecondSlot) &&
  1134. "Merging a small object into a larger one");
  1135. RemovedSlots+=1;
  1136. ReducedSize += MFI->getObjectSize(SecondSlot);
  1137. MFI->setObjectAlignment(FirstSlot, MaxAlignment);
  1138. MFI->RemoveStackObject(SecondSlot);
  1139. }
  1140. }
  1141. }
  1142. }// While changed.
  1143. // Record statistics.
  1144. StackSpaceSaved += ReducedSize;
  1145. StackSlotMerged += RemovedSlots;
  1146. DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
  1147. ReducedSize<<" bytes\n");
  1148. // Scan the entire function and update all machine operands that use frame
  1149. // indices to use the remapped frame index.
  1150. expungeSlotMap(SlotRemap, NumSlots);
  1151. remapInstructions(SlotRemap);
  1152. return removeAllMarkers();
  1153. }