blob: 1d388132e6b6f78ab23fbbc6f11be85a3aa735d0 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010023#include "mirror/class-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000024#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000026
27namespace art {
28
29void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010030 block->SetBlockId(blocks_.size());
31 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000032}
33
Nicolas Geoffray804d0932014-05-02 08:46:00 +010034void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010035 ArenaBitVector visiting(arena_, blocks_.size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000036 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000037}
38
Roland Levillainfc600dc2014-12-02 17:16:31 +000039static void RemoveAsUser(HInstruction* instruction) {
40 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000041 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000042 }
43
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010044 for (HEnvironment* environment = instruction->GetEnvironment();
45 environment != nullptr;
46 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000047 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000048 if (environment->GetInstructionAt(i) != nullptr) {
49 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000050 }
51 }
52 }
53}
54
55void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010056 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000057 if (!visited.IsBitSet(i)) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010058 HBasicBlock* block = GetBlock(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010059 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000060 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
61 RemoveAsUser(it.Current());
62 }
63 }
64 }
65}
66
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010067void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010068 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000069 if (!visited.IsBitSet(i)) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010070 HBasicBlock* block = GetBlock(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010071 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +000072 for (HBasicBlock* successor : block->GetSuccessors()) {
73 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +000074 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010075 // Remove the block from the list of blocks, so that further analyses
76 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010077 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000078 }
79 }
80}
81
82void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
83 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010084 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000085 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000086 if (visited->IsBitSet(id)) return;
87
88 visited->SetBit(id);
89 visiting->SetBit(id);
Vladimir Marko60584552015-09-03 13:35:12 +000090 for (HBasicBlock* successor : block->GetSuccessors()) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100101 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
102 // edges. This invariant simplifies building SSA form because Phis cannot
103 // collect both normal- and exceptional-flow values at the same time.
104 SimplifyCatchBlocks();
105
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100106 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000107
David Brazdilffee3d32015-07-06 11:48:53 +0100108 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 FindBackEdges(&visited);
110
David Brazdilffee3d32015-07-06 11:48:53 +0100111 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // the initial DFS as users from other instructions, so that
113 // users can be safely removed before uses later.
114 RemoveInstructionsAsUsersFromDeadBlocks(visited);
115
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000118 // predecessors list of live blocks.
119 RemoveDeadBlocks(visited);
120
David Brazdilffee3d32015-07-06 11:48:53 +0100121 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100122 // dominators and the reverse post order.
123 SimplifyCFG();
124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100126 ComputeDominanceInformation();
127}
128
129void HGraph::ClearDominanceInformation() {
130 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
131 it.Current()->ClearDominanceInformation();
132 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100134}
135
136void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000137 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100138 dominator_ = nullptr;
139}
140
141void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100142 DCHECK(reverse_post_order_.empty());
143 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100144 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100145
146 // Number of visits of a given node, indexed by block id.
147 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
148 // Number of successors visited from a given node, indexed by block id.
149 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
150 // Nodes for which we need to visit successors.
151 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
152 constexpr size_t kDefaultWorklistSize = 8;
153 worklist.reserve(kDefaultWorklistSize);
154 worklist.push_back(entry_block_);
155
156 while (!worklist.empty()) {
157 HBasicBlock* current = worklist.back();
158 uint32_t current_id = current->GetBlockId();
159 if (successors_visited[current_id] == current->GetSuccessors().size()) {
160 worklist.pop_back();
161 } else {
162 DCHECK_LT(successors_visited[current_id], current->GetSuccessors().size());
163 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
164
165 if (successor->GetDominator() == nullptr) {
166 successor->SetDominator(current);
167 } else {
168 successor->SetDominator(FindCommonDominator(successor->GetDominator(), current));
169 }
170
171 // Once all the forward edges have been visited, we know the immediate
172 // dominator of the block. We can then start visiting its successors.
173 DCHECK_LT(successor->GetBlockId(), visits.size());
174 if (++visits[successor->GetBlockId()] ==
175 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
176 successor->GetDominator()->AddDominatedBlock(successor);
177 reverse_post_order_.push_back(successor);
178 worklist.push_back(successor);
179 }
180 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000181 }
182}
183
184HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100185 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000186 // Walk the dominator tree of the first block and mark the visited blocks.
187 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000188 visited.SetBit(first->GetBlockId());
189 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000190 }
191 // Walk the dominator tree of the second block until a marked block is found.
192 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000193 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000194 return second;
195 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000196 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000197 }
198 LOG(ERROR) << "Could not find common dominator";
199 return nullptr;
200}
201
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000202void HGraph::TransformToSsa() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100203 DCHECK(!reverse_post_order_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100204 SsaBuilder ssa_builder(this);
205 ssa_builder.BuildSsa();
206}
207
David Brazdilfc6a86a2015-06-26 10:33:45 +0000208HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000209 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
210 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000211 // Use `InsertBetween` to ensure the predecessor index and successor index of
212 // `block` and `successor` are preserved.
213 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000214 return new_block;
215}
216
217void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
218 // Insert a new node between `block` and `successor` to split the
219 // critical edge.
220 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600221 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100222 if (successor->IsLoopHeader()) {
223 // If we split at a back edge boundary, make the new block the back edge.
224 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000225 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100226 info->RemoveBackEdge(block);
227 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100228 }
229 }
230}
231
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232void HGraph::SimplifyLoop(HBasicBlock* header) {
233 HLoopInformation* info = header->GetLoopInformation();
234
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100235 // Make sure the loop has only one pre header. This simplifies SSA building by having
236 // to just look at the pre header to know which locals are initialized at entry of the
237 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000238 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100239 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100240 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100241 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600242 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100243
Vladimir Marko60584552015-09-03 13:35:12 +0000244 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
245 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100246 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100247 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100248 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100249 }
250 }
251 pre_header->AddSuccessor(header);
252 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100253
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100254 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Marko60584552015-09-03 13:35:12 +0000255 if (info->IsBackEdge(*header->GetPredecessor(0))) {
256 HBasicBlock* to_swap = header->GetPredecessor(0);
257 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
258 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100259 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000260 header->predecessors_[pred] = to_swap;
261 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100262 break;
263 }
264 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100265 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100266
267 // Place the suspend check at the beginning of the header, so that live registers
268 // will be known when allocating registers. Note that code generation can still
269 // generate the suspend check at the back edge, but needs to be careful with
270 // loop phi spill slots (which are not written to at back edge).
271 HInstruction* first_instruction = header->GetFirstInstruction();
272 if (!first_instruction->IsSuspendCheck()) {
273 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
274 header->InsertInstructionBefore(check, first_instruction);
275 first_instruction = check;
276 }
277 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100278}
279
David Brazdilffee3d32015-07-06 11:48:53 +0100280static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Marko60584552015-09-03 13:35:12 +0000281 HBasicBlock* predecessor = block.GetPredecessor(pred_idx);
David Brazdilffee3d32015-07-06 11:48:53 +0100282 if (!predecessor->EndsWithTryBoundary()) {
283 // Only edges from HTryBoundary can be exceptional.
284 return false;
285 }
286 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
287 if (try_boundary->GetNormalFlowSuccessor() == &block) {
288 // This block is the normal-flow successor of `try_boundary`, but it could
289 // also be one of its exception handlers if catch blocks have not been
290 // simplified yet. Predecessors are unordered, so we will consider the first
291 // occurrence to be the normal edge and a possible second occurrence to be
292 // the exceptional edge.
293 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
294 } else {
295 // This is not the normal-flow successor of `try_boundary`, hence it must be
296 // one of its exception handlers.
297 DCHECK(try_boundary->HasExceptionHandler(block));
298 return true;
299 }
300}
301
302void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100303 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
304 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
305 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
306 HBasicBlock* catch_block = blocks_[block_id];
David Brazdilffee3d32015-07-06 11:48:53 +0100307 if (!catch_block->IsCatchBlock()) {
308 continue;
309 }
310
311 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000312 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100313 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
314 exceptional_predecessors_only = false;
315 break;
316 }
317 }
318
319 if (!exceptional_predecessors_only) {
320 // Catch block has normal-flow predecessors and needs to be simplified.
321 // Splitting the block before its first instruction moves all its
322 // instructions into `normal_block` and links the two blocks with a Goto.
323 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
324 // leaving `catch_block` with the exceptional edges only.
325 // Note that catch blocks with normal-flow predecessors cannot begin with
326 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
327 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
328 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000329 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100330 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000331 catch_block->GetPredecessor(j)->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100332 --j;
333 }
334 }
335 }
336 }
337}
338
339void HGraph::ComputeTryBlockInformation() {
340 // Iterate in reverse post order to propagate try membership information from
341 // predecessors to their successors.
342 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
343 HBasicBlock* block = it.Current();
344 if (block->IsEntryBlock() || block->IsCatchBlock()) {
345 // Catch blocks after simplification have only exceptional predecessors
346 // and hence are never in tries.
347 continue;
348 }
349
350 // Infer try membership from the first predecessor. Having simplified loops,
351 // the first predecessor can never be a back edge and therefore it must have
352 // been visited already and had its try membership set.
Vladimir Marko60584552015-09-03 13:35:12 +0000353 HBasicBlock* first_predecessor = block->GetPredecessor(0);
David Brazdilffee3d32015-07-06 11:48:53 +0100354 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100355 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
356 if (try_entry != nullptr) {
357 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
358 }
David Brazdilffee3d32015-07-06 11:48:53 +0100359 }
360}
361
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100362void HGraph::SimplifyCFG() {
363 // Simplify the CFG for future analysis, and code generation:
364 // (1): Split critical edges.
365 // (2): Simplify loops by having only one back edge, and one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100366 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
367 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
368 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
369 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100370 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100371 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000372 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
373 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100374 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000375 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100376 SplitCriticalEdge(block, successor);
377 --j;
378 }
379 }
380 }
381 if (block->IsLoopHeader()) {
382 SimplifyLoop(block);
383 }
384 }
385}
386
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000387bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100388 // Order does not matter.
389 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
390 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100391 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100392 if (block->IsCatchBlock()) {
393 // TODO: Dealing with exceptional back edges could be tricky because
394 // they only approximate the real control flow. Bail out for now.
395 return false;
396 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100397 HLoopInformation* info = block->GetLoopInformation();
398 if (!info->Populate()) {
399 // Abort if the loop is non natural. We currently bailout in such cases.
400 return false;
401 }
402 }
403 }
404 return true;
405}
406
David Brazdil8d5b8b22015-03-24 10:51:52 +0000407void HGraph::InsertConstant(HConstant* constant) {
408 // New constants are inserted before the final control-flow instruction
409 // of the graph, or at its end if called from the graph builder.
410 if (entry_block_->EndsWithControlFlowInstruction()) {
411 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000412 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000413 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000414 }
415}
416
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600417HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100418 // For simplicity, don't bother reviving the cached null constant if it is
419 // not null and not in a block. Otherwise, we need to clear the instruction
420 // id and/or any invariants the graph is assuming when adding new instructions.
421 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600422 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000423 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000424 }
425 return cached_null_constant_;
426}
427
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100428HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100429 // For simplicity, don't bother reviving the cached current method if it is
430 // not null and not in a block. Otherwise, we need to clear the instruction
431 // id and/or any invariants the graph is assuming when adding new instructions.
432 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700433 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600434 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
435 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100436 if (entry_block_->GetFirstInstruction() == nullptr) {
437 entry_block_->AddInstruction(cached_current_method_);
438 } else {
439 entry_block_->InsertInstructionBefore(
440 cached_current_method_, entry_block_->GetFirstInstruction());
441 }
442 }
443 return cached_current_method_;
444}
445
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600446HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000447 switch (type) {
448 case Primitive::Type::kPrimBoolean:
449 DCHECK(IsUint<1>(value));
450 FALLTHROUGH_INTENDED;
451 case Primitive::Type::kPrimByte:
452 case Primitive::Type::kPrimChar:
453 case Primitive::Type::kPrimShort:
454 case Primitive::Type::kPrimInt:
455 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600456 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000457
458 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600459 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000460
461 default:
462 LOG(FATAL) << "Unsupported constant type";
463 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000464 }
David Brazdil46e2a392015-03-16 17:31:52 +0000465}
466
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000467void HGraph::CacheFloatConstant(HFloatConstant* constant) {
468 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
469 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
470 cached_float_constants_.Overwrite(value, constant);
471}
472
473void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
474 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
475 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
476 cached_double_constants_.Overwrite(value, constant);
477}
478
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000479void HLoopInformation::Add(HBasicBlock* block) {
480 blocks_.SetBit(block->GetBlockId());
481}
482
David Brazdil46e2a392015-03-16 17:31:52 +0000483void HLoopInformation::Remove(HBasicBlock* block) {
484 blocks_.ClearBit(block->GetBlockId());
485}
486
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100487void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
488 if (blocks_.IsBitSet(block->GetBlockId())) {
489 return;
490 }
491
492 blocks_.SetBit(block->GetBlockId());
493 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000494 for (HBasicBlock* predecessor : block->GetPredecessors()) {
495 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100496 }
497}
498
499bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100500 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100501 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100502 DCHECK(back_edge->GetDominator() != nullptr);
503 if (!header_->Dominates(back_edge)) {
504 // This loop is not natural. Do not bother going further.
505 return false;
506 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100507
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100508 // Populate this loop: starting with the back edge, recursively add predecessors
509 // that are not already part of that loop. Set the header as part of the loop
510 // to end the recursion.
511 // This is a recursive implementation of the algorithm described in
512 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
513 blocks_.SetBit(header_->GetBlockId());
514 PopulateRecursive(back_edge);
515 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100516 return true;
517}
518
David Brazdila4b8c212015-05-07 09:59:30 +0100519void HLoopInformation::Update() {
520 HGraph* graph = header_->GetGraph();
521 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100522 HBasicBlock* block = graph->GetBlock(id);
David Brazdila4b8c212015-05-07 09:59:30 +0100523 // Reset loop information of non-header blocks inside the loop, except
524 // members of inner nested loops because those should already have been
525 // updated by their own LoopInformation.
526 if (block->GetLoopInformation() == this && block != header_) {
527 block->SetLoopInformation(nullptr);
528 }
529 }
530 blocks_.ClearAllBits();
531
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100532 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100533 // The loop has been dismantled, delete its suspend check and remove info
534 // from the header.
535 DCHECK(HasSuspendCheck());
536 header_->RemoveInstruction(suspend_check_);
537 header_->SetLoopInformation(nullptr);
538 header_ = nullptr;
539 suspend_check_ = nullptr;
540 } else {
541 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100542 for (HBasicBlock* back_edge : back_edges_) {
543 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100544 }
545 }
546 // This loop still has reachable back edges. Repopulate the list of blocks.
547 bool populate_successful = Populate();
548 DCHECK(populate_successful);
549 }
550}
551
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100552HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100553 return header_->GetDominator();
554}
555
556bool HLoopInformation::Contains(const HBasicBlock& block) const {
557 return blocks_.IsBitSet(block.GetBlockId());
558}
559
560bool HLoopInformation::IsIn(const HLoopInformation& other) const {
561 return other.blocks_.IsBitSet(header_->GetBlockId());
562}
563
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100564size_t HLoopInformation::GetLifetimeEnd() const {
565 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100566 for (HBasicBlock* back_edge : GetBackEdges()) {
567 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100568 }
569 return last_position;
570}
571
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100572bool HBasicBlock::Dominates(HBasicBlock* other) const {
573 // Walk up the dominator tree from `other`, to find out if `this`
574 // is an ancestor.
575 HBasicBlock* current = other;
576 while (current != nullptr) {
577 if (current == this) {
578 return true;
579 }
580 current = current->GetDominator();
581 }
582 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100583}
584
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100585static void UpdateInputsUsers(HInstruction* instruction) {
586 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
587 instruction->InputAt(i)->AddUseAt(instruction, i);
588 }
589 // Environment should be created later.
590 DCHECK(!instruction->HasEnvironment());
591}
592
Roland Levillainccc07a92014-09-16 14:48:16 +0100593void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
594 HInstruction* replacement) {
595 DCHECK(initial->GetBlock() == this);
596 InsertInstructionBefore(replacement, initial);
597 initial->ReplaceWith(replacement);
598 RemoveInstruction(initial);
599}
600
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100601static void Add(HInstructionList* instruction_list,
602 HBasicBlock* block,
603 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000604 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000605 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100606 instruction->SetBlock(block);
607 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100608 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100609 instruction_list->AddInstruction(instruction);
610}
611
612void HBasicBlock::AddInstruction(HInstruction* instruction) {
613 Add(&instructions_, this, instruction);
614}
615
616void HBasicBlock::AddPhi(HPhi* phi) {
617 Add(&phis_, this, phi);
618}
619
David Brazdilc3d743f2015-04-22 13:40:50 +0100620void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
621 DCHECK(!cursor->IsPhi());
622 DCHECK(!instruction->IsPhi());
623 DCHECK_EQ(instruction->GetId(), -1);
624 DCHECK_NE(cursor->GetId(), -1);
625 DCHECK_EQ(cursor->GetBlock(), this);
626 DCHECK(!instruction->IsControlFlow());
627 instruction->SetBlock(this);
628 instruction->SetId(GetGraph()->GetNextInstructionId());
629 UpdateInputsUsers(instruction);
630 instructions_.InsertInstructionBefore(instruction, cursor);
631}
632
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100633void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
634 DCHECK(!cursor->IsPhi());
635 DCHECK(!instruction->IsPhi());
636 DCHECK_EQ(instruction->GetId(), -1);
637 DCHECK_NE(cursor->GetId(), -1);
638 DCHECK_EQ(cursor->GetBlock(), this);
639 DCHECK(!instruction->IsControlFlow());
640 DCHECK(!cursor->IsControlFlow());
641 instruction->SetBlock(this);
642 instruction->SetId(GetGraph()->GetNextInstructionId());
643 UpdateInputsUsers(instruction);
644 instructions_.InsertInstructionAfter(instruction, cursor);
645}
646
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100647void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
648 DCHECK_EQ(phi->GetId(), -1);
649 DCHECK_NE(cursor->GetId(), -1);
650 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100651 phi->SetBlock(this);
652 phi->SetId(GetGraph()->GetNextInstructionId());
653 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100654 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100655}
656
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657static void Remove(HInstructionList* instruction_list,
658 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000659 HInstruction* instruction,
660 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100661 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100662 instruction->SetBlock(nullptr);
663 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000664 if (ensure_safety) {
665 DCHECK(instruction->GetUses().IsEmpty());
666 DCHECK(instruction->GetEnvUses().IsEmpty());
667 RemoveAsUser(instruction);
668 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100669}
670
David Brazdil1abb4192015-02-17 18:33:36 +0000671void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100672 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000673 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100674}
675
David Brazdil1abb4192015-02-17 18:33:36 +0000676void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
677 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100678}
679
David Brazdilc7508e92015-04-27 13:28:57 +0100680void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
681 if (instruction->IsPhi()) {
682 RemovePhi(instruction->AsPhi(), ensure_safety);
683 } else {
684 RemoveInstruction(instruction, ensure_safety);
685 }
686}
687
Vladimir Marko71bf8092015-09-15 15:33:14 +0100688void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
689 for (size_t i = 0; i < locals.size(); i++) {
690 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100691 SetRawEnvAt(i, instruction);
692 if (instruction != nullptr) {
693 instruction->AddEnvUseAt(this, i);
694 }
695 }
696}
697
David Brazdiled596192015-01-23 10:39:45 +0000698void HEnvironment::CopyFrom(HEnvironment* env) {
699 for (size_t i = 0; i < env->Size(); i++) {
700 HInstruction* instruction = env->GetInstructionAt(i);
701 SetRawEnvAt(i, instruction);
702 if (instruction != nullptr) {
703 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100704 }
David Brazdiled596192015-01-23 10:39:45 +0000705 }
706}
707
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700708void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
709 HBasicBlock* loop_header) {
710 DCHECK(loop_header->IsLoopHeader());
711 for (size_t i = 0; i < env->Size(); i++) {
712 HInstruction* instruction = env->GetInstructionAt(i);
713 SetRawEnvAt(i, instruction);
714 if (instruction == nullptr) {
715 continue;
716 }
717 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
718 // At the end of the loop pre-header, the corresponding value for instruction
719 // is the first input of the phi.
720 HInstruction* initial = instruction->AsPhi()->InputAt(0);
721 DCHECK(initial->GetBlock()->Dominates(loop_header));
722 SetRawEnvAt(i, initial);
723 initial->AddEnvUseAt(this, i);
724 } else {
725 instruction->AddEnvUseAt(this, i);
726 }
727 }
728}
729
David Brazdil1abb4192015-02-17 18:33:36 +0000730void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100731 DCHECK_LT(index, Size());
732 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000733 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100734}
735
Calin Juravle77520bc2015-01-12 18:45:46 +0000736HInstruction* HInstruction::GetNextDisregardingMoves() const {
737 HInstruction* next = GetNext();
738 while (next != nullptr && next->IsParallelMove()) {
739 next = next->GetNext();
740 }
741 return next;
742}
743
744HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
745 HInstruction* previous = GetPrevious();
746 while (previous != nullptr && previous->IsParallelMove()) {
747 previous = previous->GetPrevious();
748 }
749 return previous;
750}
751
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100752void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000753 if (first_instruction_ == nullptr) {
754 DCHECK(last_instruction_ == nullptr);
755 first_instruction_ = last_instruction_ = instruction;
756 } else {
757 last_instruction_->next_ = instruction;
758 instruction->previous_ = last_instruction_;
759 last_instruction_ = instruction;
760 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000761}
762
David Brazdilc3d743f2015-04-22 13:40:50 +0100763void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
764 DCHECK(Contains(cursor));
765 if (cursor == first_instruction_) {
766 cursor->previous_ = instruction;
767 instruction->next_ = cursor;
768 first_instruction_ = instruction;
769 } else {
770 instruction->previous_ = cursor->previous_;
771 instruction->next_ = cursor;
772 cursor->previous_ = instruction;
773 instruction->previous_->next_ = instruction;
774 }
775}
776
777void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
778 DCHECK(Contains(cursor));
779 if (cursor == last_instruction_) {
780 cursor->next_ = instruction;
781 instruction->previous_ = cursor;
782 last_instruction_ = instruction;
783 } else {
784 instruction->next_ = cursor->next_;
785 instruction->previous_ = cursor;
786 cursor->next_ = instruction;
787 instruction->next_->previous_ = instruction;
788 }
789}
790
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100791void HInstructionList::RemoveInstruction(HInstruction* instruction) {
792 if (instruction->previous_ != nullptr) {
793 instruction->previous_->next_ = instruction->next_;
794 }
795 if (instruction->next_ != nullptr) {
796 instruction->next_->previous_ = instruction->previous_;
797 }
798 if (instruction == first_instruction_) {
799 first_instruction_ = instruction->next_;
800 }
801 if (instruction == last_instruction_) {
802 last_instruction_ = instruction->previous_;
803 }
804}
805
Roland Levillain6b469232014-09-25 10:10:38 +0100806bool HInstructionList::Contains(HInstruction* instruction) const {
807 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
808 if (it.Current() == instruction) {
809 return true;
810 }
811 }
812 return false;
813}
814
Roland Levillainccc07a92014-09-16 14:48:16 +0100815bool HInstructionList::FoundBefore(const HInstruction* instruction1,
816 const HInstruction* instruction2) const {
817 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
818 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
819 if (it.Current() == instruction1) {
820 return true;
821 }
822 if (it.Current() == instruction2) {
823 return false;
824 }
825 }
826 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
827 return true;
828}
829
Roland Levillain6c82d402014-10-13 16:10:27 +0100830bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
831 if (other_instruction == this) {
832 // An instruction does not strictly dominate itself.
833 return false;
834 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100835 HBasicBlock* block = GetBlock();
836 HBasicBlock* other_block = other_instruction->GetBlock();
837 if (block != other_block) {
838 return GetBlock()->Dominates(other_instruction->GetBlock());
839 } else {
840 // If both instructions are in the same block, ensure this
841 // instruction comes before `other_instruction`.
842 if (IsPhi()) {
843 if (!other_instruction->IsPhi()) {
844 // Phis appear before non phi-instructions so this instruction
845 // dominates `other_instruction`.
846 return true;
847 } else {
848 // There is no order among phis.
849 LOG(FATAL) << "There is no dominance between phis of a same block.";
850 return false;
851 }
852 } else {
853 // `this` is not a phi.
854 if (other_instruction->IsPhi()) {
855 // Phis appear before non phi-instructions so this instruction
856 // does not dominate `other_instruction`.
857 return false;
858 } else {
859 // Check whether this instruction comes before
860 // `other_instruction` in the instruction list.
861 return block->GetInstructions().FoundBefore(this, other_instruction);
862 }
863 }
864 }
865}
866
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100867void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100868 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000869 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
870 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100871 HInstruction* user = current->GetUser();
872 size_t input_index = current->GetIndex();
873 user->SetRawInputAt(input_index, other);
874 other->AddUseAt(user, input_index);
875 }
876
David Brazdiled596192015-01-23 10:39:45 +0000877 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
878 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100879 HEnvironment* user = current->GetUser();
880 size_t input_index = current->GetIndex();
881 user->SetRawEnvAt(input_index, other);
882 other->AddEnvUseAt(user, input_index);
883 }
884
David Brazdiled596192015-01-23 10:39:45 +0000885 uses_.Clear();
886 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100887}
888
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100889void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000890 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100891 SetRawInputAt(index, replacement);
892 replacement->AddUseAt(this, index);
893}
894
Nicolas Geoffray39468442014-09-02 15:17:15 +0100895size_t HInstruction::EnvironmentSize() const {
896 return HasEnvironment() ? environment_->Size() : 0;
897}
898
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100899void HPhi::AddInput(HInstruction* input) {
900 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100901 inputs_.push_back(HUserRecord<HInstruction*>(input));
902 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100903}
904
David Brazdil2d7352b2015-04-20 14:52:42 +0100905void HPhi::RemoveInputAt(size_t index) {
906 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100907 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100908 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100909 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100910 InputRecordAt(i).GetUseNode()->SetIndex(i);
911 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100912}
913
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100914#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000915void H##name::Accept(HGraphVisitor* visitor) { \
916 visitor->Visit##name(this); \
917}
918
919FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
920
921#undef DEFINE_ACCEPT
922
923void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100924 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
925 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000926 if (block != nullptr) {
927 VisitBasicBlock(block);
928 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000929 }
930}
931
Roland Levillain633021e2014-10-01 14:12:25 +0100932void HGraphVisitor::VisitReversePostOrder() {
933 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
934 VisitBasicBlock(it.Current());
935 }
936}
937
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000938void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100939 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100940 it.Current()->Accept(this);
941 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100942 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000943 it.Current()->Accept(this);
944 }
945}
946
Mark Mendelle82549b2015-05-06 10:55:34 -0400947HConstant* HTypeConversion::TryStaticEvaluation() const {
948 HGraph* graph = GetBlock()->GetGraph();
949 if (GetInput()->IsIntConstant()) {
950 int32_t value = GetInput()->AsIntConstant()->GetValue();
951 switch (GetResultType()) {
952 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600953 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400954 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600955 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400956 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600957 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400958 default:
959 return nullptr;
960 }
961 } else if (GetInput()->IsLongConstant()) {
962 int64_t value = GetInput()->AsLongConstant()->GetValue();
963 switch (GetResultType()) {
964 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600965 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400966 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600967 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400968 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600969 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400970 default:
971 return nullptr;
972 }
973 } else if (GetInput()->IsFloatConstant()) {
974 float value = GetInput()->AsFloatConstant()->GetValue();
975 switch (GetResultType()) {
976 case Primitive::kPrimInt:
977 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600978 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400979 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600980 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400981 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600982 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
983 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400984 case Primitive::kPrimLong:
985 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600986 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400987 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600988 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400989 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600990 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
991 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400992 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600993 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400994 default:
995 return nullptr;
996 }
997 } else if (GetInput()->IsDoubleConstant()) {
998 double value = GetInput()->AsDoubleConstant()->GetValue();
999 switch (GetResultType()) {
1000 case Primitive::kPrimInt:
1001 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001002 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001003 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001004 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001005 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001006 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1007 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001008 case Primitive::kPrimLong:
1009 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001010 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001011 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001012 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001013 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001014 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1015 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001016 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001017 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001018 default:
1019 return nullptr;
1020 }
1021 }
1022 return nullptr;
1023}
1024
Roland Levillain9240d6a2014-10-20 16:47:04 +01001025HConstant* HUnaryOperation::TryStaticEvaluation() const {
1026 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001027 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001028 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001029 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001030 }
1031 return nullptr;
1032}
1033
1034HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001035 if (GetLeft()->IsIntConstant()) {
1036 if (GetRight()->IsIntConstant()) {
1037 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1038 } else if (GetRight()->IsLongConstant()) {
1039 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1040 }
1041 } else if (GetLeft()->IsLongConstant()) {
1042 if (GetRight()->IsIntConstant()) {
1043 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1044 } else if (GetRight()->IsLongConstant()) {
1045 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001046 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001047 }
1048 return nullptr;
1049}
Dave Allison20dfc792014-06-16 20:44:29 -07001050
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001051HConstant* HBinaryOperation::GetConstantRight() const {
1052 if (GetRight()->IsConstant()) {
1053 return GetRight()->AsConstant();
1054 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1055 return GetLeft()->AsConstant();
1056 } else {
1057 return nullptr;
1058 }
1059}
1060
1061// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001062// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001063HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1064 HInstruction* most_constant_right = GetConstantRight();
1065 if (most_constant_right == nullptr) {
1066 return nullptr;
1067 } else if (most_constant_right == GetLeft()) {
1068 return GetRight();
1069 } else {
1070 return GetLeft();
1071 }
1072}
1073
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001074bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1075 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001076}
1077
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001078bool HInstruction::Equals(HInstruction* other) const {
1079 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001080 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001081 if (!InstructionDataEquals(other)) return false;
1082 if (GetType() != other->GetType()) return false;
1083 if (InputCount() != other->InputCount()) return false;
1084
1085 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1086 if (InputAt(i) != other->InputAt(i)) return false;
1087 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001088 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001089 return true;
1090}
1091
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001092std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1093#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1094 switch (rhs) {
1095 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1096 default:
1097 os << "Unknown instruction kind " << static_cast<int>(rhs);
1098 break;
1099 }
1100#undef DECLARE_CASE
1101 return os;
1102}
1103
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001104void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001105 next_->previous_ = previous_;
1106 if (previous_ != nullptr) {
1107 previous_->next_ = next_;
1108 }
1109 if (block_->instructions_.first_instruction_ == this) {
1110 block_->instructions_.first_instruction_ = next_;
1111 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001112 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001113
1114 previous_ = cursor->previous_;
1115 if (previous_ != nullptr) {
1116 previous_->next_ = this;
1117 }
1118 next_ = cursor;
1119 cursor->previous_ = this;
1120 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001121
1122 if (block_->instructions_.first_instruction_ == cursor) {
1123 block_->instructions_.first_instruction_ = this;
1124 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001125}
1126
David Brazdilfc6a86a2015-06-26 10:33:45 +00001127HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1128 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1129 DCHECK_EQ(cursor->GetBlock(), this);
1130
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001131 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1132 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001133 new_block->instructions_.first_instruction_ = cursor;
1134 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1135 instructions_.last_instruction_ = cursor->previous_;
1136 if (cursor->previous_ == nullptr) {
1137 instructions_.first_instruction_ = nullptr;
1138 } else {
1139 cursor->previous_->next_ = nullptr;
1140 cursor->previous_ = nullptr;
1141 }
1142
1143 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001145
Vladimir Marko60584552015-09-03 13:35:12 +00001146 for (HBasicBlock* successor : GetSuccessors()) {
1147 new_block->successors_.push_back(successor);
1148 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001149 }
Vladimir Marko60584552015-09-03 13:35:12 +00001150 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001151 AddSuccessor(new_block);
1152
David Brazdil56e1acc2015-06-30 15:41:36 +01001153 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001154 return new_block;
1155}
1156
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001157HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1158 DCHECK(!cursor->IsControlFlow());
1159 DCHECK_NE(instructions_.last_instruction_, cursor);
1160 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001161
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001162 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1163 new_block->instructions_.first_instruction_ = cursor->GetNext();
1164 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1165 cursor->next_->previous_ = nullptr;
1166 cursor->next_ = nullptr;
1167 instructions_.last_instruction_ = cursor;
1168
1169 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001170 for (HBasicBlock* successor : GetSuccessors()) {
1171 new_block->successors_.push_back(successor);
1172 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001173 }
Vladimir Marko60584552015-09-03 13:35:12 +00001174 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001175
Vladimir Marko60584552015-09-03 13:35:12 +00001176 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001177 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001178 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001179 }
Vladimir Marko60584552015-09-03 13:35:12 +00001180 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001181 return new_block;
1182}
1183
David Brazdilec16f792015-08-19 15:04:01 +01001184const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001185 if (EndsWithTryBoundary()) {
1186 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1187 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001188 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001189 return try_boundary;
1190 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001191 DCHECK(IsTryBlock());
1192 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001193 return nullptr;
1194 }
David Brazdilec16f792015-08-19 15:04:01 +01001195 } else if (IsTryBlock()) {
1196 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001197 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001198 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001199 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001200}
1201
1202static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1203 return block.GetPhis().IsEmpty()
1204 && !block.GetInstructions().IsEmpty()
1205 && block.GetFirstInstruction() == block.GetLastInstruction();
1206}
1207
David Brazdil46e2a392015-03-16 17:31:52 +00001208bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001209 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1210}
1211
1212bool HBasicBlock::IsSingleTryBoundary() const {
1213 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001214}
1215
David Brazdil8d5b8b22015-03-24 10:51:52 +00001216bool HBasicBlock::EndsWithControlFlowInstruction() const {
1217 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1218}
1219
David Brazdilb2bd1c52015-03-25 11:17:37 +00001220bool HBasicBlock::EndsWithIf() const {
1221 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1222}
1223
David Brazdilffee3d32015-07-06 11:48:53 +01001224bool HBasicBlock::EndsWithTryBoundary() const {
1225 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1226}
1227
David Brazdilb2bd1c52015-03-25 11:17:37 +00001228bool HBasicBlock::HasSinglePhi() const {
1229 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1230}
1231
David Brazdilffee3d32015-07-06 11:48:53 +01001232bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001233 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001234 return false;
1235 }
1236
David Brazdilb618ade2015-07-29 10:31:29 +01001237 // Exception handlers need to be stored in the same order.
1238 for (HExceptionHandlerIterator it1(*this), it2(other);
1239 !it1.Done();
1240 it1.Advance(), it2.Advance()) {
1241 DCHECK(!it2.Done());
1242 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001243 return false;
1244 }
1245 }
1246 return true;
1247}
1248
David Brazdil2d7352b2015-04-20 14:52:42 +01001249size_t HInstructionList::CountSize() const {
1250 size_t size = 0;
1251 HInstruction* current = first_instruction_;
1252 for (; current != nullptr; current = current->GetNext()) {
1253 size++;
1254 }
1255 return size;
1256}
1257
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001258void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1259 for (HInstruction* current = first_instruction_;
1260 current != nullptr;
1261 current = current->GetNext()) {
1262 current->SetBlock(block);
1263 }
1264}
1265
1266void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1267 DCHECK(Contains(cursor));
1268 if (!instruction_list.IsEmpty()) {
1269 if (cursor == last_instruction_) {
1270 last_instruction_ = instruction_list.last_instruction_;
1271 } else {
1272 cursor->next_->previous_ = instruction_list.last_instruction_;
1273 }
1274 instruction_list.last_instruction_->next_ = cursor->next_;
1275 cursor->next_ = instruction_list.first_instruction_;
1276 instruction_list.first_instruction_->previous_ = cursor;
1277 }
1278}
1279
1280void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001281 if (IsEmpty()) {
1282 first_instruction_ = instruction_list.first_instruction_;
1283 last_instruction_ = instruction_list.last_instruction_;
1284 } else {
1285 AddAfter(last_instruction_, instruction_list);
1286 }
1287}
1288
David Brazdil2d7352b2015-04-20 14:52:42 +01001289void HBasicBlock::DisconnectAndDelete() {
1290 // Dominators must be removed after all the blocks they dominate. This way
1291 // a loop header is removed last, a requirement for correct loop information
1292 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001293 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001294
David Brazdil2d7352b2015-04-20 14:52:42 +01001295 // Remove the block from all loops it is included in.
1296 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1297 HLoopInformation* loop_info = it.Current();
1298 loop_info->Remove(this);
1299 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001300 // If this was the last back edge of the loop, we deliberately leave the
1301 // loop in an inconsistent state and will fail SSAChecker unless the
1302 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001303 loop_info->RemoveBackEdge(this);
1304 }
1305 }
1306
1307 // Disconnect the block from its predecessors and update their control-flow
1308 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001309 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001310 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil2d7352b2015-04-20 14:52:42 +01001311 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001312 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1313 if (num_pred_successors == 1u) {
1314 // If we have one successor after removing one, then we must have
1315 // had an HIf or HPackedSwitch, as they have more than one successor.
1316 // Replace those with a HGoto.
1317 DCHECK(last_instruction->IsIf() || last_instruction->IsPackedSwitch());
1318 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001319 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001320 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001321 // The predecessor has no remaining successors and therefore must be dead.
1322 // We deliberately leave it without a control-flow instruction so that the
1323 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001324 predecessor->RemoveInstruction(last_instruction);
1325 } else {
1326 // There are multiple successors left. This must come from a HPackedSwitch
1327 // and we are in the middle of removing the HPackedSwitch. Like above, leave
1328 // this alone, and the SSAChecker will fail if it is not removed as well.
1329 DCHECK(last_instruction->IsPackedSwitch());
David Brazdil2d7352b2015-04-20 14:52:42 +01001330 }
David Brazdil46e2a392015-03-16 17:31:52 +00001331 }
Vladimir Marko60584552015-09-03 13:35:12 +00001332 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001333
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001334 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001335 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001336 // Delete this block from the list of predecessors.
1337 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001338 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001339
1340 // Check that `successor` has other predecessors, otherwise `this` is the
1341 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001342 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001343
David Brazdil2d7352b2015-04-20 14:52:42 +01001344 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001345 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001346 // The successor has just one predecessor left. Replace phis with the only
1347 // remaining input.
1348 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1349 HPhi* phi = phi_it.Current()->AsPhi();
1350 phi->ReplaceWith(phi->InputAt(1 - this_index));
1351 successor->RemovePhi(phi);
1352 }
1353 } else {
1354 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1355 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1356 }
1357 }
1358 }
Vladimir Marko60584552015-09-03 13:35:12 +00001359 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001360
1361 // Disconnect from the dominator.
1362 dominator_->RemoveDominatedBlock(this);
1363 SetDominator(nullptr);
1364
1365 // Delete from the graph. The function safely deletes remaining instructions
1366 // and updates the reverse post order.
1367 graph_->DeleteDeadBlock(this);
1368 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001369}
1370
1371void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001372 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001373 DCHECK(ContainsElement(dominated_blocks_, other));
1374 DCHECK_EQ(GetSingleSuccessor(), other);
1375 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001376 DCHECK(other->GetPhis().IsEmpty());
1377
David Brazdil2d7352b2015-04-20 14:52:42 +01001378 // Move instructions from `other` to `this`.
1379 DCHECK(EndsWithControlFlowInstruction());
1380 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001381 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001382 other->instructions_.SetBlockOfInstructions(this);
1383 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001384
David Brazdil2d7352b2015-04-20 14:52:42 +01001385 // Remove `other` from the loops it is included in.
1386 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1387 HLoopInformation* loop_info = it.Current();
1388 loop_info->Remove(other);
1389 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001390 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001391 }
1392 }
1393
1394 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001395 successors_.clear();
1396 while (!other->successors_.empty()) {
1397 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001398 successor->ReplacePredecessor(other, this);
1399 }
1400
David Brazdil2d7352b2015-04-20 14:52:42 +01001401 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001402 RemoveDominatedBlock(other);
1403 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1404 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001405 dominated->SetDominator(this);
1406 }
Vladimir Marko60584552015-09-03 13:35:12 +00001407 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001408 other->dominator_ = nullptr;
1409
1410 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001411 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001412
1413 // Delete `other` from the graph. The function updates reverse post order.
1414 graph_->DeleteDeadBlock(other);
1415 other->SetGraph(nullptr);
1416}
1417
1418void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1419 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001420 DCHECK(GetDominatedBlocks().empty());
1421 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001422 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001423 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001424 DCHECK(other->GetPhis().IsEmpty());
1425 DCHECK(!other->IsInLoop());
1426
1427 // Move instructions from `other` to `this`.
1428 instructions_.Add(other->GetInstructions());
1429 other->instructions_.SetBlockOfInstructions(this);
1430
1431 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001432 successors_.clear();
1433 while (!other->successors_.empty()) {
1434 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001435 successor->ReplacePredecessor(other, this);
1436 }
1437
1438 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001439 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1440 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001441 dominated->SetDominator(this);
1442 }
Vladimir Marko60584552015-09-03 13:35:12 +00001443 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001444 other->dominator_ = nullptr;
1445 other->graph_ = nullptr;
1446}
1447
1448void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001449 while (!GetPredecessors().empty()) {
1450 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001451 predecessor->ReplaceSuccessor(this, other);
1452 }
Vladimir Marko60584552015-09-03 13:35:12 +00001453 while (!GetSuccessors().empty()) {
1454 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001455 successor->ReplacePredecessor(this, other);
1456 }
Vladimir Marko60584552015-09-03 13:35:12 +00001457 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1458 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001459 }
1460 GetDominator()->ReplaceDominatedBlock(this, other);
1461 other->SetDominator(GetDominator());
1462 dominator_ = nullptr;
1463 graph_ = nullptr;
1464}
1465
1466// Create space in `blocks` for adding `number_of_new_blocks` entries
1467// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001468static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001469 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001470 size_t after) {
1471 DCHECK_LT(after, blocks->size());
1472 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001473 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001474 blocks->resize(new_size);
1475 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001476}
1477
David Brazdil2d7352b2015-04-20 14:52:42 +01001478void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1479 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001480 DCHECK(block->GetSuccessors().empty());
1481 DCHECK(block->GetPredecessors().empty());
1482 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001483 DCHECK(block->GetDominator() == nullptr);
1484
1485 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1486 block->RemoveInstruction(it.Current());
1487 }
1488 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1489 block->RemovePhi(it.Current()->AsPhi());
1490 }
1491
David Brazdilc7af85d2015-05-26 12:05:55 +01001492 if (block->IsExitBlock()) {
1493 exit_block_ = nullptr;
1494 }
1495
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001496 RemoveElement(reverse_post_order_, block);
1497 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001498}
1499
Calin Juravle2e768302015-07-28 14:41:11 +00001500HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001501 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001502 // Update the environments in this graph to have the invoke's environment
1503 // as parent.
1504 {
1505 HReversePostOrderIterator it(*this);
1506 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1507 for (; !it.Done(); it.Advance()) {
1508 HBasicBlock* block = it.Current();
1509 for (HInstructionIterator instr_it(block->GetInstructions());
1510 !instr_it.Done();
1511 instr_it.Advance()) {
1512 HInstruction* current = instr_it.Current();
1513 if (current->NeedsEnvironment()) {
1514 current->GetEnvironment()->SetAndCopyParentChain(
1515 outer_graph->GetArena(), invoke->GetEnvironment());
1516 }
1517 }
1518 }
1519 }
1520 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1521 if (HasBoundsChecks()) {
1522 outer_graph->SetHasBoundsChecks(true);
1523 }
1524
Calin Juravle2e768302015-07-28 14:41:11 +00001525 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001526 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001527 // Simple case of an entry block, a body block, and an exit block.
1528 // Put the body block's instruction into `invoke`'s block.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001529 HBasicBlock* body = GetBlock(1);
1530 DCHECK(GetBlock(0)->IsEntryBlock());
1531 DCHECK(GetBlock(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001532 DCHECK(!body->IsExitBlock());
1533 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001534
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001535 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1536 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001537
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001538 // Replace the invoke with the return value of the inlined graph.
1539 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001540 return_value = last->InputAt(0);
1541 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001542 } else {
1543 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001544 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001545
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001546 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001547 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001548 // Need to inline multiple blocks. We split `invoke`'s block
1549 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001550 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001551 // with the second half.
1552 ArenaAllocator* allocator = outer_graph->GetArena();
1553 HBasicBlock* at = invoke->GetBlock();
1554 HBasicBlock* to = at->SplitAfter(invoke);
1555
Vladimir Marko60584552015-09-03 13:35:12 +00001556 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001557 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001558 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001559 exit_block_->ReplaceWith(to);
1560
1561 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001562 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001563 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1564 if (to->GetPredecessors().size() == 1) {
1565 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001566 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001567 if (!returns_void) {
1568 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001569 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001570 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001571 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001572 } else {
1573 if (!returns_void) {
1574 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001575 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001576 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001577 to->AddPhi(return_value->AsPhi());
1578 }
Vladimir Marko60584552015-09-03 13:35:12 +00001579 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001580 HInstruction* last = predecessor->GetLastInstruction();
1581 if (!returns_void) {
1582 return_value->AsPhi()->AddInput(last->InputAt(0));
1583 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001584 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001585 predecessor->RemoveInstruction(last);
1586 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001587 }
1588
1589 if (return_value != nullptr) {
1590 invoke->ReplaceWith(return_value);
1591 }
1592
1593 // Update the meta information surrounding blocks:
1594 // (1) the graph they are now in,
1595 // (2) the reverse post order of that graph,
1596 // (3) the potential loop information they are now in.
1597
1598 // We don't add the entry block, the exit block, and the first block, which
1599 // has been merged with `at`.
1600 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1601
1602 // We add the `to` block.
1603 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001604 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001605 + kNumberOfNewBlocksInCaller;
1606
1607 // Find the location of `at` in the outer graph's reverse post order. The new
1608 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001609 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001610 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1611
1612 // Do a reverse post order of the blocks in the callee and do (1), (2),
1613 // and (3) to the blocks that apply.
1614 HLoopInformation* info = at->GetLoopInformation();
1615 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1616 HBasicBlock* current = it.Current();
1617 if (current != exit_block_ && current != entry_block_ && current != first) {
1618 DCHECK(!current->IsInLoop());
1619 DCHECK(current->GetGraph() == this);
1620 current->SetGraph(outer_graph);
1621 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001622 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001623 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001624 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001625 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1626 loop_it.Current()->Add(current);
1627 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001628 }
1629 }
1630 }
1631
1632 // Do (1), (2), and (3) to `to`.
1633 to->SetGraph(outer_graph);
1634 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001635 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001636 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001637 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001638 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1639 loop_it.Current()->Add(to);
1640 }
David Brazdil46e2a392015-03-16 17:31:52 +00001641 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001642 // Only `to` can become a back edge, as the inlined blocks
1643 // are predecessors of `to`.
1644 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001645 }
1646 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001647 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001648
David Brazdil05144f42015-04-16 15:18:00 +01001649 // Update the next instruction id of the outer graph, so that instructions
1650 // added later get bigger ids than those in the inner graph.
1651 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1652
1653 // Walk over the entry block and:
1654 // - Move constants from the entry block to the outer_graph's entry block,
1655 // - Replace HParameterValue instructions with their real value.
1656 // - Remove suspend checks, that hold an environment.
1657 // We must do this after the other blocks have been inlined, otherwise ids of
1658 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001659 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001660 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1661 HInstruction* current = it.Current();
1662 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001663 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001664 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001665 current->ReplaceWith(outer_graph->GetIntConstant(
1666 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001667 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001668 current->ReplaceWith(outer_graph->GetLongConstant(
1669 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001670 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001671 current->ReplaceWith(outer_graph->GetFloatConstant(
1672 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001673 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001674 current->ReplaceWith(outer_graph->GetDoubleConstant(
1675 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001676 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001677 if (kIsDebugBuild
1678 && invoke->IsInvokeStaticOrDirect()
1679 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1680 // Ensure we do not use the last input of `invoke`, as it
1681 // contains a clinit check which is not an actual argument.
1682 size_t last_input_index = invoke->InputCount() - 1;
1683 DCHECK(parameter_index != last_input_index);
1684 }
David Brazdil05144f42015-04-16 15:18:00 +01001685 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001686 } else if (current->IsCurrentMethod()) {
1687 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001688 } else {
1689 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1690 entry_block_->RemoveInstruction(current);
1691 }
1692 }
1693
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001694 // Finally remove the invoke from the caller.
1695 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001696
1697 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001698}
1699
Mingyao Yang3584bce2015-05-19 16:01:59 -07001700/*
1701 * Loop will be transformed to:
1702 * old_pre_header
1703 * |
1704 * if_block
1705 * / \
1706 * dummy_block deopt_block
1707 * \ /
1708 * new_pre_header
1709 * |
1710 * header
1711 */
1712void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1713 DCHECK(header->IsLoopHeader());
1714 HBasicBlock* pre_header = header->GetDominator();
1715
1716 // Need this to avoid critical edge.
1717 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1718 // Need this to avoid critical edge.
1719 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1720 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1721 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1722 AddBlock(if_block);
1723 AddBlock(dummy_block);
1724 AddBlock(deopt_block);
1725 AddBlock(new_pre_header);
1726
1727 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001728 pre_header->successors_.clear();
1729 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001730
1731 pre_header->AddSuccessor(if_block);
1732 if_block->AddSuccessor(dummy_block); // True successor
1733 if_block->AddSuccessor(deopt_block); // False successor
1734 dummy_block->AddSuccessor(new_pre_header);
1735 deopt_block->AddSuccessor(new_pre_header);
1736
Vladimir Marko60584552015-09-03 13:35:12 +00001737 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001738 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001739 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001740 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001741 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001742 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001743 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001744 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001745 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001746 header->SetDominator(new_pre_header);
1747
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001748 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001749 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001750 reverse_post_order_[index_of_header++] = if_block;
1751 reverse_post_order_[index_of_header++] = dummy_block;
1752 reverse_post_order_[index_of_header++] = deopt_block;
1753 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001754
1755 HLoopInformation* info = pre_header->GetLoopInformation();
1756 if (info != nullptr) {
1757 if_block->SetLoopInformation(info);
1758 dummy_block->SetLoopInformation(info);
1759 deopt_block->SetLoopInformation(info);
1760 new_pre_header->SetLoopInformation(info);
1761 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1762 !loop_it.Done();
1763 loop_it.Advance()) {
1764 loop_it.Current()->Add(if_block);
1765 loop_it.Current()->Add(dummy_block);
1766 loop_it.Current()->Add(deopt_block);
1767 loop_it.Current()->Add(new_pre_header);
1768 }
1769 }
1770}
1771
Calin Juravle2e768302015-07-28 14:41:11 +00001772void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1773 if (kIsDebugBuild) {
1774 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1775 ScopedObjectAccess soa(Thread::Current());
1776 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1777 if (IsBoundType()) {
1778 // Having the test here spares us from making the method virtual just for
1779 // the sake of a DCHECK.
1780 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1781 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1782 << " upper_bound_rti: " << upper_bound_rti
1783 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001784 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001785 }
1786 }
1787 reference_type_info_ = rti;
1788}
1789
1790ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1791
1792ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1793 : type_handle_(type_handle), is_exact_(is_exact) {
1794 if (kIsDebugBuild) {
1795 ScopedObjectAccess soa(Thread::Current());
1796 DCHECK(IsValidHandle(type_handle));
1797 }
1798}
1799
Calin Juravleacf735c2015-02-12 15:25:22 +00001800std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1801 ScopedObjectAccess soa(Thread::Current());
1802 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001803 << " is_valid=" << rhs.IsValid()
1804 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001805 << " is_exact=" << rhs.IsExact()
1806 << " ]";
1807 return os;
1808}
1809
Mark Mendellc4701932015-04-10 13:18:51 -04001810bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1811 // For now, assume that instructions in different blocks may use the
1812 // environment.
1813 // TODO: Use the control flow to decide if this is true.
1814 if (GetBlock() != other->GetBlock()) {
1815 return true;
1816 }
1817
1818 // We know that we are in the same block. Walk from 'this' to 'other',
1819 // checking to see if there is any instruction with an environment.
1820 HInstruction* current = this;
1821 for (; current != other && current != nullptr; current = current->GetNext()) {
1822 // This is a conservative check, as the instruction result may not be in
1823 // the referenced environment.
1824 if (current->HasEnvironment()) {
1825 return true;
1826 }
1827 }
1828
1829 // We should have been called with 'this' before 'other' in the block.
1830 // Just confirm this.
1831 DCHECK(current != nullptr);
1832 return false;
1833}
1834
1835void HInstruction::RemoveEnvironmentUsers() {
1836 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1837 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1838 HEnvironment* user = user_node->GetUser();
1839 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1840 }
1841 env_uses_.Clear();
1842}
1843
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001844} // namespace art