blob: 87b9c022df8af997ab531174200424d97245a2be [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
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010057 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
59 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
60 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
61 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
62 constexpr size_t kDefaultWorklistSize = 8;
63 worklist.reserve(kDefaultWorklistSize);
64 visited->SetBit(entry_block_->GetBlockId());
65 visiting.SetBit(entry_block_->GetBlockId());
66 worklist.push_back(entry_block_);
67
68 while (!worklist.empty()) {
69 HBasicBlock* current = worklist.back();
70 uint32_t current_id = current->GetBlockId();
71 if (successors_visited[current_id] == current->GetSuccessors().size()) {
72 visiting.ClearBit(current_id);
73 worklist.pop_back();
74 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010075 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
76 uint32_t successor_id = successor->GetBlockId();
77 if (visiting.IsBitSet(successor_id)) {
78 DCHECK(ContainsElement(worklist, successor));
79 successor->AddBackEdge(current);
80 } else if (!visited->IsBitSet(successor_id)) {
81 visited->SetBit(successor_id);
82 visiting.SetBit(successor_id);
83 worklist.push_back(successor);
84 }
85 }
86 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000087}
88
Roland Levillainfc600dc2014-12-02 17:16:31 +000089static void RemoveAsUser(HInstruction* instruction) {
90 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000091 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000092 }
93
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010094 for (HEnvironment* environment = instruction->GetEnvironment();
95 environment != nullptr;
96 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000097 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000098 if (environment->GetInstructionAt(i) != nullptr) {
99 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000100 }
101 }
102 }
103}
104
105void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100106 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000107 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100108 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000109 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
112 RemoveAsUser(it.Current());
113 }
114 }
115 }
116}
117
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100118void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100119 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000120 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100121 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000122 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100123 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000124 for (HBasicBlock* successor : block->GetSuccessors()) {
125 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000126 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // Remove the block from the list of blocks, so that further analyses
128 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100129 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000130 }
131 }
132}
133
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000134GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100135 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
136 // edges. This invariant simplifies building SSA form because Phis cannot
137 // collect both normal- and exceptional-flow values at the same time.
138 SimplifyCatchBlocks();
139
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100140 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 FindBackEdges(&visited);
144
David Brazdilffee3d32015-07-06 11:48:53 +0100145 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 // the initial DFS as users from other instructions, so that
147 // users can be safely removed before uses later.
148 RemoveInstructionsAsUsersFromDeadBlocks(visited);
149
David Brazdilffee3d32015-07-06 11:48:53 +0100150 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000151 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 // predecessors list of live blocks.
153 RemoveDeadBlocks(visited);
154
David Brazdilffee3d32015-07-06 11:48:53 +0100155 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100156 // dominators and the reverse post order.
157 SimplifyCFG();
158
David Brazdilffee3d32015-07-06 11:48:53 +0100159 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100160 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161
162 // (7) Analyze loops discover through back edge analysis, and
163 // set the loop information on each block.
164 GraphAnalysisResult result = AnalyzeLoops();
165 if (result != kAnalysisSuccess) {
166 return result;
167 }
168
169 // (8) Precompute per-block try membership before entering the SSA builder,
170 // which needs the information to build catch block phis from values of
171 // locals at throwing instructions inside try blocks.
172 ComputeTryBlockInformation();
173
174 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100175}
176
177void HGraph::ClearDominanceInformation() {
178 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
179 it.Current()->ClearDominanceInformation();
180 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100181 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100182}
183
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000184void HGraph::ClearLoopInformation() {
185 SetHasIrreducibleLoops(false);
186 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000187 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000188 }
189}
190
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100191void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000192 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100193 dominator_ = nullptr;
194}
195
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000196HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
197 HInstruction* instruction = GetFirstInstruction();
198 while (instruction->IsParallelMove()) {
199 instruction = instruction->GetNext();
200 }
201 return instruction;
202}
203
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100204void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100205 DCHECK(reverse_post_order_.empty());
206 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100207 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100208
209 // Number of visits of a given node, indexed by block id.
210 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
211 // Number of successors visited from a given node, indexed by block id.
212 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
213 // Nodes for which we need to visit successors.
214 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
215 constexpr size_t kDefaultWorklistSize = 8;
216 worklist.reserve(kDefaultWorklistSize);
217 worklist.push_back(entry_block_);
218
219 while (!worklist.empty()) {
220 HBasicBlock* current = worklist.back();
221 uint32_t current_id = current->GetBlockId();
222 if (successors_visited[current_id] == current->GetSuccessors().size()) {
223 worklist.pop_back();
224 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100225 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
226
227 if (successor->GetDominator() == nullptr) {
228 successor->SetDominator(current);
229 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000230 // The CommonDominator can work for multiple blocks as long as the
231 // domination information doesn't change. However, since we're changing
232 // that information here, we can use the finder only for pairs of blocks.
233 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100234 }
235
236 // Once all the forward edges have been visited, we know the immediate
237 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100238 if (++visits[successor->GetBlockId()] ==
239 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100240 reverse_post_order_.push_back(successor);
241 worklist.push_back(successor);
242 }
243 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000244 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000245
246 // Populate `dominated_blocks_` information after computing all dominators.
247 // The potential presence of irreducible loops require to do it after.
248 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
249 HBasicBlock* block = it.Current();
250 if (!block->IsEntryBlock()) {
251 block->GetDominator()->AddDominatedBlock(block);
252 }
253 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000254}
255
David Brazdilfc6a86a2015-06-26 10:33:45 +0000256HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000257 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
258 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000259 // Use `InsertBetween` to ensure the predecessor index and successor index of
260 // `block` and `successor` are preserved.
261 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000262 return new_block;
263}
264
265void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
266 // Insert a new node between `block` and `successor` to split the
267 // critical edge.
268 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600269 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100270 if (successor->IsLoopHeader()) {
271 // If we split at a back edge boundary, make the new block the back edge.
272 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000273 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100274 info->RemoveBackEdge(block);
275 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100276 }
277 }
278}
279
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280void HGraph::SimplifyLoop(HBasicBlock* header) {
281 HLoopInformation* info = header->GetLoopInformation();
282
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100283 // Make sure the loop has only one pre header. This simplifies SSA building by having
284 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000285 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
286 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000287 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000288 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100289 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600291 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100292
Vladimir Marko60584552015-09-03 13:35:12 +0000293 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100294 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100295 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100296 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298 }
299 }
300 pre_header->AddSuccessor(header);
301 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100302
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100303 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100304 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
305 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000306 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100307 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100308 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000309 header->predecessors_[pred] = to_swap;
310 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100311 break;
312 }
313 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100314 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100315
316 // Place the suspend check at the beginning of the header, so that live registers
317 // will be known when allocating registers. Note that code generation can still
318 // generate the suspend check at the back edge, but needs to be careful with
319 // loop phi spill slots (which are not written to at back edge).
320 HInstruction* first_instruction = header->GetFirstInstruction();
321 if (!first_instruction->IsSuspendCheck()) {
322 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
323 header->InsertInstructionBefore(check, first_instruction);
324 first_instruction = check;
325 }
326 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100327}
328
David Brazdilffee3d32015-07-06 11:48:53 +0100329static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100330 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100331 if (!predecessor->EndsWithTryBoundary()) {
332 // Only edges from HTryBoundary can be exceptional.
333 return false;
334 }
335 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
336 if (try_boundary->GetNormalFlowSuccessor() == &block) {
337 // This block is the normal-flow successor of `try_boundary`, but it could
338 // also be one of its exception handlers if catch blocks have not been
339 // simplified yet. Predecessors are unordered, so we will consider the first
340 // occurrence to be the normal edge and a possible second occurrence to be
341 // the exceptional edge.
342 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
343 } else {
344 // This is not the normal-flow successor of `try_boundary`, hence it must be
345 // one of its exception handlers.
346 DCHECK(try_boundary->HasExceptionHandler(block));
347 return true;
348 }
349}
350
351void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100352 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
353 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
354 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
355 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000356 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100357 continue;
358 }
359
360 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000361 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100362 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
363 exceptional_predecessors_only = false;
364 break;
365 }
366 }
367
368 if (!exceptional_predecessors_only) {
369 // Catch block has normal-flow predecessors and needs to be simplified.
370 // Splitting the block before its first instruction moves all its
371 // instructions into `normal_block` and links the two blocks with a Goto.
372 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
373 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000374 //
David Brazdilffee3d32015-07-06 11:48:53 +0100375 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000376 // a move-exception instruction, as guaranteed by the verifier. However,
377 // trivially dead predecessors are ignored by the verifier and such code
378 // has not been removed at this stage. We therefore ignore the assumption
379 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
380 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
381 if (normal_block == nullptr) {
382 // Catch block is either empty or only contains a move-exception. It must
383 // therefore be dead and will be removed during initial DCE. Do nothing.
384 DCHECK(!catch_block->EndsWithControlFlowInstruction());
385 } else {
386 // Catch block was split. Re-link normal-flow edges to the new block.
387 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
388 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
389 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
390 --j;
391 }
David Brazdilffee3d32015-07-06 11:48:53 +0100392 }
393 }
394 }
395 }
396}
397
398void HGraph::ComputeTryBlockInformation() {
399 // Iterate in reverse post order to propagate try membership information from
400 // predecessors to their successors.
401 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
402 HBasicBlock* block = it.Current();
403 if (block->IsEntryBlock() || block->IsCatchBlock()) {
404 // Catch blocks after simplification have only exceptional predecessors
405 // and hence are never in tries.
406 continue;
407 }
408
409 // Infer try membership from the first predecessor. Having simplified loops,
410 // the first predecessor can never be a back edge and therefore it must have
411 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100412 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100413 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100414 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000415 if (try_entry != nullptr &&
416 (block->GetTryCatchInformation() == nullptr ||
417 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
418 // We are either setting try block membership for the first time or it
419 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100420 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
421 }
David Brazdilffee3d32015-07-06 11:48:53 +0100422 }
423}
424
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100425void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000426// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000428 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100429 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
430 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
431 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
432 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100433 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000434 if (block->GetSuccessors().size() > 1) {
435 // Only split normal-flow edges. We cannot split exceptional edges as they
436 // are synthesized (approximate real control flow), and we do not need to
437 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000438 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
439 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
440 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100441 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000442 if (successor == exit_block_) {
443 // Throw->TryBoundary->Exit. Special case which we do not want to split
444 // because Goto->Exit is not allowed.
445 DCHECK(block->IsSingleTryBoundary());
446 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
447 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000449 // SplitCriticalEdge could have invalidated the `normal_successors`
450 // ArrayRef. We must re-acquire it.
451 normal_successors = block->GetNormalSuccessors();
452 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
453 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 }
455 }
456 }
457 if (block->IsLoopHeader()) {
458 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000459 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
460 // We are being called by the dead code elimiation pass, and what used to be
461 // a loop got dismantled. Just remove the suspend check.
462 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100463 }
464 }
465}
466
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000467GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100468 // Order does not matter.
469 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
470 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100471 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100472 if (block->IsCatchBlock()) {
473 // TODO: Dealing with exceptional back edges could be tricky because
474 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000475 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100476 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000477 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478 }
479 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000480 return kAnalysisSuccess;
481}
482
483void HLoopInformation::Dump(std::ostream& os) {
484 os << "header: " << header_->GetBlockId() << std::endl;
485 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
486 for (HBasicBlock* block : back_edges_) {
487 os << "back edge: " << block->GetBlockId() << std::endl;
488 }
489 for (HBasicBlock* block : header_->GetPredecessors()) {
490 os << "predecessor: " << block->GetBlockId() << std::endl;
491 }
492 for (uint32_t idx : blocks_.Indexes()) {
493 os << " in loop: " << idx << std::endl;
494 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100495}
496
David Brazdil8d5b8b22015-03-24 10:51:52 +0000497void HGraph::InsertConstant(HConstant* constant) {
498 // New constants are inserted before the final control-flow instruction
499 // of the graph, or at its end if called from the graph builder.
500 if (entry_block_->EndsWithControlFlowInstruction()) {
501 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000502 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000503 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000504 }
505}
506
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600507HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100508 // For simplicity, don't bother reviving the cached null constant if it is
509 // not null and not in a block. Otherwise, we need to clear the instruction
510 // id and/or any invariants the graph is assuming when adding new instructions.
511 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600512 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000513 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000514 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000515 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000516 if (kIsDebugBuild) {
517 ScopedObjectAccess soa(Thread::Current());
518 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
519 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000520 return cached_null_constant_;
521}
522
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100523HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100524 // For simplicity, don't bother reviving the cached current method if it is
525 // not null and not in a block. Otherwise, we need to clear the instruction
526 // id and/or any invariants the graph is assuming when adding new instructions.
527 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700528 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600529 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
530 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100531 if (entry_block_->GetFirstInstruction() == nullptr) {
532 entry_block_->AddInstruction(cached_current_method_);
533 } else {
534 entry_block_->InsertInstructionBefore(
535 cached_current_method_, entry_block_->GetFirstInstruction());
536 }
537 }
538 return cached_current_method_;
539}
540
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600541HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000542 switch (type) {
543 case Primitive::Type::kPrimBoolean:
544 DCHECK(IsUint<1>(value));
545 FALLTHROUGH_INTENDED;
546 case Primitive::Type::kPrimByte:
547 case Primitive::Type::kPrimChar:
548 case Primitive::Type::kPrimShort:
549 case Primitive::Type::kPrimInt:
550 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600551 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552
553 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600554 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000555
556 default:
557 LOG(FATAL) << "Unsupported constant type";
558 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000559 }
David Brazdil46e2a392015-03-16 17:31:52 +0000560}
561
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000562void HGraph::CacheFloatConstant(HFloatConstant* constant) {
563 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
564 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
565 cached_float_constants_.Overwrite(value, constant);
566}
567
568void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
569 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
570 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
571 cached_double_constants_.Overwrite(value, constant);
572}
573
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000574void HLoopInformation::Add(HBasicBlock* block) {
575 blocks_.SetBit(block->GetBlockId());
576}
577
David Brazdil46e2a392015-03-16 17:31:52 +0000578void HLoopInformation::Remove(HBasicBlock* block) {
579 blocks_.ClearBit(block->GetBlockId());
580}
581
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100582void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
583 if (blocks_.IsBitSet(block->GetBlockId())) {
584 return;
585 }
586
587 blocks_.SetBit(block->GetBlockId());
588 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000589 for (HBasicBlock* predecessor : block->GetPredecessors()) {
590 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100591 }
592}
593
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
595 if (blocks_.IsBitSet(block->GetBlockId())) {
596 return;
597 }
598
599 if (block->IsLoopHeader()) {
600 // If we hit a loop header in an irreducible loop, we first check if the
601 // pre header of that loop belongs to the currently analyzed loop. If it does,
602 // then we visit the back edges.
603 // Note that we cannot use GetPreHeader, as the loop may have not been populated
604 // yet.
605 HBasicBlock* pre_header = block->GetPredecessors()[0];
606 PopulateIrreducibleRecursive(pre_header);
607 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
608 blocks_.SetBit(block->GetBlockId());
609 block->SetInLoop(this);
610 HLoopInformation* info = block->GetLoopInformation();
611 for (HBasicBlock* back_edge : info->GetBackEdges()) {
612 PopulateIrreducibleRecursive(back_edge);
613 }
614 }
615 } else {
616 // Visit all predecessors. If one predecessor is part of the loop, this
617 // block is also part of this loop.
618 for (HBasicBlock* predecessor : block->GetPredecessors()) {
619 PopulateIrreducibleRecursive(predecessor);
620 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
621 blocks_.SetBit(block->GetBlockId());
622 block->SetInLoop(this);
623 }
624 }
625 }
626}
627
628void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100629 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000630 // Populate this loop: starting with the back edge, recursively add predecessors
631 // that are not already part of that loop. Set the header as part of the loop
632 // to end the recursion.
633 // This is a recursive implementation of the algorithm described in
634 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
635 blocks_.SetBit(header_->GetBlockId());
636 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100637 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100638 DCHECK(back_edge->GetDominator() != nullptr);
639 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000640 irreducible_ = true;
641 header_->GetGraph()->SetHasIrreducibleLoops(true);
642 PopulateIrreducibleRecursive(back_edge);
643 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000644 if (header_->GetGraph()->IsCompilingOsr()) {
645 irreducible_ = true;
646 header_->GetGraph()->SetHasIrreducibleLoops(true);
647 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000648 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100649 }
David Brazdila4b8c212015-05-07 09:59:30 +0100650 }
651}
652
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100653HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000654 HBasicBlock* block = header_->GetPredecessors()[0];
655 DCHECK(irreducible_ || (block == header_->GetDominator()));
656 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100657}
658
659bool HLoopInformation::Contains(const HBasicBlock& block) const {
660 return blocks_.IsBitSet(block.GetBlockId());
661}
662
663bool HLoopInformation::IsIn(const HLoopInformation& other) const {
664 return other.blocks_.IsBitSet(header_->GetBlockId());
665}
666
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800667bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
668 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700669}
670
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100671size_t HLoopInformation::GetLifetimeEnd() const {
672 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100673 for (HBasicBlock* back_edge : GetBackEdges()) {
674 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100675 }
676 return last_position;
677}
678
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100679bool HBasicBlock::Dominates(HBasicBlock* other) const {
680 // Walk up the dominator tree from `other`, to find out if `this`
681 // is an ancestor.
682 HBasicBlock* current = other;
683 while (current != nullptr) {
684 if (current == this) {
685 return true;
686 }
687 current = current->GetDominator();
688 }
689 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100690}
691
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100692static void UpdateInputsUsers(HInstruction* instruction) {
693 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
694 instruction->InputAt(i)->AddUseAt(instruction, i);
695 }
696 // Environment should be created later.
697 DCHECK(!instruction->HasEnvironment());
698}
699
Roland Levillainccc07a92014-09-16 14:48:16 +0100700void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
701 HInstruction* replacement) {
702 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400703 if (initial->IsControlFlow()) {
704 // We can only replace a control flow instruction with another control flow instruction.
705 DCHECK(replacement->IsControlFlow());
706 DCHECK_EQ(replacement->GetId(), -1);
707 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
708 DCHECK_EQ(initial->GetBlock(), this);
709 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
710 DCHECK(initial->GetUses().IsEmpty());
711 DCHECK(initial->GetEnvUses().IsEmpty());
712 replacement->SetBlock(this);
713 replacement->SetId(GetGraph()->GetNextInstructionId());
714 instructions_.InsertInstructionBefore(replacement, initial);
715 UpdateInputsUsers(replacement);
716 } else {
717 InsertInstructionBefore(replacement, initial);
718 initial->ReplaceWith(replacement);
719 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100720 RemoveInstruction(initial);
721}
722
David Brazdil74eb1b22015-12-14 11:44:01 +0000723void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
724 DCHECK(!cursor->IsPhi());
725 DCHECK(!insn->IsPhi());
726 DCHECK(!insn->IsControlFlow());
727 DCHECK(insn->CanBeMoved());
728 DCHECK(!insn->HasSideEffects());
729
730 HBasicBlock* from_block = insn->GetBlock();
731 HBasicBlock* to_block = cursor->GetBlock();
732 DCHECK(from_block != to_block);
733
734 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
735 insn->SetBlock(to_block);
736 to_block->instructions_.InsertInstructionBefore(insn, cursor);
737}
738
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100739static void Add(HInstructionList* instruction_list,
740 HBasicBlock* block,
741 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000742 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000743 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100744 instruction->SetBlock(block);
745 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100746 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100747 instruction_list->AddInstruction(instruction);
748}
749
750void HBasicBlock::AddInstruction(HInstruction* instruction) {
751 Add(&instructions_, this, instruction);
752}
753
754void HBasicBlock::AddPhi(HPhi* phi) {
755 Add(&phis_, this, phi);
756}
757
David Brazdilc3d743f2015-04-22 13:40:50 +0100758void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
759 DCHECK(!cursor->IsPhi());
760 DCHECK(!instruction->IsPhi());
761 DCHECK_EQ(instruction->GetId(), -1);
762 DCHECK_NE(cursor->GetId(), -1);
763 DCHECK_EQ(cursor->GetBlock(), this);
764 DCHECK(!instruction->IsControlFlow());
765 instruction->SetBlock(this);
766 instruction->SetId(GetGraph()->GetNextInstructionId());
767 UpdateInputsUsers(instruction);
768 instructions_.InsertInstructionBefore(instruction, cursor);
769}
770
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100771void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
772 DCHECK(!cursor->IsPhi());
773 DCHECK(!instruction->IsPhi());
774 DCHECK_EQ(instruction->GetId(), -1);
775 DCHECK_NE(cursor->GetId(), -1);
776 DCHECK_EQ(cursor->GetBlock(), this);
777 DCHECK(!instruction->IsControlFlow());
778 DCHECK(!cursor->IsControlFlow());
779 instruction->SetBlock(this);
780 instruction->SetId(GetGraph()->GetNextInstructionId());
781 UpdateInputsUsers(instruction);
782 instructions_.InsertInstructionAfter(instruction, cursor);
783}
784
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100785void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
786 DCHECK_EQ(phi->GetId(), -1);
787 DCHECK_NE(cursor->GetId(), -1);
788 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100789 phi->SetBlock(this);
790 phi->SetId(GetGraph()->GetNextInstructionId());
791 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100792 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100793}
794
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100795static void Remove(HInstructionList* instruction_list,
796 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000797 HInstruction* instruction,
798 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100799 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100800 instruction->SetBlock(nullptr);
801 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000802 if (ensure_safety) {
803 DCHECK(instruction->GetUses().IsEmpty());
804 DCHECK(instruction->GetEnvUses().IsEmpty());
805 RemoveAsUser(instruction);
806 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100807}
808
David Brazdil1abb4192015-02-17 18:33:36 +0000809void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100810 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000811 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100812}
813
David Brazdil1abb4192015-02-17 18:33:36 +0000814void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
815 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100816}
817
David Brazdilc7508e92015-04-27 13:28:57 +0100818void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
819 if (instruction->IsPhi()) {
820 RemovePhi(instruction->AsPhi(), ensure_safety);
821 } else {
822 RemoveInstruction(instruction, ensure_safety);
823 }
824}
825
Vladimir Marko71bf8092015-09-15 15:33:14 +0100826void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
827 for (size_t i = 0; i < locals.size(); i++) {
828 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100829 SetRawEnvAt(i, instruction);
830 if (instruction != nullptr) {
831 instruction->AddEnvUseAt(this, i);
832 }
833 }
834}
835
David Brazdiled596192015-01-23 10:39:45 +0000836void HEnvironment::CopyFrom(HEnvironment* env) {
837 for (size_t i = 0; i < env->Size(); i++) {
838 HInstruction* instruction = env->GetInstructionAt(i);
839 SetRawEnvAt(i, instruction);
840 if (instruction != nullptr) {
841 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100842 }
David Brazdiled596192015-01-23 10:39:45 +0000843 }
844}
845
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700846void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
847 HBasicBlock* loop_header) {
848 DCHECK(loop_header->IsLoopHeader());
849 for (size_t i = 0; i < env->Size(); i++) {
850 HInstruction* instruction = env->GetInstructionAt(i);
851 SetRawEnvAt(i, instruction);
852 if (instruction == nullptr) {
853 continue;
854 }
855 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
856 // At the end of the loop pre-header, the corresponding value for instruction
857 // is the first input of the phi.
858 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700859 SetRawEnvAt(i, initial);
860 initial->AddEnvUseAt(this, i);
861 } else {
862 instruction->AddEnvUseAt(this, i);
863 }
864 }
865}
866
David Brazdil1abb4192015-02-17 18:33:36 +0000867void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100868 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000869 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870}
871
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000872HInstruction::InstructionKind HInstruction::GetKind() const {
873 return GetKindInternal();
874}
875
Calin Juravle77520bc2015-01-12 18:45:46 +0000876HInstruction* HInstruction::GetNextDisregardingMoves() const {
877 HInstruction* next = GetNext();
878 while (next != nullptr && next->IsParallelMove()) {
879 next = next->GetNext();
880 }
881 return next;
882}
883
884HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
885 HInstruction* previous = GetPrevious();
886 while (previous != nullptr && previous->IsParallelMove()) {
887 previous = previous->GetPrevious();
888 }
889 return previous;
890}
891
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100892void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000893 if (first_instruction_ == nullptr) {
894 DCHECK(last_instruction_ == nullptr);
895 first_instruction_ = last_instruction_ = instruction;
896 } else {
897 last_instruction_->next_ = instruction;
898 instruction->previous_ = last_instruction_;
899 last_instruction_ = instruction;
900 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000901}
902
David Brazdilc3d743f2015-04-22 13:40:50 +0100903void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
904 DCHECK(Contains(cursor));
905 if (cursor == first_instruction_) {
906 cursor->previous_ = instruction;
907 instruction->next_ = cursor;
908 first_instruction_ = instruction;
909 } else {
910 instruction->previous_ = cursor->previous_;
911 instruction->next_ = cursor;
912 cursor->previous_ = instruction;
913 instruction->previous_->next_ = instruction;
914 }
915}
916
917void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
918 DCHECK(Contains(cursor));
919 if (cursor == last_instruction_) {
920 cursor->next_ = instruction;
921 instruction->previous_ = cursor;
922 last_instruction_ = instruction;
923 } else {
924 instruction->next_ = cursor->next_;
925 instruction->previous_ = cursor;
926 cursor->next_ = instruction;
927 instruction->next_->previous_ = instruction;
928 }
929}
930
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931void HInstructionList::RemoveInstruction(HInstruction* instruction) {
932 if (instruction->previous_ != nullptr) {
933 instruction->previous_->next_ = instruction->next_;
934 }
935 if (instruction->next_ != nullptr) {
936 instruction->next_->previous_ = instruction->previous_;
937 }
938 if (instruction == first_instruction_) {
939 first_instruction_ = instruction->next_;
940 }
941 if (instruction == last_instruction_) {
942 last_instruction_ = instruction->previous_;
943 }
944}
945
Roland Levillain6b469232014-09-25 10:10:38 +0100946bool HInstructionList::Contains(HInstruction* instruction) const {
947 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
948 if (it.Current() == instruction) {
949 return true;
950 }
951 }
952 return false;
953}
954
Roland Levillainccc07a92014-09-16 14:48:16 +0100955bool HInstructionList::FoundBefore(const HInstruction* instruction1,
956 const HInstruction* instruction2) const {
957 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
958 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
959 if (it.Current() == instruction1) {
960 return true;
961 }
962 if (it.Current() == instruction2) {
963 return false;
964 }
965 }
966 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
967 return true;
968}
969
Roland Levillain6c82d402014-10-13 16:10:27 +0100970bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
971 if (other_instruction == this) {
972 // An instruction does not strictly dominate itself.
973 return false;
974 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100975 HBasicBlock* block = GetBlock();
976 HBasicBlock* other_block = other_instruction->GetBlock();
977 if (block != other_block) {
978 return GetBlock()->Dominates(other_instruction->GetBlock());
979 } else {
980 // If both instructions are in the same block, ensure this
981 // instruction comes before `other_instruction`.
982 if (IsPhi()) {
983 if (!other_instruction->IsPhi()) {
984 // Phis appear before non phi-instructions so this instruction
985 // dominates `other_instruction`.
986 return true;
987 } else {
988 // There is no order among phis.
989 LOG(FATAL) << "There is no dominance between phis of a same block.";
990 return false;
991 }
992 } else {
993 // `this` is not a phi.
994 if (other_instruction->IsPhi()) {
995 // Phis appear before non phi-instructions so this instruction
996 // does not dominate `other_instruction`.
997 return false;
998 } else {
999 // Check whether this instruction comes before
1000 // `other_instruction` in the instruction list.
1001 return block->GetInstructions().FoundBefore(this, other_instruction);
1002 }
1003 }
1004 }
1005}
1006
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001007void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001008 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001009 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1010 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001011 HInstruction* user = current->GetUser();
1012 size_t input_index = current->GetIndex();
1013 user->SetRawInputAt(input_index, other);
1014 other->AddUseAt(user, input_index);
1015 }
1016
David Brazdiled596192015-01-23 10:39:45 +00001017 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1018 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001019 HEnvironment* user = current->GetUser();
1020 size_t input_index = current->GetIndex();
1021 user->SetRawEnvAt(input_index, other);
1022 other->AddEnvUseAt(user, input_index);
1023 }
1024
David Brazdiled596192015-01-23 10:39:45 +00001025 uses_.Clear();
1026 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001027}
1028
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001029void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001030 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001031 SetRawInputAt(index, replacement);
1032 replacement->AddUseAt(this, index);
1033}
1034
Nicolas Geoffray39468442014-09-02 15:17:15 +01001035size_t HInstruction::EnvironmentSize() const {
1036 return HasEnvironment() ? environment_->Size() : 0;
1037}
1038
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039void HPhi::AddInput(HInstruction* input) {
1040 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001041 inputs_.push_back(HUserRecord<HInstruction*>(input));
1042 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001043}
1044
David Brazdil2d7352b2015-04-20 14:52:42 +01001045void HPhi::RemoveInputAt(size_t index) {
1046 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001047 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001048 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001049 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001050 InputRecordAt(i).GetUseNode()->SetIndex(i);
1051 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001052}
1053
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001054#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001055void H##name::Accept(HGraphVisitor* visitor) { \
1056 visitor->Visit##name(this); \
1057}
1058
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001059FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001060
1061#undef DEFINE_ACCEPT
1062
1063void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001064 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1065 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001066 if (block != nullptr) {
1067 VisitBasicBlock(block);
1068 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001069 }
1070}
1071
Roland Levillain633021e2014-10-01 14:12:25 +01001072void HGraphVisitor::VisitReversePostOrder() {
1073 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1074 VisitBasicBlock(it.Current());
1075 }
1076}
1077
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001078void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001079 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001080 it.Current()->Accept(this);
1081 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001082 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001083 it.Current()->Accept(this);
1084 }
1085}
1086
Mark Mendelle82549b2015-05-06 10:55:34 -04001087HConstant* HTypeConversion::TryStaticEvaluation() const {
1088 HGraph* graph = GetBlock()->GetGraph();
1089 if (GetInput()->IsIntConstant()) {
1090 int32_t value = GetInput()->AsIntConstant()->GetValue();
1091 switch (GetResultType()) {
1092 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001093 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001094 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001095 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001096 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001097 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001098 default:
1099 return nullptr;
1100 }
1101 } else if (GetInput()->IsLongConstant()) {
1102 int64_t value = GetInput()->AsLongConstant()->GetValue();
1103 switch (GetResultType()) {
1104 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001106 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001107 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001108 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001110 default:
1111 return nullptr;
1112 }
1113 } else if (GetInput()->IsFloatConstant()) {
1114 float value = GetInput()->AsFloatConstant()->GetValue();
1115 switch (GetResultType()) {
1116 case Primitive::kPrimInt:
1117 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001118 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001119 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001120 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001121 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001122 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1123 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 case Primitive::kPrimLong:
1125 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001126 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001129 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1131 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001134 default:
1135 return nullptr;
1136 }
1137 } else if (GetInput()->IsDoubleConstant()) {
1138 double value = GetInput()->AsDoubleConstant()->GetValue();
1139 switch (GetResultType()) {
1140 case Primitive::kPrimInt:
1141 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001142 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001143 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001145 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001146 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1147 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 case Primitive::kPrimLong:
1149 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001153 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1155 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001156 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001157 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001158 default:
1159 return nullptr;
1160 }
1161 }
1162 return nullptr;
1163}
1164
Roland Levillain9240d6a2014-10-20 16:47:04 +01001165HConstant* HUnaryOperation::TryStaticEvaluation() const {
1166 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001167 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001168 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001169 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001170 } else if (kEnableFloatingPointStaticEvaluation) {
1171 if (GetInput()->IsFloatConstant()) {
1172 return Evaluate(GetInput()->AsFloatConstant());
1173 } else if (GetInput()->IsDoubleConstant()) {
1174 return Evaluate(GetInput()->AsDoubleConstant());
1175 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001176 }
1177 return nullptr;
1178}
1179
1180HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001181 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1182 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001183 } else if (GetLeft()->IsLongConstant()) {
1184 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001185 // The binop(long, int) case is only valid for shifts and rotations.
1186 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001187 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1188 } else if (GetRight()->IsLongConstant()) {
1189 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001190 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001191 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001192 // The binop(null, null) case is only valid for equal and not-equal conditions.
1193 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001194 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001195 } else if (kEnableFloatingPointStaticEvaluation) {
1196 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1197 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1198 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1199 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1200 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001201 }
1202 return nullptr;
1203}
Dave Allison20dfc792014-06-16 20:44:29 -07001204
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001205HConstant* HBinaryOperation::GetConstantRight() const {
1206 if (GetRight()->IsConstant()) {
1207 return GetRight()->AsConstant();
1208 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1209 return GetLeft()->AsConstant();
1210 } else {
1211 return nullptr;
1212 }
1213}
1214
1215// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001216// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001217HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1218 HInstruction* most_constant_right = GetConstantRight();
1219 if (most_constant_right == nullptr) {
1220 return nullptr;
1221 } else if (most_constant_right == GetLeft()) {
1222 return GetRight();
1223 } else {
1224 return GetLeft();
1225 }
1226}
1227
Roland Levillain31dd3d62016-02-16 12:21:02 +00001228std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1229 switch (rhs) {
1230 case ComparisonBias::kNoBias:
1231 return os << "no_bias";
1232 case ComparisonBias::kGtBias:
1233 return os << "gt_bias";
1234 case ComparisonBias::kLtBias:
1235 return os << "lt_bias";
1236 default:
1237 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1238 UNREACHABLE();
1239 }
1240}
1241
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001242bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1243 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001244}
1245
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001246bool HInstruction::Equals(HInstruction* other) const {
1247 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001248 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001249 if (!InstructionDataEquals(other)) return false;
1250 if (GetType() != other->GetType()) return false;
1251 if (InputCount() != other->InputCount()) return false;
1252
1253 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1254 if (InputAt(i) != other->InputAt(i)) return false;
1255 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001256 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001257 return true;
1258}
1259
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001260std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1261#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1262 switch (rhs) {
1263 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1264 default:
1265 os << "Unknown instruction kind " << static_cast<int>(rhs);
1266 break;
1267 }
1268#undef DECLARE_CASE
1269 return os;
1270}
1271
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001272void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001273 next_->previous_ = previous_;
1274 if (previous_ != nullptr) {
1275 previous_->next_ = next_;
1276 }
1277 if (block_->instructions_.first_instruction_ == this) {
1278 block_->instructions_.first_instruction_ = next_;
1279 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001280 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001281
1282 previous_ = cursor->previous_;
1283 if (previous_ != nullptr) {
1284 previous_->next_ = this;
1285 }
1286 next_ = cursor;
1287 cursor->previous_ = this;
1288 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001289
1290 if (block_->instructions_.first_instruction_ == cursor) {
1291 block_->instructions_.first_instruction_ = this;
1292 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001293}
1294
Vladimir Markofb337ea2015-11-25 15:25:10 +00001295void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1296 DCHECK(!CanThrow());
1297 DCHECK(!HasSideEffects());
1298 DCHECK(!HasEnvironmentUses());
1299 DCHECK(HasNonEnvironmentUses());
1300 DCHECK(!IsPhi()); // Makes no sense for Phi.
1301 DCHECK_EQ(InputCount(), 0u);
1302
1303 // Find the target block.
1304 HUseIterator<HInstruction*> uses_it(GetUses());
1305 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1306 uses_it.Advance();
1307 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1308 uses_it.Advance();
1309 }
1310 if (!uses_it.Done()) {
1311 // This instruction has uses in two or more blocks. Find the common dominator.
1312 CommonDominator finder(target_block);
1313 for (; !uses_it.Done(); uses_it.Advance()) {
1314 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1315 }
1316 target_block = finder.Get();
1317 DCHECK(target_block != nullptr);
1318 }
1319 // Move to the first dominator not in a loop.
1320 while (target_block->IsInLoop()) {
1321 target_block = target_block->GetDominator();
1322 DCHECK(target_block != nullptr);
1323 }
1324
1325 // Find insertion position.
1326 HInstruction* insert_pos = nullptr;
1327 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1328 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1329 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1330 insert_pos = uses_it2.Current()->GetUser();
1331 }
1332 }
1333 if (insert_pos == nullptr) {
1334 // No user in `target_block`, insert before the control flow instruction.
1335 insert_pos = target_block->GetLastInstruction();
1336 DCHECK(insert_pos->IsControlFlow());
1337 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1338 if (insert_pos->IsIf()) {
1339 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1340 if (if_input == insert_pos->GetPrevious()) {
1341 insert_pos = if_input;
1342 }
1343 }
1344 }
1345 MoveBefore(insert_pos);
1346}
1347
David Brazdilfc6a86a2015-06-26 10:33:45 +00001348HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001349 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001350 DCHECK_EQ(cursor->GetBlock(), this);
1351
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001352 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1353 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001354 new_block->instructions_.first_instruction_ = cursor;
1355 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1356 instructions_.last_instruction_ = cursor->previous_;
1357 if (cursor->previous_ == nullptr) {
1358 instructions_.first_instruction_ = nullptr;
1359 } else {
1360 cursor->previous_->next_ = nullptr;
1361 cursor->previous_ = nullptr;
1362 }
1363
1364 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001365 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001366
Vladimir Marko60584552015-09-03 13:35:12 +00001367 for (HBasicBlock* successor : GetSuccessors()) {
1368 new_block->successors_.push_back(successor);
1369 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001370 }
Vladimir Marko60584552015-09-03 13:35:12 +00001371 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001372 AddSuccessor(new_block);
1373
David Brazdil56e1acc2015-06-30 15:41:36 +01001374 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001375 return new_block;
1376}
1377
David Brazdild7558da2015-09-22 13:04:14 +01001378HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001379 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001380 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1381
1382 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1383
1384 for (HBasicBlock* predecessor : GetPredecessors()) {
1385 new_block->predecessors_.push_back(predecessor);
1386 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1387 }
1388 predecessors_.clear();
1389 AddPredecessor(new_block);
1390
1391 GetGraph()->AddBlock(new_block);
1392 return new_block;
1393}
1394
David Brazdil9bc43612015-11-05 21:25:24 +00001395HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1396 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1397 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1398
1399 HInstruction* first_insn = GetFirstInstruction();
1400 HInstruction* split_before = nullptr;
1401
1402 if (first_insn != nullptr && first_insn->IsLoadException()) {
1403 // Catch block starts with a LoadException. Split the block after
1404 // the StoreLocal and ClearException which must come after the load.
1405 DCHECK(first_insn->GetNext()->IsStoreLocal());
1406 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1407 split_before = first_insn->GetNext()->GetNext()->GetNext();
1408 } else {
1409 // Catch block does not load the exception. Split at the beginning
1410 // to create an empty catch block.
1411 split_before = first_insn;
1412 }
1413
1414 if (split_before == nullptr) {
1415 // Catch block has no instructions after the split point (must be dead).
1416 // Do not split it but rather signal error by returning nullptr.
1417 return nullptr;
1418 } else {
1419 return SplitBefore(split_before);
1420 }
1421}
1422
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001423HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1424 DCHECK_EQ(cursor->GetBlock(), this);
1425
1426 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1427 cursor->GetDexPc());
1428 new_block->instructions_.first_instruction_ = cursor;
1429 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1430 instructions_.last_instruction_ = cursor->previous_;
1431 if (cursor->previous_ == nullptr) {
1432 instructions_.first_instruction_ = nullptr;
1433 } else {
1434 cursor->previous_->next_ = nullptr;
1435 cursor->previous_ = nullptr;
1436 }
1437
1438 new_block->instructions_.SetBlockOfInstructions(new_block);
1439
1440 for (HBasicBlock* successor : GetSuccessors()) {
1441 new_block->successors_.push_back(successor);
1442 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1443 }
1444 successors_.clear();
1445
1446 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1447 dominated->dominator_ = new_block;
1448 new_block->dominated_blocks_.push_back(dominated);
1449 }
1450 dominated_blocks_.clear();
1451 return new_block;
1452}
1453
1454HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001455 DCHECK(!cursor->IsControlFlow());
1456 DCHECK_NE(instructions_.last_instruction_, cursor);
1457 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001458
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001459 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1460 new_block->instructions_.first_instruction_ = cursor->GetNext();
1461 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1462 cursor->next_->previous_ = nullptr;
1463 cursor->next_ = nullptr;
1464 instructions_.last_instruction_ = cursor;
1465
1466 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001467 for (HBasicBlock* successor : GetSuccessors()) {
1468 new_block->successors_.push_back(successor);
1469 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001470 }
Vladimir Marko60584552015-09-03 13:35:12 +00001471 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001472
Vladimir Marko60584552015-09-03 13:35:12 +00001473 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001474 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001475 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001476 }
Vladimir Marko60584552015-09-03 13:35:12 +00001477 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001478 return new_block;
1479}
1480
David Brazdilec16f792015-08-19 15:04:01 +01001481const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001482 if (EndsWithTryBoundary()) {
1483 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1484 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001485 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001486 return try_boundary;
1487 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001488 DCHECK(IsTryBlock());
1489 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001490 return nullptr;
1491 }
David Brazdilec16f792015-08-19 15:04:01 +01001492 } else if (IsTryBlock()) {
1493 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001494 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001495 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001496 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001497}
1498
David Brazdild7558da2015-09-22 13:04:14 +01001499bool HBasicBlock::HasThrowingInstructions() const {
1500 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1501 if (it.Current()->CanThrow()) {
1502 return true;
1503 }
1504 }
1505 return false;
1506}
1507
David Brazdilfc6a86a2015-06-26 10:33:45 +00001508static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1509 return block.GetPhis().IsEmpty()
1510 && !block.GetInstructions().IsEmpty()
1511 && block.GetFirstInstruction() == block.GetLastInstruction();
1512}
1513
David Brazdil46e2a392015-03-16 17:31:52 +00001514bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001515 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1516}
1517
1518bool HBasicBlock::IsSingleTryBoundary() const {
1519 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001520}
1521
David Brazdil8d5b8b22015-03-24 10:51:52 +00001522bool HBasicBlock::EndsWithControlFlowInstruction() const {
1523 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1524}
1525
David Brazdilb2bd1c52015-03-25 11:17:37 +00001526bool HBasicBlock::EndsWithIf() const {
1527 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1528}
1529
David Brazdilffee3d32015-07-06 11:48:53 +01001530bool HBasicBlock::EndsWithTryBoundary() const {
1531 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1532}
1533
David Brazdilb2bd1c52015-03-25 11:17:37 +00001534bool HBasicBlock::HasSinglePhi() const {
1535 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1536}
1537
David Brazdild26a4112015-11-10 11:07:31 +00001538ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1539 if (EndsWithTryBoundary()) {
1540 // The normal-flow successor of HTryBoundary is always stored at index zero.
1541 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1542 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1543 } else {
1544 // All successors of blocks not ending with TryBoundary are normal.
1545 return ArrayRef<HBasicBlock* const>(successors_);
1546 }
1547}
1548
1549ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1550 if (EndsWithTryBoundary()) {
1551 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1552 } else {
1553 // Blocks not ending with TryBoundary do not have exceptional successors.
1554 return ArrayRef<HBasicBlock* const>();
1555 }
1556}
1557
David Brazdilffee3d32015-07-06 11:48:53 +01001558bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001559 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1560 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1561
1562 size_t length = handlers1.size();
1563 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001564 return false;
1565 }
1566
David Brazdilb618ade2015-07-29 10:31:29 +01001567 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001568 for (size_t i = 0; i < length; ++i) {
1569 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001570 return false;
1571 }
1572 }
1573 return true;
1574}
1575
David Brazdil2d7352b2015-04-20 14:52:42 +01001576size_t HInstructionList::CountSize() const {
1577 size_t size = 0;
1578 HInstruction* current = first_instruction_;
1579 for (; current != nullptr; current = current->GetNext()) {
1580 size++;
1581 }
1582 return size;
1583}
1584
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001585void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1586 for (HInstruction* current = first_instruction_;
1587 current != nullptr;
1588 current = current->GetNext()) {
1589 current->SetBlock(block);
1590 }
1591}
1592
1593void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1594 DCHECK(Contains(cursor));
1595 if (!instruction_list.IsEmpty()) {
1596 if (cursor == last_instruction_) {
1597 last_instruction_ = instruction_list.last_instruction_;
1598 } else {
1599 cursor->next_->previous_ = instruction_list.last_instruction_;
1600 }
1601 instruction_list.last_instruction_->next_ = cursor->next_;
1602 cursor->next_ = instruction_list.first_instruction_;
1603 instruction_list.first_instruction_->previous_ = cursor;
1604 }
1605}
1606
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001607void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1608 DCHECK(Contains(cursor));
1609 if (!instruction_list.IsEmpty()) {
1610 if (cursor == first_instruction_) {
1611 first_instruction_ = instruction_list.first_instruction_;
1612 } else {
1613 cursor->previous_->next_ = instruction_list.first_instruction_;
1614 }
1615 instruction_list.last_instruction_->next_ = cursor;
1616 instruction_list.first_instruction_->previous_ = cursor->previous_;
1617 cursor->previous_ = instruction_list.last_instruction_;
1618 }
1619}
1620
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001621void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001622 if (IsEmpty()) {
1623 first_instruction_ = instruction_list.first_instruction_;
1624 last_instruction_ = instruction_list.last_instruction_;
1625 } else {
1626 AddAfter(last_instruction_, instruction_list);
1627 }
1628}
1629
David Brazdil04ff4e82015-12-10 13:54:52 +00001630// Should be called on instructions in a dead block in post order. This method
1631// assumes `insn` has been removed from all users with the exception of catch
1632// phis because of missing exceptional edges in the graph. It removes the
1633// instruction from catch phi uses, together with inputs of other catch phis in
1634// the catch block at the same index, as these must be dead too.
1635static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1636 DCHECK(!insn->HasEnvironmentUses());
1637 while (insn->HasNonEnvironmentUses()) {
1638 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1639 size_t use_index = use->GetIndex();
1640 HBasicBlock* user_block = use->GetUser()->GetBlock();
1641 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1642 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1643 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1644 }
1645 }
1646}
1647
David Brazdil2d7352b2015-04-20 14:52:42 +01001648void HBasicBlock::DisconnectAndDelete() {
1649 // Dominators must be removed after all the blocks they dominate. This way
1650 // a loop header is removed last, a requirement for correct loop information
1651 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001652 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001653
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001654 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001655 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1656 HLoopInformation* loop_info = it.Current();
1657 loop_info->Remove(this);
1658 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001659 // If this was the last back edge of the loop, we deliberately leave the
David Brazdilbadd8262016-02-02 16:28:56 +00001660 // loop in an inconsistent state and will fail GraphChecker unless the
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001661 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001662 loop_info->RemoveBackEdge(this);
1663 }
1664 }
1665
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001666 // (2) Disconnect the block from its predecessors and update their
1667 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001668 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001669 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001670 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1671 // This block is the only normal-flow successor of the TryBoundary which
1672 // makes `predecessor` dead. Since DCE removes blocks in post order,
1673 // exception handlers of this TryBoundary were already visited and any
1674 // remaining handlers therefore must be live. We remove `predecessor` from
1675 // their list of predecessors.
1676 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1677 while (predecessor->GetSuccessors().size() > 1) {
1678 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1679 DCHECK(handler->IsCatchBlock());
1680 predecessor->RemoveSuccessor(handler);
1681 handler->RemovePredecessor(predecessor);
1682 }
1683 }
1684
David Brazdil2d7352b2015-04-20 14:52:42 +01001685 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001686 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1687 if (num_pred_successors == 1u) {
1688 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001689 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1690 // successor. Replace those with a HGoto.
1691 DCHECK(last_instruction->IsIf() ||
1692 last_instruction->IsPackedSwitch() ||
1693 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001694 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001695 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001696 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001697 // The predecessor has no remaining successors and therefore must be dead.
1698 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001699 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001700 predecessor->RemoveInstruction(last_instruction);
1701 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001702 // There are multiple successors left. The removed block might be a successor
1703 // of a PackedSwitch which will be completely removed (perhaps replaced with
1704 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1705 // case, leave `last_instruction` as is for now.
1706 DCHECK(last_instruction->IsPackedSwitch() ||
1707 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001708 }
David Brazdil46e2a392015-03-16 17:31:52 +00001709 }
Vladimir Marko60584552015-09-03 13:35:12 +00001710 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001711
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001712 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001713 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 // Delete this block from the list of predecessors.
1715 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001716 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001717
1718 // Check that `successor` has other predecessors, otherwise `this` is the
1719 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001720 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001721
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001722 // Remove this block's entries in the successor's phis. Skip exceptional
1723 // successors because catch phi inputs do not correspond to predecessor
1724 // blocks but throwing instructions. Their inputs will be updated in step (4).
1725 if (!successor->IsCatchBlock()) {
1726 if (successor->predecessors_.size() == 1u) {
1727 // The successor has just one predecessor left. Replace phis with the only
1728 // remaining input.
1729 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1730 HPhi* phi = phi_it.Current()->AsPhi();
1731 phi->ReplaceWith(phi->InputAt(1 - this_index));
1732 successor->RemovePhi(phi);
1733 }
1734 } else {
1735 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1736 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1737 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001738 }
1739 }
1740 }
Vladimir Marko60584552015-09-03 13:35:12 +00001741 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001742
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001743 // (4) Remove instructions and phis. Instructions should have no remaining uses
1744 // except in catch phis. If an instruction is used by a catch phi at `index`,
1745 // remove `index`-th input of all phis in the catch block since they are
1746 // guaranteed dead. Note that we may miss dead inputs this way but the
1747 // graph will always remain consistent.
1748 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1749 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001750 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001751 RemoveInstruction(insn);
1752 }
1753 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001754 HPhi* insn = it.Current()->AsPhi();
1755 RemoveUsesOfDeadInstruction(insn);
1756 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001757 }
1758
David Brazdil2d7352b2015-04-20 14:52:42 +01001759 // Disconnect from the dominator.
1760 dominator_->RemoveDominatedBlock(this);
1761 SetDominator(nullptr);
1762
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001763 // Delete from the graph, update reverse post order.
1764 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001765 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001766}
1767
1768void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001769 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001770 DCHECK(ContainsElement(dominated_blocks_, other));
1771 DCHECK_EQ(GetSingleSuccessor(), other);
1772 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 DCHECK(other->GetPhis().IsEmpty());
1774
David Brazdil2d7352b2015-04-20 14:52:42 +01001775 // Move instructions from `other` to `this`.
1776 DCHECK(EndsWithControlFlowInstruction());
1777 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001778 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001779 other->instructions_.SetBlockOfInstructions(this);
1780 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001781
David Brazdil2d7352b2015-04-20 14:52:42 +01001782 // Remove `other` from the loops it is included in.
1783 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1784 HLoopInformation* loop_info = it.Current();
1785 loop_info->Remove(other);
1786 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001787 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001788 }
1789 }
1790
1791 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001792 successors_.clear();
1793 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001794 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001795 successor->ReplacePredecessor(other, this);
1796 }
1797
David Brazdil2d7352b2015-04-20 14:52:42 +01001798 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001799 RemoveDominatedBlock(other);
1800 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1801 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001802 dominated->SetDominator(this);
1803 }
Vladimir Marko60584552015-09-03 13:35:12 +00001804 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001805 other->dominator_ = nullptr;
1806
1807 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001808 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001809
1810 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001811 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001812 other->SetGraph(nullptr);
1813}
1814
1815void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1816 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001817 DCHECK(GetDominatedBlocks().empty());
1818 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001819 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001820 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001821 DCHECK(other->GetPhis().IsEmpty());
1822 DCHECK(!other->IsInLoop());
1823
1824 // Move instructions from `other` to `this`.
1825 instructions_.Add(other->GetInstructions());
1826 other->instructions_.SetBlockOfInstructions(this);
1827
1828 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001829 successors_.clear();
1830 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001831 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001832 successor->ReplacePredecessor(other, this);
1833 }
1834
1835 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001836 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1837 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001838 dominated->SetDominator(this);
1839 }
Vladimir Marko60584552015-09-03 13:35:12 +00001840 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001841 other->dominator_ = nullptr;
1842 other->graph_ = nullptr;
1843}
1844
1845void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001846 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001847 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001848 predecessor->ReplaceSuccessor(this, other);
1849 }
Vladimir Marko60584552015-09-03 13:35:12 +00001850 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001851 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001852 successor->ReplacePredecessor(this, other);
1853 }
Vladimir Marko60584552015-09-03 13:35:12 +00001854 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1855 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001856 }
1857 GetDominator()->ReplaceDominatedBlock(this, other);
1858 other->SetDominator(GetDominator());
1859 dominator_ = nullptr;
1860 graph_ = nullptr;
1861}
1862
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001863void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001864 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001865 DCHECK(block->GetSuccessors().empty());
1866 DCHECK(block->GetPredecessors().empty());
1867 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001868 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001869 DCHECK(block->GetInstructions().IsEmpty());
1870 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001871
David Brazdilc7af85d2015-05-26 12:05:55 +01001872 if (block->IsExitBlock()) {
1873 exit_block_ = nullptr;
1874 }
1875
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001876 RemoveElement(reverse_post_order_, block);
1877 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001878}
1879
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001880void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1881 HBasicBlock* reference,
1882 bool replace_if_back_edge) {
1883 if (block->IsLoopHeader()) {
1884 // Clear the information of which blocks are contained in that loop. Since the
1885 // information is stored as a bit vector based on block ids, we have to update
1886 // it, as those block ids were specific to the callee graph and we are now adding
1887 // these blocks to the caller graph.
1888 block->GetLoopInformation()->ClearAllBlocks();
1889 }
1890
1891 // If not already in a loop, update the loop information.
1892 if (!block->IsInLoop()) {
1893 block->SetLoopInformation(reference->GetLoopInformation());
1894 }
1895
1896 // If the block is in a loop, update all its outward loops.
1897 HLoopInformation* loop_info = block->GetLoopInformation();
1898 if (loop_info != nullptr) {
1899 for (HLoopInformationOutwardIterator loop_it(*block);
1900 !loop_it.Done();
1901 loop_it.Advance()) {
1902 loop_it.Current()->Add(block);
1903 }
1904 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1905 loop_info->ReplaceBackEdge(reference, block);
1906 }
1907 }
1908
1909 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1910 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1911 ? reference->GetTryCatchInformation()
1912 : nullptr;
1913 block->SetTryCatchInformation(try_catch_info);
1914}
1915
Calin Juravle2e768302015-07-28 14:41:11 +00001916HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001917 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001918 // Update the environments in this graph to have the invoke's environment
1919 // as parent.
1920 {
1921 HReversePostOrderIterator it(*this);
1922 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1923 for (; !it.Done(); it.Advance()) {
1924 HBasicBlock* block = it.Current();
1925 for (HInstructionIterator instr_it(block->GetInstructions());
1926 !instr_it.Done();
1927 instr_it.Advance()) {
1928 HInstruction* current = instr_it.Current();
1929 if (current->NeedsEnvironment()) {
1930 current->GetEnvironment()->SetAndCopyParentChain(
1931 outer_graph->GetArena(), invoke->GetEnvironment());
1932 }
1933 }
1934 }
1935 }
1936 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1937 if (HasBoundsChecks()) {
1938 outer_graph->SetHasBoundsChecks(true);
1939 }
1940
Calin Juravle2e768302015-07-28 14:41:11 +00001941 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001942 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001943 // Simple case of an entry block, a body block, and an exit block.
1944 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001945 HBasicBlock* body = GetBlocks()[1];
1946 DCHECK(GetBlocks()[0]->IsEntryBlock());
1947 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001948 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001949 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001950 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001951
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001952 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1953 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001954 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001955
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001956 // Replace the invoke with the return value of the inlined graph.
1957 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001958 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001959 } else {
1960 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001961 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001962
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001963 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001964 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001965 // Need to inline multiple blocks. We split `invoke`'s block
1966 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001967 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001968 // with the second half.
1969 ArenaAllocator* allocator = outer_graph->GetArena();
1970 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001971 // Note that we split before the invoke only to simplify polymorphic inlining.
1972 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001973
Vladimir Markoec7802a2015-10-01 20:57:57 +01001974 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001975 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001976 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001977 exit_block_->ReplaceWith(to);
1978
1979 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001980 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001981 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001982 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001983 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001984 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001985 if (!returns_void) {
1986 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001987 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001988 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001990 } else {
1991 if (!returns_void) {
1992 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001993 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001994 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001995 to->AddPhi(return_value->AsPhi());
1996 }
Vladimir Marko60584552015-09-03 13:35:12 +00001997 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001998 HInstruction* last = predecessor->GetLastInstruction();
1999 if (!returns_void) {
2000 return_value->AsPhi()->AddInput(last->InputAt(0));
2001 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06002002 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00002003 predecessor->RemoveInstruction(last);
2004 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002005 }
2006
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002007 // Update the meta information surrounding blocks:
2008 // (1) the graph they are now in,
2009 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002010 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002011 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002012 // Note that we do not need to update catch phi inputs because they
2013 // correspond to the register file of the outer method which the inlinee
2014 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002015
2016 // We don't add the entry block, the exit block, and the first block, which
2017 // has been merged with `at`.
2018 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2019
2020 // We add the `to` block.
2021 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002022 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002023 + kNumberOfNewBlocksInCaller;
2024
2025 // Find the location of `at` in the outer graph's reverse post order. The new
2026 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002027 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002028 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2029
David Brazdil95177982015-10-30 12:56:58 -05002030 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2031 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002032 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2033 HBasicBlock* current = it.Current();
2034 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002035 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002036 DCHECK(current->GetGraph() == this);
2037 current->SetGraph(outer_graph);
2038 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002039 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002040 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002041 }
2042 }
2043
David Brazdil95177982015-10-30 12:56:58 -05002044 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002045 to->SetGraph(outer_graph);
2046 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002047 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002048 // Only `to` can become a back edge, as the inlined blocks
2049 // are predecessors of `to`.
2050 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002051 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002052
David Brazdil05144f42015-04-16 15:18:00 +01002053 // Update the next instruction id of the outer graph, so that instructions
2054 // added later get bigger ids than those in the inner graph.
2055 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
2056
2057 // Walk over the entry block and:
2058 // - Move constants from the entry block to the outer_graph's entry block,
2059 // - Replace HParameterValue instructions with their real value.
2060 // - Remove suspend checks, that hold an environment.
2061 // We must do this after the other blocks have been inlined, otherwise ids of
2062 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002063 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002064 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2065 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002066 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002067 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002068 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002069 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002070 replacement = outer_graph->GetIntConstant(
2071 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002072 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002073 replacement = outer_graph->GetLongConstant(
2074 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002075 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002076 replacement = outer_graph->GetFloatConstant(
2077 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002078 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002079 replacement = outer_graph->GetDoubleConstant(
2080 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002081 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002082 if (kIsDebugBuild
2083 && invoke->IsInvokeStaticOrDirect()
2084 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2085 // Ensure we do not use the last input of `invoke`, as it
2086 // contains a clinit check which is not an actual argument.
2087 size_t last_input_index = invoke->InputCount() - 1;
2088 DCHECK(parameter_index != last_input_index);
2089 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002090 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002091 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002092 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002093 } else {
2094 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2095 entry_block_->RemoveInstruction(current);
2096 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002097 if (replacement != nullptr) {
2098 current->ReplaceWith(replacement);
2099 // If the current is the return value then we need to update the latter.
2100 if (current == return_value) {
2101 DCHECK_EQ(entry_block_, return_value->GetBlock());
2102 return_value = replacement;
2103 }
2104 }
2105 }
2106
Calin Juravle2e768302015-07-28 14:41:11 +00002107 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002108}
2109
Mingyao Yang3584bce2015-05-19 16:01:59 -07002110/*
2111 * Loop will be transformed to:
2112 * old_pre_header
2113 * |
2114 * if_block
2115 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002116 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002117 * \ /
2118 * new_pre_header
2119 * |
2120 * header
2121 */
2122void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2123 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002124 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002125
Aart Bik3fc7f352015-11-20 22:03:03 -08002126 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002127 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002128 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2129 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002130 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2131 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002132 AddBlock(true_block);
2133 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002134 AddBlock(new_pre_header);
2135
Aart Bik3fc7f352015-11-20 22:03:03 -08002136 header->ReplacePredecessor(old_pre_header, new_pre_header);
2137 old_pre_header->successors_.clear();
2138 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002139
Aart Bik3fc7f352015-11-20 22:03:03 -08002140 old_pre_header->AddSuccessor(if_block);
2141 if_block->AddSuccessor(true_block); // True successor
2142 if_block->AddSuccessor(false_block); // False successor
2143 true_block->AddSuccessor(new_pre_header);
2144 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002145
Aart Bik3fc7f352015-11-20 22:03:03 -08002146 old_pre_header->dominated_blocks_.push_back(if_block);
2147 if_block->SetDominator(old_pre_header);
2148 if_block->dominated_blocks_.push_back(true_block);
2149 true_block->SetDominator(if_block);
2150 if_block->dominated_blocks_.push_back(false_block);
2151 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002152 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002153 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002154 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002155 header->SetDominator(new_pre_header);
2156
Aart Bik3fc7f352015-11-20 22:03:03 -08002157 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002158 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002159 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002160 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002161 reverse_post_order_[index_of_header++] = true_block;
2162 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002163 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002164
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002165 // The pre_header can never be a back edge of a loop.
2166 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2167 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2168 UpdateLoopAndTryInformationOfNewBlock(
2169 if_block, old_pre_header, /* replace_if_back_edge */ false);
2170 UpdateLoopAndTryInformationOfNewBlock(
2171 true_block, old_pre_header, /* replace_if_back_edge */ false);
2172 UpdateLoopAndTryInformationOfNewBlock(
2173 false_block, old_pre_header, /* replace_if_back_edge */ false);
2174 UpdateLoopAndTryInformationOfNewBlock(
2175 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002176}
2177
David Brazdilf5552582015-12-27 13:36:12 +00002178static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2179 SHARED_REQUIRES(Locks::mutator_lock_) {
2180 if (rti.IsValid()) {
2181 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2182 << " upper_bound_rti: " << upper_bound_rti
2183 << " rti: " << rti;
2184 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2185 }
2186}
2187
Calin Juravle2e768302015-07-28 14:41:11 +00002188void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2189 if (kIsDebugBuild) {
2190 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2191 ScopedObjectAccess soa(Thread::Current());
2192 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2193 if (IsBoundType()) {
2194 // Having the test here spares us from making the method virtual just for
2195 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002196 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002197 }
2198 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002199 reference_type_handle_ = rti.GetTypeHandle();
2200 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002201}
2202
David Brazdilf5552582015-12-27 13:36:12 +00002203void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2204 if (kIsDebugBuild) {
2205 ScopedObjectAccess soa(Thread::Current());
2206 DCHECK(upper_bound.IsValid());
2207 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2208 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2209 }
2210 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002211 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002212}
2213
Vladimir Markoa1de9182016-02-25 11:37:38 +00002214ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002215 if (kIsDebugBuild) {
2216 ScopedObjectAccess soa(Thread::Current());
2217 DCHECK(IsValidHandle(type_handle));
2218 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002219 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002220}
2221
Calin Juravleacf735c2015-02-12 15:25:22 +00002222std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2223 ScopedObjectAccess soa(Thread::Current());
2224 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002225 << " is_valid=" << rhs.IsValid()
2226 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002227 << " is_exact=" << rhs.IsExact()
2228 << " ]";
2229 return os;
2230}
2231
Mark Mendellc4701932015-04-10 13:18:51 -04002232bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2233 // For now, assume that instructions in different blocks may use the
2234 // environment.
2235 // TODO: Use the control flow to decide if this is true.
2236 if (GetBlock() != other->GetBlock()) {
2237 return true;
2238 }
2239
2240 // We know that we are in the same block. Walk from 'this' to 'other',
2241 // checking to see if there is any instruction with an environment.
2242 HInstruction* current = this;
2243 for (; current != other && current != nullptr; current = current->GetNext()) {
2244 // This is a conservative check, as the instruction result may not be in
2245 // the referenced environment.
2246 if (current->HasEnvironment()) {
2247 return true;
2248 }
2249 }
2250
2251 // We should have been called with 'this' before 'other' in the block.
2252 // Just confirm this.
2253 DCHECK(current != nullptr);
2254 return false;
2255}
2256
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002257void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002258 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2259 IntrinsicSideEffects side_effects,
2260 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002261 intrinsic_ = intrinsic;
2262 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002263
Aart Bik5d75afe2015-12-14 11:57:01 -08002264 // Adjust method's side effects from intrinsic table.
2265 switch (side_effects) {
2266 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2267 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2268 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2269 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2270 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002271
2272 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2273 opt.SetDoesNotNeedDexCache();
2274 opt.SetDoesNotNeedEnvironment();
2275 } else {
2276 // If we need an environment, that means there will be a call, which can trigger GC.
2277 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2278 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002279 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002280 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002281}
2282
David Brazdil6de19382016-01-08 17:37:10 +00002283bool HNewInstance::IsStringAlloc() const {
2284 ScopedObjectAccess soa(Thread::Current());
2285 return GetReferenceTypeInfo().IsStringClass();
2286}
2287
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002288bool HInvoke::NeedsEnvironment() const {
2289 if (!IsIntrinsic()) {
2290 return true;
2291 }
2292 IntrinsicOptimizations opt(*this);
2293 return !opt.GetDoesNotNeedEnvironment();
2294}
2295
Vladimir Markodc151b22015-10-15 18:02:30 +01002296bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2297 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002298 return false;
2299 }
2300 if (!IsIntrinsic()) {
2301 return true;
2302 }
2303 IntrinsicOptimizations opt(*this);
2304 return !opt.GetDoesNotNeedDexCache();
2305}
2306
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002307void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2308 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2309 input->AddUseAt(this, index);
2310 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2311 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2312 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2313 InputRecordAt(i).GetUseNode()->SetIndex(i);
2314 }
2315}
2316
Vladimir Markob554b5a2015-11-06 12:57:55 +00002317void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2318 RemoveAsUserOfInput(index);
2319 inputs_.erase(inputs_.begin() + index);
2320 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2321 for (size_t i = index, e = InputCount(); i < e; ++i) {
2322 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2323 InputRecordAt(i).GetUseNode()->SetIndex(i);
2324 }
2325}
2326
Vladimir Markof64242a2015-12-01 14:58:23 +00002327std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2328 switch (rhs) {
2329 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2330 return os << "string_init";
2331 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2332 return os << "recursive";
2333 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2334 return os << "direct";
2335 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2336 return os << "direct_fixup";
2337 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2338 return os << "dex_cache_pc_relative";
2339 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2340 return os << "dex_cache_via_method";
2341 default:
2342 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2343 UNREACHABLE();
2344 }
2345}
2346
Vladimir Markofbb184a2015-11-13 14:47:00 +00002347std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2348 switch (rhs) {
2349 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2350 return os << "explicit";
2351 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2352 return os << "implicit";
2353 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2354 return os << "none";
2355 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002356 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2357 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002358 }
2359}
2360
Mark Mendellc4701932015-04-10 13:18:51 -04002361void HInstruction::RemoveEnvironmentUsers() {
2362 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2363 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2364 HEnvironment* user = user_node->GetUser();
2365 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2366 }
2367 env_uses_.Clear();
2368}
2369
Mark Mendellf6529172015-11-17 11:16:56 -05002370// Returns an instruction with the opposite boolean value from 'cond'.
2371HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2372 ArenaAllocator* allocator = GetArena();
2373
2374 if (cond->IsCondition() &&
2375 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2376 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2377 HInstruction* lhs = cond->InputAt(0);
2378 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002379 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002380 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2381 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2382 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2383 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2384 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2385 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2386 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2387 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2388 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2389 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2390 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002391 default:
2392 LOG(FATAL) << "Unexpected condition";
2393 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002394 }
2395 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2396 return replacement;
2397 } else if (cond->IsIntConstant()) {
2398 HIntConstant* int_const = cond->AsIntConstant();
2399 if (int_const->IsZero()) {
2400 return GetIntConstant(1);
2401 } else {
2402 DCHECK(int_const->IsOne());
2403 return GetIntConstant(0);
2404 }
2405 } else {
2406 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2407 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2408 return replacement;
2409 }
2410}
2411
Roland Levillainc9285912015-12-18 10:38:42 +00002412std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2413 os << "["
2414 << " source=" << rhs.GetSource()
2415 << " destination=" << rhs.GetDestination()
2416 << " type=" << rhs.GetType()
2417 << " instruction=";
2418 if (rhs.GetInstruction() != nullptr) {
2419 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2420 } else {
2421 os << "null";
2422 }
2423 os << " ]";
2424 return os;
2425}
2426
Roland Levillain86503782016-02-11 19:07:30 +00002427std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2428 switch (rhs) {
2429 case TypeCheckKind::kUnresolvedCheck:
2430 return os << "unresolved_check";
2431 case TypeCheckKind::kExactCheck:
2432 return os << "exact_check";
2433 case TypeCheckKind::kClassHierarchyCheck:
2434 return os << "class_hierarchy_check";
2435 case TypeCheckKind::kAbstractClassCheck:
2436 return os << "abstract_class_check";
2437 case TypeCheckKind::kInterfaceCheck:
2438 return os << "interface_check";
2439 case TypeCheckKind::kArrayObjectCheck:
2440 return os << "array_object_check";
2441 case TypeCheckKind::kArrayCheck:
2442 return os << "array_check";
2443 default:
2444 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2445 UNREACHABLE();
2446 }
2447}
2448
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002449} // namespace art