blob: c057eca434ad03e8b0f2956fb97c16e4ecec153b [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 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Mark Mendelle82549b2015-05-06 10:55:34 -040018#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000019#include "common_dominator.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"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010023#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010025#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000026#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027
28namespace art {
29
30void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010031 block->SetBlockId(blocks_.size());
32 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033}
34
Nicolas Geoffray804d0932014-05-02 08:46:00 +010035void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010036 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
37 DCHECK_EQ(visited->GetHighestBitSet(), -1);
38
39 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010040 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010041 // Number of successors visited from a given node, indexed by block id.
42 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
43 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
44 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
45 constexpr size_t kDefaultWorklistSize = 8;
46 worklist.reserve(kDefaultWorklistSize);
47 visited->SetBit(entry_block_->GetBlockId());
48 visiting.SetBit(entry_block_->GetBlockId());
49 worklist.push_back(entry_block_);
50
51 while (!worklist.empty()) {
52 HBasicBlock* current = worklist.back();
53 uint32_t current_id = current->GetBlockId();
54 if (successors_visited[current_id] == current->GetSuccessors().size()) {
55 visiting.ClearBit(current_id);
56 worklist.pop_back();
57 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
59 uint32_t successor_id = successor->GetBlockId();
60 if (visiting.IsBitSet(successor_id)) {
61 DCHECK(ContainsElement(worklist, successor));
62 successor->AddBackEdge(current);
63 } else if (!visited->IsBitSet(successor_id)) {
64 visited->SetBit(successor_id);
65 visiting.SetBit(successor_id);
66 worklist.push_back(successor);
67 }
68 }
69 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000070}
71
Roland Levillainfc600dc2014-12-02 17:16:31 +000072static void RemoveAsUser(HInstruction* instruction) {
73 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000074 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000075 }
76
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010077 for (HEnvironment* environment = instruction->GetEnvironment();
78 environment != nullptr;
79 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000080 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000081 if (environment->GetInstructionAt(i) != nullptr) {
82 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000083 }
84 }
85 }
86}
87
88void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010089 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000090 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010091 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +000092 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010093 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
95 RemoveAsUser(it.Current());
96 }
97 }
98 }
99}
100
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100101void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100102 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100104 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000105 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100106 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000107 for (HBasicBlock* successor : block->GetSuccessors()) {
108 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000109 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110 // Remove the block from the list of blocks, so that further analyses
111 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100112 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 }
114 }
115}
116
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000117GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100118 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
119 // edges. This invariant simplifies building SSA form because Phis cannot
120 // collect both normal- and exceptional-flow values at the same time.
121 SimplifyCatchBlocks();
122
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000126 FindBackEdges(&visited);
127
David Brazdilffee3d32015-07-06 11:48:53 +0100128 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000129 // the initial DFS as users from other instructions, so that
130 // users can be safely removed before uses later.
131 RemoveInstructionsAsUsersFromDeadBlocks(visited);
132
David Brazdilffee3d32015-07-06 11:48:53 +0100133 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000134 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000135 // predecessors list of live blocks.
136 RemoveDeadBlocks(visited);
137
David Brazdilffee3d32015-07-06 11:48:53 +0100138 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100139 // dominators and the reverse post order.
140 SimplifyCFG();
141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100143 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144
145 // (7) Analyze loops discover through back edge analysis, and
146 // set the loop information on each block.
147 GraphAnalysisResult result = AnalyzeLoops();
148 if (result != kAnalysisSuccess) {
149 return result;
150 }
151
152 // (8) Precompute per-block try membership before entering the SSA builder,
153 // which needs the information to build catch block phis from values of
154 // locals at throwing instructions inside try blocks.
155 ComputeTryBlockInformation();
156
157 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100158}
159
160void HGraph::ClearDominanceInformation() {
161 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
162 it.Current()->ClearDominanceInformation();
163 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165}
166
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167void HGraph::ClearLoopInformation() {
168 SetHasIrreducibleLoops(false);
169 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000170 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000171 }
172}
173
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100174void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000175 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100176 dominator_ = nullptr;
177}
178
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000179HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
180 HInstruction* instruction = GetFirstInstruction();
181 while (instruction->IsParallelMove()) {
182 instruction = instruction->GetNext();
183 }
184 return instruction;
185}
186
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 DCHECK(reverse_post_order_.empty());
189 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100190 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100191
192 // Number of visits of a given node, indexed by block id.
193 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
194 // Number of successors visited from a given node, indexed by block id.
195 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
196 // Nodes for which we need to visit successors.
197 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
198 constexpr size_t kDefaultWorklistSize = 8;
199 worklist.reserve(kDefaultWorklistSize);
200 worklist.push_back(entry_block_);
201
202 while (!worklist.empty()) {
203 HBasicBlock* current = worklist.back();
204 uint32_t current_id = current->GetBlockId();
205 if (successors_visited[current_id] == current->GetSuccessors().size()) {
206 worklist.pop_back();
207 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100208 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
209
210 if (successor->GetDominator() == nullptr) {
211 successor->SetDominator(current);
212 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000213 // The CommonDominator can work for multiple blocks as long as the
214 // domination information doesn't change. However, since we're changing
215 // that information here, we can use the finder only for pairs of blocks.
216 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100217 }
218
219 // Once all the forward edges have been visited, we know the immediate
220 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100221 if (++visits[successor->GetBlockId()] ==
222 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100223 reverse_post_order_.push_back(successor);
224 worklist.push_back(successor);
225 }
226 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000227 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228
229 // Populate `dominated_blocks_` information after computing all dominators.
230 // The potential presence of irreducible loops require to do it after.
231 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
232 HBasicBlock* block = it.Current();
233 if (!block->IsEntryBlock()) {
234 block->GetDominator()->AddDominatedBlock(block);
235 }
236 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000237}
238
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000239GraphAnalysisResult HGraph::TryBuildingSsa(StackHandleScopeCollection* handles) {
240 GraphAnalysisResult result = BuildDominatorTree();
241 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000242 return result;
243 }
244
David Brazdil4833f5a2015-12-16 10:37:39 +0000245 // Create the inexact Object reference type and store it in the HGraph.
246 ScopedObjectAccess soa(Thread::Current());
247 ClassLinker* linker = Runtime::Current()->GetClassLinker();
248 inexact_object_rti_ = ReferenceTypeInfo::Create(
249 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
250 /* is_exact */ false);
251
252 // Tranforms graph to SSA form.
253 result = SsaBuilder(this, handles).BuildSsa();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000254 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000255 return result;
256 }
257
258 in_ssa_form_ = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000259 return kAnalysisSuccess;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100260}
261
David Brazdilfc6a86a2015-06-26 10:33:45 +0000262HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000263 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
264 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000265 // Use `InsertBetween` to ensure the predecessor index and successor index of
266 // `block` and `successor` are preserved.
267 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000268 return new_block;
269}
270
271void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
272 // Insert a new node between `block` and `successor` to split the
273 // critical edge.
274 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600275 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100276 if (successor->IsLoopHeader()) {
277 // If we split at a back edge boundary, make the new block the back edge.
278 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000279 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280 info->RemoveBackEdge(block);
281 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100282 }
283 }
284}
285
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100286void HGraph::SimplifyLoop(HBasicBlock* header) {
287 HLoopInformation* info = header->GetLoopInformation();
288
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100289 // Make sure the loop has only one pre header. This simplifies SSA building by having
290 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000291 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
292 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000293 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000294 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100295 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100296 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600297 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298
Vladimir Marko60584552015-09-03 13:35:12 +0000299 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100300 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100301 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100302 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100304 }
305 }
306 pre_header->AddSuccessor(header);
307 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100308
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100309 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100310 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
311 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000312 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100313 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100314 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000315 header->predecessors_[pred] = to_swap;
316 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100317 break;
318 }
319 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100320 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100321
322 // Place the suspend check at the beginning of the header, so that live registers
323 // will be known when allocating registers. Note that code generation can still
324 // generate the suspend check at the back edge, but needs to be careful with
325 // loop phi spill slots (which are not written to at back edge).
326 HInstruction* first_instruction = header->GetFirstInstruction();
327 if (!first_instruction->IsSuspendCheck()) {
328 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
329 header->InsertInstructionBefore(check, first_instruction);
330 first_instruction = check;
331 }
332 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100333}
334
David Brazdilffee3d32015-07-06 11:48:53 +0100335static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100336 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100337 if (!predecessor->EndsWithTryBoundary()) {
338 // Only edges from HTryBoundary can be exceptional.
339 return false;
340 }
341 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
342 if (try_boundary->GetNormalFlowSuccessor() == &block) {
343 // This block is the normal-flow successor of `try_boundary`, but it could
344 // also be one of its exception handlers if catch blocks have not been
345 // simplified yet. Predecessors are unordered, so we will consider the first
346 // occurrence to be the normal edge and a possible second occurrence to be
347 // the exceptional edge.
348 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
349 } else {
350 // This is not the normal-flow successor of `try_boundary`, hence it must be
351 // one of its exception handlers.
352 DCHECK(try_boundary->HasExceptionHandler(block));
353 return true;
354 }
355}
356
357void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100358 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
359 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
360 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
361 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000362 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100363 continue;
364 }
365
366 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000367 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100368 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
369 exceptional_predecessors_only = false;
370 break;
371 }
372 }
373
374 if (!exceptional_predecessors_only) {
375 // Catch block has normal-flow predecessors and needs to be simplified.
376 // Splitting the block before its first instruction moves all its
377 // instructions into `normal_block` and links the two blocks with a Goto.
378 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
379 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000380 //
David Brazdilffee3d32015-07-06 11:48:53 +0100381 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000382 // a move-exception instruction, as guaranteed by the verifier. However,
383 // trivially dead predecessors are ignored by the verifier and such code
384 // has not been removed at this stage. We therefore ignore the assumption
385 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
386 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
387 if (normal_block == nullptr) {
388 // Catch block is either empty or only contains a move-exception. It must
389 // therefore be dead and will be removed during initial DCE. Do nothing.
390 DCHECK(!catch_block->EndsWithControlFlowInstruction());
391 } else {
392 // Catch block was split. Re-link normal-flow edges to the new block.
393 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
394 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
395 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
396 --j;
397 }
David Brazdilffee3d32015-07-06 11:48:53 +0100398 }
399 }
400 }
401 }
402}
403
404void HGraph::ComputeTryBlockInformation() {
405 // Iterate in reverse post order to propagate try membership information from
406 // predecessors to their successors.
407 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
408 HBasicBlock* block = it.Current();
409 if (block->IsEntryBlock() || block->IsCatchBlock()) {
410 // Catch blocks after simplification have only exceptional predecessors
411 // and hence are never in tries.
412 continue;
413 }
414
415 // Infer try membership from the first predecessor. Having simplified loops,
416 // the first predecessor can never be a back edge and therefore it must have
417 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100418 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100419 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100420 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000421 if (try_entry != nullptr &&
422 (block->GetTryCatchInformation() == nullptr ||
423 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
424 // We are either setting try block membership for the first time or it
425 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100426 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
427 }
David Brazdilffee3d32015-07-06 11:48:53 +0100428 }
429}
430
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100431void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000432// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100433 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000434 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100435 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
436 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
437 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
438 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100439 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000440 if (block->GetSuccessors().size() > 1) {
441 // Only split normal-flow edges. We cannot split exceptional edges as they
442 // are synthesized (approximate real control flow), and we do not need to
443 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000444 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
445 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
446 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100447 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000448 if (successor == exit_block_) {
449 // Throw->TryBoundary->Exit. Special case which we do not want to split
450 // because Goto->Exit is not allowed.
451 DCHECK(block->IsSingleTryBoundary());
452 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
453 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000455 // SplitCriticalEdge could have invalidated the `normal_successors`
456 // ArrayRef. We must re-acquire it.
457 normal_successors = block->GetNormalSuccessors();
458 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
459 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100460 }
461 }
462 }
463 if (block->IsLoopHeader()) {
464 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000465 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
466 // We are being called by the dead code elimiation pass, and what used to be
467 // a loop got dismantled. Just remove the suspend check.
468 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100469 }
470 }
471}
472
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000473GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100474 // Order does not matter.
475 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
476 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100477 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100478 if (block->IsCatchBlock()) {
479 // TODO: Dealing with exceptional back edges could be tricky because
480 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000481 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100482 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000483 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100484 }
485 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000486 return kAnalysisSuccess;
487}
488
489void HLoopInformation::Dump(std::ostream& os) {
490 os << "header: " << header_->GetBlockId() << std::endl;
491 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
492 for (HBasicBlock* block : back_edges_) {
493 os << "back edge: " << block->GetBlockId() << std::endl;
494 }
495 for (HBasicBlock* block : header_->GetPredecessors()) {
496 os << "predecessor: " << block->GetBlockId() << std::endl;
497 }
498 for (uint32_t idx : blocks_.Indexes()) {
499 os << " in loop: " << idx << std::endl;
500 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100501}
502
David Brazdil8d5b8b22015-03-24 10:51:52 +0000503void HGraph::InsertConstant(HConstant* constant) {
504 // New constants are inserted before the final control-flow instruction
505 // of the graph, or at its end if called from the graph builder.
506 if (entry_block_->EndsWithControlFlowInstruction()) {
507 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000508 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000509 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000510 }
511}
512
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600513HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100514 // For simplicity, don't bother reviving the cached null constant if it is
515 // not null and not in a block. Otherwise, we need to clear the instruction
516 // id and/or any invariants the graph is assuming when adding new instructions.
517 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600518 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000519 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000520 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000521 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000522 if (kIsDebugBuild) {
523 ScopedObjectAccess soa(Thread::Current());
524 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
525 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000526 return cached_null_constant_;
527}
528
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100529HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100530 // For simplicity, don't bother reviving the cached current method if it is
531 // not null and not in a block. Otherwise, we need to clear the instruction
532 // id and/or any invariants the graph is assuming when adding new instructions.
533 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700534 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600535 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
536 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100537 if (entry_block_->GetFirstInstruction() == nullptr) {
538 entry_block_->AddInstruction(cached_current_method_);
539 } else {
540 entry_block_->InsertInstructionBefore(
541 cached_current_method_, entry_block_->GetFirstInstruction());
542 }
543 }
544 return cached_current_method_;
545}
546
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548 switch (type) {
549 case Primitive::Type::kPrimBoolean:
550 DCHECK(IsUint<1>(value));
551 FALLTHROUGH_INTENDED;
552 case Primitive::Type::kPrimByte:
553 case Primitive::Type::kPrimChar:
554 case Primitive::Type::kPrimShort:
555 case Primitive::Type::kPrimInt:
556 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600557 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000558
559 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600560 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000561
562 default:
563 LOG(FATAL) << "Unsupported constant type";
564 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000565 }
David Brazdil46e2a392015-03-16 17:31:52 +0000566}
567
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000568void HGraph::CacheFloatConstant(HFloatConstant* constant) {
569 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
570 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
571 cached_float_constants_.Overwrite(value, constant);
572}
573
574void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
575 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
576 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
577 cached_double_constants_.Overwrite(value, constant);
578}
579
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000580void HLoopInformation::Add(HBasicBlock* block) {
581 blocks_.SetBit(block->GetBlockId());
582}
583
David Brazdil46e2a392015-03-16 17:31:52 +0000584void HLoopInformation::Remove(HBasicBlock* block) {
585 blocks_.ClearBit(block->GetBlockId());
586}
587
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100588void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
589 if (blocks_.IsBitSet(block->GetBlockId())) {
590 return;
591 }
592
593 blocks_.SetBit(block->GetBlockId());
594 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000595 for (HBasicBlock* predecessor : block->GetPredecessors()) {
596 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100597 }
598}
599
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000600void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
601 if (blocks_.IsBitSet(block->GetBlockId())) {
602 return;
603 }
604
605 if (block->IsLoopHeader()) {
606 // If we hit a loop header in an irreducible loop, we first check if the
607 // pre header of that loop belongs to the currently analyzed loop. If it does,
608 // then we visit the back edges.
609 // Note that we cannot use GetPreHeader, as the loop may have not been populated
610 // yet.
611 HBasicBlock* pre_header = block->GetPredecessors()[0];
612 PopulateIrreducibleRecursive(pre_header);
613 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
614 blocks_.SetBit(block->GetBlockId());
615 block->SetInLoop(this);
616 HLoopInformation* info = block->GetLoopInformation();
617 for (HBasicBlock* back_edge : info->GetBackEdges()) {
618 PopulateIrreducibleRecursive(back_edge);
619 }
620 }
621 } else {
622 // Visit all predecessors. If one predecessor is part of the loop, this
623 // block is also part of this loop.
624 for (HBasicBlock* predecessor : block->GetPredecessors()) {
625 PopulateIrreducibleRecursive(predecessor);
626 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
627 blocks_.SetBit(block->GetBlockId());
628 block->SetInLoop(this);
629 }
630 }
631 }
632}
633
634void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100635 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000636 // Populate this loop: starting with the back edge, recursively add predecessors
637 // that are not already part of that loop. Set the header as part of the loop
638 // to end the recursion.
639 // This is a recursive implementation of the algorithm described in
640 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
641 blocks_.SetBit(header_->GetBlockId());
642 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100643 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100644 DCHECK(back_edge->GetDominator() != nullptr);
645 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 irreducible_ = true;
647 header_->GetGraph()->SetHasIrreducibleLoops(true);
648 PopulateIrreducibleRecursive(back_edge);
649 } else {
650 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100651 }
David Brazdila4b8c212015-05-07 09:59:30 +0100652 }
653}
654
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100655HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000656 HBasicBlock* block = header_->GetPredecessors()[0];
657 DCHECK(irreducible_ || (block == header_->GetDominator()));
658 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100659}
660
661bool HLoopInformation::Contains(const HBasicBlock& block) const {
662 return blocks_.IsBitSet(block.GetBlockId());
663}
664
665bool HLoopInformation::IsIn(const HLoopInformation& other) const {
666 return other.blocks_.IsBitSet(header_->GetBlockId());
667}
668
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800669bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
670 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700671}
672
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100673size_t HLoopInformation::GetLifetimeEnd() const {
674 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100675 for (HBasicBlock* back_edge : GetBackEdges()) {
676 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100677 }
678 return last_position;
679}
680
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100681bool HBasicBlock::Dominates(HBasicBlock* other) const {
682 // Walk up the dominator tree from `other`, to find out if `this`
683 // is an ancestor.
684 HBasicBlock* current = other;
685 while (current != nullptr) {
686 if (current == this) {
687 return true;
688 }
689 current = current->GetDominator();
690 }
691 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100692}
693
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100694static void UpdateInputsUsers(HInstruction* instruction) {
695 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
696 instruction->InputAt(i)->AddUseAt(instruction, i);
697 }
698 // Environment should be created later.
699 DCHECK(!instruction->HasEnvironment());
700}
701
Roland Levillainccc07a92014-09-16 14:48:16 +0100702void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
703 HInstruction* replacement) {
704 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400705 if (initial->IsControlFlow()) {
706 // We can only replace a control flow instruction with another control flow instruction.
707 DCHECK(replacement->IsControlFlow());
708 DCHECK_EQ(replacement->GetId(), -1);
709 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
710 DCHECK_EQ(initial->GetBlock(), this);
711 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
712 DCHECK(initial->GetUses().IsEmpty());
713 DCHECK(initial->GetEnvUses().IsEmpty());
714 replacement->SetBlock(this);
715 replacement->SetId(GetGraph()->GetNextInstructionId());
716 instructions_.InsertInstructionBefore(replacement, initial);
717 UpdateInputsUsers(replacement);
718 } else {
719 InsertInstructionBefore(replacement, initial);
720 initial->ReplaceWith(replacement);
721 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100722 RemoveInstruction(initial);
723}
724
David Brazdil74eb1b22015-12-14 11:44:01 +0000725void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
726 DCHECK(!cursor->IsPhi());
727 DCHECK(!insn->IsPhi());
728 DCHECK(!insn->IsControlFlow());
729 DCHECK(insn->CanBeMoved());
730 DCHECK(!insn->HasSideEffects());
731
732 HBasicBlock* from_block = insn->GetBlock();
733 HBasicBlock* to_block = cursor->GetBlock();
734 DCHECK(from_block != to_block);
735
736 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
737 insn->SetBlock(to_block);
738 to_block->instructions_.InsertInstructionBefore(insn, cursor);
739}
740
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100741static void Add(HInstructionList* instruction_list,
742 HBasicBlock* block,
743 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000744 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000745 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746 instruction->SetBlock(block);
747 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100748 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100749 instruction_list->AddInstruction(instruction);
750}
751
752void HBasicBlock::AddInstruction(HInstruction* instruction) {
753 Add(&instructions_, this, instruction);
754}
755
756void HBasicBlock::AddPhi(HPhi* phi) {
757 Add(&phis_, this, phi);
758}
759
David Brazdilc3d743f2015-04-22 13:40:50 +0100760void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
761 DCHECK(!cursor->IsPhi());
762 DCHECK(!instruction->IsPhi());
763 DCHECK_EQ(instruction->GetId(), -1);
764 DCHECK_NE(cursor->GetId(), -1);
765 DCHECK_EQ(cursor->GetBlock(), this);
766 DCHECK(!instruction->IsControlFlow());
767 instruction->SetBlock(this);
768 instruction->SetId(GetGraph()->GetNextInstructionId());
769 UpdateInputsUsers(instruction);
770 instructions_.InsertInstructionBefore(instruction, cursor);
771}
772
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100773void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
774 DCHECK(!cursor->IsPhi());
775 DCHECK(!instruction->IsPhi());
776 DCHECK_EQ(instruction->GetId(), -1);
777 DCHECK_NE(cursor->GetId(), -1);
778 DCHECK_EQ(cursor->GetBlock(), this);
779 DCHECK(!instruction->IsControlFlow());
780 DCHECK(!cursor->IsControlFlow());
781 instruction->SetBlock(this);
782 instruction->SetId(GetGraph()->GetNextInstructionId());
783 UpdateInputsUsers(instruction);
784 instructions_.InsertInstructionAfter(instruction, cursor);
785}
786
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100787void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
788 DCHECK_EQ(phi->GetId(), -1);
789 DCHECK_NE(cursor->GetId(), -1);
790 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100791 phi->SetBlock(this);
792 phi->SetId(GetGraph()->GetNextInstructionId());
793 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100794 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100795}
796
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100797static void Remove(HInstructionList* instruction_list,
798 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000799 HInstruction* instruction,
800 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100801 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802 instruction->SetBlock(nullptr);
803 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000804 if (ensure_safety) {
805 DCHECK(instruction->GetUses().IsEmpty());
806 DCHECK(instruction->GetEnvUses().IsEmpty());
807 RemoveAsUser(instruction);
808 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100809}
810
David Brazdil1abb4192015-02-17 18:33:36 +0000811void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100812 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000813 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100814}
815
David Brazdil1abb4192015-02-17 18:33:36 +0000816void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
817 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100818}
819
David Brazdilc7508e92015-04-27 13:28:57 +0100820void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
821 if (instruction->IsPhi()) {
822 RemovePhi(instruction->AsPhi(), ensure_safety);
823 } else {
824 RemoveInstruction(instruction, ensure_safety);
825 }
826}
827
Vladimir Marko71bf8092015-09-15 15:33:14 +0100828void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
829 for (size_t i = 0; i < locals.size(); i++) {
830 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100831 SetRawEnvAt(i, instruction);
832 if (instruction != nullptr) {
833 instruction->AddEnvUseAt(this, i);
834 }
835 }
836}
837
David Brazdiled596192015-01-23 10:39:45 +0000838void HEnvironment::CopyFrom(HEnvironment* env) {
839 for (size_t i = 0; i < env->Size(); i++) {
840 HInstruction* instruction = env->GetInstructionAt(i);
841 SetRawEnvAt(i, instruction);
842 if (instruction != nullptr) {
843 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100844 }
David Brazdiled596192015-01-23 10:39:45 +0000845 }
846}
847
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700848void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
849 HBasicBlock* loop_header) {
850 DCHECK(loop_header->IsLoopHeader());
851 for (size_t i = 0; i < env->Size(); i++) {
852 HInstruction* instruction = env->GetInstructionAt(i);
853 SetRawEnvAt(i, instruction);
854 if (instruction == nullptr) {
855 continue;
856 }
857 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
858 // At the end of the loop pre-header, the corresponding value for instruction
859 // is the first input of the phi.
860 HInstruction* initial = instruction->AsPhi()->InputAt(0);
861 DCHECK(initial->GetBlock()->Dominates(loop_header));
862 SetRawEnvAt(i, initial);
863 initial->AddEnvUseAt(this, i);
864 } else {
865 instruction->AddEnvUseAt(this, i);
866 }
867 }
868}
869
David Brazdil1abb4192015-02-17 18:33:36 +0000870void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100871 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000872 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100873}
874
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000875HInstruction::InstructionKind HInstruction::GetKind() const {
876 return GetKindInternal();
877}
878
Calin Juravle77520bc2015-01-12 18:45:46 +0000879HInstruction* HInstruction::GetNextDisregardingMoves() const {
880 HInstruction* next = GetNext();
881 while (next != nullptr && next->IsParallelMove()) {
882 next = next->GetNext();
883 }
884 return next;
885}
886
887HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
888 HInstruction* previous = GetPrevious();
889 while (previous != nullptr && previous->IsParallelMove()) {
890 previous = previous->GetPrevious();
891 }
892 return previous;
893}
894
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000896 if (first_instruction_ == nullptr) {
897 DCHECK(last_instruction_ == nullptr);
898 first_instruction_ = last_instruction_ = instruction;
899 } else {
900 last_instruction_->next_ = instruction;
901 instruction->previous_ = last_instruction_;
902 last_instruction_ = instruction;
903 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000904}
905
David Brazdilc3d743f2015-04-22 13:40:50 +0100906void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
907 DCHECK(Contains(cursor));
908 if (cursor == first_instruction_) {
909 cursor->previous_ = instruction;
910 instruction->next_ = cursor;
911 first_instruction_ = instruction;
912 } else {
913 instruction->previous_ = cursor->previous_;
914 instruction->next_ = cursor;
915 cursor->previous_ = instruction;
916 instruction->previous_->next_ = instruction;
917 }
918}
919
920void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
921 DCHECK(Contains(cursor));
922 if (cursor == last_instruction_) {
923 cursor->next_ = instruction;
924 instruction->previous_ = cursor;
925 last_instruction_ = instruction;
926 } else {
927 instruction->next_ = cursor->next_;
928 instruction->previous_ = cursor;
929 cursor->next_ = instruction;
930 instruction->next_->previous_ = instruction;
931 }
932}
933
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934void HInstructionList::RemoveInstruction(HInstruction* instruction) {
935 if (instruction->previous_ != nullptr) {
936 instruction->previous_->next_ = instruction->next_;
937 }
938 if (instruction->next_ != nullptr) {
939 instruction->next_->previous_ = instruction->previous_;
940 }
941 if (instruction == first_instruction_) {
942 first_instruction_ = instruction->next_;
943 }
944 if (instruction == last_instruction_) {
945 last_instruction_ = instruction->previous_;
946 }
947}
948
Roland Levillain6b469232014-09-25 10:10:38 +0100949bool HInstructionList::Contains(HInstruction* instruction) const {
950 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
951 if (it.Current() == instruction) {
952 return true;
953 }
954 }
955 return false;
956}
957
Roland Levillainccc07a92014-09-16 14:48:16 +0100958bool HInstructionList::FoundBefore(const HInstruction* instruction1,
959 const HInstruction* instruction2) const {
960 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
961 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
962 if (it.Current() == instruction1) {
963 return true;
964 }
965 if (it.Current() == instruction2) {
966 return false;
967 }
968 }
969 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
970 return true;
971}
972
Roland Levillain6c82d402014-10-13 16:10:27 +0100973bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
974 if (other_instruction == this) {
975 // An instruction does not strictly dominate itself.
976 return false;
977 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100978 HBasicBlock* block = GetBlock();
979 HBasicBlock* other_block = other_instruction->GetBlock();
980 if (block != other_block) {
981 return GetBlock()->Dominates(other_instruction->GetBlock());
982 } else {
983 // If both instructions are in the same block, ensure this
984 // instruction comes before `other_instruction`.
985 if (IsPhi()) {
986 if (!other_instruction->IsPhi()) {
987 // Phis appear before non phi-instructions so this instruction
988 // dominates `other_instruction`.
989 return true;
990 } else {
991 // There is no order among phis.
992 LOG(FATAL) << "There is no dominance between phis of a same block.";
993 return false;
994 }
995 } else {
996 // `this` is not a phi.
997 if (other_instruction->IsPhi()) {
998 // Phis appear before non phi-instructions so this instruction
999 // does not dominate `other_instruction`.
1000 return false;
1001 } else {
1002 // Check whether this instruction comes before
1003 // `other_instruction` in the instruction list.
1004 return block->GetInstructions().FoundBefore(this, other_instruction);
1005 }
1006 }
1007 }
1008}
1009
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001010void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001011 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001012 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1013 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001014 HInstruction* user = current->GetUser();
1015 size_t input_index = current->GetIndex();
1016 user->SetRawInputAt(input_index, other);
1017 other->AddUseAt(user, input_index);
1018 }
1019
David Brazdiled596192015-01-23 10:39:45 +00001020 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1021 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001022 HEnvironment* user = current->GetUser();
1023 size_t input_index = current->GetIndex();
1024 user->SetRawEnvAt(input_index, other);
1025 other->AddEnvUseAt(user, input_index);
1026 }
1027
David Brazdiled596192015-01-23 10:39:45 +00001028 uses_.Clear();
1029 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001030}
1031
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001032void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001033 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001034 SetRawInputAt(index, replacement);
1035 replacement->AddUseAt(this, index);
1036}
1037
Nicolas Geoffray39468442014-09-02 15:17:15 +01001038size_t HInstruction::EnvironmentSize() const {
1039 return HasEnvironment() ? environment_->Size() : 0;
1040}
1041
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001042void HPhi::AddInput(HInstruction* input) {
1043 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001044 inputs_.push_back(HUserRecord<HInstruction*>(input));
1045 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001046}
1047
David Brazdil2d7352b2015-04-20 14:52:42 +01001048void HPhi::RemoveInputAt(size_t index) {
1049 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001050 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001051 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001052 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001053 InputRecordAt(i).GetUseNode()->SetIndex(i);
1054 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001055}
1056
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001057#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001058void H##name::Accept(HGraphVisitor* visitor) { \
1059 visitor->Visit##name(this); \
1060}
1061
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001062FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001063
1064#undef DEFINE_ACCEPT
1065
1066void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001067 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1068 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001069 if (block != nullptr) {
1070 VisitBasicBlock(block);
1071 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001072 }
1073}
1074
Roland Levillain633021e2014-10-01 14:12:25 +01001075void HGraphVisitor::VisitReversePostOrder() {
1076 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1077 VisitBasicBlock(it.Current());
1078 }
1079}
1080
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001081void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001082 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001083 it.Current()->Accept(this);
1084 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001085 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001086 it.Current()->Accept(this);
1087 }
1088}
1089
Mark Mendelle82549b2015-05-06 10:55:34 -04001090HConstant* HTypeConversion::TryStaticEvaluation() const {
1091 HGraph* graph = GetBlock()->GetGraph();
1092 if (GetInput()->IsIntConstant()) {
1093 int32_t value = GetInput()->AsIntConstant()->GetValue();
1094 switch (GetResultType()) {
1095 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001096 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001097 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001098 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001099 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001100 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001101 default:
1102 return nullptr;
1103 }
1104 } else if (GetInput()->IsLongConstant()) {
1105 int64_t value = GetInput()->AsLongConstant()->GetValue();
1106 switch (GetResultType()) {
1107 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001108 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001109 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001110 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001111 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001112 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001113 default:
1114 return nullptr;
1115 }
1116 } else if (GetInput()->IsFloatConstant()) {
1117 float value = GetInput()->AsFloatConstant()->GetValue();
1118 switch (GetResultType()) {
1119 case Primitive::kPrimInt:
1120 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001121 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001122 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001123 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001125 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1126 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 case Primitive::kPrimLong:
1128 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001131 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1134 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 default:
1138 return nullptr;
1139 }
1140 } else if (GetInput()->IsDoubleConstant()) {
1141 double value = GetInput()->AsDoubleConstant()->GetValue();
1142 switch (GetResultType()) {
1143 case Primitive::kPrimInt:
1144 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001145 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001146 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001147 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001149 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1150 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 case Primitive::kPrimLong:
1152 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001153 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001154 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001155 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001156 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001157 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1158 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001159 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001160 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001161 default:
1162 return nullptr;
1163 }
1164 }
1165 return nullptr;
1166}
1167
Roland Levillain9240d6a2014-10-20 16:47:04 +01001168HConstant* HUnaryOperation::TryStaticEvaluation() const {
1169 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001170 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001171 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001172 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001173 }
1174 return nullptr;
1175}
1176
1177HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001178 if (GetLeft()->IsIntConstant()) {
1179 if (GetRight()->IsIntConstant()) {
1180 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1181 } else if (GetRight()->IsLongConstant()) {
1182 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1183 }
1184 } else if (GetLeft()->IsLongConstant()) {
1185 if (GetRight()->IsIntConstant()) {
1186 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1187 } else if (GetRight()->IsLongConstant()) {
1188 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001189 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001190 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1191 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001192 }
1193 return nullptr;
1194}
Dave Allison20dfc792014-06-16 20:44:29 -07001195
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001196HConstant* HBinaryOperation::GetConstantRight() const {
1197 if (GetRight()->IsConstant()) {
1198 return GetRight()->AsConstant();
1199 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1200 return GetLeft()->AsConstant();
1201 } else {
1202 return nullptr;
1203 }
1204}
1205
1206// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001207// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001208HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1209 HInstruction* most_constant_right = GetConstantRight();
1210 if (most_constant_right == nullptr) {
1211 return nullptr;
1212 } else if (most_constant_right == GetLeft()) {
1213 return GetRight();
1214 } else {
1215 return GetLeft();
1216 }
1217}
1218
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001219bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1220 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001221}
1222
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001223bool HInstruction::Equals(HInstruction* other) const {
1224 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001225 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001226 if (!InstructionDataEquals(other)) return false;
1227 if (GetType() != other->GetType()) return false;
1228 if (InputCount() != other->InputCount()) return false;
1229
1230 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1231 if (InputAt(i) != other->InputAt(i)) return false;
1232 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001233 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001234 return true;
1235}
1236
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001237std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1238#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1239 switch (rhs) {
1240 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1241 default:
1242 os << "Unknown instruction kind " << static_cast<int>(rhs);
1243 break;
1244 }
1245#undef DECLARE_CASE
1246 return os;
1247}
1248
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001249void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001250 next_->previous_ = previous_;
1251 if (previous_ != nullptr) {
1252 previous_->next_ = next_;
1253 }
1254 if (block_->instructions_.first_instruction_ == this) {
1255 block_->instructions_.first_instruction_ = next_;
1256 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001257 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001258
1259 previous_ = cursor->previous_;
1260 if (previous_ != nullptr) {
1261 previous_->next_ = this;
1262 }
1263 next_ = cursor;
1264 cursor->previous_ = this;
1265 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001266
1267 if (block_->instructions_.first_instruction_ == cursor) {
1268 block_->instructions_.first_instruction_ = this;
1269 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001270}
1271
Vladimir Markofb337ea2015-11-25 15:25:10 +00001272void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1273 DCHECK(!CanThrow());
1274 DCHECK(!HasSideEffects());
1275 DCHECK(!HasEnvironmentUses());
1276 DCHECK(HasNonEnvironmentUses());
1277 DCHECK(!IsPhi()); // Makes no sense for Phi.
1278 DCHECK_EQ(InputCount(), 0u);
1279
1280 // Find the target block.
1281 HUseIterator<HInstruction*> uses_it(GetUses());
1282 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1283 uses_it.Advance();
1284 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1285 uses_it.Advance();
1286 }
1287 if (!uses_it.Done()) {
1288 // This instruction has uses in two or more blocks. Find the common dominator.
1289 CommonDominator finder(target_block);
1290 for (; !uses_it.Done(); uses_it.Advance()) {
1291 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1292 }
1293 target_block = finder.Get();
1294 DCHECK(target_block != nullptr);
1295 }
1296 // Move to the first dominator not in a loop.
1297 while (target_block->IsInLoop()) {
1298 target_block = target_block->GetDominator();
1299 DCHECK(target_block != nullptr);
1300 }
1301
1302 // Find insertion position.
1303 HInstruction* insert_pos = nullptr;
1304 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1305 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1306 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1307 insert_pos = uses_it2.Current()->GetUser();
1308 }
1309 }
1310 if (insert_pos == nullptr) {
1311 // No user in `target_block`, insert before the control flow instruction.
1312 insert_pos = target_block->GetLastInstruction();
1313 DCHECK(insert_pos->IsControlFlow());
1314 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1315 if (insert_pos->IsIf()) {
1316 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1317 if (if_input == insert_pos->GetPrevious()) {
1318 insert_pos = if_input;
1319 }
1320 }
1321 }
1322 MoveBefore(insert_pos);
1323}
1324
David Brazdilfc6a86a2015-06-26 10:33:45 +00001325HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001326 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001327 DCHECK_EQ(cursor->GetBlock(), this);
1328
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001329 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1330 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001331 new_block->instructions_.first_instruction_ = cursor;
1332 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1333 instructions_.last_instruction_ = cursor->previous_;
1334 if (cursor->previous_ == nullptr) {
1335 instructions_.first_instruction_ = nullptr;
1336 } else {
1337 cursor->previous_->next_ = nullptr;
1338 cursor->previous_ = nullptr;
1339 }
1340
1341 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001342 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001343
Vladimir Marko60584552015-09-03 13:35:12 +00001344 for (HBasicBlock* successor : GetSuccessors()) {
1345 new_block->successors_.push_back(successor);
1346 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001347 }
Vladimir Marko60584552015-09-03 13:35:12 +00001348 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001349 AddSuccessor(new_block);
1350
David Brazdil56e1acc2015-06-30 15:41:36 +01001351 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001352 return new_block;
1353}
1354
David Brazdild7558da2015-09-22 13:04:14 +01001355HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001356 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001357 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1358
1359 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1360
1361 for (HBasicBlock* predecessor : GetPredecessors()) {
1362 new_block->predecessors_.push_back(predecessor);
1363 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1364 }
1365 predecessors_.clear();
1366 AddPredecessor(new_block);
1367
1368 GetGraph()->AddBlock(new_block);
1369 return new_block;
1370}
1371
David Brazdil9bc43612015-11-05 21:25:24 +00001372HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1373 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1374 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1375
1376 HInstruction* first_insn = GetFirstInstruction();
1377 HInstruction* split_before = nullptr;
1378
1379 if (first_insn != nullptr && first_insn->IsLoadException()) {
1380 // Catch block starts with a LoadException. Split the block after
1381 // the StoreLocal and ClearException which must come after the load.
1382 DCHECK(first_insn->GetNext()->IsStoreLocal());
1383 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1384 split_before = first_insn->GetNext()->GetNext()->GetNext();
1385 } else {
1386 // Catch block does not load the exception. Split at the beginning
1387 // to create an empty catch block.
1388 split_before = first_insn;
1389 }
1390
1391 if (split_before == nullptr) {
1392 // Catch block has no instructions after the split point (must be dead).
1393 // Do not split it but rather signal error by returning nullptr.
1394 return nullptr;
1395 } else {
1396 return SplitBefore(split_before);
1397 }
1398}
1399
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001400HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1401 DCHECK(!cursor->IsControlFlow());
1402 DCHECK_NE(instructions_.last_instruction_, cursor);
1403 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001404
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1406 new_block->instructions_.first_instruction_ = cursor->GetNext();
1407 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1408 cursor->next_->previous_ = nullptr;
1409 cursor->next_ = nullptr;
1410 instructions_.last_instruction_ = cursor;
1411
1412 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001413 for (HBasicBlock* successor : GetSuccessors()) {
1414 new_block->successors_.push_back(successor);
1415 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001416 }
Vladimir Marko60584552015-09-03 13:35:12 +00001417 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001418
Vladimir Marko60584552015-09-03 13:35:12 +00001419 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001420 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001421 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001422 }
Vladimir Marko60584552015-09-03 13:35:12 +00001423 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001424 return new_block;
1425}
1426
David Brazdilec16f792015-08-19 15:04:01 +01001427const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001428 if (EndsWithTryBoundary()) {
1429 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1430 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001431 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001432 return try_boundary;
1433 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001434 DCHECK(IsTryBlock());
1435 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001436 return nullptr;
1437 }
David Brazdilec16f792015-08-19 15:04:01 +01001438 } else if (IsTryBlock()) {
1439 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001440 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001441 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001442 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001443}
1444
David Brazdild7558da2015-09-22 13:04:14 +01001445bool HBasicBlock::HasThrowingInstructions() const {
1446 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1447 if (it.Current()->CanThrow()) {
1448 return true;
1449 }
1450 }
1451 return false;
1452}
1453
David Brazdilfc6a86a2015-06-26 10:33:45 +00001454static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1455 return block.GetPhis().IsEmpty()
1456 && !block.GetInstructions().IsEmpty()
1457 && block.GetFirstInstruction() == block.GetLastInstruction();
1458}
1459
David Brazdil46e2a392015-03-16 17:31:52 +00001460bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001461 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1462}
1463
1464bool HBasicBlock::IsSingleTryBoundary() const {
1465 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001466}
1467
David Brazdil8d5b8b22015-03-24 10:51:52 +00001468bool HBasicBlock::EndsWithControlFlowInstruction() const {
1469 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1470}
1471
David Brazdilb2bd1c52015-03-25 11:17:37 +00001472bool HBasicBlock::EndsWithIf() const {
1473 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1474}
1475
David Brazdilffee3d32015-07-06 11:48:53 +01001476bool HBasicBlock::EndsWithTryBoundary() const {
1477 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1478}
1479
David Brazdilb2bd1c52015-03-25 11:17:37 +00001480bool HBasicBlock::HasSinglePhi() const {
1481 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1482}
1483
David Brazdild26a4112015-11-10 11:07:31 +00001484ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1485 if (EndsWithTryBoundary()) {
1486 // The normal-flow successor of HTryBoundary is always stored at index zero.
1487 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1488 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1489 } else {
1490 // All successors of blocks not ending with TryBoundary are normal.
1491 return ArrayRef<HBasicBlock* const>(successors_);
1492 }
1493}
1494
1495ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1496 if (EndsWithTryBoundary()) {
1497 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1498 } else {
1499 // Blocks not ending with TryBoundary do not have exceptional successors.
1500 return ArrayRef<HBasicBlock* const>();
1501 }
1502}
1503
David Brazdilffee3d32015-07-06 11:48:53 +01001504bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001505 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1506 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1507
1508 size_t length = handlers1.size();
1509 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001510 return false;
1511 }
1512
David Brazdilb618ade2015-07-29 10:31:29 +01001513 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001514 for (size_t i = 0; i < length; ++i) {
1515 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001516 return false;
1517 }
1518 }
1519 return true;
1520}
1521
David Brazdil2d7352b2015-04-20 14:52:42 +01001522size_t HInstructionList::CountSize() const {
1523 size_t size = 0;
1524 HInstruction* current = first_instruction_;
1525 for (; current != nullptr; current = current->GetNext()) {
1526 size++;
1527 }
1528 return size;
1529}
1530
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001531void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1532 for (HInstruction* current = first_instruction_;
1533 current != nullptr;
1534 current = current->GetNext()) {
1535 current->SetBlock(block);
1536 }
1537}
1538
1539void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1540 DCHECK(Contains(cursor));
1541 if (!instruction_list.IsEmpty()) {
1542 if (cursor == last_instruction_) {
1543 last_instruction_ = instruction_list.last_instruction_;
1544 } else {
1545 cursor->next_->previous_ = instruction_list.last_instruction_;
1546 }
1547 instruction_list.last_instruction_->next_ = cursor->next_;
1548 cursor->next_ = instruction_list.first_instruction_;
1549 instruction_list.first_instruction_->previous_ = cursor;
1550 }
1551}
1552
1553void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001554 if (IsEmpty()) {
1555 first_instruction_ = instruction_list.first_instruction_;
1556 last_instruction_ = instruction_list.last_instruction_;
1557 } else {
1558 AddAfter(last_instruction_, instruction_list);
1559 }
1560}
1561
David Brazdil04ff4e82015-12-10 13:54:52 +00001562// Should be called on instructions in a dead block in post order. This method
1563// assumes `insn` has been removed from all users with the exception of catch
1564// phis because of missing exceptional edges in the graph. It removes the
1565// instruction from catch phi uses, together with inputs of other catch phis in
1566// the catch block at the same index, as these must be dead too.
1567static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1568 DCHECK(!insn->HasEnvironmentUses());
1569 while (insn->HasNonEnvironmentUses()) {
1570 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1571 size_t use_index = use->GetIndex();
1572 HBasicBlock* user_block = use->GetUser()->GetBlock();
1573 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1574 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1575 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1576 }
1577 }
1578}
1579
David Brazdil2d7352b2015-04-20 14:52:42 +01001580void HBasicBlock::DisconnectAndDelete() {
1581 // Dominators must be removed after all the blocks they dominate. This way
1582 // a loop header is removed last, a requirement for correct loop information
1583 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001584 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001585
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001586 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001587 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1588 HLoopInformation* loop_info = it.Current();
1589 loop_info->Remove(this);
1590 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001591 // If this was the last back edge of the loop, we deliberately leave the
1592 // loop in an inconsistent state and will fail SSAChecker unless the
1593 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001594 loop_info->RemoveBackEdge(this);
1595 }
1596 }
1597
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001598 // (2) Disconnect the block from its predecessors and update their
1599 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001600 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001601 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001602 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1603 // This block is the only normal-flow successor of the TryBoundary which
1604 // makes `predecessor` dead. Since DCE removes blocks in post order,
1605 // exception handlers of this TryBoundary were already visited and any
1606 // remaining handlers therefore must be live. We remove `predecessor` from
1607 // their list of predecessors.
1608 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1609 while (predecessor->GetSuccessors().size() > 1) {
1610 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1611 DCHECK(handler->IsCatchBlock());
1612 predecessor->RemoveSuccessor(handler);
1613 handler->RemovePredecessor(predecessor);
1614 }
1615 }
1616
David Brazdil2d7352b2015-04-20 14:52:42 +01001617 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001618 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1619 if (num_pred_successors == 1u) {
1620 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001621 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1622 // successor. Replace those with a HGoto.
1623 DCHECK(last_instruction->IsIf() ||
1624 last_instruction->IsPackedSwitch() ||
1625 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001626 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001627 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001628 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001629 // The predecessor has no remaining successors and therefore must be dead.
1630 // We deliberately leave it without a control-flow instruction so that the
1631 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001632 predecessor->RemoveInstruction(last_instruction);
1633 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001634 // There are multiple successors left. The removed block might be a successor
1635 // of a PackedSwitch which will be completely removed (perhaps replaced with
1636 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1637 // case, leave `last_instruction` as is for now.
1638 DCHECK(last_instruction->IsPackedSwitch() ||
1639 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001640 }
David Brazdil46e2a392015-03-16 17:31:52 +00001641 }
Vladimir Marko60584552015-09-03 13:35:12 +00001642 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001643
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001644 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001645 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001646 // Delete this block from the list of predecessors.
1647 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001648 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001649
1650 // Check that `successor` has other predecessors, otherwise `this` is the
1651 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001652 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001653
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001654 // Remove this block's entries in the successor's phis. Skip exceptional
1655 // successors because catch phi inputs do not correspond to predecessor
1656 // blocks but throwing instructions. Their inputs will be updated in step (4).
1657 if (!successor->IsCatchBlock()) {
1658 if (successor->predecessors_.size() == 1u) {
1659 // The successor has just one predecessor left. Replace phis with the only
1660 // remaining input.
1661 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1662 HPhi* phi = phi_it.Current()->AsPhi();
1663 phi->ReplaceWith(phi->InputAt(1 - this_index));
1664 successor->RemovePhi(phi);
1665 }
1666 } else {
1667 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1668 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1669 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001670 }
1671 }
1672 }
Vladimir Marko60584552015-09-03 13:35:12 +00001673 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001674
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001675 // (4) Remove instructions and phis. Instructions should have no remaining uses
1676 // except in catch phis. If an instruction is used by a catch phi at `index`,
1677 // remove `index`-th input of all phis in the catch block since they are
1678 // guaranteed dead. Note that we may miss dead inputs this way but the
1679 // graph will always remain consistent.
1680 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1681 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001682 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001683 RemoveInstruction(insn);
1684 }
1685 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001686 HPhi* insn = it.Current()->AsPhi();
1687 RemoveUsesOfDeadInstruction(insn);
1688 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001689 }
1690
David Brazdil2d7352b2015-04-20 14:52:42 +01001691 // Disconnect from the dominator.
1692 dominator_->RemoveDominatedBlock(this);
1693 SetDominator(nullptr);
1694
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001695 // Delete from the graph, update reverse post order.
1696 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001697 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001698}
1699
1700void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001701 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001702 DCHECK(ContainsElement(dominated_blocks_, other));
1703 DCHECK_EQ(GetSingleSuccessor(), other);
1704 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001705 DCHECK(other->GetPhis().IsEmpty());
1706
David Brazdil2d7352b2015-04-20 14:52:42 +01001707 // Move instructions from `other` to `this`.
1708 DCHECK(EndsWithControlFlowInstruction());
1709 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001710 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001711 other->instructions_.SetBlockOfInstructions(this);
1712 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001713
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 // Remove `other` from the loops it is included in.
1715 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1716 HLoopInformation* loop_info = it.Current();
1717 loop_info->Remove(other);
1718 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001719 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001720 }
1721 }
1722
1723 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001724 successors_.clear();
1725 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001726 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001727 successor->ReplacePredecessor(other, this);
1728 }
1729
David Brazdil2d7352b2015-04-20 14:52:42 +01001730 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001731 RemoveDominatedBlock(other);
1732 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1733 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001734 dominated->SetDominator(this);
1735 }
Vladimir Marko60584552015-09-03 13:35:12 +00001736 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001737 other->dominator_ = nullptr;
1738
1739 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001740 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001741
1742 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001743 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001744 other->SetGraph(nullptr);
1745}
1746
1747void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1748 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001749 DCHECK(GetDominatedBlocks().empty());
1750 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001751 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001752 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001753 DCHECK(other->GetPhis().IsEmpty());
1754 DCHECK(!other->IsInLoop());
1755
1756 // Move instructions from `other` to `this`.
1757 instructions_.Add(other->GetInstructions());
1758 other->instructions_.SetBlockOfInstructions(this);
1759
1760 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001761 successors_.clear();
1762 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001763 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001764 successor->ReplacePredecessor(other, this);
1765 }
1766
1767 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001768 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1769 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001770 dominated->SetDominator(this);
1771 }
Vladimir Marko60584552015-09-03 13:35:12 +00001772 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 other->dominator_ = nullptr;
1774 other->graph_ = nullptr;
1775}
1776
1777void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001778 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001779 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001780 predecessor->ReplaceSuccessor(this, other);
1781 }
Vladimir Marko60584552015-09-03 13:35:12 +00001782 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001783 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001784 successor->ReplacePredecessor(this, other);
1785 }
Vladimir Marko60584552015-09-03 13:35:12 +00001786 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1787 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001788 }
1789 GetDominator()->ReplaceDominatedBlock(this, other);
1790 other->SetDominator(GetDominator());
1791 dominator_ = nullptr;
1792 graph_ = nullptr;
1793}
1794
1795// Create space in `blocks` for adding `number_of_new_blocks` entries
1796// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001797static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001798 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001799 size_t after) {
1800 DCHECK_LT(after, blocks->size());
1801 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001802 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001803 blocks->resize(new_size);
1804 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001805}
1806
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001807void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001808 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001809 DCHECK(block->GetSuccessors().empty());
1810 DCHECK(block->GetPredecessors().empty());
1811 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001812 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001813 DCHECK(block->GetInstructions().IsEmpty());
1814 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001815
David Brazdilc7af85d2015-05-26 12:05:55 +01001816 if (block->IsExitBlock()) {
1817 exit_block_ = nullptr;
1818 }
1819
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001820 RemoveElement(reverse_post_order_, block);
1821 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001822}
1823
Calin Juravle2e768302015-07-28 14:41:11 +00001824HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001825 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001826 // Update the environments in this graph to have the invoke's environment
1827 // as parent.
1828 {
1829 HReversePostOrderIterator it(*this);
1830 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1831 for (; !it.Done(); it.Advance()) {
1832 HBasicBlock* block = it.Current();
1833 for (HInstructionIterator instr_it(block->GetInstructions());
1834 !instr_it.Done();
1835 instr_it.Advance()) {
1836 HInstruction* current = instr_it.Current();
1837 if (current->NeedsEnvironment()) {
1838 current->GetEnvironment()->SetAndCopyParentChain(
1839 outer_graph->GetArena(), invoke->GetEnvironment());
1840 }
1841 }
1842 }
1843 }
1844 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1845 if (HasBoundsChecks()) {
1846 outer_graph->SetHasBoundsChecks(true);
1847 }
1848
Calin Juravle2e768302015-07-28 14:41:11 +00001849 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001850 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001851 // Simple case of an entry block, a body block, and an exit block.
1852 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001853 HBasicBlock* body = GetBlocks()[1];
1854 DCHECK(GetBlocks()[0]->IsEntryBlock());
1855 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001856 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001857 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001858 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001859
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001860 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1861 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001862
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001863 // Replace the invoke with the return value of the inlined graph.
1864 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001865 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001866 } else {
1867 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001868 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001869
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001870 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001871 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001872 // Need to inline multiple blocks. We split `invoke`'s block
1873 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001874 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001875 // with the second half.
1876 ArenaAllocator* allocator = outer_graph->GetArena();
1877 HBasicBlock* at = invoke->GetBlock();
1878 HBasicBlock* to = at->SplitAfter(invoke);
1879
Vladimir Markoec7802a2015-10-01 20:57:57 +01001880 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001881 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001882 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001883 exit_block_->ReplaceWith(to);
1884
1885 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001886 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001887 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001888 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001889 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001890 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001891 if (!returns_void) {
1892 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001894 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001896 } else {
1897 if (!returns_void) {
1898 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001899 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001900 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001901 to->AddPhi(return_value->AsPhi());
1902 }
Vladimir Marko60584552015-09-03 13:35:12 +00001903 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001904 HInstruction* last = predecessor->GetLastInstruction();
1905 if (!returns_void) {
1906 return_value->AsPhi()->AddInput(last->InputAt(0));
1907 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001908 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001909 predecessor->RemoveInstruction(last);
1910 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001911 }
1912
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001913 // Update the meta information surrounding blocks:
1914 // (1) the graph they are now in,
1915 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001916 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001917 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001918 // Note that we do not need to update catch phi inputs because they
1919 // correspond to the register file of the outer method which the inlinee
1920 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001921
1922 // We don't add the entry block, the exit block, and the first block, which
1923 // has been merged with `at`.
1924 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1925
1926 // We add the `to` block.
1927 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001928 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001929 + kNumberOfNewBlocksInCaller;
1930
1931 // Find the location of `at` in the outer graph's reverse post order. The new
1932 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001933 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001934 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1935
David Brazdil95177982015-10-30 12:56:58 -05001936 HLoopInformation* loop_info = at->GetLoopInformation();
1937 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1938 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1939
1940 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1941 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001942 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1943 HBasicBlock* current = it.Current();
1944 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001945 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001946 DCHECK(current->GetGraph() == this);
1947 current->SetGraph(outer_graph);
1948 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001949 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001950 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001951 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001952 } else if (current->IsLoopHeader()) {
1953 // Clear the information of which blocks are contained in that loop. Since the
1954 // information is stored as a bit vector based on block ids, we have to update
1955 // it, as those block ids were specific to the callee graph and we are now adding
1956 // these blocks to the caller graph.
1957 current->GetLoopInformation()->ClearAllBlocks();
1958 }
1959 if (current->IsInLoop()) {
1960 for (HLoopInformationOutwardIterator loop_it(*current);
1961 !loop_it.Done();
1962 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001963 loop_it.Current()->Add(current);
1964 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001965 }
David Brazdil95177982015-10-30 12:56:58 -05001966 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001967 }
1968 }
1969
David Brazdil95177982015-10-30 12:56:58 -05001970 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001971 to->SetGraph(outer_graph);
1972 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001973 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001974 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001975 if (!to->IsInLoop()) {
1976 to->SetLoopInformation(loop_info);
1977 }
David Brazdil7d275372015-04-21 16:36:35 +01001978 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1979 loop_it.Current()->Add(to);
1980 }
David Brazdil95177982015-10-30 12:56:58 -05001981 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001982 // Only `to` can become a back edge, as the inlined blocks
1983 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001984 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001985 }
1986 }
David Brazdil95177982015-10-30 12:56:58 -05001987 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001988 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001989
David Brazdil05144f42015-04-16 15:18:00 +01001990 // Update the next instruction id of the outer graph, so that instructions
1991 // added later get bigger ids than those in the inner graph.
1992 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1993
1994 // Walk over the entry block and:
1995 // - Move constants from the entry block to the outer_graph's entry block,
1996 // - Replace HParameterValue instructions with their real value.
1997 // - Remove suspend checks, that hold an environment.
1998 // We must do this after the other blocks have been inlined, otherwise ids of
1999 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002000 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002001 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2002 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002003 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002004 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002005 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002006 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002007 replacement = outer_graph->GetIntConstant(
2008 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002009 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002010 replacement = outer_graph->GetLongConstant(
2011 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002012 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002013 replacement = outer_graph->GetFloatConstant(
2014 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002015 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002016 replacement = outer_graph->GetDoubleConstant(
2017 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002018 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002019 if (kIsDebugBuild
2020 && invoke->IsInvokeStaticOrDirect()
2021 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2022 // Ensure we do not use the last input of `invoke`, as it
2023 // contains a clinit check which is not an actual argument.
2024 size_t last_input_index = invoke->InputCount() - 1;
2025 DCHECK(parameter_index != last_input_index);
2026 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002027 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002028 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002029 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002030 } else {
2031 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2032 entry_block_->RemoveInstruction(current);
2033 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002034 if (replacement != nullptr) {
2035 current->ReplaceWith(replacement);
2036 // If the current is the return value then we need to update the latter.
2037 if (current == return_value) {
2038 DCHECK_EQ(entry_block_, return_value->GetBlock());
2039 return_value = replacement;
2040 }
2041 }
2042 }
2043
2044 if (return_value != nullptr) {
2045 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002046 }
2047
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002048 // Finally remove the invoke from the caller.
2049 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002050
2051 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002052}
2053
Mingyao Yang3584bce2015-05-19 16:01:59 -07002054/*
2055 * Loop will be transformed to:
2056 * old_pre_header
2057 * |
2058 * if_block
2059 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002060 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002061 * \ /
2062 * new_pre_header
2063 * |
2064 * header
2065 */
2066void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2067 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002068 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002069
Aart Bik3fc7f352015-11-20 22:03:03 -08002070 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002071 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002072 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2073 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002074 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2075 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002076 AddBlock(true_block);
2077 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002078 AddBlock(new_pre_header);
2079
Aart Bik3fc7f352015-11-20 22:03:03 -08002080 header->ReplacePredecessor(old_pre_header, new_pre_header);
2081 old_pre_header->successors_.clear();
2082 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002083
Aart Bik3fc7f352015-11-20 22:03:03 -08002084 old_pre_header->AddSuccessor(if_block);
2085 if_block->AddSuccessor(true_block); // True successor
2086 if_block->AddSuccessor(false_block); // False successor
2087 true_block->AddSuccessor(new_pre_header);
2088 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002089
Aart Bik3fc7f352015-11-20 22:03:03 -08002090 old_pre_header->dominated_blocks_.push_back(if_block);
2091 if_block->SetDominator(old_pre_header);
2092 if_block->dominated_blocks_.push_back(true_block);
2093 true_block->SetDominator(if_block);
2094 if_block->dominated_blocks_.push_back(false_block);
2095 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002096 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002097 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002098 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002099 header->SetDominator(new_pre_header);
2100
Aart Bik3fc7f352015-11-20 22:03:03 -08002101 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002102 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002103 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002104 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002105 reverse_post_order_[index_of_header++] = true_block;
2106 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002107 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002108
Aart Bik3fc7f352015-11-20 22:03:03 -08002109 // Fix loop information.
2110 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2111 if (loop_info != nullptr) {
2112 if_block->SetLoopInformation(loop_info);
2113 true_block->SetLoopInformation(loop_info);
2114 false_block->SetLoopInformation(loop_info);
2115 new_pre_header->SetLoopInformation(loop_info);
2116 // Add blocks to all enveloping loops.
2117 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002118 !loop_it.Done();
2119 loop_it.Advance()) {
2120 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002121 loop_it.Current()->Add(true_block);
2122 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002123 loop_it.Current()->Add(new_pre_header);
2124 }
2125 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002126
2127 // Fix try/catch information.
2128 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2129 ? old_pre_header->GetTryCatchInformation()
2130 : nullptr;
2131 if_block->SetTryCatchInformation(try_catch_info);
2132 true_block->SetTryCatchInformation(try_catch_info);
2133 false_block->SetTryCatchInformation(try_catch_info);
2134 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002135}
2136
David Brazdilf5552582015-12-27 13:36:12 +00002137static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2138 SHARED_REQUIRES(Locks::mutator_lock_) {
2139 if (rti.IsValid()) {
2140 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2141 << " upper_bound_rti: " << upper_bound_rti
2142 << " rti: " << rti;
2143 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2144 }
2145}
2146
Calin Juravle2e768302015-07-28 14:41:11 +00002147void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2148 if (kIsDebugBuild) {
2149 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2150 ScopedObjectAccess soa(Thread::Current());
2151 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2152 if (IsBoundType()) {
2153 // Having the test here spares us from making the method virtual just for
2154 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002155 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002156 }
2157 }
2158 reference_type_info_ = rti;
2159}
2160
David Brazdilf5552582015-12-27 13:36:12 +00002161void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2162 if (kIsDebugBuild) {
2163 ScopedObjectAccess soa(Thread::Current());
2164 DCHECK(upper_bound.IsValid());
2165 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2166 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2167 }
2168 upper_bound_ = upper_bound;
2169 upper_can_be_null_ = can_be_null;
2170}
2171
Calin Juravle2e768302015-07-28 14:41:11 +00002172ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2173
2174ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2175 : type_handle_(type_handle), is_exact_(is_exact) {
2176 if (kIsDebugBuild) {
2177 ScopedObjectAccess soa(Thread::Current());
2178 DCHECK(IsValidHandle(type_handle));
2179 }
2180}
2181
Calin Juravleacf735c2015-02-12 15:25:22 +00002182std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2183 ScopedObjectAccess soa(Thread::Current());
2184 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002185 << " is_valid=" << rhs.IsValid()
2186 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002187 << " is_exact=" << rhs.IsExact()
2188 << " ]";
2189 return os;
2190}
2191
Mark Mendellc4701932015-04-10 13:18:51 -04002192bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2193 // For now, assume that instructions in different blocks may use the
2194 // environment.
2195 // TODO: Use the control flow to decide if this is true.
2196 if (GetBlock() != other->GetBlock()) {
2197 return true;
2198 }
2199
2200 // We know that we are in the same block. Walk from 'this' to 'other',
2201 // checking to see if there is any instruction with an environment.
2202 HInstruction* current = this;
2203 for (; current != other && current != nullptr; current = current->GetNext()) {
2204 // This is a conservative check, as the instruction result may not be in
2205 // the referenced environment.
2206 if (current->HasEnvironment()) {
2207 return true;
2208 }
2209 }
2210
2211 // We should have been called with 'this' before 'other' in the block.
2212 // Just confirm this.
2213 DCHECK(current != nullptr);
2214 return false;
2215}
2216
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002217void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002218 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2219 IntrinsicSideEffects side_effects,
2220 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002221 intrinsic_ = intrinsic;
2222 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002223
Aart Bik5d75afe2015-12-14 11:57:01 -08002224 // Adjust method's side effects from intrinsic table.
2225 switch (side_effects) {
2226 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2227 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2228 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2229 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2230 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002231
2232 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2233 opt.SetDoesNotNeedDexCache();
2234 opt.SetDoesNotNeedEnvironment();
2235 } else {
2236 // If we need an environment, that means there will be a call, which can trigger GC.
2237 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2238 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002239 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002240 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002241}
2242
David Brazdil6de19382016-01-08 17:37:10 +00002243bool HNewInstance::IsStringAlloc() const {
2244 ScopedObjectAccess soa(Thread::Current());
2245 return GetReferenceTypeInfo().IsStringClass();
2246}
2247
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002248bool HInvoke::NeedsEnvironment() const {
2249 if (!IsIntrinsic()) {
2250 return true;
2251 }
2252 IntrinsicOptimizations opt(*this);
2253 return !opt.GetDoesNotNeedEnvironment();
2254}
2255
Vladimir Markodc151b22015-10-15 18:02:30 +01002256bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2257 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002258 return false;
2259 }
2260 if (!IsIntrinsic()) {
2261 return true;
2262 }
2263 IntrinsicOptimizations opt(*this);
2264 return !opt.GetDoesNotNeedDexCache();
2265}
2266
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002267void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2268 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2269 input->AddUseAt(this, index);
2270 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2271 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2272 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2273 InputRecordAt(i).GetUseNode()->SetIndex(i);
2274 }
2275}
2276
Vladimir Markob554b5a2015-11-06 12:57:55 +00002277void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2278 RemoveAsUserOfInput(index);
2279 inputs_.erase(inputs_.begin() + index);
2280 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2281 for (size_t i = index, e = InputCount(); i < e; ++i) {
2282 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2283 InputRecordAt(i).GetUseNode()->SetIndex(i);
2284 }
2285}
2286
Vladimir Markof64242a2015-12-01 14:58:23 +00002287std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2288 switch (rhs) {
2289 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2290 return os << "string_init";
2291 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2292 return os << "recursive";
2293 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2294 return os << "direct";
2295 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2296 return os << "direct_fixup";
2297 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2298 return os << "dex_cache_pc_relative";
2299 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2300 return os << "dex_cache_via_method";
2301 default:
2302 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2303 UNREACHABLE();
2304 }
2305}
2306
Vladimir Markofbb184a2015-11-13 14:47:00 +00002307std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2308 switch (rhs) {
2309 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2310 return os << "explicit";
2311 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2312 return os << "implicit";
2313 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2314 return os << "none";
2315 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002316 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2317 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002318 }
2319}
2320
Mark Mendellc4701932015-04-10 13:18:51 -04002321void HInstruction::RemoveEnvironmentUsers() {
2322 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2323 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2324 HEnvironment* user = user_node->GetUser();
2325 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2326 }
2327 env_uses_.Clear();
2328}
2329
Mark Mendellf6529172015-11-17 11:16:56 -05002330// Returns an instruction with the opposite boolean value from 'cond'.
2331HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2332 ArenaAllocator* allocator = GetArena();
2333
2334 if (cond->IsCondition() &&
2335 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2336 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2337 HInstruction* lhs = cond->InputAt(0);
2338 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002339 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002340 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2341 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2342 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2343 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2344 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2345 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2346 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2347 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2348 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2349 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2350 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002351 default:
2352 LOG(FATAL) << "Unexpected condition";
2353 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002354 }
2355 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2356 return replacement;
2357 } else if (cond->IsIntConstant()) {
2358 HIntConstant* int_const = cond->AsIntConstant();
2359 if (int_const->IsZero()) {
2360 return GetIntConstant(1);
2361 } else {
2362 DCHECK(int_const->IsOne());
2363 return GetIntConstant(0);
2364 }
2365 } else {
2366 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2367 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2368 return replacement;
2369 }
2370}
2371
Roland Levillainc9285912015-12-18 10:38:42 +00002372std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2373 os << "["
2374 << " source=" << rhs.GetSource()
2375 << " destination=" << rhs.GetDestination()
2376 << " type=" << rhs.GetType()
2377 << " instruction=";
2378 if (rhs.GetInstruction() != nullptr) {
2379 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2380 } else {
2381 os << "null";
2382 }
2383 os << " ]";
2384 return os;
2385}
2386
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002387} // namespace art