blob: ca66f631a61a53673bc8d18f5feda2de93374747 [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
David Brazdilbadd8262016-02-02 16:28:56 +000030void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
31 ScopedObjectAccess soa(Thread::Current());
32 // Create the inexact Object reference type and store it in the HGraph.
33 ClassLinker* linker = Runtime::Current()->GetClassLinker();
34 inexact_object_rti_ = ReferenceTypeInfo::Create(
35 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
36 /* is_exact */ false);
37}
38
Nicolas Geoffray818f2102014-02-18 16:43:35 +000039void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010040 block->SetBlockId(blocks_.size());
41 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000042}
43
Nicolas Geoffray804d0932014-05-02 08:46:00 +010044void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010045 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
46 DCHECK_EQ(visited->GetHighestBitSet(), -1);
47
48 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010049 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010050 // Number of successors visited from a given node, indexed by block id.
51 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
52 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
53 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
54 constexpr size_t kDefaultWorklistSize = 8;
55 worklist.reserve(kDefaultWorklistSize);
56 visited->SetBit(entry_block_->GetBlockId());
57 visiting.SetBit(entry_block_->GetBlockId());
58 worklist.push_back(entry_block_);
59
60 while (!worklist.empty()) {
61 HBasicBlock* current = worklist.back();
62 uint32_t current_id = current->GetBlockId();
63 if (successors_visited[current_id] == current->GetSuccessors().size()) {
64 visiting.ClearBit(current_id);
65 worklist.pop_back();
66 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010067 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
68 uint32_t successor_id = successor->GetBlockId();
69 if (visiting.IsBitSet(successor_id)) {
70 DCHECK(ContainsElement(worklist, successor));
71 successor->AddBackEdge(current);
72 } else if (!visited->IsBitSet(successor_id)) {
73 visited->SetBit(successor_id);
74 visiting.SetBit(successor_id);
75 worklist.push_back(successor);
76 }
77 }
78 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000079}
80
Roland Levillainfc600dc2014-12-02 17:16:31 +000081static void RemoveAsUser(HInstruction* instruction) {
82 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000083 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000084 }
85
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010086 for (HEnvironment* environment = instruction->GetEnvironment();
87 environment != nullptr;
88 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000089 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000090 if (environment->GetInstructionAt(i) != nullptr) {
91 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000092 }
93 }
94 }
95}
96
97void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010098 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000099 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100100 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000101 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100102 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000103 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
104 RemoveAsUser(it.Current());
105 }
106 }
107 }
108}
109
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000112 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100113 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000114 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100115 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000116 for (HBasicBlock* successor : block->GetSuccessors()) {
117 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000118 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100119 // Remove the block from the list of blocks, so that further analyses
120 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100121 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000122 }
123 }
124}
125
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100127 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
128 // edges. This invariant simplifies building SSA form because Phis cannot
129 // collect both normal- and exceptional-flow values at the same time.
130 SimplifyCatchBlocks();
131
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100132 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133
David Brazdilffee3d32015-07-06 11:48:53 +0100134 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000135 FindBackEdges(&visited);
136
David Brazdilffee3d32015-07-06 11:48:53 +0100137 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000138 // the initial DFS as users from other instructions, so that
139 // users can be safely removed before uses later.
140 RemoveInstructionsAsUsersFromDeadBlocks(visited);
141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000143 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 // predecessors list of live blocks.
145 RemoveDeadBlocks(visited);
146
David Brazdilffee3d32015-07-06 11:48:53 +0100147 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100148 // dominators and the reverse post order.
149 SimplifyCFG();
150
David Brazdilffee3d32015-07-06 11:48:53 +0100151 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100152 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000153
154 // (7) Analyze loops discover through back edge analysis, and
155 // set the loop information on each block.
156 GraphAnalysisResult result = AnalyzeLoops();
157 if (result != kAnalysisSuccess) {
158 return result;
159 }
160
161 // (8) Precompute per-block try membership before entering the SSA builder,
162 // which needs the information to build catch block phis from values of
163 // locals at throwing instructions inside try blocks.
164 ComputeTryBlockInformation();
165
166 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100167}
168
169void HGraph::ClearDominanceInformation() {
170 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
171 it.Current()->ClearDominanceInformation();
172 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100173 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100174}
175
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000176void HGraph::ClearLoopInformation() {
177 SetHasIrreducibleLoops(false);
178 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000179 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000180 }
181}
182
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100183void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000184 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100185 dominator_ = nullptr;
186}
187
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000188HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
189 HInstruction* instruction = GetFirstInstruction();
190 while (instruction->IsParallelMove()) {
191 instruction = instruction->GetNext();
192 }
193 return instruction;
194}
195
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100197 DCHECK(reverse_post_order_.empty());
198 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100199 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100200
201 // Number of visits of a given node, indexed by block id.
202 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
203 // Number of successors visited from a given node, indexed by block id.
204 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
205 // Nodes for which we need to visit successors.
206 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
207 constexpr size_t kDefaultWorklistSize = 8;
208 worklist.reserve(kDefaultWorklistSize);
209 worklist.push_back(entry_block_);
210
211 while (!worklist.empty()) {
212 HBasicBlock* current = worklist.back();
213 uint32_t current_id = current->GetBlockId();
214 if (successors_visited[current_id] == current->GetSuccessors().size()) {
215 worklist.pop_back();
216 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100217 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
218
219 if (successor->GetDominator() == nullptr) {
220 successor->SetDominator(current);
221 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000222 // The CommonDominator can work for multiple blocks as long as the
223 // domination information doesn't change. However, since we're changing
224 // that information here, we can use the finder only for pairs of blocks.
225 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100226 }
227
228 // Once all the forward edges have been visited, we know the immediate
229 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100230 if (++visits[successor->GetBlockId()] ==
231 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100232 reverse_post_order_.push_back(successor);
233 worklist.push_back(successor);
234 }
235 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000236 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000237
238 // Populate `dominated_blocks_` information after computing all dominators.
239 // The potential presence of irreducible loops require to do it after.
240 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
241 HBasicBlock* block = it.Current();
242 if (!block->IsEntryBlock()) {
243 block->GetDominator()->AddDominatedBlock(block);
244 }
245 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000246}
247
David Brazdilfc6a86a2015-06-26 10:33:45 +0000248HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000249 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
250 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000251 // Use `InsertBetween` to ensure the predecessor index and successor index of
252 // `block` and `successor` are preserved.
253 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000254 return new_block;
255}
256
257void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
258 // Insert a new node between `block` and `successor` to split the
259 // critical edge.
260 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600261 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100262 if (successor->IsLoopHeader()) {
263 // If we split at a back edge boundary, make the new block the back edge.
264 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000265 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100266 info->RemoveBackEdge(block);
267 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100268 }
269 }
270}
271
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100272void HGraph::SimplifyLoop(HBasicBlock* header) {
273 HLoopInformation* info = header->GetLoopInformation();
274
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100275 // Make sure the loop has only one pre header. This simplifies SSA building by having
276 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000277 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
278 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000279 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000280 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100281 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100282 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600283 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100284
Vladimir Marko60584552015-09-03 13:35:12 +0000285 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100286 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100287 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100288 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100289 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 }
291 }
292 pre_header->AddSuccessor(header);
293 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100294
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100295 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100296 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
297 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++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)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000301 header->predecessors_[pred] = to_swap;
302 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100303 break;
304 }
305 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100306 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100307
308 // Place the suspend check at the beginning of the header, so that live registers
309 // will be known when allocating registers. Note that code generation can still
310 // generate the suspend check at the back edge, but needs to be careful with
311 // loop phi spill slots (which are not written to at back edge).
312 HInstruction* first_instruction = header->GetFirstInstruction();
313 if (!first_instruction->IsSuspendCheck()) {
314 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
315 header->InsertInstructionBefore(check, first_instruction);
316 first_instruction = check;
317 }
318 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100319}
320
David Brazdilffee3d32015-07-06 11:48:53 +0100321static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100322 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100323 if (!predecessor->EndsWithTryBoundary()) {
324 // Only edges from HTryBoundary can be exceptional.
325 return false;
326 }
327 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
328 if (try_boundary->GetNormalFlowSuccessor() == &block) {
329 // This block is the normal-flow successor of `try_boundary`, but it could
330 // also be one of its exception handlers if catch blocks have not been
331 // simplified yet. Predecessors are unordered, so we will consider the first
332 // occurrence to be the normal edge and a possible second occurrence to be
333 // the exceptional edge.
334 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
335 } else {
336 // This is not the normal-flow successor of `try_boundary`, hence it must be
337 // one of its exception handlers.
338 DCHECK(try_boundary->HasExceptionHandler(block));
339 return true;
340 }
341}
342
343void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100344 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
345 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
346 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
347 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000348 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100349 continue;
350 }
351
352 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000353 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100354 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
355 exceptional_predecessors_only = false;
356 break;
357 }
358 }
359
360 if (!exceptional_predecessors_only) {
361 // Catch block has normal-flow predecessors and needs to be simplified.
362 // Splitting the block before its first instruction moves all its
363 // instructions into `normal_block` and links the two blocks with a Goto.
364 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
365 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000366 //
David Brazdilffee3d32015-07-06 11:48:53 +0100367 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000368 // a move-exception instruction, as guaranteed by the verifier. However,
369 // trivially dead predecessors are ignored by the verifier and such code
370 // has not been removed at this stage. We therefore ignore the assumption
371 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
372 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
373 if (normal_block == nullptr) {
374 // Catch block is either empty or only contains a move-exception. It must
375 // therefore be dead and will be removed during initial DCE. Do nothing.
376 DCHECK(!catch_block->EndsWithControlFlowInstruction());
377 } else {
378 // Catch block was split. Re-link normal-flow edges to the new block.
379 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
380 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
381 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
382 --j;
383 }
David Brazdilffee3d32015-07-06 11:48:53 +0100384 }
385 }
386 }
387 }
388}
389
390void HGraph::ComputeTryBlockInformation() {
391 // Iterate in reverse post order to propagate try membership information from
392 // predecessors to their successors.
393 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
394 HBasicBlock* block = it.Current();
395 if (block->IsEntryBlock() || block->IsCatchBlock()) {
396 // Catch blocks after simplification have only exceptional predecessors
397 // and hence are never in tries.
398 continue;
399 }
400
401 // Infer try membership from the first predecessor. Having simplified loops,
402 // the first predecessor can never be a back edge and therefore it must have
403 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100404 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100405 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100406 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000407 if (try_entry != nullptr &&
408 (block->GetTryCatchInformation() == nullptr ||
409 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
410 // We are either setting try block membership for the first time or it
411 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100412 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
413 }
David Brazdilffee3d32015-07-06 11:48:53 +0100414 }
415}
416
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100417void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000418// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100419 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000420 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100421 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
422 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
423 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
424 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100425 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000426 if (block->GetSuccessors().size() > 1) {
427 // Only split normal-flow edges. We cannot split exceptional edges as they
428 // are synthesized (approximate real control flow), and we do not need to
429 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000430 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
431 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
432 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100433 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000434 if (successor == exit_block_) {
435 // Throw->TryBoundary->Exit. Special case which we do not want to split
436 // because Goto->Exit is not allowed.
437 DCHECK(block->IsSingleTryBoundary());
438 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
439 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100440 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000441 // SplitCriticalEdge could have invalidated the `normal_successors`
442 // ArrayRef. We must re-acquire it.
443 normal_successors = block->GetNormalSuccessors();
444 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
445 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446 }
447 }
448 }
449 if (block->IsLoopHeader()) {
450 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000451 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
452 // We are being called by the dead code elimiation pass, and what used to be
453 // a loop got dismantled. Just remove the suspend check.
454 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 }
456 }
457}
458
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000459GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100460 // Order does not matter.
461 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
462 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100463 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100464 if (block->IsCatchBlock()) {
465 // TODO: Dealing with exceptional back edges could be tricky because
466 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000467 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100468 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000469 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470 }
471 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000472 return kAnalysisSuccess;
473}
474
475void HLoopInformation::Dump(std::ostream& os) {
476 os << "header: " << header_->GetBlockId() << std::endl;
477 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
478 for (HBasicBlock* block : back_edges_) {
479 os << "back edge: " << block->GetBlockId() << std::endl;
480 }
481 for (HBasicBlock* block : header_->GetPredecessors()) {
482 os << "predecessor: " << block->GetBlockId() << std::endl;
483 }
484 for (uint32_t idx : blocks_.Indexes()) {
485 os << " in loop: " << idx << std::endl;
486 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100487}
488
David Brazdil8d5b8b22015-03-24 10:51:52 +0000489void HGraph::InsertConstant(HConstant* constant) {
490 // New constants are inserted before the final control-flow instruction
491 // of the graph, or at its end if called from the graph builder.
492 if (entry_block_->EndsWithControlFlowInstruction()) {
493 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000494 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000495 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000496 }
497}
498
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600499HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100500 // For simplicity, don't bother reviving the cached null constant if it is
501 // not null and not in a block. Otherwise, we need to clear the instruction
502 // id and/or any invariants the graph is assuming when adding new instructions.
503 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600504 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000505 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000506 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000507 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000508 if (kIsDebugBuild) {
509 ScopedObjectAccess soa(Thread::Current());
510 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
511 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000512 return cached_null_constant_;
513}
514
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100515HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100516 // For simplicity, don't bother reviving the cached current method if it is
517 // not null and not in a block. Otherwise, we need to clear the instruction
518 // id and/or any invariants the graph is assuming when adding new instructions.
519 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700520 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600521 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
522 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100523 if (entry_block_->GetFirstInstruction() == nullptr) {
524 entry_block_->AddInstruction(cached_current_method_);
525 } else {
526 entry_block_->InsertInstructionBefore(
527 cached_current_method_, entry_block_->GetFirstInstruction());
528 }
529 }
530 return cached_current_method_;
531}
532
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600533HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000534 switch (type) {
535 case Primitive::Type::kPrimBoolean:
536 DCHECK(IsUint<1>(value));
537 FALLTHROUGH_INTENDED;
538 case Primitive::Type::kPrimByte:
539 case Primitive::Type::kPrimChar:
540 case Primitive::Type::kPrimShort:
541 case Primitive::Type::kPrimInt:
542 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600543 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000544
545 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600546 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000547
548 default:
549 LOG(FATAL) << "Unsupported constant type";
550 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000551 }
David Brazdil46e2a392015-03-16 17:31:52 +0000552}
553
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000554void HGraph::CacheFloatConstant(HFloatConstant* constant) {
555 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
556 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
557 cached_float_constants_.Overwrite(value, constant);
558}
559
560void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
561 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
562 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
563 cached_double_constants_.Overwrite(value, constant);
564}
565
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000566void HLoopInformation::Add(HBasicBlock* block) {
567 blocks_.SetBit(block->GetBlockId());
568}
569
David Brazdil46e2a392015-03-16 17:31:52 +0000570void HLoopInformation::Remove(HBasicBlock* block) {
571 blocks_.ClearBit(block->GetBlockId());
572}
573
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100574void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
575 if (blocks_.IsBitSet(block->GetBlockId())) {
576 return;
577 }
578
579 blocks_.SetBit(block->GetBlockId());
580 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000581 for (HBasicBlock* predecessor : block->GetPredecessors()) {
582 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100583 }
584}
585
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000586void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
587 if (blocks_.IsBitSet(block->GetBlockId())) {
588 return;
589 }
590
591 if (block->IsLoopHeader()) {
592 // If we hit a loop header in an irreducible loop, we first check if the
593 // pre header of that loop belongs to the currently analyzed loop. If it does,
594 // then we visit the back edges.
595 // Note that we cannot use GetPreHeader, as the loop may have not been populated
596 // yet.
597 HBasicBlock* pre_header = block->GetPredecessors()[0];
598 PopulateIrreducibleRecursive(pre_header);
599 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
600 blocks_.SetBit(block->GetBlockId());
601 block->SetInLoop(this);
602 HLoopInformation* info = block->GetLoopInformation();
603 for (HBasicBlock* back_edge : info->GetBackEdges()) {
604 PopulateIrreducibleRecursive(back_edge);
605 }
606 }
607 } else {
608 // Visit all predecessors. If one predecessor is part of the loop, this
609 // block is also part of this loop.
610 for (HBasicBlock* predecessor : block->GetPredecessors()) {
611 PopulateIrreducibleRecursive(predecessor);
612 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
613 blocks_.SetBit(block->GetBlockId());
614 block->SetInLoop(this);
615 }
616 }
617 }
618}
619
620void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100621 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000622 // Populate this loop: starting with the back edge, recursively add predecessors
623 // that are not already part of that loop. Set the header as part of the loop
624 // to end the recursion.
625 // This is a recursive implementation of the algorithm described in
626 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
627 blocks_.SetBit(header_->GetBlockId());
628 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100629 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100630 DCHECK(back_edge->GetDominator() != nullptr);
631 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000632 irreducible_ = true;
633 header_->GetGraph()->SetHasIrreducibleLoops(true);
634 PopulateIrreducibleRecursive(back_edge);
635 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000636 if (header_->GetGraph()->IsCompilingOsr()) {
637 irreducible_ = true;
638 header_->GetGraph()->SetHasIrreducibleLoops(true);
639 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000640 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100641 }
David Brazdila4b8c212015-05-07 09:59:30 +0100642 }
643}
644
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100645HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 HBasicBlock* block = header_->GetPredecessors()[0];
647 DCHECK(irreducible_ || (block == header_->GetDominator()));
648 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100649}
650
651bool HLoopInformation::Contains(const HBasicBlock& block) const {
652 return blocks_.IsBitSet(block.GetBlockId());
653}
654
655bool HLoopInformation::IsIn(const HLoopInformation& other) const {
656 return other.blocks_.IsBitSet(header_->GetBlockId());
657}
658
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800659bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
660 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700661}
662
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100663size_t HLoopInformation::GetLifetimeEnd() const {
664 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100665 for (HBasicBlock* back_edge : GetBackEdges()) {
666 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100667 }
668 return last_position;
669}
670
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100671bool HBasicBlock::Dominates(HBasicBlock* other) const {
672 // Walk up the dominator tree from `other`, to find out if `this`
673 // is an ancestor.
674 HBasicBlock* current = other;
675 while (current != nullptr) {
676 if (current == this) {
677 return true;
678 }
679 current = current->GetDominator();
680 }
681 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100682}
683
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100684static void UpdateInputsUsers(HInstruction* instruction) {
685 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
686 instruction->InputAt(i)->AddUseAt(instruction, i);
687 }
688 // Environment should be created later.
689 DCHECK(!instruction->HasEnvironment());
690}
691
Roland Levillainccc07a92014-09-16 14:48:16 +0100692void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
693 HInstruction* replacement) {
694 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400695 if (initial->IsControlFlow()) {
696 // We can only replace a control flow instruction with another control flow instruction.
697 DCHECK(replacement->IsControlFlow());
698 DCHECK_EQ(replacement->GetId(), -1);
699 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
700 DCHECK_EQ(initial->GetBlock(), this);
701 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
702 DCHECK(initial->GetUses().IsEmpty());
703 DCHECK(initial->GetEnvUses().IsEmpty());
704 replacement->SetBlock(this);
705 replacement->SetId(GetGraph()->GetNextInstructionId());
706 instructions_.InsertInstructionBefore(replacement, initial);
707 UpdateInputsUsers(replacement);
708 } else {
709 InsertInstructionBefore(replacement, initial);
710 initial->ReplaceWith(replacement);
711 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100712 RemoveInstruction(initial);
713}
714
David Brazdil74eb1b22015-12-14 11:44:01 +0000715void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
716 DCHECK(!cursor->IsPhi());
717 DCHECK(!insn->IsPhi());
718 DCHECK(!insn->IsControlFlow());
719 DCHECK(insn->CanBeMoved());
720 DCHECK(!insn->HasSideEffects());
721
722 HBasicBlock* from_block = insn->GetBlock();
723 HBasicBlock* to_block = cursor->GetBlock();
724 DCHECK(from_block != to_block);
725
726 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
727 insn->SetBlock(to_block);
728 to_block->instructions_.InsertInstructionBefore(insn, cursor);
729}
730
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100731static void Add(HInstructionList* instruction_list,
732 HBasicBlock* block,
733 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000734 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000735 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100736 instruction->SetBlock(block);
737 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100738 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100739 instruction_list->AddInstruction(instruction);
740}
741
742void HBasicBlock::AddInstruction(HInstruction* instruction) {
743 Add(&instructions_, this, instruction);
744}
745
746void HBasicBlock::AddPhi(HPhi* phi) {
747 Add(&phis_, this, phi);
748}
749
David Brazdilc3d743f2015-04-22 13:40:50 +0100750void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
751 DCHECK(!cursor->IsPhi());
752 DCHECK(!instruction->IsPhi());
753 DCHECK_EQ(instruction->GetId(), -1);
754 DCHECK_NE(cursor->GetId(), -1);
755 DCHECK_EQ(cursor->GetBlock(), this);
756 DCHECK(!instruction->IsControlFlow());
757 instruction->SetBlock(this);
758 instruction->SetId(GetGraph()->GetNextInstructionId());
759 UpdateInputsUsers(instruction);
760 instructions_.InsertInstructionBefore(instruction, cursor);
761}
762
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100763void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
764 DCHECK(!cursor->IsPhi());
765 DCHECK(!instruction->IsPhi());
766 DCHECK_EQ(instruction->GetId(), -1);
767 DCHECK_NE(cursor->GetId(), -1);
768 DCHECK_EQ(cursor->GetBlock(), this);
769 DCHECK(!instruction->IsControlFlow());
770 DCHECK(!cursor->IsControlFlow());
771 instruction->SetBlock(this);
772 instruction->SetId(GetGraph()->GetNextInstructionId());
773 UpdateInputsUsers(instruction);
774 instructions_.InsertInstructionAfter(instruction, cursor);
775}
776
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100777void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
778 DCHECK_EQ(phi->GetId(), -1);
779 DCHECK_NE(cursor->GetId(), -1);
780 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100781 phi->SetBlock(this);
782 phi->SetId(GetGraph()->GetNextInstructionId());
783 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100784 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100785}
786
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100787static void Remove(HInstructionList* instruction_list,
788 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000789 HInstruction* instruction,
790 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100791 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100792 instruction->SetBlock(nullptr);
793 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000794 if (ensure_safety) {
795 DCHECK(instruction->GetUses().IsEmpty());
796 DCHECK(instruction->GetEnvUses().IsEmpty());
797 RemoveAsUser(instruction);
798 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100799}
800
David Brazdil1abb4192015-02-17 18:33:36 +0000801void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100802 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000803 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100804}
805
David Brazdil1abb4192015-02-17 18:33:36 +0000806void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
807 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100808}
809
David Brazdilc7508e92015-04-27 13:28:57 +0100810void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
811 if (instruction->IsPhi()) {
812 RemovePhi(instruction->AsPhi(), ensure_safety);
813 } else {
814 RemoveInstruction(instruction, ensure_safety);
815 }
816}
817
Vladimir Marko71bf8092015-09-15 15:33:14 +0100818void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
819 for (size_t i = 0; i < locals.size(); i++) {
820 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100821 SetRawEnvAt(i, instruction);
822 if (instruction != nullptr) {
823 instruction->AddEnvUseAt(this, i);
824 }
825 }
826}
827
David Brazdiled596192015-01-23 10:39:45 +0000828void HEnvironment::CopyFrom(HEnvironment* env) {
829 for (size_t i = 0; i < env->Size(); i++) {
830 HInstruction* instruction = env->GetInstructionAt(i);
831 SetRawEnvAt(i, instruction);
832 if (instruction != nullptr) {
833 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100834 }
David Brazdiled596192015-01-23 10:39:45 +0000835 }
836}
837
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700838void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
839 HBasicBlock* loop_header) {
840 DCHECK(loop_header->IsLoopHeader());
841 for (size_t i = 0; i < env->Size(); i++) {
842 HInstruction* instruction = env->GetInstructionAt(i);
843 SetRawEnvAt(i, instruction);
844 if (instruction == nullptr) {
845 continue;
846 }
847 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
848 // At the end of the loop pre-header, the corresponding value for instruction
849 // is the first input of the phi.
850 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700851 SetRawEnvAt(i, initial);
852 initial->AddEnvUseAt(this, i);
853 } else {
854 instruction->AddEnvUseAt(this, i);
855 }
856 }
857}
858
David Brazdil1abb4192015-02-17 18:33:36 +0000859void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100860 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000861 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100862}
863
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000864HInstruction::InstructionKind HInstruction::GetKind() const {
865 return GetKindInternal();
866}
867
Calin Juravle77520bc2015-01-12 18:45:46 +0000868HInstruction* HInstruction::GetNextDisregardingMoves() const {
869 HInstruction* next = GetNext();
870 while (next != nullptr && next->IsParallelMove()) {
871 next = next->GetNext();
872 }
873 return next;
874}
875
876HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
877 HInstruction* previous = GetPrevious();
878 while (previous != nullptr && previous->IsParallelMove()) {
879 previous = previous->GetPrevious();
880 }
881 return previous;
882}
883
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100884void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000885 if (first_instruction_ == nullptr) {
886 DCHECK(last_instruction_ == nullptr);
887 first_instruction_ = last_instruction_ = instruction;
888 } else {
889 last_instruction_->next_ = instruction;
890 instruction->previous_ = last_instruction_;
891 last_instruction_ = instruction;
892 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000893}
894
David Brazdilc3d743f2015-04-22 13:40:50 +0100895void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
896 DCHECK(Contains(cursor));
897 if (cursor == first_instruction_) {
898 cursor->previous_ = instruction;
899 instruction->next_ = cursor;
900 first_instruction_ = instruction;
901 } else {
902 instruction->previous_ = cursor->previous_;
903 instruction->next_ = cursor;
904 cursor->previous_ = instruction;
905 instruction->previous_->next_ = instruction;
906 }
907}
908
909void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
910 DCHECK(Contains(cursor));
911 if (cursor == last_instruction_) {
912 cursor->next_ = instruction;
913 instruction->previous_ = cursor;
914 last_instruction_ = instruction;
915 } else {
916 instruction->next_ = cursor->next_;
917 instruction->previous_ = cursor;
918 cursor->next_ = instruction;
919 instruction->next_->previous_ = instruction;
920 }
921}
922
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100923void HInstructionList::RemoveInstruction(HInstruction* instruction) {
924 if (instruction->previous_ != nullptr) {
925 instruction->previous_->next_ = instruction->next_;
926 }
927 if (instruction->next_ != nullptr) {
928 instruction->next_->previous_ = instruction->previous_;
929 }
930 if (instruction == first_instruction_) {
931 first_instruction_ = instruction->next_;
932 }
933 if (instruction == last_instruction_) {
934 last_instruction_ = instruction->previous_;
935 }
936}
937
Roland Levillain6b469232014-09-25 10:10:38 +0100938bool HInstructionList::Contains(HInstruction* instruction) const {
939 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
940 if (it.Current() == instruction) {
941 return true;
942 }
943 }
944 return false;
945}
946
Roland Levillainccc07a92014-09-16 14:48:16 +0100947bool HInstructionList::FoundBefore(const HInstruction* instruction1,
948 const HInstruction* instruction2) const {
949 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
950 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
951 if (it.Current() == instruction1) {
952 return true;
953 }
954 if (it.Current() == instruction2) {
955 return false;
956 }
957 }
958 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
959 return true;
960}
961
Roland Levillain6c82d402014-10-13 16:10:27 +0100962bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
963 if (other_instruction == this) {
964 // An instruction does not strictly dominate itself.
965 return false;
966 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100967 HBasicBlock* block = GetBlock();
968 HBasicBlock* other_block = other_instruction->GetBlock();
969 if (block != other_block) {
970 return GetBlock()->Dominates(other_instruction->GetBlock());
971 } else {
972 // If both instructions are in the same block, ensure this
973 // instruction comes before `other_instruction`.
974 if (IsPhi()) {
975 if (!other_instruction->IsPhi()) {
976 // Phis appear before non phi-instructions so this instruction
977 // dominates `other_instruction`.
978 return true;
979 } else {
980 // There is no order among phis.
981 LOG(FATAL) << "There is no dominance between phis of a same block.";
982 return false;
983 }
984 } else {
985 // `this` is not a phi.
986 if (other_instruction->IsPhi()) {
987 // Phis appear before non phi-instructions so this instruction
988 // does not dominate `other_instruction`.
989 return false;
990 } else {
991 // Check whether this instruction comes before
992 // `other_instruction` in the instruction list.
993 return block->GetInstructions().FoundBefore(this, other_instruction);
994 }
995 }
996 }
997}
998
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100999void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001000 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001001 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1002 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001003 HInstruction* user = current->GetUser();
1004 size_t input_index = current->GetIndex();
1005 user->SetRawInputAt(input_index, other);
1006 other->AddUseAt(user, input_index);
1007 }
1008
David Brazdiled596192015-01-23 10:39:45 +00001009 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1010 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001011 HEnvironment* user = current->GetUser();
1012 size_t input_index = current->GetIndex();
1013 user->SetRawEnvAt(input_index, other);
1014 other->AddEnvUseAt(user, input_index);
1015 }
1016
David Brazdiled596192015-01-23 10:39:45 +00001017 uses_.Clear();
1018 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001019}
1020
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001021void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001022 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001023 SetRawInputAt(index, replacement);
1024 replacement->AddUseAt(this, index);
1025}
1026
Nicolas Geoffray39468442014-09-02 15:17:15 +01001027size_t HInstruction::EnvironmentSize() const {
1028 return HasEnvironment() ? environment_->Size() : 0;
1029}
1030
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001031void HPhi::AddInput(HInstruction* input) {
1032 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001033 inputs_.push_back(HUserRecord<HInstruction*>(input));
1034 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001035}
1036
David Brazdil2d7352b2015-04-20 14:52:42 +01001037void HPhi::RemoveInputAt(size_t index) {
1038 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001039 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001040 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001041 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001042 InputRecordAt(i).GetUseNode()->SetIndex(i);
1043 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001044}
1045
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001046#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001047void H##name::Accept(HGraphVisitor* visitor) { \
1048 visitor->Visit##name(this); \
1049}
1050
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001051FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001052
1053#undef DEFINE_ACCEPT
1054
1055void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001056 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1057 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001058 if (block != nullptr) {
1059 VisitBasicBlock(block);
1060 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001061 }
1062}
1063
Roland Levillain633021e2014-10-01 14:12:25 +01001064void HGraphVisitor::VisitReversePostOrder() {
1065 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1066 VisitBasicBlock(it.Current());
1067 }
1068}
1069
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001070void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001071 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001072 it.Current()->Accept(this);
1073 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001074 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001075 it.Current()->Accept(this);
1076 }
1077}
1078
Mark Mendelle82549b2015-05-06 10:55:34 -04001079HConstant* HTypeConversion::TryStaticEvaluation() const {
1080 HGraph* graph = GetBlock()->GetGraph();
1081 if (GetInput()->IsIntConstant()) {
1082 int32_t value = GetInput()->AsIntConstant()->GetValue();
1083 switch (GetResultType()) {
1084 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001085 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001086 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001087 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001088 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001089 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001090 default:
1091 return nullptr;
1092 }
1093 } else if (GetInput()->IsLongConstant()) {
1094 int64_t value = GetInput()->AsLongConstant()->GetValue();
1095 switch (GetResultType()) {
1096 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001097 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001098 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001099 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001100 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001102 default:
1103 return nullptr;
1104 }
1105 } else if (GetInput()->IsFloatConstant()) {
1106 float value = GetInput()->AsFloatConstant()->GetValue();
1107 switch (GetResultType()) {
1108 case Primitive::kPrimInt:
1109 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001110 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001111 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001112 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001113 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001114 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1115 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001116 case Primitive::kPrimLong:
1117 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001118 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001119 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001120 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001121 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001122 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1123 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001125 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001126 default:
1127 return nullptr;
1128 }
1129 } else if (GetInput()->IsDoubleConstant()) {
1130 double value = GetInput()->AsDoubleConstant()->GetValue();
1131 switch (GetResultType()) {
1132 case Primitive::kPrimInt:
1133 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001134 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1139 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001140 case Primitive::kPrimLong:
1141 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001142 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001143 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001145 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001146 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1147 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001149 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001150 default:
1151 return nullptr;
1152 }
1153 }
1154 return nullptr;
1155}
1156
Roland Levillain9240d6a2014-10-20 16:47:04 +01001157HConstant* HUnaryOperation::TryStaticEvaluation() const {
1158 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001159 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001160 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001161 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001162 }
1163 return nullptr;
1164}
1165
1166HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001167 if (GetLeft()->IsIntConstant()) {
1168 if (GetRight()->IsIntConstant()) {
1169 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1170 } else if (GetRight()->IsLongConstant()) {
1171 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1172 }
1173 } else if (GetLeft()->IsLongConstant()) {
1174 if (GetRight()->IsIntConstant()) {
1175 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1176 } else if (GetRight()->IsLongConstant()) {
1177 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001178 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001179 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1180 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001181 }
1182 return nullptr;
1183}
Dave Allison20dfc792014-06-16 20:44:29 -07001184
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001185HConstant* HBinaryOperation::GetConstantRight() const {
1186 if (GetRight()->IsConstant()) {
1187 return GetRight()->AsConstant();
1188 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1189 return GetLeft()->AsConstant();
1190 } else {
1191 return nullptr;
1192 }
1193}
1194
1195// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001196// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001197HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1198 HInstruction* most_constant_right = GetConstantRight();
1199 if (most_constant_right == nullptr) {
1200 return nullptr;
1201 } else if (most_constant_right == GetLeft()) {
1202 return GetRight();
1203 } else {
1204 return GetLeft();
1205 }
1206}
1207
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001208bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1209 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001210}
1211
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001212bool HInstruction::Equals(HInstruction* other) const {
1213 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001214 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001215 if (!InstructionDataEquals(other)) return false;
1216 if (GetType() != other->GetType()) return false;
1217 if (InputCount() != other->InputCount()) return false;
1218
1219 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1220 if (InputAt(i) != other->InputAt(i)) return false;
1221 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001222 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001223 return true;
1224}
1225
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001226std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1227#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1228 switch (rhs) {
1229 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1230 default:
1231 os << "Unknown instruction kind " << static_cast<int>(rhs);
1232 break;
1233 }
1234#undef DECLARE_CASE
1235 return os;
1236}
1237
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001238void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001239 next_->previous_ = previous_;
1240 if (previous_ != nullptr) {
1241 previous_->next_ = next_;
1242 }
1243 if (block_->instructions_.first_instruction_ == this) {
1244 block_->instructions_.first_instruction_ = next_;
1245 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001246 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001247
1248 previous_ = cursor->previous_;
1249 if (previous_ != nullptr) {
1250 previous_->next_ = this;
1251 }
1252 next_ = cursor;
1253 cursor->previous_ = this;
1254 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001255
1256 if (block_->instructions_.first_instruction_ == cursor) {
1257 block_->instructions_.first_instruction_ = this;
1258 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001259}
1260
Vladimir Markofb337ea2015-11-25 15:25:10 +00001261void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1262 DCHECK(!CanThrow());
1263 DCHECK(!HasSideEffects());
1264 DCHECK(!HasEnvironmentUses());
1265 DCHECK(HasNonEnvironmentUses());
1266 DCHECK(!IsPhi()); // Makes no sense for Phi.
1267 DCHECK_EQ(InputCount(), 0u);
1268
1269 // Find the target block.
1270 HUseIterator<HInstruction*> uses_it(GetUses());
1271 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1272 uses_it.Advance();
1273 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1274 uses_it.Advance();
1275 }
1276 if (!uses_it.Done()) {
1277 // This instruction has uses in two or more blocks. Find the common dominator.
1278 CommonDominator finder(target_block);
1279 for (; !uses_it.Done(); uses_it.Advance()) {
1280 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1281 }
1282 target_block = finder.Get();
1283 DCHECK(target_block != nullptr);
1284 }
1285 // Move to the first dominator not in a loop.
1286 while (target_block->IsInLoop()) {
1287 target_block = target_block->GetDominator();
1288 DCHECK(target_block != nullptr);
1289 }
1290
1291 // Find insertion position.
1292 HInstruction* insert_pos = nullptr;
1293 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1294 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1295 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1296 insert_pos = uses_it2.Current()->GetUser();
1297 }
1298 }
1299 if (insert_pos == nullptr) {
1300 // No user in `target_block`, insert before the control flow instruction.
1301 insert_pos = target_block->GetLastInstruction();
1302 DCHECK(insert_pos->IsControlFlow());
1303 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1304 if (insert_pos->IsIf()) {
1305 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1306 if (if_input == insert_pos->GetPrevious()) {
1307 insert_pos = if_input;
1308 }
1309 }
1310 }
1311 MoveBefore(insert_pos);
1312}
1313
David Brazdilfc6a86a2015-06-26 10:33:45 +00001314HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001315 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001316 DCHECK_EQ(cursor->GetBlock(), this);
1317
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001318 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1319 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001320 new_block->instructions_.first_instruction_ = cursor;
1321 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1322 instructions_.last_instruction_ = cursor->previous_;
1323 if (cursor->previous_ == nullptr) {
1324 instructions_.first_instruction_ = nullptr;
1325 } else {
1326 cursor->previous_->next_ = nullptr;
1327 cursor->previous_ = nullptr;
1328 }
1329
1330 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001331 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001332
Vladimir Marko60584552015-09-03 13:35:12 +00001333 for (HBasicBlock* successor : GetSuccessors()) {
1334 new_block->successors_.push_back(successor);
1335 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001336 }
Vladimir Marko60584552015-09-03 13:35:12 +00001337 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001338 AddSuccessor(new_block);
1339
David Brazdil56e1acc2015-06-30 15:41:36 +01001340 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001341 return new_block;
1342}
1343
David Brazdild7558da2015-09-22 13:04:14 +01001344HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001345 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001346 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1347
1348 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1349
1350 for (HBasicBlock* predecessor : GetPredecessors()) {
1351 new_block->predecessors_.push_back(predecessor);
1352 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1353 }
1354 predecessors_.clear();
1355 AddPredecessor(new_block);
1356
1357 GetGraph()->AddBlock(new_block);
1358 return new_block;
1359}
1360
David Brazdil9bc43612015-11-05 21:25:24 +00001361HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1362 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1363 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1364
1365 HInstruction* first_insn = GetFirstInstruction();
1366 HInstruction* split_before = nullptr;
1367
1368 if (first_insn != nullptr && first_insn->IsLoadException()) {
1369 // Catch block starts with a LoadException. Split the block after
1370 // the StoreLocal and ClearException which must come after the load.
1371 DCHECK(first_insn->GetNext()->IsStoreLocal());
1372 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1373 split_before = first_insn->GetNext()->GetNext()->GetNext();
1374 } else {
1375 // Catch block does not load the exception. Split at the beginning
1376 // to create an empty catch block.
1377 split_before = first_insn;
1378 }
1379
1380 if (split_before == nullptr) {
1381 // Catch block has no instructions after the split point (must be dead).
1382 // Do not split it but rather signal error by returning nullptr.
1383 return nullptr;
1384 } else {
1385 return SplitBefore(split_before);
1386 }
1387}
1388
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001389HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1390 DCHECK(!cursor->IsControlFlow());
1391 DCHECK_NE(instructions_.last_instruction_, cursor);
1392 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001393
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001394 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1395 new_block->instructions_.first_instruction_ = cursor->GetNext();
1396 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1397 cursor->next_->previous_ = nullptr;
1398 cursor->next_ = nullptr;
1399 instructions_.last_instruction_ = cursor;
1400
1401 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001402 for (HBasicBlock* successor : GetSuccessors()) {
1403 new_block->successors_.push_back(successor);
1404 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 }
Vladimir Marko60584552015-09-03 13:35:12 +00001406 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001407
Vladimir Marko60584552015-09-03 13:35:12 +00001408 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001409 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001410 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001411 }
Vladimir Marko60584552015-09-03 13:35:12 +00001412 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001413 return new_block;
1414}
1415
David Brazdilec16f792015-08-19 15:04:01 +01001416const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001417 if (EndsWithTryBoundary()) {
1418 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1419 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001420 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001421 return try_boundary;
1422 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001423 DCHECK(IsTryBlock());
1424 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001425 return nullptr;
1426 }
David Brazdilec16f792015-08-19 15:04:01 +01001427 } else if (IsTryBlock()) {
1428 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001429 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001430 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001431 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001432}
1433
David Brazdild7558da2015-09-22 13:04:14 +01001434bool HBasicBlock::HasThrowingInstructions() const {
1435 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1436 if (it.Current()->CanThrow()) {
1437 return true;
1438 }
1439 }
1440 return false;
1441}
1442
David Brazdilfc6a86a2015-06-26 10:33:45 +00001443static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1444 return block.GetPhis().IsEmpty()
1445 && !block.GetInstructions().IsEmpty()
1446 && block.GetFirstInstruction() == block.GetLastInstruction();
1447}
1448
David Brazdil46e2a392015-03-16 17:31:52 +00001449bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001450 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1451}
1452
1453bool HBasicBlock::IsSingleTryBoundary() const {
1454 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001455}
1456
David Brazdil8d5b8b22015-03-24 10:51:52 +00001457bool HBasicBlock::EndsWithControlFlowInstruction() const {
1458 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1459}
1460
David Brazdilb2bd1c52015-03-25 11:17:37 +00001461bool HBasicBlock::EndsWithIf() const {
1462 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1463}
1464
David Brazdilffee3d32015-07-06 11:48:53 +01001465bool HBasicBlock::EndsWithTryBoundary() const {
1466 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1467}
1468
David Brazdilb2bd1c52015-03-25 11:17:37 +00001469bool HBasicBlock::HasSinglePhi() const {
1470 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1471}
1472
David Brazdild26a4112015-11-10 11:07:31 +00001473ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1474 if (EndsWithTryBoundary()) {
1475 // The normal-flow successor of HTryBoundary is always stored at index zero.
1476 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1477 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1478 } else {
1479 // All successors of blocks not ending with TryBoundary are normal.
1480 return ArrayRef<HBasicBlock* const>(successors_);
1481 }
1482}
1483
1484ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1485 if (EndsWithTryBoundary()) {
1486 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1487 } else {
1488 // Blocks not ending with TryBoundary do not have exceptional successors.
1489 return ArrayRef<HBasicBlock* const>();
1490 }
1491}
1492
David Brazdilffee3d32015-07-06 11:48:53 +01001493bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001494 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1495 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1496
1497 size_t length = handlers1.size();
1498 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001499 return false;
1500 }
1501
David Brazdilb618ade2015-07-29 10:31:29 +01001502 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001503 for (size_t i = 0; i < length; ++i) {
1504 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001505 return false;
1506 }
1507 }
1508 return true;
1509}
1510
David Brazdil2d7352b2015-04-20 14:52:42 +01001511size_t HInstructionList::CountSize() const {
1512 size_t size = 0;
1513 HInstruction* current = first_instruction_;
1514 for (; current != nullptr; current = current->GetNext()) {
1515 size++;
1516 }
1517 return size;
1518}
1519
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001520void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1521 for (HInstruction* current = first_instruction_;
1522 current != nullptr;
1523 current = current->GetNext()) {
1524 current->SetBlock(block);
1525 }
1526}
1527
1528void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1529 DCHECK(Contains(cursor));
1530 if (!instruction_list.IsEmpty()) {
1531 if (cursor == last_instruction_) {
1532 last_instruction_ = instruction_list.last_instruction_;
1533 } else {
1534 cursor->next_->previous_ = instruction_list.last_instruction_;
1535 }
1536 instruction_list.last_instruction_->next_ = cursor->next_;
1537 cursor->next_ = instruction_list.first_instruction_;
1538 instruction_list.first_instruction_->previous_ = cursor;
1539 }
1540}
1541
1542void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001543 if (IsEmpty()) {
1544 first_instruction_ = instruction_list.first_instruction_;
1545 last_instruction_ = instruction_list.last_instruction_;
1546 } else {
1547 AddAfter(last_instruction_, instruction_list);
1548 }
1549}
1550
David Brazdil04ff4e82015-12-10 13:54:52 +00001551// Should be called on instructions in a dead block in post order. This method
1552// assumes `insn` has been removed from all users with the exception of catch
1553// phis because of missing exceptional edges in the graph. It removes the
1554// instruction from catch phi uses, together with inputs of other catch phis in
1555// the catch block at the same index, as these must be dead too.
1556static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1557 DCHECK(!insn->HasEnvironmentUses());
1558 while (insn->HasNonEnvironmentUses()) {
1559 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1560 size_t use_index = use->GetIndex();
1561 HBasicBlock* user_block = use->GetUser()->GetBlock();
1562 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1563 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1564 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1565 }
1566 }
1567}
1568
David Brazdil2d7352b2015-04-20 14:52:42 +01001569void HBasicBlock::DisconnectAndDelete() {
1570 // Dominators must be removed after all the blocks they dominate. This way
1571 // a loop header is removed last, a requirement for correct loop information
1572 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001573 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001574
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001575 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001576 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1577 HLoopInformation* loop_info = it.Current();
1578 loop_info->Remove(this);
1579 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001580 // If this was the last back edge of the loop, we deliberately leave the
David Brazdilbadd8262016-02-02 16:28:56 +00001581 // loop in an inconsistent state and will fail GraphChecker unless the
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001582 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001583 loop_info->RemoveBackEdge(this);
1584 }
1585 }
1586
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001587 // (2) Disconnect the block from its predecessors and update their
1588 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001589 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001590 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001591 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1592 // This block is the only normal-flow successor of the TryBoundary which
1593 // makes `predecessor` dead. Since DCE removes blocks in post order,
1594 // exception handlers of this TryBoundary were already visited and any
1595 // remaining handlers therefore must be live. We remove `predecessor` from
1596 // their list of predecessors.
1597 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1598 while (predecessor->GetSuccessors().size() > 1) {
1599 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1600 DCHECK(handler->IsCatchBlock());
1601 predecessor->RemoveSuccessor(handler);
1602 handler->RemovePredecessor(predecessor);
1603 }
1604 }
1605
David Brazdil2d7352b2015-04-20 14:52:42 +01001606 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001607 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1608 if (num_pred_successors == 1u) {
1609 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001610 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1611 // successor. Replace those with a HGoto.
1612 DCHECK(last_instruction->IsIf() ||
1613 last_instruction->IsPackedSwitch() ||
1614 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001615 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001616 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001617 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001618 // The predecessor has no remaining successors and therefore must be dead.
1619 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001620 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001621 predecessor->RemoveInstruction(last_instruction);
1622 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001623 // There are multiple successors left. The removed block might be a successor
1624 // of a PackedSwitch which will be completely removed (perhaps replaced with
1625 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1626 // case, leave `last_instruction` as is for now.
1627 DCHECK(last_instruction->IsPackedSwitch() ||
1628 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001629 }
David Brazdil46e2a392015-03-16 17:31:52 +00001630 }
Vladimir Marko60584552015-09-03 13:35:12 +00001631 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001632
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001633 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001634 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001635 // Delete this block from the list of predecessors.
1636 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001637 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001638
1639 // Check that `successor` has other predecessors, otherwise `this` is the
1640 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001641 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001642
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001643 // Remove this block's entries in the successor's phis. Skip exceptional
1644 // successors because catch phi inputs do not correspond to predecessor
1645 // blocks but throwing instructions. Their inputs will be updated in step (4).
1646 if (!successor->IsCatchBlock()) {
1647 if (successor->predecessors_.size() == 1u) {
1648 // The successor has just one predecessor left. Replace phis with the only
1649 // remaining input.
1650 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1651 HPhi* phi = phi_it.Current()->AsPhi();
1652 phi->ReplaceWith(phi->InputAt(1 - this_index));
1653 successor->RemovePhi(phi);
1654 }
1655 } else {
1656 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1657 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1658 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001659 }
1660 }
1661 }
Vladimir Marko60584552015-09-03 13:35:12 +00001662 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001663
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001664 // (4) Remove instructions and phis. Instructions should have no remaining uses
1665 // except in catch phis. If an instruction is used by a catch phi at `index`,
1666 // remove `index`-th input of all phis in the catch block since they are
1667 // guaranteed dead. Note that we may miss dead inputs this way but the
1668 // graph will always remain consistent.
1669 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1670 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001671 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001672 RemoveInstruction(insn);
1673 }
1674 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001675 HPhi* insn = it.Current()->AsPhi();
1676 RemoveUsesOfDeadInstruction(insn);
1677 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001678 }
1679
David Brazdil2d7352b2015-04-20 14:52:42 +01001680 // Disconnect from the dominator.
1681 dominator_->RemoveDominatedBlock(this);
1682 SetDominator(nullptr);
1683
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001684 // Delete from the graph, update reverse post order.
1685 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001686 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001687}
1688
1689void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001690 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001691 DCHECK(ContainsElement(dominated_blocks_, other));
1692 DCHECK_EQ(GetSingleSuccessor(), other);
1693 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001694 DCHECK(other->GetPhis().IsEmpty());
1695
David Brazdil2d7352b2015-04-20 14:52:42 +01001696 // Move instructions from `other` to `this`.
1697 DCHECK(EndsWithControlFlowInstruction());
1698 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001699 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001700 other->instructions_.SetBlockOfInstructions(this);
1701 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001702
David Brazdil2d7352b2015-04-20 14:52:42 +01001703 // Remove `other` from the loops it is included in.
1704 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1705 HLoopInformation* loop_info = it.Current();
1706 loop_info->Remove(other);
1707 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001708 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001709 }
1710 }
1711
1712 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001713 successors_.clear();
1714 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001715 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001716 successor->ReplacePredecessor(other, this);
1717 }
1718
David Brazdil2d7352b2015-04-20 14:52:42 +01001719 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001720 RemoveDominatedBlock(other);
1721 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1722 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001723 dominated->SetDominator(this);
1724 }
Vladimir Marko60584552015-09-03 13:35:12 +00001725 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001726 other->dominator_ = nullptr;
1727
1728 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001729 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001730
1731 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001732 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001733 other->SetGraph(nullptr);
1734}
1735
1736void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1737 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001738 DCHECK(GetDominatedBlocks().empty());
1739 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001740 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001741 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001742 DCHECK(other->GetPhis().IsEmpty());
1743 DCHECK(!other->IsInLoop());
1744
1745 // Move instructions from `other` to `this`.
1746 instructions_.Add(other->GetInstructions());
1747 other->instructions_.SetBlockOfInstructions(this);
1748
1749 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001750 successors_.clear();
1751 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001752 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001753 successor->ReplacePredecessor(other, this);
1754 }
1755
1756 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001757 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1758 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001759 dominated->SetDominator(this);
1760 }
Vladimir Marko60584552015-09-03 13:35:12 +00001761 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001762 other->dominator_ = nullptr;
1763 other->graph_ = nullptr;
1764}
1765
1766void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001767 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001768 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001769 predecessor->ReplaceSuccessor(this, other);
1770 }
Vladimir Marko60584552015-09-03 13:35:12 +00001771 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001772 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 successor->ReplacePredecessor(this, other);
1774 }
Vladimir Marko60584552015-09-03 13:35:12 +00001775 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1776 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001777 }
1778 GetDominator()->ReplaceDominatedBlock(this, other);
1779 other->SetDominator(GetDominator());
1780 dominator_ = nullptr;
1781 graph_ = nullptr;
1782}
1783
1784// Create space in `blocks` for adding `number_of_new_blocks` entries
1785// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001786static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001787 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001788 size_t after) {
1789 DCHECK_LT(after, blocks->size());
1790 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001791 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001792 blocks->resize(new_size);
1793 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001794}
1795
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001796void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001797 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001798 DCHECK(block->GetSuccessors().empty());
1799 DCHECK(block->GetPredecessors().empty());
1800 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001801 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001802 DCHECK(block->GetInstructions().IsEmpty());
1803 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001804
David Brazdilc7af85d2015-05-26 12:05:55 +01001805 if (block->IsExitBlock()) {
1806 exit_block_ = nullptr;
1807 }
1808
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001809 RemoveElement(reverse_post_order_, block);
1810 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001811}
1812
Calin Juravle2e768302015-07-28 14:41:11 +00001813HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001814 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001815 // Update the environments in this graph to have the invoke's environment
1816 // as parent.
1817 {
1818 HReversePostOrderIterator it(*this);
1819 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1820 for (; !it.Done(); it.Advance()) {
1821 HBasicBlock* block = it.Current();
1822 for (HInstructionIterator instr_it(block->GetInstructions());
1823 !instr_it.Done();
1824 instr_it.Advance()) {
1825 HInstruction* current = instr_it.Current();
1826 if (current->NeedsEnvironment()) {
1827 current->GetEnvironment()->SetAndCopyParentChain(
1828 outer_graph->GetArena(), invoke->GetEnvironment());
1829 }
1830 }
1831 }
1832 }
1833 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1834 if (HasBoundsChecks()) {
1835 outer_graph->SetHasBoundsChecks(true);
1836 }
1837
Calin Juravle2e768302015-07-28 14:41:11 +00001838 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001839 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001840 // Simple case of an entry block, a body block, and an exit block.
1841 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001842 HBasicBlock* body = GetBlocks()[1];
1843 DCHECK(GetBlocks()[0]->IsEntryBlock());
1844 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001845 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001846 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001847 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001848
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001849 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1850 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001851
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001852 // Replace the invoke with the return value of the inlined graph.
1853 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001854 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001855 } else {
1856 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001857 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001858
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001859 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001860 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001861 // Need to inline multiple blocks. We split `invoke`'s block
1862 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001863 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001864 // with the second half.
1865 ArenaAllocator* allocator = outer_graph->GetArena();
1866 HBasicBlock* at = invoke->GetBlock();
1867 HBasicBlock* to = at->SplitAfter(invoke);
1868
Vladimir Markoec7802a2015-10-01 20:57:57 +01001869 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001870 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001871 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001872 exit_block_->ReplaceWith(to);
1873
1874 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001875 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001876 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001877 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001878 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001879 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001880 if (!returns_void) {
1881 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001882 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001883 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001885 } else {
1886 if (!returns_void) {
1887 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001888 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001889 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001890 to->AddPhi(return_value->AsPhi());
1891 }
Vladimir Marko60584552015-09-03 13:35:12 +00001892 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001893 HInstruction* last = predecessor->GetLastInstruction();
1894 if (!returns_void) {
1895 return_value->AsPhi()->AddInput(last->InputAt(0));
1896 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001897 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001898 predecessor->RemoveInstruction(last);
1899 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001900 }
1901
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001902 // Update the meta information surrounding blocks:
1903 // (1) the graph they are now in,
1904 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001905 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001906 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001907 // Note that we do not need to update catch phi inputs because they
1908 // correspond to the register file of the outer method which the inlinee
1909 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001910
1911 // We don't add the entry block, the exit block, and the first block, which
1912 // has been merged with `at`.
1913 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1914
1915 // We add the `to` block.
1916 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001917 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 + kNumberOfNewBlocksInCaller;
1919
1920 // Find the location of `at` in the outer graph's reverse post order. The new
1921 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001922 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001923 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1924
David Brazdil95177982015-10-30 12:56:58 -05001925 HLoopInformation* loop_info = at->GetLoopInformation();
1926 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1927 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1928
1929 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1930 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001931 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1932 HBasicBlock* current = it.Current();
1933 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001934 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001935 DCHECK(current->GetGraph() == this);
1936 current->SetGraph(outer_graph);
1937 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001938 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001939 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001940 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001941 } else if (current->IsLoopHeader()) {
1942 // Clear the information of which blocks are contained in that loop. Since the
1943 // information is stored as a bit vector based on block ids, we have to update
1944 // it, as those block ids were specific to the callee graph and we are now adding
1945 // these blocks to the caller graph.
1946 current->GetLoopInformation()->ClearAllBlocks();
1947 }
1948 if (current->IsInLoop()) {
1949 for (HLoopInformationOutwardIterator loop_it(*current);
1950 !loop_it.Done();
1951 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001952 loop_it.Current()->Add(current);
1953 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001954 }
David Brazdil95177982015-10-30 12:56:58 -05001955 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001956 }
1957 }
1958
David Brazdil95177982015-10-30 12:56:58 -05001959 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001960 to->SetGraph(outer_graph);
1961 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001962 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001963 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001964 if (!to->IsInLoop()) {
1965 to->SetLoopInformation(loop_info);
1966 }
David Brazdil7d275372015-04-21 16:36:35 +01001967 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1968 loop_it.Current()->Add(to);
1969 }
David Brazdil95177982015-10-30 12:56:58 -05001970 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001971 // Only `to` can become a back edge, as the inlined blocks
1972 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001973 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001974 }
1975 }
David Brazdil95177982015-10-30 12:56:58 -05001976 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001977 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001978
David Brazdil05144f42015-04-16 15:18:00 +01001979 // Update the next instruction id of the outer graph, so that instructions
1980 // added later get bigger ids than those in the inner graph.
1981 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1982
1983 // Walk over the entry block and:
1984 // - Move constants from the entry block to the outer_graph's entry block,
1985 // - Replace HParameterValue instructions with their real value.
1986 // - Remove suspend checks, that hold an environment.
1987 // We must do this after the other blocks have been inlined, otherwise ids of
1988 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001989 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001990 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1991 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001992 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001993 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001994 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001995 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001996 replacement = outer_graph->GetIntConstant(
1997 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001998 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001999 replacement = outer_graph->GetLongConstant(
2000 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002001 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002002 replacement = outer_graph->GetFloatConstant(
2003 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002004 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002005 replacement = outer_graph->GetDoubleConstant(
2006 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002007 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002008 if (kIsDebugBuild
2009 && invoke->IsInvokeStaticOrDirect()
2010 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2011 // Ensure we do not use the last input of `invoke`, as it
2012 // contains a clinit check which is not an actual argument.
2013 size_t last_input_index = invoke->InputCount() - 1;
2014 DCHECK(parameter_index != last_input_index);
2015 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002016 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002017 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002018 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002019 } else {
2020 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2021 entry_block_->RemoveInstruction(current);
2022 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002023 if (replacement != nullptr) {
2024 current->ReplaceWith(replacement);
2025 // If the current is the return value then we need to update the latter.
2026 if (current == return_value) {
2027 DCHECK_EQ(entry_block_, return_value->GetBlock());
2028 return_value = replacement;
2029 }
2030 }
2031 }
2032
2033 if (return_value != nullptr) {
2034 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002035 }
2036
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002037 // Finally remove the invoke from the caller.
2038 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002039
2040 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002041}
2042
Mingyao Yang3584bce2015-05-19 16:01:59 -07002043/*
2044 * Loop will be transformed to:
2045 * old_pre_header
2046 * |
2047 * if_block
2048 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002049 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002050 * \ /
2051 * new_pre_header
2052 * |
2053 * header
2054 */
2055void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2056 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002057 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002058
Aart Bik3fc7f352015-11-20 22:03:03 -08002059 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002060 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002061 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2062 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002063 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2064 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002065 AddBlock(true_block);
2066 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002067 AddBlock(new_pre_header);
2068
Aart Bik3fc7f352015-11-20 22:03:03 -08002069 header->ReplacePredecessor(old_pre_header, new_pre_header);
2070 old_pre_header->successors_.clear();
2071 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002072
Aart Bik3fc7f352015-11-20 22:03:03 -08002073 old_pre_header->AddSuccessor(if_block);
2074 if_block->AddSuccessor(true_block); // True successor
2075 if_block->AddSuccessor(false_block); // False successor
2076 true_block->AddSuccessor(new_pre_header);
2077 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002078
Aart Bik3fc7f352015-11-20 22:03:03 -08002079 old_pre_header->dominated_blocks_.push_back(if_block);
2080 if_block->SetDominator(old_pre_header);
2081 if_block->dominated_blocks_.push_back(true_block);
2082 true_block->SetDominator(if_block);
2083 if_block->dominated_blocks_.push_back(false_block);
2084 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002085 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002086 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002087 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002088 header->SetDominator(new_pre_header);
2089
Aart Bik3fc7f352015-11-20 22:03:03 -08002090 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002091 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002092 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002093 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002094 reverse_post_order_[index_of_header++] = true_block;
2095 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002096 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002097
Aart Bik3fc7f352015-11-20 22:03:03 -08002098 // Fix loop information.
2099 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2100 if (loop_info != nullptr) {
2101 if_block->SetLoopInformation(loop_info);
2102 true_block->SetLoopInformation(loop_info);
2103 false_block->SetLoopInformation(loop_info);
2104 new_pre_header->SetLoopInformation(loop_info);
2105 // Add blocks to all enveloping loops.
2106 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107 !loop_it.Done();
2108 loop_it.Advance()) {
2109 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002110 loop_it.Current()->Add(true_block);
2111 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002112 loop_it.Current()->Add(new_pre_header);
2113 }
2114 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002115
2116 // Fix try/catch information.
2117 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2118 ? old_pre_header->GetTryCatchInformation()
2119 : nullptr;
2120 if_block->SetTryCatchInformation(try_catch_info);
2121 true_block->SetTryCatchInformation(try_catch_info);
2122 false_block->SetTryCatchInformation(try_catch_info);
2123 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002124}
2125
David Brazdilf5552582015-12-27 13:36:12 +00002126static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2127 SHARED_REQUIRES(Locks::mutator_lock_) {
2128 if (rti.IsValid()) {
2129 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2130 << " upper_bound_rti: " << upper_bound_rti
2131 << " rti: " << rti;
2132 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2133 }
2134}
2135
Calin Juravle2e768302015-07-28 14:41:11 +00002136void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2137 if (kIsDebugBuild) {
2138 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2139 ScopedObjectAccess soa(Thread::Current());
2140 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2141 if (IsBoundType()) {
2142 // Having the test here spares us from making the method virtual just for
2143 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002144 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002145 }
2146 }
2147 reference_type_info_ = rti;
2148}
2149
David Brazdilf5552582015-12-27 13:36:12 +00002150void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2151 if (kIsDebugBuild) {
2152 ScopedObjectAccess soa(Thread::Current());
2153 DCHECK(upper_bound.IsValid());
2154 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2155 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2156 }
2157 upper_bound_ = upper_bound;
2158 upper_can_be_null_ = can_be_null;
2159}
2160
Calin Juravle2e768302015-07-28 14:41:11 +00002161ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2162
2163ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2164 : type_handle_(type_handle), is_exact_(is_exact) {
2165 if (kIsDebugBuild) {
2166 ScopedObjectAccess soa(Thread::Current());
2167 DCHECK(IsValidHandle(type_handle));
2168 }
2169}
2170
Calin Juravleacf735c2015-02-12 15:25:22 +00002171std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2172 ScopedObjectAccess soa(Thread::Current());
2173 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002174 << " is_valid=" << rhs.IsValid()
2175 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002176 << " is_exact=" << rhs.IsExact()
2177 << " ]";
2178 return os;
2179}
2180
Mark Mendellc4701932015-04-10 13:18:51 -04002181bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2182 // For now, assume that instructions in different blocks may use the
2183 // environment.
2184 // TODO: Use the control flow to decide if this is true.
2185 if (GetBlock() != other->GetBlock()) {
2186 return true;
2187 }
2188
2189 // We know that we are in the same block. Walk from 'this' to 'other',
2190 // checking to see if there is any instruction with an environment.
2191 HInstruction* current = this;
2192 for (; current != other && current != nullptr; current = current->GetNext()) {
2193 // This is a conservative check, as the instruction result may not be in
2194 // the referenced environment.
2195 if (current->HasEnvironment()) {
2196 return true;
2197 }
2198 }
2199
2200 // We should have been called with 'this' before 'other' in the block.
2201 // Just confirm this.
2202 DCHECK(current != nullptr);
2203 return false;
2204}
2205
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002206void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002207 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2208 IntrinsicSideEffects side_effects,
2209 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002210 intrinsic_ = intrinsic;
2211 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002212
Aart Bik5d75afe2015-12-14 11:57:01 -08002213 // Adjust method's side effects from intrinsic table.
2214 switch (side_effects) {
2215 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2216 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2217 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2218 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2219 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002220
2221 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2222 opt.SetDoesNotNeedDexCache();
2223 opt.SetDoesNotNeedEnvironment();
2224 } else {
2225 // If we need an environment, that means there will be a call, which can trigger GC.
2226 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2227 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002228 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002229 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002230}
2231
David Brazdil6de19382016-01-08 17:37:10 +00002232bool HNewInstance::IsStringAlloc() const {
2233 ScopedObjectAccess soa(Thread::Current());
2234 return GetReferenceTypeInfo().IsStringClass();
2235}
2236
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002237bool HInvoke::NeedsEnvironment() const {
2238 if (!IsIntrinsic()) {
2239 return true;
2240 }
2241 IntrinsicOptimizations opt(*this);
2242 return !opt.GetDoesNotNeedEnvironment();
2243}
2244
Vladimir Markodc151b22015-10-15 18:02:30 +01002245bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2246 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002247 return false;
2248 }
2249 if (!IsIntrinsic()) {
2250 return true;
2251 }
2252 IntrinsicOptimizations opt(*this);
2253 return !opt.GetDoesNotNeedDexCache();
2254}
2255
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002256void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2257 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2258 input->AddUseAt(this, index);
2259 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2260 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2261 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2262 InputRecordAt(i).GetUseNode()->SetIndex(i);
2263 }
2264}
2265
Vladimir Markob554b5a2015-11-06 12:57:55 +00002266void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2267 RemoveAsUserOfInput(index);
2268 inputs_.erase(inputs_.begin() + index);
2269 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2270 for (size_t i = index, e = InputCount(); i < e; ++i) {
2271 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2272 InputRecordAt(i).GetUseNode()->SetIndex(i);
2273 }
2274}
2275
Vladimir Markof64242a2015-12-01 14:58:23 +00002276std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2277 switch (rhs) {
2278 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2279 return os << "string_init";
2280 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2281 return os << "recursive";
2282 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2283 return os << "direct";
2284 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2285 return os << "direct_fixup";
2286 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2287 return os << "dex_cache_pc_relative";
2288 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2289 return os << "dex_cache_via_method";
2290 default:
2291 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2292 UNREACHABLE();
2293 }
2294}
2295
Vladimir Markofbb184a2015-11-13 14:47:00 +00002296std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2297 switch (rhs) {
2298 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2299 return os << "explicit";
2300 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2301 return os << "implicit";
2302 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2303 return os << "none";
2304 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002305 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2306 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002307 }
2308}
2309
Mark Mendellc4701932015-04-10 13:18:51 -04002310void HInstruction::RemoveEnvironmentUsers() {
2311 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2312 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2313 HEnvironment* user = user_node->GetUser();
2314 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2315 }
2316 env_uses_.Clear();
2317}
2318
Mark Mendellf6529172015-11-17 11:16:56 -05002319// Returns an instruction with the opposite boolean value from 'cond'.
2320HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2321 ArenaAllocator* allocator = GetArena();
2322
2323 if (cond->IsCondition() &&
2324 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2325 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2326 HInstruction* lhs = cond->InputAt(0);
2327 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002328 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002329 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2330 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2331 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2332 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2333 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2334 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2335 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2336 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2337 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2338 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2339 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002340 default:
2341 LOG(FATAL) << "Unexpected condition";
2342 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002343 }
2344 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2345 return replacement;
2346 } else if (cond->IsIntConstant()) {
2347 HIntConstant* int_const = cond->AsIntConstant();
2348 if (int_const->IsZero()) {
2349 return GetIntConstant(1);
2350 } else {
2351 DCHECK(int_const->IsOne());
2352 return GetIntConstant(0);
2353 }
2354 } else {
2355 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2356 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2357 return replacement;
2358 }
2359}
2360
Roland Levillainc9285912015-12-18 10:38:42 +00002361std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2362 os << "["
2363 << " source=" << rhs.GetSource()
2364 << " destination=" << rhs.GetDestination()
2365 << " type=" << rhs.GetType()
2366 << " instruction=";
2367 if (rhs.GetInstruction() != nullptr) {
2368 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2369 } else {
2370 os << "null";
2371 }
2372 os << " ]";
2373 return os;
2374}
2375
Roland Levillain86503782016-02-11 19:07:30 +00002376std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2377 switch (rhs) {
2378 case TypeCheckKind::kUnresolvedCheck:
2379 return os << "unresolved_check";
2380 case TypeCheckKind::kExactCheck:
2381 return os << "exact_check";
2382 case TypeCheckKind::kClassHierarchyCheck:
2383 return os << "class_hierarchy_check";
2384 case TypeCheckKind::kAbstractClassCheck:
2385 return os << "abstract_class_check";
2386 case TypeCheckKind::kInterfaceCheck:
2387 return os << "interface_check";
2388 case TypeCheckKind::kArrayObjectCheck:
2389 return os << "array_object_check";
2390 case TypeCheckKind::kArrayCheck:
2391 return os << "array_check";
2392 default:
2393 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2394 UNREACHABLE();
2395 }
2396}
2397
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002398} // namespace art