blob: 2eabadf86156168b7a25f04949e32770a9b7f8bc [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
Andreas Gampe451ad8d2016-01-20 21:23:30 +0000291 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000292 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Andreas Gampe451ad8d2016-01-20 21:23:30 +0000293 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100294 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100295 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600296 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100299 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100300 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100301 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100302 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 }
304 }
305 pre_header->AddSuccessor(header);
306 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100307
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100308 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100309 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
310 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000311 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100312 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100313 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000314 header->predecessors_[pred] = to_swap;
315 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100316 break;
317 }
318 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100319 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100320
321 // Place the suspend check at the beginning of the header, so that live registers
322 // will be known when allocating registers. Note that code generation can still
323 // generate the suspend check at the back edge, but needs to be careful with
324 // loop phi spill slots (which are not written to at back edge).
325 HInstruction* first_instruction = header->GetFirstInstruction();
326 if (!first_instruction->IsSuspendCheck()) {
327 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
328 header->InsertInstructionBefore(check, first_instruction);
329 first_instruction = check;
330 }
331 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100332}
333
David Brazdilffee3d32015-07-06 11:48:53 +0100334static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100335 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100336 if (!predecessor->EndsWithTryBoundary()) {
337 // Only edges from HTryBoundary can be exceptional.
338 return false;
339 }
340 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
341 if (try_boundary->GetNormalFlowSuccessor() == &block) {
342 // This block is the normal-flow successor of `try_boundary`, but it could
343 // also be one of its exception handlers if catch blocks have not been
344 // simplified yet. Predecessors are unordered, so we will consider the first
345 // occurrence to be the normal edge and a possible second occurrence to be
346 // the exceptional edge.
347 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
348 } else {
349 // This is not the normal-flow successor of `try_boundary`, hence it must be
350 // one of its exception handlers.
351 DCHECK(try_boundary->HasExceptionHandler(block));
352 return true;
353 }
354}
355
356void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100357 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
358 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
359 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
360 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000361 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100362 continue;
363 }
364
365 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000366 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100367 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
368 exceptional_predecessors_only = false;
369 break;
370 }
371 }
372
373 if (!exceptional_predecessors_only) {
374 // Catch block has normal-flow predecessors and needs to be simplified.
375 // Splitting the block before its first instruction moves all its
376 // instructions into `normal_block` and links the two blocks with a Goto.
377 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
378 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000379 //
David Brazdilffee3d32015-07-06 11:48:53 +0100380 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000381 // a move-exception instruction, as guaranteed by the verifier. However,
382 // trivially dead predecessors are ignored by the verifier and such code
383 // has not been removed at this stage. We therefore ignore the assumption
384 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
385 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
386 if (normal_block == nullptr) {
387 // Catch block is either empty or only contains a move-exception. It must
388 // therefore be dead and will be removed during initial DCE. Do nothing.
389 DCHECK(!catch_block->EndsWithControlFlowInstruction());
390 } else {
391 // Catch block was split. Re-link normal-flow edges to the new block.
392 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
393 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
394 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
395 --j;
396 }
David Brazdilffee3d32015-07-06 11:48:53 +0100397 }
398 }
399 }
400 }
401}
402
403void HGraph::ComputeTryBlockInformation() {
404 // Iterate in reverse post order to propagate try membership information from
405 // predecessors to their successors.
406 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
407 HBasicBlock* block = it.Current();
408 if (block->IsEntryBlock() || block->IsCatchBlock()) {
409 // Catch blocks after simplification have only exceptional predecessors
410 // and hence are never in tries.
411 continue;
412 }
413
414 // Infer try membership from the first predecessor. Having simplified loops,
415 // the first predecessor can never be a back edge and therefore it must have
416 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100417 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100418 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100419 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000420 if (try_entry != nullptr &&
421 (block->GetTryCatchInformation() == nullptr ||
422 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
423 // We are either setting try block membership for the first time or it
424 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100425 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
426 }
David Brazdilffee3d32015-07-06 11:48:53 +0100427 }
428}
429
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000431// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100432 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000433 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100434 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
435 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
436 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
437 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100438 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000439 if (block->GetSuccessors().size() > 1) {
440 // Only split normal-flow edges. We cannot split exceptional edges as they
441 // are synthesized (approximate real control flow), and we do not need to
442 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000443 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
444 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
445 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100446 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000447 if (successor == exit_block_) {
448 // Throw->TryBoundary->Exit. Special case which we do not want to split
449 // because Goto->Exit is not allowed.
450 DCHECK(block->IsSingleTryBoundary());
451 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
452 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100453 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000454 // SplitCriticalEdge could have invalidated the `normal_successors`
455 // ArrayRef. We must re-acquire it.
456 normal_successors = block->GetNormalSuccessors();
457 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
458 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100459 }
460 }
461 }
462 if (block->IsLoopHeader()) {
463 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000464 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
465 // We are being called by the dead code elimiation pass, and what used to be
466 // a loop got dismantled. Just remove the suspend check.
467 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100468 }
469 }
470}
471
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000472GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100473 // Order does not matter.
474 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
475 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100476 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100477 if (block->IsCatchBlock()) {
478 // TODO: Dealing with exceptional back edges could be tricky because
479 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000480 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100481 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000482 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100483 }
484 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000485 return kAnalysisSuccess;
486}
487
488void HLoopInformation::Dump(std::ostream& os) {
489 os << "header: " << header_->GetBlockId() << std::endl;
490 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
491 for (HBasicBlock* block : back_edges_) {
492 os << "back edge: " << block->GetBlockId() << std::endl;
493 }
494 for (HBasicBlock* block : header_->GetPredecessors()) {
495 os << "predecessor: " << block->GetBlockId() << std::endl;
496 }
497 for (uint32_t idx : blocks_.Indexes()) {
498 os << " in loop: " << idx << std::endl;
499 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100500}
501
David Brazdil8d5b8b22015-03-24 10:51:52 +0000502void HGraph::InsertConstant(HConstant* constant) {
503 // New constants are inserted before the final control-flow instruction
504 // of the graph, or at its end if called from the graph builder.
505 if (entry_block_->EndsWithControlFlowInstruction()) {
506 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000507 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000508 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000509 }
510}
511
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600512HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100513 // For simplicity, don't bother reviving the cached null constant if it is
514 // not null and not in a block. Otherwise, we need to clear the instruction
515 // id and/or any invariants the graph is assuming when adding new instructions.
516 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600517 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000518 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000519 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000520 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000521 if (kIsDebugBuild) {
522 ScopedObjectAccess soa(Thread::Current());
523 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
524 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000525 return cached_null_constant_;
526}
527
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100528HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100529 // For simplicity, don't bother reviving the cached current method if it is
530 // not null and not in a block. Otherwise, we need to clear the instruction
531 // id and/or any invariants the graph is assuming when adding new instructions.
532 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700533 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600534 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
535 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100536 if (entry_block_->GetFirstInstruction() == nullptr) {
537 entry_block_->AddInstruction(cached_current_method_);
538 } else {
539 entry_block_->InsertInstructionBefore(
540 cached_current_method_, entry_block_->GetFirstInstruction());
541 }
542 }
543 return cached_current_method_;
544}
545
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600546HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000547 switch (type) {
548 case Primitive::Type::kPrimBoolean:
549 DCHECK(IsUint<1>(value));
550 FALLTHROUGH_INTENDED;
551 case Primitive::Type::kPrimByte:
552 case Primitive::Type::kPrimChar:
553 case Primitive::Type::kPrimShort:
554 case Primitive::Type::kPrimInt:
555 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600556 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000557
558 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600559 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000560
561 default:
562 LOG(FATAL) << "Unsupported constant type";
563 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000564 }
David Brazdil46e2a392015-03-16 17:31:52 +0000565}
566
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000567void HGraph::CacheFloatConstant(HFloatConstant* constant) {
568 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
569 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
570 cached_float_constants_.Overwrite(value, constant);
571}
572
573void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
574 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
575 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
576 cached_double_constants_.Overwrite(value, constant);
577}
578
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000579void HLoopInformation::Add(HBasicBlock* block) {
580 blocks_.SetBit(block->GetBlockId());
581}
582
David Brazdil46e2a392015-03-16 17:31:52 +0000583void HLoopInformation::Remove(HBasicBlock* block) {
584 blocks_.ClearBit(block->GetBlockId());
585}
586
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100587void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
588 if (blocks_.IsBitSet(block->GetBlockId())) {
589 return;
590 }
591
592 blocks_.SetBit(block->GetBlockId());
593 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000594 for (HBasicBlock* predecessor : block->GetPredecessors()) {
595 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100596 }
597}
598
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000599void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
600 if (blocks_.IsBitSet(block->GetBlockId())) {
601 return;
602 }
603
604 if (block->IsLoopHeader()) {
605 // If we hit a loop header in an irreducible loop, we first check if the
606 // pre header of that loop belongs to the currently analyzed loop. If it does,
607 // then we visit the back edges.
608 // Note that we cannot use GetPreHeader, as the loop may have not been populated
609 // yet.
610 HBasicBlock* pre_header = block->GetPredecessors()[0];
611 PopulateIrreducibleRecursive(pre_header);
612 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
613 blocks_.SetBit(block->GetBlockId());
614 block->SetInLoop(this);
615 HLoopInformation* info = block->GetLoopInformation();
616 for (HBasicBlock* back_edge : info->GetBackEdges()) {
617 PopulateIrreducibleRecursive(back_edge);
618 }
619 }
620 } else {
621 // Visit all predecessors. If one predecessor is part of the loop, this
622 // block is also part of this loop.
623 for (HBasicBlock* predecessor : block->GetPredecessors()) {
624 PopulateIrreducibleRecursive(predecessor);
625 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
626 blocks_.SetBit(block->GetBlockId());
627 block->SetInLoop(this);
628 }
629 }
630 }
631}
632
633void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100634 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000635 // Populate this loop: starting with the back edge, recursively add predecessors
636 // that are not already part of that loop. Set the header as part of the loop
637 // to end the recursion.
638 // This is a recursive implementation of the algorithm described in
639 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
640 blocks_.SetBit(header_->GetBlockId());
641 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100642 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100643 DCHECK(back_edge->GetDominator() != nullptr);
644 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000645 irreducible_ = true;
646 header_->GetGraph()->SetHasIrreducibleLoops(true);
647 PopulateIrreducibleRecursive(back_edge);
648 } else {
649 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100650 }
David Brazdila4b8c212015-05-07 09:59:30 +0100651 }
652}
653
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100654HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 HBasicBlock* block = header_->GetPredecessors()[0];
656 DCHECK(irreducible_ || (block == header_->GetDominator()));
657 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100658}
659
660bool HLoopInformation::Contains(const HBasicBlock& block) const {
661 return blocks_.IsBitSet(block.GetBlockId());
662}
663
664bool HLoopInformation::IsIn(const HLoopInformation& other) const {
665 return other.blocks_.IsBitSet(header_->GetBlockId());
666}
667
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800668bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
669 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700670}
671
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100672size_t HLoopInformation::GetLifetimeEnd() const {
673 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100674 for (HBasicBlock* back_edge : GetBackEdges()) {
675 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100676 }
677 return last_position;
678}
679
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100680bool HBasicBlock::Dominates(HBasicBlock* other) const {
681 // Walk up the dominator tree from `other`, to find out if `this`
682 // is an ancestor.
683 HBasicBlock* current = other;
684 while (current != nullptr) {
685 if (current == this) {
686 return true;
687 }
688 current = current->GetDominator();
689 }
690 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100691}
692
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100693static void UpdateInputsUsers(HInstruction* instruction) {
694 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
695 instruction->InputAt(i)->AddUseAt(instruction, i);
696 }
697 // Environment should be created later.
698 DCHECK(!instruction->HasEnvironment());
699}
700
Roland Levillainccc07a92014-09-16 14:48:16 +0100701void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
702 HInstruction* replacement) {
703 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400704 if (initial->IsControlFlow()) {
705 // We can only replace a control flow instruction with another control flow instruction.
706 DCHECK(replacement->IsControlFlow());
707 DCHECK_EQ(replacement->GetId(), -1);
708 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
709 DCHECK_EQ(initial->GetBlock(), this);
710 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
711 DCHECK(initial->GetUses().IsEmpty());
712 DCHECK(initial->GetEnvUses().IsEmpty());
713 replacement->SetBlock(this);
714 replacement->SetId(GetGraph()->GetNextInstructionId());
715 instructions_.InsertInstructionBefore(replacement, initial);
716 UpdateInputsUsers(replacement);
717 } else {
718 InsertInstructionBefore(replacement, initial);
719 initial->ReplaceWith(replacement);
720 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100721 RemoveInstruction(initial);
722}
723
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100724static void Add(HInstructionList* instruction_list,
725 HBasicBlock* block,
726 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000727 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000728 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100729 instruction->SetBlock(block);
730 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100731 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100732 instruction_list->AddInstruction(instruction);
733}
734
735void HBasicBlock::AddInstruction(HInstruction* instruction) {
736 Add(&instructions_, this, instruction);
737}
738
739void HBasicBlock::AddPhi(HPhi* phi) {
740 Add(&phis_, this, phi);
741}
742
David Brazdilc3d743f2015-04-22 13:40:50 +0100743void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
744 DCHECK(!cursor->IsPhi());
745 DCHECK(!instruction->IsPhi());
746 DCHECK_EQ(instruction->GetId(), -1);
747 DCHECK_NE(cursor->GetId(), -1);
748 DCHECK_EQ(cursor->GetBlock(), this);
749 DCHECK(!instruction->IsControlFlow());
750 instruction->SetBlock(this);
751 instruction->SetId(GetGraph()->GetNextInstructionId());
752 UpdateInputsUsers(instruction);
753 instructions_.InsertInstructionBefore(instruction, cursor);
754}
755
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100756void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
757 DCHECK(!cursor->IsPhi());
758 DCHECK(!instruction->IsPhi());
759 DCHECK_EQ(instruction->GetId(), -1);
760 DCHECK_NE(cursor->GetId(), -1);
761 DCHECK_EQ(cursor->GetBlock(), this);
762 DCHECK(!instruction->IsControlFlow());
763 DCHECK(!cursor->IsControlFlow());
764 instruction->SetBlock(this);
765 instruction->SetId(GetGraph()->GetNextInstructionId());
766 UpdateInputsUsers(instruction);
767 instructions_.InsertInstructionAfter(instruction, cursor);
768}
769
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100770void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
771 DCHECK_EQ(phi->GetId(), -1);
772 DCHECK_NE(cursor->GetId(), -1);
773 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100774 phi->SetBlock(this);
775 phi->SetId(GetGraph()->GetNextInstructionId());
776 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100777 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100778}
779
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100780static void Remove(HInstructionList* instruction_list,
781 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000782 HInstruction* instruction,
783 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100784 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100785 instruction->SetBlock(nullptr);
786 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000787 if (ensure_safety) {
788 DCHECK(instruction->GetUses().IsEmpty());
789 DCHECK(instruction->GetEnvUses().IsEmpty());
790 RemoveAsUser(instruction);
791 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100792}
793
David Brazdil1abb4192015-02-17 18:33:36 +0000794void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100795 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000796 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100797}
798
David Brazdil1abb4192015-02-17 18:33:36 +0000799void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
800 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100801}
802
David Brazdilc7508e92015-04-27 13:28:57 +0100803void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
804 if (instruction->IsPhi()) {
805 RemovePhi(instruction->AsPhi(), ensure_safety);
806 } else {
807 RemoveInstruction(instruction, ensure_safety);
808 }
809}
810
Vladimir Marko71bf8092015-09-15 15:33:14 +0100811void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
812 for (size_t i = 0; i < locals.size(); i++) {
813 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100814 SetRawEnvAt(i, instruction);
815 if (instruction != nullptr) {
816 instruction->AddEnvUseAt(this, i);
817 }
818 }
819}
820
David Brazdiled596192015-01-23 10:39:45 +0000821void HEnvironment::CopyFrom(HEnvironment* env) {
822 for (size_t i = 0; i < env->Size(); i++) {
823 HInstruction* instruction = env->GetInstructionAt(i);
824 SetRawEnvAt(i, instruction);
825 if (instruction != nullptr) {
826 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100827 }
David Brazdiled596192015-01-23 10:39:45 +0000828 }
829}
830
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700831void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
832 HBasicBlock* loop_header) {
833 DCHECK(loop_header->IsLoopHeader());
834 for (size_t i = 0; i < env->Size(); i++) {
835 HInstruction* instruction = env->GetInstructionAt(i);
836 SetRawEnvAt(i, instruction);
837 if (instruction == nullptr) {
838 continue;
839 }
840 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
841 // At the end of the loop pre-header, the corresponding value for instruction
842 // is the first input of the phi.
843 HInstruction* initial = instruction->AsPhi()->InputAt(0);
844 DCHECK(initial->GetBlock()->Dominates(loop_header));
845 SetRawEnvAt(i, initial);
846 initial->AddEnvUseAt(this, i);
847 } else {
848 instruction->AddEnvUseAt(this, i);
849 }
850 }
851}
852
David Brazdil1abb4192015-02-17 18:33:36 +0000853void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100854 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000855 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100856}
857
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000858HInstruction::InstructionKind HInstruction::GetKind() const {
859 return GetKindInternal();
860}
861
Calin Juravle77520bc2015-01-12 18:45:46 +0000862HInstruction* HInstruction::GetNextDisregardingMoves() const {
863 HInstruction* next = GetNext();
864 while (next != nullptr && next->IsParallelMove()) {
865 next = next->GetNext();
866 }
867 return next;
868}
869
870HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
871 HInstruction* previous = GetPrevious();
872 while (previous != nullptr && previous->IsParallelMove()) {
873 previous = previous->GetPrevious();
874 }
875 return previous;
876}
877
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100878void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000879 if (first_instruction_ == nullptr) {
880 DCHECK(last_instruction_ == nullptr);
881 first_instruction_ = last_instruction_ = instruction;
882 } else {
883 last_instruction_->next_ = instruction;
884 instruction->previous_ = last_instruction_;
885 last_instruction_ = instruction;
886 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000887}
888
David Brazdilc3d743f2015-04-22 13:40:50 +0100889void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
890 DCHECK(Contains(cursor));
891 if (cursor == first_instruction_) {
892 cursor->previous_ = instruction;
893 instruction->next_ = cursor;
894 first_instruction_ = instruction;
895 } else {
896 instruction->previous_ = cursor->previous_;
897 instruction->next_ = cursor;
898 cursor->previous_ = instruction;
899 instruction->previous_->next_ = instruction;
900 }
901}
902
903void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
904 DCHECK(Contains(cursor));
905 if (cursor == last_instruction_) {
906 cursor->next_ = instruction;
907 instruction->previous_ = cursor;
908 last_instruction_ = instruction;
909 } else {
910 instruction->next_ = cursor->next_;
911 instruction->previous_ = cursor;
912 cursor->next_ = instruction;
913 instruction->next_->previous_ = instruction;
914 }
915}
916
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100917void HInstructionList::RemoveInstruction(HInstruction* instruction) {
918 if (instruction->previous_ != nullptr) {
919 instruction->previous_->next_ = instruction->next_;
920 }
921 if (instruction->next_ != nullptr) {
922 instruction->next_->previous_ = instruction->previous_;
923 }
924 if (instruction == first_instruction_) {
925 first_instruction_ = instruction->next_;
926 }
927 if (instruction == last_instruction_) {
928 last_instruction_ = instruction->previous_;
929 }
930}
931
Roland Levillain6b469232014-09-25 10:10:38 +0100932bool HInstructionList::Contains(HInstruction* instruction) const {
933 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
934 if (it.Current() == instruction) {
935 return true;
936 }
937 }
938 return false;
939}
940
Roland Levillainccc07a92014-09-16 14:48:16 +0100941bool HInstructionList::FoundBefore(const HInstruction* instruction1,
942 const HInstruction* instruction2) const {
943 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
944 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
945 if (it.Current() == instruction1) {
946 return true;
947 }
948 if (it.Current() == instruction2) {
949 return false;
950 }
951 }
952 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
953 return true;
954}
955
Roland Levillain6c82d402014-10-13 16:10:27 +0100956bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
957 if (other_instruction == this) {
958 // An instruction does not strictly dominate itself.
959 return false;
960 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100961 HBasicBlock* block = GetBlock();
962 HBasicBlock* other_block = other_instruction->GetBlock();
963 if (block != other_block) {
964 return GetBlock()->Dominates(other_instruction->GetBlock());
965 } else {
966 // If both instructions are in the same block, ensure this
967 // instruction comes before `other_instruction`.
968 if (IsPhi()) {
969 if (!other_instruction->IsPhi()) {
970 // Phis appear before non phi-instructions so this instruction
971 // dominates `other_instruction`.
972 return true;
973 } else {
974 // There is no order among phis.
975 LOG(FATAL) << "There is no dominance between phis of a same block.";
976 return false;
977 }
978 } else {
979 // `this` is not a phi.
980 if (other_instruction->IsPhi()) {
981 // Phis appear before non phi-instructions so this instruction
982 // does not dominate `other_instruction`.
983 return false;
984 } else {
985 // Check whether this instruction comes before
986 // `other_instruction` in the instruction list.
987 return block->GetInstructions().FoundBefore(this, other_instruction);
988 }
989 }
990 }
991}
992
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100993void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100994 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000995 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
996 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100997 HInstruction* user = current->GetUser();
998 size_t input_index = current->GetIndex();
999 user->SetRawInputAt(input_index, other);
1000 other->AddUseAt(user, input_index);
1001 }
1002
David Brazdiled596192015-01-23 10:39:45 +00001003 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1004 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001005 HEnvironment* user = current->GetUser();
1006 size_t input_index = current->GetIndex();
1007 user->SetRawEnvAt(input_index, other);
1008 other->AddEnvUseAt(user, input_index);
1009 }
1010
David Brazdiled596192015-01-23 10:39:45 +00001011 uses_.Clear();
1012 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001013}
1014
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001015void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001016 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001017 SetRawInputAt(index, replacement);
1018 replacement->AddUseAt(this, index);
1019}
1020
Nicolas Geoffray39468442014-09-02 15:17:15 +01001021size_t HInstruction::EnvironmentSize() const {
1022 return HasEnvironment() ? environment_->Size() : 0;
1023}
1024
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001025void HPhi::AddInput(HInstruction* input) {
1026 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001027 inputs_.push_back(HUserRecord<HInstruction*>(input));
1028 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001029}
1030
David Brazdil2d7352b2015-04-20 14:52:42 +01001031void HPhi::RemoveInputAt(size_t index) {
1032 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001033 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001034 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001035 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001036 InputRecordAt(i).GetUseNode()->SetIndex(i);
1037 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001038}
1039
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001040#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001041void H##name::Accept(HGraphVisitor* visitor) { \
1042 visitor->Visit##name(this); \
1043}
1044
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001045FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001046
1047#undef DEFINE_ACCEPT
1048
1049void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001050 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1051 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001052 if (block != nullptr) {
1053 VisitBasicBlock(block);
1054 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001055 }
1056}
1057
Roland Levillain633021e2014-10-01 14:12:25 +01001058void HGraphVisitor::VisitReversePostOrder() {
1059 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1060 VisitBasicBlock(it.Current());
1061 }
1062}
1063
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001064void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001065 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001066 it.Current()->Accept(this);
1067 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001068 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001069 it.Current()->Accept(this);
1070 }
1071}
1072
Mark Mendelle82549b2015-05-06 10:55:34 -04001073HConstant* HTypeConversion::TryStaticEvaluation() const {
1074 HGraph* graph = GetBlock()->GetGraph();
1075 if (GetInput()->IsIntConstant()) {
1076 int32_t value = GetInput()->AsIntConstant()->GetValue();
1077 switch (GetResultType()) {
1078 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001079 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001080 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001081 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001082 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001083 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001084 default:
1085 return nullptr;
1086 }
1087 } else if (GetInput()->IsLongConstant()) {
1088 int64_t value = GetInput()->AsLongConstant()->GetValue();
1089 switch (GetResultType()) {
1090 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001091 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001092 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001093 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001094 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001095 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001096 default:
1097 return nullptr;
1098 }
1099 } else if (GetInput()->IsFloatConstant()) {
1100 float value = GetInput()->AsFloatConstant()->GetValue();
1101 switch (GetResultType()) {
1102 case Primitive::kPrimInt:
1103 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001104 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001105 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001106 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001107 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001108 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1109 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001110 case Primitive::kPrimLong:
1111 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001112 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001113 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001114 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001115 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001116 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1117 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001118 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001119 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001120 default:
1121 return nullptr;
1122 }
1123 } else if (GetInput()->IsDoubleConstant()) {
1124 double value = GetInput()->AsDoubleConstant()->GetValue();
1125 switch (GetResultType()) {
1126 case Primitive::kPrimInt:
1127 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001129 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001131 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001132 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1133 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001134 case Primitive::kPrimLong:
1135 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001139 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001140 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1141 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001142 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001143 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001144 default:
1145 return nullptr;
1146 }
1147 }
1148 return nullptr;
1149}
1150
Roland Levillain9240d6a2014-10-20 16:47:04 +01001151HConstant* HUnaryOperation::TryStaticEvaluation() const {
1152 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001153 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001154 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001155 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001156 }
1157 return nullptr;
1158}
1159
1160HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001161 if (GetLeft()->IsIntConstant()) {
1162 if (GetRight()->IsIntConstant()) {
1163 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1164 } else if (GetRight()->IsLongConstant()) {
1165 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1166 }
1167 } else if (GetLeft()->IsLongConstant()) {
1168 if (GetRight()->IsIntConstant()) {
1169 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1170 } else if (GetRight()->IsLongConstant()) {
1171 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001172 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001173 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1174 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001175 }
1176 return nullptr;
1177}
Dave Allison20dfc792014-06-16 20:44:29 -07001178
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001179HConstant* HBinaryOperation::GetConstantRight() const {
1180 if (GetRight()->IsConstant()) {
1181 return GetRight()->AsConstant();
1182 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1183 return GetLeft()->AsConstant();
1184 } else {
1185 return nullptr;
1186 }
1187}
1188
1189// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001190// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001191HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1192 HInstruction* most_constant_right = GetConstantRight();
1193 if (most_constant_right == nullptr) {
1194 return nullptr;
1195 } else if (most_constant_right == GetLeft()) {
1196 return GetRight();
1197 } else {
1198 return GetLeft();
1199 }
1200}
1201
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001202bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1203 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001204}
1205
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001206bool HInstruction::Equals(HInstruction* other) const {
1207 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001208 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001209 if (!InstructionDataEquals(other)) return false;
1210 if (GetType() != other->GetType()) return false;
1211 if (InputCount() != other->InputCount()) return false;
1212
1213 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1214 if (InputAt(i) != other->InputAt(i)) return false;
1215 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001216 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001217 return true;
1218}
1219
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001220std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1221#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1222 switch (rhs) {
1223 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1224 default:
1225 os << "Unknown instruction kind " << static_cast<int>(rhs);
1226 break;
1227 }
1228#undef DECLARE_CASE
1229 return os;
1230}
1231
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001232void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001233 next_->previous_ = previous_;
1234 if (previous_ != nullptr) {
1235 previous_->next_ = next_;
1236 }
1237 if (block_->instructions_.first_instruction_ == this) {
1238 block_->instructions_.first_instruction_ = next_;
1239 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001240 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001241
1242 previous_ = cursor->previous_;
1243 if (previous_ != nullptr) {
1244 previous_->next_ = this;
1245 }
1246 next_ = cursor;
1247 cursor->previous_ = this;
1248 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001249
1250 if (block_->instructions_.first_instruction_ == cursor) {
1251 block_->instructions_.first_instruction_ = this;
1252 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001253}
1254
Vladimir Markofb337ea2015-11-25 15:25:10 +00001255void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1256 DCHECK(!CanThrow());
1257 DCHECK(!HasSideEffects());
1258 DCHECK(!HasEnvironmentUses());
1259 DCHECK(HasNonEnvironmentUses());
1260 DCHECK(!IsPhi()); // Makes no sense for Phi.
1261 DCHECK_EQ(InputCount(), 0u);
1262
1263 // Find the target block.
1264 HUseIterator<HInstruction*> uses_it(GetUses());
1265 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1266 uses_it.Advance();
1267 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1268 uses_it.Advance();
1269 }
1270 if (!uses_it.Done()) {
1271 // This instruction has uses in two or more blocks. Find the common dominator.
1272 CommonDominator finder(target_block);
1273 for (; !uses_it.Done(); uses_it.Advance()) {
1274 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1275 }
1276 target_block = finder.Get();
1277 DCHECK(target_block != nullptr);
1278 }
1279 // Move to the first dominator not in a loop.
1280 while (target_block->IsInLoop()) {
1281 target_block = target_block->GetDominator();
1282 DCHECK(target_block != nullptr);
1283 }
1284
1285 // Find insertion position.
1286 HInstruction* insert_pos = nullptr;
1287 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1288 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1289 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1290 insert_pos = uses_it2.Current()->GetUser();
1291 }
1292 }
1293 if (insert_pos == nullptr) {
1294 // No user in `target_block`, insert before the control flow instruction.
1295 insert_pos = target_block->GetLastInstruction();
1296 DCHECK(insert_pos->IsControlFlow());
1297 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1298 if (insert_pos->IsIf()) {
1299 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1300 if (if_input == insert_pos->GetPrevious()) {
1301 insert_pos = if_input;
1302 }
1303 }
1304 }
1305 MoveBefore(insert_pos);
1306}
1307
David Brazdilfc6a86a2015-06-26 10:33:45 +00001308HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001309 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001310 DCHECK_EQ(cursor->GetBlock(), this);
1311
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001312 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1313 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001314 new_block->instructions_.first_instruction_ = cursor;
1315 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1316 instructions_.last_instruction_ = cursor->previous_;
1317 if (cursor->previous_ == nullptr) {
1318 instructions_.first_instruction_ = nullptr;
1319 } else {
1320 cursor->previous_->next_ = nullptr;
1321 cursor->previous_ = nullptr;
1322 }
1323
1324 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001325 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001326
Vladimir Marko60584552015-09-03 13:35:12 +00001327 for (HBasicBlock* successor : GetSuccessors()) {
1328 new_block->successors_.push_back(successor);
1329 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001330 }
Vladimir Marko60584552015-09-03 13:35:12 +00001331 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001332 AddSuccessor(new_block);
1333
David Brazdil56e1acc2015-06-30 15:41:36 +01001334 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001335 return new_block;
1336}
1337
David Brazdild7558da2015-09-22 13:04:14 +01001338HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001339 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001340 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1341
1342 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1343
1344 for (HBasicBlock* predecessor : GetPredecessors()) {
1345 new_block->predecessors_.push_back(predecessor);
1346 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1347 }
1348 predecessors_.clear();
1349 AddPredecessor(new_block);
1350
1351 GetGraph()->AddBlock(new_block);
1352 return new_block;
1353}
1354
David Brazdil9bc43612015-11-05 21:25:24 +00001355HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1356 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1357 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1358
1359 HInstruction* first_insn = GetFirstInstruction();
1360 HInstruction* split_before = nullptr;
1361
1362 if (first_insn != nullptr && first_insn->IsLoadException()) {
1363 // Catch block starts with a LoadException. Split the block after
1364 // the StoreLocal and ClearException which must come after the load.
1365 DCHECK(first_insn->GetNext()->IsStoreLocal());
1366 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1367 split_before = first_insn->GetNext()->GetNext()->GetNext();
1368 } else {
1369 // Catch block does not load the exception. Split at the beginning
1370 // to create an empty catch block.
1371 split_before = first_insn;
1372 }
1373
1374 if (split_before == nullptr) {
1375 // Catch block has no instructions after the split point (must be dead).
1376 // Do not split it but rather signal error by returning nullptr.
1377 return nullptr;
1378 } else {
1379 return SplitBefore(split_before);
1380 }
1381}
1382
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001383HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1384 DCHECK(!cursor->IsControlFlow());
1385 DCHECK_NE(instructions_.last_instruction_, cursor);
1386 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001387
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001388 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1389 new_block->instructions_.first_instruction_ = cursor->GetNext();
1390 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1391 cursor->next_->previous_ = nullptr;
1392 cursor->next_ = nullptr;
1393 instructions_.last_instruction_ = cursor;
1394
1395 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001396 for (HBasicBlock* successor : GetSuccessors()) {
1397 new_block->successors_.push_back(successor);
1398 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001399 }
Vladimir Marko60584552015-09-03 13:35:12 +00001400 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001401
Vladimir Marko60584552015-09-03 13:35:12 +00001402 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001403 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001404 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 }
Vladimir Marko60584552015-09-03 13:35:12 +00001406 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001407 return new_block;
1408}
1409
David Brazdilec16f792015-08-19 15:04:01 +01001410const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001411 if (EndsWithTryBoundary()) {
1412 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1413 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001414 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001415 return try_boundary;
1416 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001417 DCHECK(IsTryBlock());
1418 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001419 return nullptr;
1420 }
David Brazdilec16f792015-08-19 15:04:01 +01001421 } else if (IsTryBlock()) {
1422 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001423 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001424 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001425 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001426}
1427
David Brazdild7558da2015-09-22 13:04:14 +01001428bool HBasicBlock::HasThrowingInstructions() const {
1429 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1430 if (it.Current()->CanThrow()) {
1431 return true;
1432 }
1433 }
1434 return false;
1435}
1436
David Brazdilfc6a86a2015-06-26 10:33:45 +00001437static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1438 return block.GetPhis().IsEmpty()
1439 && !block.GetInstructions().IsEmpty()
1440 && block.GetFirstInstruction() == block.GetLastInstruction();
1441}
1442
David Brazdil46e2a392015-03-16 17:31:52 +00001443bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001444 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1445}
1446
1447bool HBasicBlock::IsSingleTryBoundary() const {
1448 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001449}
1450
David Brazdil8d5b8b22015-03-24 10:51:52 +00001451bool HBasicBlock::EndsWithControlFlowInstruction() const {
1452 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1453}
1454
David Brazdilb2bd1c52015-03-25 11:17:37 +00001455bool HBasicBlock::EndsWithIf() const {
1456 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1457}
1458
David Brazdilffee3d32015-07-06 11:48:53 +01001459bool HBasicBlock::EndsWithTryBoundary() const {
1460 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1461}
1462
David Brazdilb2bd1c52015-03-25 11:17:37 +00001463bool HBasicBlock::HasSinglePhi() const {
1464 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1465}
1466
David Brazdild26a4112015-11-10 11:07:31 +00001467ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1468 if (EndsWithTryBoundary()) {
1469 // The normal-flow successor of HTryBoundary is always stored at index zero.
1470 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1471 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1472 } else {
1473 // All successors of blocks not ending with TryBoundary are normal.
1474 return ArrayRef<HBasicBlock* const>(successors_);
1475 }
1476}
1477
1478ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1479 if (EndsWithTryBoundary()) {
1480 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1481 } else {
1482 // Blocks not ending with TryBoundary do not have exceptional successors.
1483 return ArrayRef<HBasicBlock* const>();
1484 }
1485}
1486
David Brazdilffee3d32015-07-06 11:48:53 +01001487bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001488 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1489 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1490
1491 size_t length = handlers1.size();
1492 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001493 return false;
1494 }
1495
David Brazdilb618ade2015-07-29 10:31:29 +01001496 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001497 for (size_t i = 0; i < length; ++i) {
1498 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001499 return false;
1500 }
1501 }
1502 return true;
1503}
1504
David Brazdil2d7352b2015-04-20 14:52:42 +01001505size_t HInstructionList::CountSize() const {
1506 size_t size = 0;
1507 HInstruction* current = first_instruction_;
1508 for (; current != nullptr; current = current->GetNext()) {
1509 size++;
1510 }
1511 return size;
1512}
1513
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001514void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1515 for (HInstruction* current = first_instruction_;
1516 current != nullptr;
1517 current = current->GetNext()) {
1518 current->SetBlock(block);
1519 }
1520}
1521
1522void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1523 DCHECK(Contains(cursor));
1524 if (!instruction_list.IsEmpty()) {
1525 if (cursor == last_instruction_) {
1526 last_instruction_ = instruction_list.last_instruction_;
1527 } else {
1528 cursor->next_->previous_ = instruction_list.last_instruction_;
1529 }
1530 instruction_list.last_instruction_->next_ = cursor->next_;
1531 cursor->next_ = instruction_list.first_instruction_;
1532 instruction_list.first_instruction_->previous_ = cursor;
1533 }
1534}
1535
1536void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001537 if (IsEmpty()) {
1538 first_instruction_ = instruction_list.first_instruction_;
1539 last_instruction_ = instruction_list.last_instruction_;
1540 } else {
1541 AddAfter(last_instruction_, instruction_list);
1542 }
1543}
1544
David Brazdil04ff4e82015-12-10 13:54:52 +00001545// Should be called on instructions in a dead block in post order. This method
1546// assumes `insn` has been removed from all users with the exception of catch
1547// phis because of missing exceptional edges in the graph. It removes the
1548// instruction from catch phi uses, together with inputs of other catch phis in
1549// the catch block at the same index, as these must be dead too.
1550static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1551 DCHECK(!insn->HasEnvironmentUses());
1552 while (insn->HasNonEnvironmentUses()) {
1553 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1554 size_t use_index = use->GetIndex();
1555 HBasicBlock* user_block = use->GetUser()->GetBlock();
1556 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1557 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1558 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1559 }
1560 }
1561}
1562
David Brazdil2d7352b2015-04-20 14:52:42 +01001563void HBasicBlock::DisconnectAndDelete() {
1564 // Dominators must be removed after all the blocks they dominate. This way
1565 // a loop header is removed last, a requirement for correct loop information
1566 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001567 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001568
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001569 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001570 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1571 HLoopInformation* loop_info = it.Current();
1572 loop_info->Remove(this);
1573 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001574 // If this was the last back edge of the loop, we deliberately leave the
1575 // loop in an inconsistent state and will fail SSAChecker unless the
1576 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001577 loop_info->RemoveBackEdge(this);
1578 }
1579 }
1580
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001581 // (2) Disconnect the block from its predecessors and update their
1582 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001583 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001584 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001585 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1586 // This block is the only normal-flow successor of the TryBoundary which
1587 // makes `predecessor` dead. Since DCE removes blocks in post order,
1588 // exception handlers of this TryBoundary were already visited and any
1589 // remaining handlers therefore must be live. We remove `predecessor` from
1590 // their list of predecessors.
1591 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1592 while (predecessor->GetSuccessors().size() > 1) {
1593 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1594 DCHECK(handler->IsCatchBlock());
1595 predecessor->RemoveSuccessor(handler);
1596 handler->RemovePredecessor(predecessor);
1597 }
1598 }
1599
David Brazdil2d7352b2015-04-20 14:52:42 +01001600 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001601 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1602 if (num_pred_successors == 1u) {
1603 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001604 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1605 // successor. Replace those with a HGoto.
1606 DCHECK(last_instruction->IsIf() ||
1607 last_instruction->IsPackedSwitch() ||
1608 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001609 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001610 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001611 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001612 // The predecessor has no remaining successors and therefore must be dead.
1613 // We deliberately leave it without a control-flow instruction so that the
1614 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001615 predecessor->RemoveInstruction(last_instruction);
1616 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001617 // There are multiple successors left. The removed block might be a successor
1618 // of a PackedSwitch which will be completely removed (perhaps replaced with
1619 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1620 // case, leave `last_instruction` as is for now.
1621 DCHECK(last_instruction->IsPackedSwitch() ||
1622 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001623 }
David Brazdil46e2a392015-03-16 17:31:52 +00001624 }
Vladimir Marko60584552015-09-03 13:35:12 +00001625 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001626
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001627 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001628 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001629 // Delete this block from the list of predecessors.
1630 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001631 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001632
1633 // Check that `successor` has other predecessors, otherwise `this` is the
1634 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001635 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001636
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001637 // Remove this block's entries in the successor's phis. Skip exceptional
1638 // successors because catch phi inputs do not correspond to predecessor
1639 // blocks but throwing instructions. Their inputs will be updated in step (4).
1640 if (!successor->IsCatchBlock()) {
1641 if (successor->predecessors_.size() == 1u) {
1642 // The successor has just one predecessor left. Replace phis with the only
1643 // remaining input.
1644 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1645 HPhi* phi = phi_it.Current()->AsPhi();
1646 phi->ReplaceWith(phi->InputAt(1 - this_index));
1647 successor->RemovePhi(phi);
1648 }
1649 } else {
1650 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1651 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1652 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001653 }
1654 }
1655 }
Vladimir Marko60584552015-09-03 13:35:12 +00001656 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001657
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001658 // (4) Remove instructions and phis. Instructions should have no remaining uses
1659 // except in catch phis. If an instruction is used by a catch phi at `index`,
1660 // remove `index`-th input of all phis in the catch block since they are
1661 // guaranteed dead. Note that we may miss dead inputs this way but the
1662 // graph will always remain consistent.
1663 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1664 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001665 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001666 RemoveInstruction(insn);
1667 }
1668 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001669 HPhi* insn = it.Current()->AsPhi();
1670 RemoveUsesOfDeadInstruction(insn);
1671 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001672 }
1673
David Brazdil2d7352b2015-04-20 14:52:42 +01001674 // Disconnect from the dominator.
1675 dominator_->RemoveDominatedBlock(this);
1676 SetDominator(nullptr);
1677
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001678 // Delete from the graph, update reverse post order.
1679 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001680 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001681}
1682
1683void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001684 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001685 DCHECK(ContainsElement(dominated_blocks_, other));
1686 DCHECK_EQ(GetSingleSuccessor(), other);
1687 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001688 DCHECK(other->GetPhis().IsEmpty());
1689
David Brazdil2d7352b2015-04-20 14:52:42 +01001690 // Move instructions from `other` to `this`.
1691 DCHECK(EndsWithControlFlowInstruction());
1692 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001693 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001694 other->instructions_.SetBlockOfInstructions(this);
1695 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001696
David Brazdil2d7352b2015-04-20 14:52:42 +01001697 // Remove `other` from the loops it is included in.
1698 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1699 HLoopInformation* loop_info = it.Current();
1700 loop_info->Remove(other);
1701 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001702 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001703 }
1704 }
1705
1706 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001707 successors_.clear();
1708 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001709 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001710 successor->ReplacePredecessor(other, this);
1711 }
1712
David Brazdil2d7352b2015-04-20 14:52:42 +01001713 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001714 RemoveDominatedBlock(other);
1715 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1716 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001717 dominated->SetDominator(this);
1718 }
Vladimir Marko60584552015-09-03 13:35:12 +00001719 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001720 other->dominator_ = nullptr;
1721
1722 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001723 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001724
1725 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001726 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001727 other->SetGraph(nullptr);
1728}
1729
1730void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1731 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001732 DCHECK(GetDominatedBlocks().empty());
1733 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001734 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001735 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001736 DCHECK(other->GetPhis().IsEmpty());
1737 DCHECK(!other->IsInLoop());
1738
1739 // Move instructions from `other` to `this`.
1740 instructions_.Add(other->GetInstructions());
1741 other->instructions_.SetBlockOfInstructions(this);
1742
1743 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001744 successors_.clear();
1745 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001746 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001747 successor->ReplacePredecessor(other, this);
1748 }
1749
1750 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001751 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1752 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001753 dominated->SetDominator(this);
1754 }
Vladimir Marko60584552015-09-03 13:35:12 +00001755 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001756 other->dominator_ = nullptr;
1757 other->graph_ = nullptr;
1758}
1759
1760void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001761 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001762 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001763 predecessor->ReplaceSuccessor(this, other);
1764 }
Vladimir Marko60584552015-09-03 13:35:12 +00001765 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001766 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001767 successor->ReplacePredecessor(this, other);
1768 }
Vladimir Marko60584552015-09-03 13:35:12 +00001769 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1770 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001771 }
1772 GetDominator()->ReplaceDominatedBlock(this, other);
1773 other->SetDominator(GetDominator());
1774 dominator_ = nullptr;
1775 graph_ = nullptr;
1776}
1777
1778// Create space in `blocks` for adding `number_of_new_blocks` entries
1779// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001780static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001781 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001782 size_t after) {
1783 DCHECK_LT(after, blocks->size());
1784 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001785 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001786 blocks->resize(new_size);
1787 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001788}
1789
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001790void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001791 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001792 DCHECK(block->GetSuccessors().empty());
1793 DCHECK(block->GetPredecessors().empty());
1794 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001795 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001796 DCHECK(block->GetInstructions().IsEmpty());
1797 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001798
David Brazdilc7af85d2015-05-26 12:05:55 +01001799 if (block->IsExitBlock()) {
1800 exit_block_ = nullptr;
1801 }
1802
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001803 RemoveElement(reverse_post_order_, block);
1804 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001805}
1806
Calin Juravle2e768302015-07-28 14:41:11 +00001807HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001808 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001809 // Update the environments in this graph to have the invoke's environment
1810 // as parent.
1811 {
1812 HReversePostOrderIterator it(*this);
1813 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1814 for (; !it.Done(); it.Advance()) {
1815 HBasicBlock* block = it.Current();
1816 for (HInstructionIterator instr_it(block->GetInstructions());
1817 !instr_it.Done();
1818 instr_it.Advance()) {
1819 HInstruction* current = instr_it.Current();
1820 if (current->NeedsEnvironment()) {
1821 current->GetEnvironment()->SetAndCopyParentChain(
1822 outer_graph->GetArena(), invoke->GetEnvironment());
1823 }
1824 }
1825 }
1826 }
1827 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1828 if (HasBoundsChecks()) {
1829 outer_graph->SetHasBoundsChecks(true);
1830 }
1831
Calin Juravle2e768302015-07-28 14:41:11 +00001832 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001833 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001834 // Simple case of an entry block, a body block, and an exit block.
1835 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001836 HBasicBlock* body = GetBlocks()[1];
1837 DCHECK(GetBlocks()[0]->IsEntryBlock());
1838 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001839 DCHECK(!body->IsExitBlock());
1840 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001841
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001842 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1843 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001844
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001845 // Replace the invoke with the return value of the inlined graph.
1846 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001847 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001848 } else {
1849 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001850 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001851
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001852 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001853 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001854 // Need to inline multiple blocks. We split `invoke`'s block
1855 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001856 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001857 // with the second half.
1858 ArenaAllocator* allocator = outer_graph->GetArena();
1859 HBasicBlock* at = invoke->GetBlock();
1860 HBasicBlock* to = at->SplitAfter(invoke);
1861
Vladimir Markoec7802a2015-10-01 20:57:57 +01001862 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001863 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001864 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001865 exit_block_->ReplaceWith(to);
1866
1867 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001868 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001869 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001870 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001871 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001872 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001873 if (!returns_void) {
1874 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001875 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001876 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001877 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001878 } else {
1879 if (!returns_void) {
1880 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001881 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001882 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001883 to->AddPhi(return_value->AsPhi());
1884 }
Vladimir Marko60584552015-09-03 13:35:12 +00001885 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001886 HInstruction* last = predecessor->GetLastInstruction();
1887 if (!returns_void) {
1888 return_value->AsPhi()->AddInput(last->InputAt(0));
1889 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001890 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001891 predecessor->RemoveInstruction(last);
1892 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 }
1894
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 // Update the meta information surrounding blocks:
1896 // (1) the graph they are now in,
1897 // (2) the reverse post order of that graph,
Andreas Gampe451ad8d2016-01-20 21:23:30 +00001898 // (3) the potential loop information they are now in,
David Brazdil95177982015-10-30 12:56:58 -05001899 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001900 // Note that we do not need to update catch phi inputs because they
1901 // correspond to the register file of the outer method which the inlinee
1902 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903
1904 // We don't add the entry block, the exit block, and the first block, which
1905 // has been merged with `at`.
1906 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1907
1908 // We add the `to` block.
1909 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001910 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001911 + kNumberOfNewBlocksInCaller;
1912
1913 // Find the location of `at` in the outer graph's reverse post order. The new
1914 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001915 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1917
David Brazdil95177982015-10-30 12:56:58 -05001918 HLoopInformation* loop_info = at->GetLoopInformation();
1919 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1920 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1921
1922 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1923 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001924 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1925 HBasicBlock* current = it.Current();
1926 if (current != exit_block_ && current != entry_block_ && current != first) {
Andreas Gampe451ad8d2016-01-20 21:23:30 +00001927 DCHECK(!current->IsInLoop());
David Brazdil95177982015-10-30 12:56:58 -05001928 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001929 DCHECK(current->GetGraph() == this);
1930 current->SetGraph(outer_graph);
1931 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001932 outer_graph->reverse_post_order_[++index_of_at] = current;
Andreas Gampe451ad8d2016-01-20 21:23:30 +00001933 if (loop_info != nullptr) {
David Brazdil95177982015-10-30 12:56:58 -05001934 current->SetLoopInformation(loop_info);
Andreas Gampe451ad8d2016-01-20 21:23:30 +00001935 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001936 loop_it.Current()->Add(current);
1937 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001938 }
David Brazdil95177982015-10-30 12:56:58 -05001939 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001940 }
1941 }
1942
David Brazdil95177982015-10-30 12:56:58 -05001943 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001944 to->SetGraph(outer_graph);
1945 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001946 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001947 if (loop_info != nullptr) {
Andreas Gampe451ad8d2016-01-20 21:23:30 +00001948 to->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001949 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1950 loop_it.Current()->Add(to);
1951 }
David Brazdil95177982015-10-30 12:56:58 -05001952 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001953 // Only `to` can become a back edge, as the inlined blocks
1954 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001955 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001956 }
1957 }
David Brazdil95177982015-10-30 12:56:58 -05001958 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001959 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001960
David Brazdil05144f42015-04-16 15:18:00 +01001961 // Update the next instruction id of the outer graph, so that instructions
1962 // added later get bigger ids than those in the inner graph.
1963 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1964
1965 // Walk over the entry block and:
1966 // - Move constants from the entry block to the outer_graph's entry block,
1967 // - Replace HParameterValue instructions with their real value.
1968 // - Remove suspend checks, that hold an environment.
1969 // We must do this after the other blocks have been inlined, otherwise ids of
1970 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001971 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001972 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1973 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001974 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001975 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001976 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001977 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001978 replacement = outer_graph->GetIntConstant(
1979 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001980 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001981 replacement = outer_graph->GetLongConstant(
1982 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001983 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001984 replacement = outer_graph->GetFloatConstant(
1985 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001986 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001987 replacement = outer_graph->GetDoubleConstant(
1988 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001989 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001990 if (kIsDebugBuild
1991 && invoke->IsInvokeStaticOrDirect()
1992 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1993 // Ensure we do not use the last input of `invoke`, as it
1994 // contains a clinit check which is not an actual argument.
1995 size_t last_input_index = invoke->InputCount() - 1;
1996 DCHECK(parameter_index != last_input_index);
1997 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001998 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001999 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002000 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002001 } else {
2002 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2003 entry_block_->RemoveInstruction(current);
2004 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002005 if (replacement != nullptr) {
2006 current->ReplaceWith(replacement);
2007 // If the current is the return value then we need to update the latter.
2008 if (current == return_value) {
2009 DCHECK_EQ(entry_block_, return_value->GetBlock());
2010 return_value = replacement;
2011 }
2012 }
2013 }
2014
2015 if (return_value != nullptr) {
2016 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002017 }
2018
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002019 // Finally remove the invoke from the caller.
2020 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002021
2022 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002023}
2024
Mingyao Yang3584bce2015-05-19 16:01:59 -07002025/*
2026 * Loop will be transformed to:
2027 * old_pre_header
2028 * |
2029 * if_block
2030 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002031 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002032 * \ /
2033 * new_pre_header
2034 * |
2035 * header
2036 */
2037void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2038 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002039 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002040
Aart Bik3fc7f352015-11-20 22:03:03 -08002041 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002042 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002043 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2044 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002045 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2046 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002047 AddBlock(true_block);
2048 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002049 AddBlock(new_pre_header);
2050
Aart Bik3fc7f352015-11-20 22:03:03 -08002051 header->ReplacePredecessor(old_pre_header, new_pre_header);
2052 old_pre_header->successors_.clear();
2053 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002054
Aart Bik3fc7f352015-11-20 22:03:03 -08002055 old_pre_header->AddSuccessor(if_block);
2056 if_block->AddSuccessor(true_block); // True successor
2057 if_block->AddSuccessor(false_block); // False successor
2058 true_block->AddSuccessor(new_pre_header);
2059 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002060
Aart Bik3fc7f352015-11-20 22:03:03 -08002061 old_pre_header->dominated_blocks_.push_back(if_block);
2062 if_block->SetDominator(old_pre_header);
2063 if_block->dominated_blocks_.push_back(true_block);
2064 true_block->SetDominator(if_block);
2065 if_block->dominated_blocks_.push_back(false_block);
2066 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002067 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002068 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002069 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002070 header->SetDominator(new_pre_header);
2071
Aart Bik3fc7f352015-11-20 22:03:03 -08002072 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002073 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002074 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002075 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002076 reverse_post_order_[index_of_header++] = true_block;
2077 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002078 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002079
Aart Bik3fc7f352015-11-20 22:03:03 -08002080 // Fix loop information.
2081 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2082 if (loop_info != nullptr) {
2083 if_block->SetLoopInformation(loop_info);
2084 true_block->SetLoopInformation(loop_info);
2085 false_block->SetLoopInformation(loop_info);
2086 new_pre_header->SetLoopInformation(loop_info);
2087 // Add blocks to all enveloping loops.
2088 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002089 !loop_it.Done();
2090 loop_it.Advance()) {
2091 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002092 loop_it.Current()->Add(true_block);
2093 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002094 loop_it.Current()->Add(new_pre_header);
2095 }
2096 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002097
2098 // Fix try/catch information.
2099 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2100 ? old_pre_header->GetTryCatchInformation()
2101 : nullptr;
2102 if_block->SetTryCatchInformation(try_catch_info);
2103 true_block->SetTryCatchInformation(try_catch_info);
2104 false_block->SetTryCatchInformation(try_catch_info);
2105 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002106}
2107
David Brazdilf5552582015-12-27 13:36:12 +00002108static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2109 SHARED_REQUIRES(Locks::mutator_lock_) {
2110 if (rti.IsValid()) {
2111 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2112 << " upper_bound_rti: " << upper_bound_rti
2113 << " rti: " << rti;
2114 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2115 }
2116}
2117
Calin Juravle2e768302015-07-28 14:41:11 +00002118void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2119 if (kIsDebugBuild) {
2120 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2121 ScopedObjectAccess soa(Thread::Current());
2122 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2123 if (IsBoundType()) {
2124 // Having the test here spares us from making the method virtual just for
2125 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002126 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002127 }
2128 }
2129 reference_type_info_ = rti;
2130}
2131
David Brazdilf5552582015-12-27 13:36:12 +00002132void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2133 if (kIsDebugBuild) {
2134 ScopedObjectAccess soa(Thread::Current());
2135 DCHECK(upper_bound.IsValid());
2136 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2137 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2138 }
2139 upper_bound_ = upper_bound;
2140 upper_can_be_null_ = can_be_null;
2141}
2142
Calin Juravle2e768302015-07-28 14:41:11 +00002143ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2144
2145ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2146 : type_handle_(type_handle), is_exact_(is_exact) {
2147 if (kIsDebugBuild) {
2148 ScopedObjectAccess soa(Thread::Current());
2149 DCHECK(IsValidHandle(type_handle));
2150 }
2151}
2152
Calin Juravleacf735c2015-02-12 15:25:22 +00002153std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2154 ScopedObjectAccess soa(Thread::Current());
2155 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002156 << " is_valid=" << rhs.IsValid()
2157 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002158 << " is_exact=" << rhs.IsExact()
2159 << " ]";
2160 return os;
2161}
2162
Mark Mendellc4701932015-04-10 13:18:51 -04002163bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2164 // For now, assume that instructions in different blocks may use the
2165 // environment.
2166 // TODO: Use the control flow to decide if this is true.
2167 if (GetBlock() != other->GetBlock()) {
2168 return true;
2169 }
2170
2171 // We know that we are in the same block. Walk from 'this' to 'other',
2172 // checking to see if there is any instruction with an environment.
2173 HInstruction* current = this;
2174 for (; current != other && current != nullptr; current = current->GetNext()) {
2175 // This is a conservative check, as the instruction result may not be in
2176 // the referenced environment.
2177 if (current->HasEnvironment()) {
2178 return true;
2179 }
2180 }
2181
2182 // We should have been called with 'this' before 'other' in the block.
2183 // Just confirm this.
2184 DCHECK(current != nullptr);
2185 return false;
2186}
2187
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002188void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002189 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2190 IntrinsicSideEffects side_effects,
2191 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002192 intrinsic_ = intrinsic;
2193 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002194
Aart Bik5d75afe2015-12-14 11:57:01 -08002195 // Adjust method's side effects from intrinsic table.
2196 switch (side_effects) {
2197 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2198 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2199 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2200 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2201 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002202
2203 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2204 opt.SetDoesNotNeedDexCache();
2205 opt.SetDoesNotNeedEnvironment();
2206 } else {
2207 // If we need an environment, that means there will be a call, which can trigger GC.
2208 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2209 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002210 // Adjust method's exception status from intrinsic table.
Nicolas Geoffray69fd1b52016-01-22 10:43:39 +00002211 switch (exceptions) {
2212 case kNoThrow: SetCanThrow(false); break;
2213 case kCanThrow: SetCanThrow(true); break;
2214 }
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002215}
2216
David Brazdil6de19382016-01-08 17:37:10 +00002217bool HNewInstance::IsStringAlloc() const {
2218 ScopedObjectAccess soa(Thread::Current());
2219 return GetReferenceTypeInfo().IsStringClass();
2220}
2221
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002222bool HInvoke::NeedsEnvironment() const {
2223 if (!IsIntrinsic()) {
2224 return true;
2225 }
2226 IntrinsicOptimizations opt(*this);
2227 return !opt.GetDoesNotNeedEnvironment();
2228}
2229
Vladimir Markodc151b22015-10-15 18:02:30 +01002230bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2231 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002232 return false;
2233 }
2234 if (!IsIntrinsic()) {
2235 return true;
2236 }
2237 IntrinsicOptimizations opt(*this);
2238 return !opt.GetDoesNotNeedDexCache();
2239}
2240
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002241void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2242 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2243 input->AddUseAt(this, index);
2244 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2245 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2246 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2247 InputRecordAt(i).GetUseNode()->SetIndex(i);
2248 }
2249}
2250
Vladimir Markob554b5a2015-11-06 12:57:55 +00002251void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2252 RemoveAsUserOfInput(index);
2253 inputs_.erase(inputs_.begin() + index);
2254 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2255 for (size_t i = index, e = InputCount(); i < e; ++i) {
2256 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2257 InputRecordAt(i).GetUseNode()->SetIndex(i);
2258 }
2259}
2260
Vladimir Markof64242a2015-12-01 14:58:23 +00002261std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2262 switch (rhs) {
2263 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2264 return os << "string_init";
2265 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2266 return os << "recursive";
2267 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2268 return os << "direct";
2269 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2270 return os << "direct_fixup";
2271 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2272 return os << "dex_cache_pc_relative";
2273 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2274 return os << "dex_cache_via_method";
2275 default:
2276 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2277 UNREACHABLE();
2278 }
2279}
2280
Vladimir Markofbb184a2015-11-13 14:47:00 +00002281std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2282 switch (rhs) {
2283 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2284 return os << "explicit";
2285 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2286 return os << "implicit";
2287 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2288 return os << "none";
2289 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002290 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2291 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002292 }
2293}
2294
Mark Mendellc4701932015-04-10 13:18:51 -04002295void HInstruction::RemoveEnvironmentUsers() {
2296 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2297 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2298 HEnvironment* user = user_node->GetUser();
2299 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2300 }
2301 env_uses_.Clear();
2302}
2303
Mark Mendellf6529172015-11-17 11:16:56 -05002304// Returns an instruction with the opposite boolean value from 'cond'.
2305HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2306 ArenaAllocator* allocator = GetArena();
2307
2308 if (cond->IsCondition() &&
2309 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2310 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2311 HInstruction* lhs = cond->InputAt(0);
2312 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002313 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002314 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2315 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2316 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2317 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2318 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2319 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2320 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2321 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2322 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2323 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2324 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002325 default:
2326 LOG(FATAL) << "Unexpected condition";
2327 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002328 }
2329 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2330 return replacement;
2331 } else if (cond->IsIntConstant()) {
2332 HIntConstant* int_const = cond->AsIntConstant();
2333 if (int_const->IsZero()) {
2334 return GetIntConstant(1);
2335 } else {
2336 DCHECK(int_const->IsOne());
2337 return GetIntConstant(0);
2338 }
2339 } else {
2340 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2341 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2342 return replacement;
2343 }
2344}
2345
Roland Levillainc9285912015-12-18 10:38:42 +00002346std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2347 os << "["
2348 << " source=" << rhs.GetSource()
2349 << " destination=" << rhs.GetDestination()
2350 << " type=" << rhs.GetType()
2351 << " instruction=";
2352 if (rhs.GetInstruction() != nullptr) {
2353 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2354 } else {
2355 os << "null";
2356 }
2357 os << " ]";
2358 return os;
2359}
2360
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002361} // namespace art