blob: 95d0af539deab544d1519493fb3cd2f2f48337b1 [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 Geoffray916cc1d2016-02-18 11:12:31 +00001389HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1390 DCHECK_EQ(cursor->GetBlock(), this);
1391
1392 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1393 cursor->GetDexPc());
1394 new_block->instructions_.first_instruction_ = cursor;
1395 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1396 instructions_.last_instruction_ = cursor->previous_;
1397 if (cursor->previous_ == nullptr) {
1398 instructions_.first_instruction_ = nullptr;
1399 } else {
1400 cursor->previous_->next_ = nullptr;
1401 cursor->previous_ = nullptr;
1402 }
1403
1404 new_block->instructions_.SetBlockOfInstructions(new_block);
1405
1406 for (HBasicBlock* successor : GetSuccessors()) {
1407 new_block->successors_.push_back(successor);
1408 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1409 }
1410 successors_.clear();
1411
1412 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1413 dominated->dominator_ = new_block;
1414 new_block->dominated_blocks_.push_back(dominated);
1415 }
1416 dominated_blocks_.clear();
1417 return new_block;
1418}
1419
1420HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001421 DCHECK(!cursor->IsControlFlow());
1422 DCHECK_NE(instructions_.last_instruction_, cursor);
1423 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001424
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001425 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1426 new_block->instructions_.first_instruction_ = cursor->GetNext();
1427 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1428 cursor->next_->previous_ = nullptr;
1429 cursor->next_ = nullptr;
1430 instructions_.last_instruction_ = cursor;
1431
1432 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001433 for (HBasicBlock* successor : GetSuccessors()) {
1434 new_block->successors_.push_back(successor);
1435 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 }
Vladimir Marko60584552015-09-03 13:35:12 +00001437 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001438
Vladimir Marko60584552015-09-03 13:35:12 +00001439 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001440 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001441 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001442 }
Vladimir Marko60584552015-09-03 13:35:12 +00001443 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001444 return new_block;
1445}
1446
David Brazdilec16f792015-08-19 15:04:01 +01001447const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001448 if (EndsWithTryBoundary()) {
1449 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1450 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001451 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001452 return try_boundary;
1453 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001454 DCHECK(IsTryBlock());
1455 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001456 return nullptr;
1457 }
David Brazdilec16f792015-08-19 15:04:01 +01001458 } else if (IsTryBlock()) {
1459 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001460 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001461 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001462 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001463}
1464
David Brazdild7558da2015-09-22 13:04:14 +01001465bool HBasicBlock::HasThrowingInstructions() const {
1466 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1467 if (it.Current()->CanThrow()) {
1468 return true;
1469 }
1470 }
1471 return false;
1472}
1473
David Brazdilfc6a86a2015-06-26 10:33:45 +00001474static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1475 return block.GetPhis().IsEmpty()
1476 && !block.GetInstructions().IsEmpty()
1477 && block.GetFirstInstruction() == block.GetLastInstruction();
1478}
1479
David Brazdil46e2a392015-03-16 17:31:52 +00001480bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001481 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1482}
1483
1484bool HBasicBlock::IsSingleTryBoundary() const {
1485 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001486}
1487
David Brazdil8d5b8b22015-03-24 10:51:52 +00001488bool HBasicBlock::EndsWithControlFlowInstruction() const {
1489 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1490}
1491
David Brazdilb2bd1c52015-03-25 11:17:37 +00001492bool HBasicBlock::EndsWithIf() const {
1493 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1494}
1495
David Brazdilffee3d32015-07-06 11:48:53 +01001496bool HBasicBlock::EndsWithTryBoundary() const {
1497 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1498}
1499
David Brazdilb2bd1c52015-03-25 11:17:37 +00001500bool HBasicBlock::HasSinglePhi() const {
1501 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1502}
1503
David Brazdild26a4112015-11-10 11:07:31 +00001504ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1505 if (EndsWithTryBoundary()) {
1506 // The normal-flow successor of HTryBoundary is always stored at index zero.
1507 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1508 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1509 } else {
1510 // All successors of blocks not ending with TryBoundary are normal.
1511 return ArrayRef<HBasicBlock* const>(successors_);
1512 }
1513}
1514
1515ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1516 if (EndsWithTryBoundary()) {
1517 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1518 } else {
1519 // Blocks not ending with TryBoundary do not have exceptional successors.
1520 return ArrayRef<HBasicBlock* const>();
1521 }
1522}
1523
David Brazdilffee3d32015-07-06 11:48:53 +01001524bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001525 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1526 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1527
1528 size_t length = handlers1.size();
1529 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001530 return false;
1531 }
1532
David Brazdilb618ade2015-07-29 10:31:29 +01001533 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001534 for (size_t i = 0; i < length; ++i) {
1535 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001536 return false;
1537 }
1538 }
1539 return true;
1540}
1541
David Brazdil2d7352b2015-04-20 14:52:42 +01001542size_t HInstructionList::CountSize() const {
1543 size_t size = 0;
1544 HInstruction* current = first_instruction_;
1545 for (; current != nullptr; current = current->GetNext()) {
1546 size++;
1547 }
1548 return size;
1549}
1550
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001551void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1552 for (HInstruction* current = first_instruction_;
1553 current != nullptr;
1554 current = current->GetNext()) {
1555 current->SetBlock(block);
1556 }
1557}
1558
1559void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1560 DCHECK(Contains(cursor));
1561 if (!instruction_list.IsEmpty()) {
1562 if (cursor == last_instruction_) {
1563 last_instruction_ = instruction_list.last_instruction_;
1564 } else {
1565 cursor->next_->previous_ = instruction_list.last_instruction_;
1566 }
1567 instruction_list.last_instruction_->next_ = cursor->next_;
1568 cursor->next_ = instruction_list.first_instruction_;
1569 instruction_list.first_instruction_->previous_ = cursor;
1570 }
1571}
1572
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001573void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1574 DCHECK(Contains(cursor));
1575 if (!instruction_list.IsEmpty()) {
1576 if (cursor == first_instruction_) {
1577 first_instruction_ = instruction_list.first_instruction_;
1578 } else {
1579 cursor->previous_->next_ = instruction_list.first_instruction_;
1580 }
1581 instruction_list.last_instruction_->next_ = cursor;
1582 instruction_list.first_instruction_->previous_ = cursor->previous_;
1583 cursor->previous_ = instruction_list.last_instruction_;
1584 }
1585}
1586
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001587void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001588 if (IsEmpty()) {
1589 first_instruction_ = instruction_list.first_instruction_;
1590 last_instruction_ = instruction_list.last_instruction_;
1591 } else {
1592 AddAfter(last_instruction_, instruction_list);
1593 }
1594}
1595
David Brazdil04ff4e82015-12-10 13:54:52 +00001596// Should be called on instructions in a dead block in post order. This method
1597// assumes `insn` has been removed from all users with the exception of catch
1598// phis because of missing exceptional edges in the graph. It removes the
1599// instruction from catch phi uses, together with inputs of other catch phis in
1600// the catch block at the same index, as these must be dead too.
1601static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1602 DCHECK(!insn->HasEnvironmentUses());
1603 while (insn->HasNonEnvironmentUses()) {
1604 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1605 size_t use_index = use->GetIndex();
1606 HBasicBlock* user_block = use->GetUser()->GetBlock();
1607 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1608 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1609 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1610 }
1611 }
1612}
1613
David Brazdil2d7352b2015-04-20 14:52:42 +01001614void HBasicBlock::DisconnectAndDelete() {
1615 // Dominators must be removed after all the blocks they dominate. This way
1616 // a loop header is removed last, a requirement for correct loop information
1617 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001618 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001619
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001620 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001621 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1622 HLoopInformation* loop_info = it.Current();
1623 loop_info->Remove(this);
1624 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001625 // If this was the last back edge of the loop, we deliberately leave the
David Brazdilbadd8262016-02-02 16:28:56 +00001626 // loop in an inconsistent state and will fail GraphChecker unless the
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001627 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001628 loop_info->RemoveBackEdge(this);
1629 }
1630 }
1631
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001632 // (2) Disconnect the block from its predecessors and update their
1633 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001634 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001635 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001636 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1637 // This block is the only normal-flow successor of the TryBoundary which
1638 // makes `predecessor` dead. Since DCE removes blocks in post order,
1639 // exception handlers of this TryBoundary were already visited and any
1640 // remaining handlers therefore must be live. We remove `predecessor` from
1641 // their list of predecessors.
1642 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1643 while (predecessor->GetSuccessors().size() > 1) {
1644 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1645 DCHECK(handler->IsCatchBlock());
1646 predecessor->RemoveSuccessor(handler);
1647 handler->RemovePredecessor(predecessor);
1648 }
1649 }
1650
David Brazdil2d7352b2015-04-20 14:52:42 +01001651 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001652 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1653 if (num_pred_successors == 1u) {
1654 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001655 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1656 // successor. Replace those with a HGoto.
1657 DCHECK(last_instruction->IsIf() ||
1658 last_instruction->IsPackedSwitch() ||
1659 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001660 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001661 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001662 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001663 // The predecessor has no remaining successors and therefore must be dead.
1664 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001665 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001666 predecessor->RemoveInstruction(last_instruction);
1667 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001668 // There are multiple successors left. The removed block might be a successor
1669 // of a PackedSwitch which will be completely removed (perhaps replaced with
1670 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1671 // case, leave `last_instruction` as is for now.
1672 DCHECK(last_instruction->IsPackedSwitch() ||
1673 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001674 }
David Brazdil46e2a392015-03-16 17:31:52 +00001675 }
Vladimir Marko60584552015-09-03 13:35:12 +00001676 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001677
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001678 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001679 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001680 // Delete this block from the list of predecessors.
1681 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001682 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001683
1684 // Check that `successor` has other predecessors, otherwise `this` is the
1685 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001686 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001687
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001688 // Remove this block's entries in the successor's phis. Skip exceptional
1689 // successors because catch phi inputs do not correspond to predecessor
1690 // blocks but throwing instructions. Their inputs will be updated in step (4).
1691 if (!successor->IsCatchBlock()) {
1692 if (successor->predecessors_.size() == 1u) {
1693 // The successor has just one predecessor left. Replace phis with the only
1694 // remaining input.
1695 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1696 HPhi* phi = phi_it.Current()->AsPhi();
1697 phi->ReplaceWith(phi->InputAt(1 - this_index));
1698 successor->RemovePhi(phi);
1699 }
1700 } else {
1701 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1702 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1703 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001704 }
1705 }
1706 }
Vladimir Marko60584552015-09-03 13:35:12 +00001707 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001708
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001709 // (4) Remove instructions and phis. Instructions should have no remaining uses
1710 // except in catch phis. If an instruction is used by a catch phi at `index`,
1711 // remove `index`-th input of all phis in the catch block since they are
1712 // guaranteed dead. Note that we may miss dead inputs this way but the
1713 // graph will always remain consistent.
1714 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1715 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001716 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001717 RemoveInstruction(insn);
1718 }
1719 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001720 HPhi* insn = it.Current()->AsPhi();
1721 RemoveUsesOfDeadInstruction(insn);
1722 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001723 }
1724
David Brazdil2d7352b2015-04-20 14:52:42 +01001725 // Disconnect from the dominator.
1726 dominator_->RemoveDominatedBlock(this);
1727 SetDominator(nullptr);
1728
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001729 // Delete from the graph, update reverse post order.
1730 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001731 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001732}
1733
1734void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001735 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001736 DCHECK(ContainsElement(dominated_blocks_, other));
1737 DCHECK_EQ(GetSingleSuccessor(), other);
1738 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001739 DCHECK(other->GetPhis().IsEmpty());
1740
David Brazdil2d7352b2015-04-20 14:52:42 +01001741 // Move instructions from `other` to `this`.
1742 DCHECK(EndsWithControlFlowInstruction());
1743 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001744 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001745 other->instructions_.SetBlockOfInstructions(this);
1746 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001747
David Brazdil2d7352b2015-04-20 14:52:42 +01001748 // Remove `other` from the loops it is included in.
1749 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1750 HLoopInformation* loop_info = it.Current();
1751 loop_info->Remove(other);
1752 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001753 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001754 }
1755 }
1756
1757 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001758 successors_.clear();
1759 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001760 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001761 successor->ReplacePredecessor(other, this);
1762 }
1763
David Brazdil2d7352b2015-04-20 14:52:42 +01001764 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001765 RemoveDominatedBlock(other);
1766 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1767 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001768 dominated->SetDominator(this);
1769 }
Vladimir Marko60584552015-09-03 13:35:12 +00001770 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001771 other->dominator_ = nullptr;
1772
1773 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001774 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001775
1776 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001777 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001778 other->SetGraph(nullptr);
1779}
1780
1781void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1782 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001783 DCHECK(GetDominatedBlocks().empty());
1784 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001785 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001786 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001787 DCHECK(other->GetPhis().IsEmpty());
1788 DCHECK(!other->IsInLoop());
1789
1790 // Move instructions from `other` to `this`.
1791 instructions_.Add(other->GetInstructions());
1792 other->instructions_.SetBlockOfInstructions(this);
1793
1794 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001795 successors_.clear();
1796 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001797 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001798 successor->ReplacePredecessor(other, this);
1799 }
1800
1801 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001802 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1803 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001804 dominated->SetDominator(this);
1805 }
Vladimir Marko60584552015-09-03 13:35:12 +00001806 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001807 other->dominator_ = nullptr;
1808 other->graph_ = nullptr;
1809}
1810
1811void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001812 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001813 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001814 predecessor->ReplaceSuccessor(this, other);
1815 }
Vladimir Marko60584552015-09-03 13:35:12 +00001816 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001817 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001818 successor->ReplacePredecessor(this, other);
1819 }
Vladimir Marko60584552015-09-03 13:35:12 +00001820 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1821 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001822 }
1823 GetDominator()->ReplaceDominatedBlock(this, other);
1824 other->SetDominator(GetDominator());
1825 dominator_ = nullptr;
1826 graph_ = nullptr;
1827}
1828
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001829void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001830 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001831 DCHECK(block->GetSuccessors().empty());
1832 DCHECK(block->GetPredecessors().empty());
1833 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001834 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001835 DCHECK(block->GetInstructions().IsEmpty());
1836 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001837
David Brazdilc7af85d2015-05-26 12:05:55 +01001838 if (block->IsExitBlock()) {
1839 exit_block_ = nullptr;
1840 }
1841
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001842 RemoveElement(reverse_post_order_, block);
1843 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001844}
1845
Calin Juravle2e768302015-07-28 14:41:11 +00001846HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001847 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001848 // Update the environments in this graph to have the invoke's environment
1849 // as parent.
1850 {
1851 HReversePostOrderIterator it(*this);
1852 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1853 for (; !it.Done(); it.Advance()) {
1854 HBasicBlock* block = it.Current();
1855 for (HInstructionIterator instr_it(block->GetInstructions());
1856 !instr_it.Done();
1857 instr_it.Advance()) {
1858 HInstruction* current = instr_it.Current();
1859 if (current->NeedsEnvironment()) {
1860 current->GetEnvironment()->SetAndCopyParentChain(
1861 outer_graph->GetArena(), invoke->GetEnvironment());
1862 }
1863 }
1864 }
1865 }
1866 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1867 if (HasBoundsChecks()) {
1868 outer_graph->SetHasBoundsChecks(true);
1869 }
1870
Calin Juravle2e768302015-07-28 14:41:11 +00001871 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001872 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001873 // Simple case of an entry block, a body block, and an exit block.
1874 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001875 HBasicBlock* body = GetBlocks()[1];
1876 DCHECK(GetBlocks()[0]->IsEntryBlock());
1877 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001878 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001879 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001880 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001881
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001882 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1883 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001885
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001886 // Replace the invoke with the return value of the inlined graph.
1887 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001888 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001889 } else {
1890 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001891 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001892
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001894 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 // Need to inline multiple blocks. We split `invoke`'s block
1896 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001897 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 // with the second half.
1899 ArenaAllocator* allocator = outer_graph->GetArena();
1900 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001901 // Note that we split before the invoke only to simplify polymorphic inlining.
1902 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903
Vladimir Markoec7802a2015-10-01 20:57:57 +01001904 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001905 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001906 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001907 exit_block_->ReplaceWith(to);
1908
1909 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001910 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001911 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001912 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001913 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001914 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001915 if (!returns_void) {
1916 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001917 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001918 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001919 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001920 } else {
1921 if (!returns_void) {
1922 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001923 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001924 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001925 to->AddPhi(return_value->AsPhi());
1926 }
Vladimir Marko60584552015-09-03 13:35:12 +00001927 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001928 HInstruction* last = predecessor->GetLastInstruction();
1929 if (!returns_void) {
1930 return_value->AsPhi()->AddInput(last->InputAt(0));
1931 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001932 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001933 predecessor->RemoveInstruction(last);
1934 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001935 }
1936
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001937 // Update the meta information surrounding blocks:
1938 // (1) the graph they are now in,
1939 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001940 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001941 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001942 // Note that we do not need to update catch phi inputs because they
1943 // correspond to the register file of the outer method which the inlinee
1944 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001945
1946 // We don't add the entry block, the exit block, and the first block, which
1947 // has been merged with `at`.
1948 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1949
1950 // We add the `to` block.
1951 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001952 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001953 + kNumberOfNewBlocksInCaller;
1954
1955 // Find the location of `at` in the outer graph's reverse post order. The new
1956 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001957 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001958 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1959
David Brazdil95177982015-10-30 12:56:58 -05001960 HLoopInformation* loop_info = at->GetLoopInformation();
1961 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1962 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1963
1964 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1965 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001966 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1967 HBasicBlock* current = it.Current();
1968 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001969 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001970 DCHECK(current->GetGraph() == this);
1971 current->SetGraph(outer_graph);
1972 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001973 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001974 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001975 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001976 } else if (current->IsLoopHeader()) {
1977 // Clear the information of which blocks are contained in that loop. Since the
1978 // information is stored as a bit vector based on block ids, we have to update
1979 // it, as those block ids were specific to the callee graph and we are now adding
1980 // these blocks to the caller graph.
1981 current->GetLoopInformation()->ClearAllBlocks();
1982 }
1983 if (current->IsInLoop()) {
1984 for (HLoopInformationOutwardIterator loop_it(*current);
1985 !loop_it.Done();
1986 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001987 loop_it.Current()->Add(current);
1988 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989 }
David Brazdil95177982015-10-30 12:56:58 -05001990 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001991 }
1992 }
1993
David Brazdil95177982015-10-30 12:56:58 -05001994 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001995 to->SetGraph(outer_graph);
1996 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001997 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001998 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001999 if (!to->IsInLoop()) {
2000 to->SetLoopInformation(loop_info);
2001 }
David Brazdil7d275372015-04-21 16:36:35 +01002002 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
2003 loop_it.Current()->Add(to);
2004 }
David Brazdil95177982015-10-30 12:56:58 -05002005 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002006 // Only `to` can become a back edge, as the inlined blocks
2007 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05002008 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002009 }
2010 }
David Brazdil95177982015-10-30 12:56:58 -05002011 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002012 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002013
David Brazdil05144f42015-04-16 15:18:00 +01002014 // Update the next instruction id of the outer graph, so that instructions
2015 // added later get bigger ids than those in the inner graph.
2016 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
2017
2018 // Walk over the entry block and:
2019 // - Move constants from the entry block to the outer_graph's entry block,
2020 // - Replace HParameterValue instructions with their real value.
2021 // - Remove suspend checks, that hold an environment.
2022 // We must do this after the other blocks have been inlined, otherwise ids of
2023 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002024 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002025 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2026 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002027 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002028 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002029 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002030 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002031 replacement = outer_graph->GetIntConstant(
2032 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002033 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002034 replacement = outer_graph->GetLongConstant(
2035 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002036 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002037 replacement = outer_graph->GetFloatConstant(
2038 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002039 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002040 replacement = outer_graph->GetDoubleConstant(
2041 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002042 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002043 if (kIsDebugBuild
2044 && invoke->IsInvokeStaticOrDirect()
2045 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2046 // Ensure we do not use the last input of `invoke`, as it
2047 // contains a clinit check which is not an actual argument.
2048 size_t last_input_index = invoke->InputCount() - 1;
2049 DCHECK(parameter_index != last_input_index);
2050 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002051 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002052 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002053 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002054 } else {
2055 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2056 entry_block_->RemoveInstruction(current);
2057 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002058 if (replacement != nullptr) {
2059 current->ReplaceWith(replacement);
2060 // If the current is the return value then we need to update the latter.
2061 if (current == return_value) {
2062 DCHECK_EQ(entry_block_, return_value->GetBlock());
2063 return_value = replacement;
2064 }
2065 }
2066 }
2067
Calin Juravle2e768302015-07-28 14:41:11 +00002068 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002069}
2070
Mingyao Yang3584bce2015-05-19 16:01:59 -07002071/*
2072 * Loop will be transformed to:
2073 * old_pre_header
2074 * |
2075 * if_block
2076 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002077 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002078 * \ /
2079 * new_pre_header
2080 * |
2081 * header
2082 */
2083void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2084 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002085 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002086
Aart Bik3fc7f352015-11-20 22:03:03 -08002087 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002088 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002089 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2090 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002091 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2092 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002093 AddBlock(true_block);
2094 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002095 AddBlock(new_pre_header);
2096
Aart Bik3fc7f352015-11-20 22:03:03 -08002097 header->ReplacePredecessor(old_pre_header, new_pre_header);
2098 old_pre_header->successors_.clear();
2099 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002100
Aart Bik3fc7f352015-11-20 22:03:03 -08002101 old_pre_header->AddSuccessor(if_block);
2102 if_block->AddSuccessor(true_block); // True successor
2103 if_block->AddSuccessor(false_block); // False successor
2104 true_block->AddSuccessor(new_pre_header);
2105 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002106
Aart Bik3fc7f352015-11-20 22:03:03 -08002107 old_pre_header->dominated_blocks_.push_back(if_block);
2108 if_block->SetDominator(old_pre_header);
2109 if_block->dominated_blocks_.push_back(true_block);
2110 true_block->SetDominator(if_block);
2111 if_block->dominated_blocks_.push_back(false_block);
2112 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002113 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002114 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002115 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002116 header->SetDominator(new_pre_header);
2117
Aart Bik3fc7f352015-11-20 22:03:03 -08002118 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002119 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002120 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002121 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002122 reverse_post_order_[index_of_header++] = true_block;
2123 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002124 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002125
Aart Bik3fc7f352015-11-20 22:03:03 -08002126 // Fix loop information.
2127 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2128 if (loop_info != nullptr) {
2129 if_block->SetLoopInformation(loop_info);
2130 true_block->SetLoopInformation(loop_info);
2131 false_block->SetLoopInformation(loop_info);
2132 new_pre_header->SetLoopInformation(loop_info);
2133 // Add blocks to all enveloping loops.
2134 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002135 !loop_it.Done();
2136 loop_it.Advance()) {
2137 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002138 loop_it.Current()->Add(true_block);
2139 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002140 loop_it.Current()->Add(new_pre_header);
2141 }
2142 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002143
2144 // Fix try/catch information.
2145 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2146 ? old_pre_header->GetTryCatchInformation()
2147 : nullptr;
2148 if_block->SetTryCatchInformation(try_catch_info);
2149 true_block->SetTryCatchInformation(try_catch_info);
2150 false_block->SetTryCatchInformation(try_catch_info);
2151 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002152}
2153
David Brazdilf5552582015-12-27 13:36:12 +00002154static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2155 SHARED_REQUIRES(Locks::mutator_lock_) {
2156 if (rti.IsValid()) {
2157 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2158 << " upper_bound_rti: " << upper_bound_rti
2159 << " rti: " << rti;
2160 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2161 }
2162}
2163
Calin Juravle2e768302015-07-28 14:41:11 +00002164void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2165 if (kIsDebugBuild) {
2166 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2167 ScopedObjectAccess soa(Thread::Current());
2168 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2169 if (IsBoundType()) {
2170 // Having the test here spares us from making the method virtual just for
2171 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002172 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002173 }
2174 }
2175 reference_type_info_ = rti;
2176}
2177
David Brazdilf5552582015-12-27 13:36:12 +00002178void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2179 if (kIsDebugBuild) {
2180 ScopedObjectAccess soa(Thread::Current());
2181 DCHECK(upper_bound.IsValid());
2182 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2183 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2184 }
2185 upper_bound_ = upper_bound;
2186 upper_can_be_null_ = can_be_null;
2187}
2188
Calin Juravle2e768302015-07-28 14:41:11 +00002189ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2190
2191ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2192 : type_handle_(type_handle), is_exact_(is_exact) {
2193 if (kIsDebugBuild) {
2194 ScopedObjectAccess soa(Thread::Current());
2195 DCHECK(IsValidHandle(type_handle));
2196 }
2197}
2198
Calin Juravleacf735c2015-02-12 15:25:22 +00002199std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2200 ScopedObjectAccess soa(Thread::Current());
2201 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002202 << " is_valid=" << rhs.IsValid()
2203 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002204 << " is_exact=" << rhs.IsExact()
2205 << " ]";
2206 return os;
2207}
2208
Mark Mendellc4701932015-04-10 13:18:51 -04002209bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2210 // For now, assume that instructions in different blocks may use the
2211 // environment.
2212 // TODO: Use the control flow to decide if this is true.
2213 if (GetBlock() != other->GetBlock()) {
2214 return true;
2215 }
2216
2217 // We know that we are in the same block. Walk from 'this' to 'other',
2218 // checking to see if there is any instruction with an environment.
2219 HInstruction* current = this;
2220 for (; current != other && current != nullptr; current = current->GetNext()) {
2221 // This is a conservative check, as the instruction result may not be in
2222 // the referenced environment.
2223 if (current->HasEnvironment()) {
2224 return true;
2225 }
2226 }
2227
2228 // We should have been called with 'this' before 'other' in the block.
2229 // Just confirm this.
2230 DCHECK(current != nullptr);
2231 return false;
2232}
2233
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002234void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002235 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2236 IntrinsicSideEffects side_effects,
2237 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002238 intrinsic_ = intrinsic;
2239 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002240
Aart Bik5d75afe2015-12-14 11:57:01 -08002241 // Adjust method's side effects from intrinsic table.
2242 switch (side_effects) {
2243 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2244 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2245 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2246 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2247 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002248
2249 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2250 opt.SetDoesNotNeedDexCache();
2251 opt.SetDoesNotNeedEnvironment();
2252 } else {
2253 // If we need an environment, that means there will be a call, which can trigger GC.
2254 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2255 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002256 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002257 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002258}
2259
David Brazdil6de19382016-01-08 17:37:10 +00002260bool HNewInstance::IsStringAlloc() const {
2261 ScopedObjectAccess soa(Thread::Current());
2262 return GetReferenceTypeInfo().IsStringClass();
2263}
2264
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002265bool HInvoke::NeedsEnvironment() const {
2266 if (!IsIntrinsic()) {
2267 return true;
2268 }
2269 IntrinsicOptimizations opt(*this);
2270 return !opt.GetDoesNotNeedEnvironment();
2271}
2272
Vladimir Markodc151b22015-10-15 18:02:30 +01002273bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2274 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002275 return false;
2276 }
2277 if (!IsIntrinsic()) {
2278 return true;
2279 }
2280 IntrinsicOptimizations opt(*this);
2281 return !opt.GetDoesNotNeedDexCache();
2282}
2283
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002284void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2285 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2286 input->AddUseAt(this, index);
2287 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2288 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2289 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2290 InputRecordAt(i).GetUseNode()->SetIndex(i);
2291 }
2292}
2293
Vladimir Markob554b5a2015-11-06 12:57:55 +00002294void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2295 RemoveAsUserOfInput(index);
2296 inputs_.erase(inputs_.begin() + index);
2297 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2298 for (size_t i = index, e = InputCount(); i < e; ++i) {
2299 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2300 InputRecordAt(i).GetUseNode()->SetIndex(i);
2301 }
2302}
2303
Vladimir Markof64242a2015-12-01 14:58:23 +00002304std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2305 switch (rhs) {
2306 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2307 return os << "string_init";
2308 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2309 return os << "recursive";
2310 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2311 return os << "direct";
2312 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2313 return os << "direct_fixup";
2314 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2315 return os << "dex_cache_pc_relative";
2316 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2317 return os << "dex_cache_via_method";
2318 default:
2319 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2320 UNREACHABLE();
2321 }
2322}
2323
Vladimir Markofbb184a2015-11-13 14:47:00 +00002324std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2325 switch (rhs) {
2326 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2327 return os << "explicit";
2328 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2329 return os << "implicit";
2330 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2331 return os << "none";
2332 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002333 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2334 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002335 }
2336}
2337
Mark Mendellc4701932015-04-10 13:18:51 -04002338void HInstruction::RemoveEnvironmentUsers() {
2339 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2340 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2341 HEnvironment* user = user_node->GetUser();
2342 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2343 }
2344 env_uses_.Clear();
2345}
2346
Mark Mendellf6529172015-11-17 11:16:56 -05002347// Returns an instruction with the opposite boolean value from 'cond'.
2348HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2349 ArenaAllocator* allocator = GetArena();
2350
2351 if (cond->IsCondition() &&
2352 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2353 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2354 HInstruction* lhs = cond->InputAt(0);
2355 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002356 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002357 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2358 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2359 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2360 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2361 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2362 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2363 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2364 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2365 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2366 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2367 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002368 default:
2369 LOG(FATAL) << "Unexpected condition";
2370 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002371 }
2372 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2373 return replacement;
2374 } else if (cond->IsIntConstant()) {
2375 HIntConstant* int_const = cond->AsIntConstant();
2376 if (int_const->IsZero()) {
2377 return GetIntConstant(1);
2378 } else {
2379 DCHECK(int_const->IsOne());
2380 return GetIntConstant(0);
2381 }
2382 } else {
2383 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2384 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2385 return replacement;
2386 }
2387}
2388
Roland Levillainc9285912015-12-18 10:38:42 +00002389std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2390 os << "["
2391 << " source=" << rhs.GetSource()
2392 << " destination=" << rhs.GetDestination()
2393 << " type=" << rhs.GetType()
2394 << " instruction=";
2395 if (rhs.GetInstruction() != nullptr) {
2396 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2397 } else {
2398 os << "null";
2399 }
2400 os << " ]";
2401 return os;
2402}
2403
Roland Levillain86503782016-02-11 19:07:30 +00002404std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2405 switch (rhs) {
2406 case TypeCheckKind::kUnresolvedCheck:
2407 return os << "unresolved_check";
2408 case TypeCheckKind::kExactCheck:
2409 return os << "exact_check";
2410 case TypeCheckKind::kClassHierarchyCheck:
2411 return os << "class_hierarchy_check";
2412 case TypeCheckKind::kAbstractClassCheck:
2413 return os << "abstract_class_check";
2414 case TypeCheckKind::kInterfaceCheck:
2415 return os << "interface_check";
2416 case TypeCheckKind::kArrayObjectCheck:
2417 return os << "array_object_check";
2418 case TypeCheckKind::kArrayCheck:
2419 return os << "array_check";
2420 default:
2421 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2422 UNREACHABLE();
2423 }
2424}
2425
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002426} // namespace art