blob: 950448136d467b22a657bd027e96e71866f437f6 [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 Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
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
Vladimir Markocac5a7e2016-02-22 10:39:50 +000089static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010090 for (HEnvironment* environment = instruction->GetEnvironment();
91 environment != nullptr;
92 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000094 if (environment->GetInstructionAt(i) != nullptr) {
95 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000096 }
97 }
98 }
99}
100
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000101static void RemoveAsUser(HInstruction* instruction) {
102 for (size_t i = 0; i < instruction->InputCount(); i++) {
103 instruction->RemoveAsUserOfInput(i);
104 }
105
106 RemoveEnvironmentUses(instruction);
107}
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100112 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000113 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100114 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000115 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
116 RemoveAsUser(it.Current());
117 }
118 }
119 }
120}
121
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100122void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100125 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000128 for (HBasicBlock* successor : block->GetSuccessors()) {
129 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000130 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100131 // Remove the block from the list of blocks, so that further analyses
132 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600134 if (block->IsExitBlock()) {
135 SetExitBlock(nullptr);
136 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 }
138 }
139}
140
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000141GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
143 // edges. This invariant simplifies building SSA form because Phis cannot
144 // collect both normal- and exceptional-flow values at the same time.
145 SimplifyCatchBlocks();
146
Vladimir Markof6a35de2016-03-21 12:01:50 +0000147 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148
David Brazdilffee3d32015-07-06 11:48:53 +0100149 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 FindBackEdges(&visited);
151
David Brazdilffee3d32015-07-06 11:48:53 +0100152 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000153 // the initial DFS as users from other instructions, so that
154 // users can be safely removed before uses later.
155 RemoveInstructionsAsUsersFromDeadBlocks(visited);
156
David Brazdilffee3d32015-07-06 11:48:53 +0100157 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000158 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // predecessors list of live blocks.
160 RemoveDeadBlocks(visited);
161
David Brazdilffee3d32015-07-06 11:48:53 +0100162 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100163 // dominators and the reverse post order.
164 SimplifyCFG();
165
David Brazdilffee3d32015-07-06 11:48:53 +0100166 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100167 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168
Roland Levillainc9b21f82016-03-23 16:36:59 +0000169 // (7) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000170 // set the loop information on each block.
171 GraphAnalysisResult result = AnalyzeLoops();
172 if (result != kAnalysisSuccess) {
173 return result;
174 }
175
176 // (8) Precompute per-block try membership before entering the SSA builder,
177 // which needs the information to build catch block phis from values of
178 // locals at throwing instructions inside try blocks.
179 ComputeTryBlockInformation();
180
181 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100182}
183
184void HGraph::ClearDominanceInformation() {
185 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
186 it.Current()->ClearDominanceInformation();
187 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100189}
190
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000191void HGraph::ClearLoopInformation() {
192 SetHasIrreducibleLoops(false);
193 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000194 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 }
196}
197
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000199 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100200 dominator_ = nullptr;
201}
202
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000203HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
204 HInstruction* instruction = GetFirstInstruction();
205 while (instruction->IsParallelMove()) {
206 instruction = instruction->GetNext();
207 }
208 return instruction;
209}
210
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100212 DCHECK(reverse_post_order_.empty());
213 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100214 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100215
216 // Number of visits of a given node, indexed by block id.
217 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
218 // Number of successors visited from a given node, indexed by block id.
219 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
220 // Nodes for which we need to visit successors.
221 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
222 constexpr size_t kDefaultWorklistSize = 8;
223 worklist.reserve(kDefaultWorklistSize);
224 worklist.push_back(entry_block_);
225
226 while (!worklist.empty()) {
227 HBasicBlock* current = worklist.back();
228 uint32_t current_id = current->GetBlockId();
229 if (successors_visited[current_id] == current->GetSuccessors().size()) {
230 worklist.pop_back();
231 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100232 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
233
234 if (successor->GetDominator() == nullptr) {
235 successor->SetDominator(current);
236 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000237 // The CommonDominator can work for multiple blocks as long as the
238 // domination information doesn't change. However, since we're changing
239 // that information here, we can use the finder only for pairs of blocks.
240 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100241 }
242
243 // Once all the forward edges have been visited, we know the immediate
244 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100245 if (++visits[successor->GetBlockId()] ==
246 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100247 reverse_post_order_.push_back(successor);
248 worklist.push_back(successor);
249 }
250 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000251 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000252
253 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000254 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000255 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
256 HBasicBlock* block = it.Current();
257 if (!block->IsEntryBlock()) {
258 block->GetDominator()->AddDominatedBlock(block);
259 }
260 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000261}
262
David Brazdilfc6a86a2015-06-26 10:33:45 +0000263HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000264 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
265 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000266 // Use `InsertBetween` to ensure the predecessor index and successor index of
267 // `block` and `successor` are preserved.
268 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000269 return new_block;
270}
271
272void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
273 // Insert a new node between `block` and `successor` to split the
274 // critical edge.
275 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600276 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 if (successor->IsLoopHeader()) {
278 // If we split at a back edge boundary, make the new block the back edge.
279 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000280 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100281 info->RemoveBackEdge(block);
282 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100283 }
284 }
285}
286
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100287void HGraph::SimplifyLoop(HBasicBlock* header) {
288 HLoopInformation* info = header->GetLoopInformation();
289
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 // Make sure the loop has only one pre header. This simplifies SSA building by having
291 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000292 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
293 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000294 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000295 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100296 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600298 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100299
Vladimir Marko60584552015-09-03 13:35:12 +0000300 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100301 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100302 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100303 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100304 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100305 }
306 }
307 pre_header->AddSuccessor(header);
308 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100309
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100310 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100311 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
312 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000313 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100314 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100315 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000316 header->predecessors_[pred] = to_swap;
317 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100318 break;
319 }
320 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100321 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100322
323 // Place the suspend check at the beginning of the header, so that live registers
324 // will be known when allocating registers. Note that code generation can still
325 // generate the suspend check at the back edge, but needs to be careful with
326 // loop phi spill slots (which are not written to at back edge).
327 HInstruction* first_instruction = header->GetFirstInstruction();
328 if (!first_instruction->IsSuspendCheck()) {
329 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
330 header->InsertInstructionBefore(check, first_instruction);
331 first_instruction = check;
332 }
333 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100334}
335
David Brazdilffee3d32015-07-06 11:48:53 +0100336static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100337 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100338 if (!predecessor->EndsWithTryBoundary()) {
339 // Only edges from HTryBoundary can be exceptional.
340 return false;
341 }
342 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
343 if (try_boundary->GetNormalFlowSuccessor() == &block) {
344 // This block is the normal-flow successor of `try_boundary`, but it could
345 // also be one of its exception handlers if catch blocks have not been
346 // simplified yet. Predecessors are unordered, so we will consider the first
347 // occurrence to be the normal edge and a possible second occurrence to be
348 // the exceptional edge.
349 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
350 } else {
351 // This is not the normal-flow successor of `try_boundary`, hence it must be
352 // one of its exception handlers.
353 DCHECK(try_boundary->HasExceptionHandler(block));
354 return true;
355 }
356}
357
358void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100359 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
360 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
361 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
362 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000363 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100364 continue;
365 }
366
367 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000368 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100369 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
370 exceptional_predecessors_only = false;
371 break;
372 }
373 }
374
375 if (!exceptional_predecessors_only) {
376 // Catch block has normal-flow predecessors and needs to be simplified.
377 // Splitting the block before its first instruction moves all its
378 // instructions into `normal_block` and links the two blocks with a Goto.
379 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
380 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000381 //
David Brazdilffee3d32015-07-06 11:48:53 +0100382 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000383 // a move-exception instruction, as guaranteed by the verifier. However,
384 // trivially dead predecessors are ignored by the verifier and such code
385 // has not been removed at this stage. We therefore ignore the assumption
386 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
387 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
388 if (normal_block == nullptr) {
389 // Catch block is either empty or only contains a move-exception. It must
390 // therefore be dead and will be removed during initial DCE. Do nothing.
391 DCHECK(!catch_block->EndsWithControlFlowInstruction());
392 } else {
393 // Catch block was split. Re-link normal-flow edges to the new block.
394 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
395 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
396 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
397 --j;
398 }
David Brazdilffee3d32015-07-06 11:48:53 +0100399 }
400 }
401 }
402 }
403}
404
405void HGraph::ComputeTryBlockInformation() {
406 // Iterate in reverse post order to propagate try membership information from
407 // predecessors to their successors.
408 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
409 HBasicBlock* block = it.Current();
410 if (block->IsEntryBlock() || block->IsCatchBlock()) {
411 // Catch blocks after simplification have only exceptional predecessors
412 // and hence are never in tries.
413 continue;
414 }
415
416 // Infer try membership from the first predecessor. Having simplified loops,
417 // the first predecessor can never be a back edge and therefore it must have
418 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100419 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100420 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100421 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000422 if (try_entry != nullptr &&
423 (block->GetTryCatchInformation() == nullptr ||
424 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
425 // We are either setting try block membership for the first time or it
426 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100427 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
428 }
David Brazdilffee3d32015-07-06 11:48:53 +0100429 }
430}
431
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100432void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000433// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100434 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000435 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100436 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
437 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
438 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
439 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100440 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000441 if (block->GetSuccessors().size() > 1) {
442 // Only split normal-flow edges. We cannot split exceptional edges as they
443 // are synthesized (approximate real control flow), and we do not need to
444 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000445 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
446 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
447 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100448 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000449 if (successor == exit_block_) {
450 // Throw->TryBoundary->Exit. Special case which we do not want to split
451 // because Goto->Exit is not allowed.
452 DCHECK(block->IsSingleTryBoundary());
453 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
454 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000456 // SplitCriticalEdge could have invalidated the `normal_successors`
457 // ArrayRef. We must re-acquire it.
458 normal_successors = block->GetNormalSuccessors();
459 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
460 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100461 }
462 }
463 }
464 if (block->IsLoopHeader()) {
465 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000466 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
Roland Levillainc9b21f82016-03-23 16:36:59 +0000467 // We are being called by the dead code elimination pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000468 // a loop got dismantled. Just remove the suspend check.
469 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470 }
471 }
472}
473
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000474GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100475 // Order does not matter.
476 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
477 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100479 if (block->IsCatchBlock()) {
480 // TODO: Dealing with exceptional back edges could be tricky because
481 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000482 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100483 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000484 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100485 }
486 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000487 return kAnalysisSuccess;
488}
489
490void HLoopInformation::Dump(std::ostream& os) {
491 os << "header: " << header_->GetBlockId() << std::endl;
492 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
493 for (HBasicBlock* block : back_edges_) {
494 os << "back edge: " << block->GetBlockId() << std::endl;
495 }
496 for (HBasicBlock* block : header_->GetPredecessors()) {
497 os << "predecessor: " << block->GetBlockId() << std::endl;
498 }
499 for (uint32_t idx : blocks_.Indexes()) {
500 os << " in loop: " << idx << std::endl;
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502}
503
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504void HGraph::InsertConstant(HConstant* constant) {
505 // New constants are inserted before the final control-flow instruction
506 // of the graph, or at its end if called from the graph builder.
507 if (entry_block_->EndsWithControlFlowInstruction()) {
508 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000509 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000510 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000511 }
512}
513
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600514HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100515 // For simplicity, don't bother reviving the cached null constant if it is
516 // not null and not in a block. Otherwise, we need to clear the instruction
517 // id and/or any invariants the graph is assuming when adding new instructions.
518 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600519 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000520 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000521 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000522 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000523 if (kIsDebugBuild) {
524 ScopedObjectAccess soa(Thread::Current());
525 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
526 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000527 return cached_null_constant_;
528}
529
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100530HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100531 // For simplicity, don't bother reviving the cached current method if it is
532 // not null and not in a block. Otherwise, we need to clear the instruction
533 // id and/or any invariants the graph is assuming when adding new instructions.
534 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700535 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600536 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
537 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100538 if (entry_block_->GetFirstInstruction() == nullptr) {
539 entry_block_->AddInstruction(cached_current_method_);
540 } else {
541 entry_block_->InsertInstructionBefore(
542 cached_current_method_, entry_block_->GetFirstInstruction());
543 }
544 }
545 return cached_current_method_;
546}
547
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600548HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000549 switch (type) {
550 case Primitive::Type::kPrimBoolean:
551 DCHECK(IsUint<1>(value));
552 FALLTHROUGH_INTENDED;
553 case Primitive::Type::kPrimByte:
554 case Primitive::Type::kPrimChar:
555 case Primitive::Type::kPrimShort:
556 case Primitive::Type::kPrimInt:
557 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600558 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000559
560 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600561 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000562
563 default:
564 LOG(FATAL) << "Unsupported constant type";
565 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000566 }
David Brazdil46e2a392015-03-16 17:31:52 +0000567}
568
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000569void HGraph::CacheFloatConstant(HFloatConstant* constant) {
570 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
571 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
572 cached_float_constants_.Overwrite(value, constant);
573}
574
575void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
576 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
577 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
578 cached_double_constants_.Overwrite(value, constant);
579}
580
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000581void HLoopInformation::Add(HBasicBlock* block) {
582 blocks_.SetBit(block->GetBlockId());
583}
584
David Brazdil46e2a392015-03-16 17:31:52 +0000585void HLoopInformation::Remove(HBasicBlock* block) {
586 blocks_.ClearBit(block->GetBlockId());
587}
588
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100589void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
590 if (blocks_.IsBitSet(block->GetBlockId())) {
591 return;
592 }
593
594 blocks_.SetBit(block->GetBlockId());
595 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000596 for (HBasicBlock* predecessor : block->GetPredecessors()) {
597 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100598 }
599}
600
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000601void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
602 if (blocks_.IsBitSet(block->GetBlockId())) {
603 return;
604 }
605
606 if (block->IsLoopHeader()) {
607 // If we hit a loop header in an irreducible loop, we first check if the
608 // pre header of that loop belongs to the currently analyzed loop. If it does,
609 // then we visit the back edges.
610 // Note that we cannot use GetPreHeader, as the loop may have not been populated
611 // yet.
612 HBasicBlock* pre_header = block->GetPredecessors()[0];
613 PopulateIrreducibleRecursive(pre_header);
614 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
615 blocks_.SetBit(block->GetBlockId());
616 block->SetInLoop(this);
617 HLoopInformation* info = block->GetLoopInformation();
618 for (HBasicBlock* back_edge : info->GetBackEdges()) {
619 PopulateIrreducibleRecursive(back_edge);
620 }
621 }
622 } else {
623 // Visit all predecessors. If one predecessor is part of the loop, this
624 // block is also part of this loop.
625 for (HBasicBlock* predecessor : block->GetPredecessors()) {
626 PopulateIrreducibleRecursive(predecessor);
627 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
628 blocks_.SetBit(block->GetBlockId());
629 block->SetInLoop(this);
630 }
631 }
632 }
633}
634
635void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100636 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 // Populate this loop: starting with the back edge, recursively add predecessors
638 // that are not already part of that loop. Set the header as part of the loop
639 // to end the recursion.
640 // This is a recursive implementation of the algorithm described in
641 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
642 blocks_.SetBit(header_->GetBlockId());
643 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100644 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100645 DCHECK(back_edge->GetDominator() != nullptr);
646 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000647 irreducible_ = true;
648 header_->GetGraph()->SetHasIrreducibleLoops(true);
649 PopulateIrreducibleRecursive(back_edge);
650 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000651 if (header_->GetGraph()->IsCompilingOsr()) {
652 irreducible_ = true;
653 header_->GetGraph()->SetHasIrreducibleLoops(true);
654 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100656 }
David Brazdila4b8c212015-05-07 09:59:30 +0100657 }
658}
659
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100660HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000661 HBasicBlock* block = header_->GetPredecessors()[0];
662 DCHECK(irreducible_ || (block == header_->GetDominator()));
663 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100664}
665
666bool HLoopInformation::Contains(const HBasicBlock& block) const {
667 return blocks_.IsBitSet(block.GetBlockId());
668}
669
670bool HLoopInformation::IsIn(const HLoopInformation& other) const {
671 return other.blocks_.IsBitSet(header_->GetBlockId());
672}
673
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800674bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
675 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700676}
677
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100678size_t HLoopInformation::GetLifetimeEnd() const {
679 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100680 for (HBasicBlock* back_edge : GetBackEdges()) {
681 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100682 }
683 return last_position;
684}
685
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100686bool HBasicBlock::Dominates(HBasicBlock* other) const {
687 // Walk up the dominator tree from `other`, to find out if `this`
688 // is an ancestor.
689 HBasicBlock* current = other;
690 while (current != nullptr) {
691 if (current == this) {
692 return true;
693 }
694 current = current->GetDominator();
695 }
696 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100697}
698
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100699static void UpdateInputsUsers(HInstruction* instruction) {
700 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
701 instruction->InputAt(i)->AddUseAt(instruction, i);
702 }
703 // Environment should be created later.
704 DCHECK(!instruction->HasEnvironment());
705}
706
Roland Levillainccc07a92014-09-16 14:48:16 +0100707void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
708 HInstruction* replacement) {
709 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400710 if (initial->IsControlFlow()) {
711 // We can only replace a control flow instruction with another control flow instruction.
712 DCHECK(replacement->IsControlFlow());
713 DCHECK_EQ(replacement->GetId(), -1);
714 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
715 DCHECK_EQ(initial->GetBlock(), this);
716 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
717 DCHECK(initial->GetUses().IsEmpty());
718 DCHECK(initial->GetEnvUses().IsEmpty());
719 replacement->SetBlock(this);
720 replacement->SetId(GetGraph()->GetNextInstructionId());
721 instructions_.InsertInstructionBefore(replacement, initial);
722 UpdateInputsUsers(replacement);
723 } else {
724 InsertInstructionBefore(replacement, initial);
725 initial->ReplaceWith(replacement);
726 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100727 RemoveInstruction(initial);
728}
729
David Brazdil74eb1b22015-12-14 11:44:01 +0000730void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
731 DCHECK(!cursor->IsPhi());
732 DCHECK(!insn->IsPhi());
733 DCHECK(!insn->IsControlFlow());
734 DCHECK(insn->CanBeMoved());
735 DCHECK(!insn->HasSideEffects());
736
737 HBasicBlock* from_block = insn->GetBlock();
738 HBasicBlock* to_block = cursor->GetBlock();
739 DCHECK(from_block != to_block);
740
741 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
742 insn->SetBlock(to_block);
743 to_block->instructions_.InsertInstructionBefore(insn, cursor);
744}
745
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746static void Add(HInstructionList* instruction_list,
747 HBasicBlock* block,
748 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000749 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000750 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100751 instruction->SetBlock(block);
752 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100753 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100754 instruction_list->AddInstruction(instruction);
755}
756
757void HBasicBlock::AddInstruction(HInstruction* instruction) {
758 Add(&instructions_, this, instruction);
759}
760
761void HBasicBlock::AddPhi(HPhi* phi) {
762 Add(&phis_, this, phi);
763}
764
David Brazdilc3d743f2015-04-22 13:40:50 +0100765void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
766 DCHECK(!cursor->IsPhi());
767 DCHECK(!instruction->IsPhi());
768 DCHECK_EQ(instruction->GetId(), -1);
769 DCHECK_NE(cursor->GetId(), -1);
770 DCHECK_EQ(cursor->GetBlock(), this);
771 DCHECK(!instruction->IsControlFlow());
772 instruction->SetBlock(this);
773 instruction->SetId(GetGraph()->GetNextInstructionId());
774 UpdateInputsUsers(instruction);
775 instructions_.InsertInstructionBefore(instruction, cursor);
776}
777
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100778void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
779 DCHECK(!cursor->IsPhi());
780 DCHECK(!instruction->IsPhi());
781 DCHECK_EQ(instruction->GetId(), -1);
782 DCHECK_NE(cursor->GetId(), -1);
783 DCHECK_EQ(cursor->GetBlock(), this);
784 DCHECK(!instruction->IsControlFlow());
785 DCHECK(!cursor->IsControlFlow());
786 instruction->SetBlock(this);
787 instruction->SetId(GetGraph()->GetNextInstructionId());
788 UpdateInputsUsers(instruction);
789 instructions_.InsertInstructionAfter(instruction, cursor);
790}
791
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100792void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
793 DCHECK_EQ(phi->GetId(), -1);
794 DCHECK_NE(cursor->GetId(), -1);
795 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100796 phi->SetBlock(this);
797 phi->SetId(GetGraph()->GetNextInstructionId());
798 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100799 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100800}
801
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802static void Remove(HInstructionList* instruction_list,
803 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000804 HInstruction* instruction,
805 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100807 instruction->SetBlock(nullptr);
808 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000809 if (ensure_safety) {
810 DCHECK(instruction->GetUses().IsEmpty());
811 DCHECK(instruction->GetEnvUses().IsEmpty());
812 RemoveAsUser(instruction);
813 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100814}
815
David Brazdil1abb4192015-02-17 18:33:36 +0000816void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100817 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000818 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100819}
820
David Brazdil1abb4192015-02-17 18:33:36 +0000821void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
822 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100823}
824
David Brazdilc7508e92015-04-27 13:28:57 +0100825void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
826 if (instruction->IsPhi()) {
827 RemovePhi(instruction->AsPhi(), ensure_safety);
828 } else {
829 RemoveInstruction(instruction, ensure_safety);
830 }
831}
832
Vladimir Marko71bf8092015-09-15 15:33:14 +0100833void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
834 for (size_t i = 0; i < locals.size(); i++) {
835 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100836 SetRawEnvAt(i, instruction);
837 if (instruction != nullptr) {
838 instruction->AddEnvUseAt(this, i);
839 }
840 }
841}
842
David Brazdiled596192015-01-23 10:39:45 +0000843void HEnvironment::CopyFrom(HEnvironment* env) {
844 for (size_t i = 0; i < env->Size(); i++) {
845 HInstruction* instruction = env->GetInstructionAt(i);
846 SetRawEnvAt(i, instruction);
847 if (instruction != nullptr) {
848 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100849 }
David Brazdiled596192015-01-23 10:39:45 +0000850 }
851}
852
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700853void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
854 HBasicBlock* loop_header) {
855 DCHECK(loop_header->IsLoopHeader());
856 for (size_t i = 0; i < env->Size(); i++) {
857 HInstruction* instruction = env->GetInstructionAt(i);
858 SetRawEnvAt(i, instruction);
859 if (instruction == nullptr) {
860 continue;
861 }
862 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
863 // At the end of the loop pre-header, the corresponding value for instruction
864 // is the first input of the phi.
865 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700866 SetRawEnvAt(i, initial);
867 initial->AddEnvUseAt(this, i);
868 } else {
869 instruction->AddEnvUseAt(this, i);
870 }
871 }
872}
873
David Brazdil1abb4192015-02-17 18:33:36 +0000874void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100875 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000876 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100877}
878
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000879HInstruction::InstructionKind HInstruction::GetKind() const {
880 return GetKindInternal();
881}
882
Calin Juravle77520bc2015-01-12 18:45:46 +0000883HInstruction* HInstruction::GetNextDisregardingMoves() const {
884 HInstruction* next = GetNext();
885 while (next != nullptr && next->IsParallelMove()) {
886 next = next->GetNext();
887 }
888 return next;
889}
890
891HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
892 HInstruction* previous = GetPrevious();
893 while (previous != nullptr && previous->IsParallelMove()) {
894 previous = previous->GetPrevious();
895 }
896 return previous;
897}
898
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100899void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000900 if (first_instruction_ == nullptr) {
901 DCHECK(last_instruction_ == nullptr);
902 first_instruction_ = last_instruction_ = instruction;
903 } else {
904 last_instruction_->next_ = instruction;
905 instruction->previous_ = last_instruction_;
906 last_instruction_ = instruction;
907 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000908}
909
David Brazdilc3d743f2015-04-22 13:40:50 +0100910void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
911 DCHECK(Contains(cursor));
912 if (cursor == first_instruction_) {
913 cursor->previous_ = instruction;
914 instruction->next_ = cursor;
915 first_instruction_ = instruction;
916 } else {
917 instruction->previous_ = cursor->previous_;
918 instruction->next_ = cursor;
919 cursor->previous_ = instruction;
920 instruction->previous_->next_ = instruction;
921 }
922}
923
924void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
925 DCHECK(Contains(cursor));
926 if (cursor == last_instruction_) {
927 cursor->next_ = instruction;
928 instruction->previous_ = cursor;
929 last_instruction_ = instruction;
930 } else {
931 instruction->next_ = cursor->next_;
932 instruction->previous_ = cursor;
933 cursor->next_ = instruction;
934 instruction->next_->previous_ = instruction;
935 }
936}
937
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938void HInstructionList::RemoveInstruction(HInstruction* instruction) {
939 if (instruction->previous_ != nullptr) {
940 instruction->previous_->next_ = instruction->next_;
941 }
942 if (instruction->next_ != nullptr) {
943 instruction->next_->previous_ = instruction->previous_;
944 }
945 if (instruction == first_instruction_) {
946 first_instruction_ = instruction->next_;
947 }
948 if (instruction == last_instruction_) {
949 last_instruction_ = instruction->previous_;
950 }
951}
952
Roland Levillain6b469232014-09-25 10:10:38 +0100953bool HInstructionList::Contains(HInstruction* instruction) const {
954 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
955 if (it.Current() == instruction) {
956 return true;
957 }
958 }
959 return false;
960}
961
Roland Levillainccc07a92014-09-16 14:48:16 +0100962bool HInstructionList::FoundBefore(const HInstruction* instruction1,
963 const HInstruction* instruction2) const {
964 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
965 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
966 if (it.Current() == instruction1) {
967 return true;
968 }
969 if (it.Current() == instruction2) {
970 return false;
971 }
972 }
973 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
974 return true;
975}
976
Roland Levillain6c82d402014-10-13 16:10:27 +0100977bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
978 if (other_instruction == this) {
979 // An instruction does not strictly dominate itself.
980 return false;
981 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100982 HBasicBlock* block = GetBlock();
983 HBasicBlock* other_block = other_instruction->GetBlock();
984 if (block != other_block) {
985 return GetBlock()->Dominates(other_instruction->GetBlock());
986 } else {
987 // If both instructions are in the same block, ensure this
988 // instruction comes before `other_instruction`.
989 if (IsPhi()) {
990 if (!other_instruction->IsPhi()) {
991 // Phis appear before non phi-instructions so this instruction
992 // dominates `other_instruction`.
993 return true;
994 } else {
995 // There is no order among phis.
996 LOG(FATAL) << "There is no dominance between phis of a same block.";
997 return false;
998 }
999 } else {
1000 // `this` is not a phi.
1001 if (other_instruction->IsPhi()) {
1002 // Phis appear before non phi-instructions so this instruction
1003 // does not dominate `other_instruction`.
1004 return false;
1005 } else {
1006 // Check whether this instruction comes before
1007 // `other_instruction` in the instruction list.
1008 return block->GetInstructions().FoundBefore(this, other_instruction);
1009 }
1010 }
1011 }
1012}
1013
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001014void HInstruction::RemoveEnvironment() {
1015 RemoveEnvironmentUses(this);
1016 environment_ = nullptr;
1017}
1018
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001019void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001020 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001021 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1022 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001023 HInstruction* user = current->GetUser();
1024 size_t input_index = current->GetIndex();
1025 user->SetRawInputAt(input_index, other);
1026 other->AddUseAt(user, input_index);
1027 }
1028
David Brazdiled596192015-01-23 10:39:45 +00001029 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1030 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001031 HEnvironment* user = current->GetUser();
1032 size_t input_index = current->GetIndex();
1033 user->SetRawEnvAt(input_index, other);
1034 other->AddEnvUseAt(user, input_index);
1035 }
1036
David Brazdiled596192015-01-23 10:39:45 +00001037 uses_.Clear();
1038 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039}
1040
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001041void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001042 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001043 SetRawInputAt(index, replacement);
1044 replacement->AddUseAt(this, index);
1045}
1046
Nicolas Geoffray39468442014-09-02 15:17:15 +01001047size_t HInstruction::EnvironmentSize() const {
1048 return HasEnvironment() ? environment_->Size() : 0;
1049}
1050
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001051void HPhi::AddInput(HInstruction* input) {
1052 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001053 inputs_.push_back(HUserRecord<HInstruction*>(input));
1054 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001055}
1056
David Brazdil2d7352b2015-04-20 14:52:42 +01001057void HPhi::RemoveInputAt(size_t index) {
1058 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001059 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001060 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001061 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001062 InputRecordAt(i).GetUseNode()->SetIndex(i);
1063 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001064}
1065
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001066#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001067void H##name::Accept(HGraphVisitor* visitor) { \
1068 visitor->Visit##name(this); \
1069}
1070
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001071FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001072
1073#undef DEFINE_ACCEPT
1074
1075void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001076 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1077 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001078 if (block != nullptr) {
1079 VisitBasicBlock(block);
1080 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001081 }
1082}
1083
Roland Levillain633021e2014-10-01 14:12:25 +01001084void HGraphVisitor::VisitReversePostOrder() {
1085 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1086 VisitBasicBlock(it.Current());
1087 }
1088}
1089
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001090void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001091 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001092 it.Current()->Accept(this);
1093 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001095 it.Current()->Accept(this);
1096 }
1097}
1098
Mark Mendelle82549b2015-05-06 10:55:34 -04001099HConstant* HTypeConversion::TryStaticEvaluation() const {
1100 HGraph* graph = GetBlock()->GetGraph();
1101 if (GetInput()->IsIntConstant()) {
1102 int32_t value = GetInput()->AsIntConstant()->GetValue();
1103 switch (GetResultType()) {
1104 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetLongConstant(static_cast<int64_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()->IsLongConstant()) {
1114 int64_t value = GetInput()->AsLongConstant()->GetValue();
1115 switch (GetResultType()) {
1116 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001117 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001118 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001119 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001120 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001121 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001122 default:
1123 return nullptr;
1124 }
1125 } else if (GetInput()->IsFloatConstant()) {
1126 float value = GetInput()->AsFloatConstant()->GetValue();
1127 switch (GetResultType()) {
1128 case Primitive::kPrimInt:
1129 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001131 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001132 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001133 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001134 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1135 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001136 case Primitive::kPrimLong:
1137 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001139 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001140 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001141 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001142 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1143 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001144 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001145 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001146 default:
1147 return nullptr;
1148 }
1149 } else if (GetInput()->IsDoubleConstant()) {
1150 double value = GetInput()->AsDoubleConstant()->GetValue();
1151 switch (GetResultType()) {
1152 case Primitive::kPrimInt:
1153 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001155 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001156 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001157 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001158 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1159 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001160 case Primitive::kPrimLong:
1161 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001162 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001163 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001164 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001165 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001166 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1167 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001168 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001169 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001170 default:
1171 return nullptr;
1172 }
1173 }
1174 return nullptr;
1175}
1176
Roland Levillain9240d6a2014-10-20 16:47:04 +01001177HConstant* HUnaryOperation::TryStaticEvaluation() const {
1178 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001179 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001180 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001181 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001182 } else if (kEnableFloatingPointStaticEvaluation) {
1183 if (GetInput()->IsFloatConstant()) {
1184 return Evaluate(GetInput()->AsFloatConstant());
1185 } else if (GetInput()->IsDoubleConstant()) {
1186 return Evaluate(GetInput()->AsDoubleConstant());
1187 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001188 }
1189 return nullptr;
1190}
1191
1192HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001193 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1194 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001195 } else if (GetLeft()->IsLongConstant()) {
1196 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001197 // The binop(long, int) case is only valid for shifts and rotations.
1198 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001199 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1200 } else if (GetRight()->IsLongConstant()) {
1201 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001202 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001203 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001204 // The binop(null, null) case is only valid for equal and not-equal conditions.
1205 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001206 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001207 } else if (kEnableFloatingPointStaticEvaluation) {
1208 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1209 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1210 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1211 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1212 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001213 }
1214 return nullptr;
1215}
Dave Allison20dfc792014-06-16 20:44:29 -07001216
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001217HConstant* HBinaryOperation::GetConstantRight() const {
1218 if (GetRight()->IsConstant()) {
1219 return GetRight()->AsConstant();
1220 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1221 return GetLeft()->AsConstant();
1222 } else {
1223 return nullptr;
1224 }
1225}
1226
1227// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001228// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001229HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1230 HInstruction* most_constant_right = GetConstantRight();
1231 if (most_constant_right == nullptr) {
1232 return nullptr;
1233 } else if (most_constant_right == GetLeft()) {
1234 return GetRight();
1235 } else {
1236 return GetLeft();
1237 }
1238}
1239
Roland Levillain31dd3d62016-02-16 12:21:02 +00001240std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1241 switch (rhs) {
1242 case ComparisonBias::kNoBias:
1243 return os << "no_bias";
1244 case ComparisonBias::kGtBias:
1245 return os << "gt_bias";
1246 case ComparisonBias::kLtBias:
1247 return os << "lt_bias";
1248 default:
1249 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1250 UNREACHABLE();
1251 }
1252}
1253
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001254bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1255 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001256}
1257
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001258bool HInstruction::Equals(HInstruction* other) const {
1259 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001260 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001261 if (!InstructionDataEquals(other)) return false;
1262 if (GetType() != other->GetType()) return false;
1263 if (InputCount() != other->InputCount()) return false;
1264
1265 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1266 if (InputAt(i) != other->InputAt(i)) return false;
1267 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001268 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001269 return true;
1270}
1271
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001272std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1273#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1274 switch (rhs) {
1275 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1276 default:
1277 os << "Unknown instruction kind " << static_cast<int>(rhs);
1278 break;
1279 }
1280#undef DECLARE_CASE
1281 return os;
1282}
1283
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001284void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001285 next_->previous_ = previous_;
1286 if (previous_ != nullptr) {
1287 previous_->next_ = next_;
1288 }
1289 if (block_->instructions_.first_instruction_ == this) {
1290 block_->instructions_.first_instruction_ = next_;
1291 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001292 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001293
1294 previous_ = cursor->previous_;
1295 if (previous_ != nullptr) {
1296 previous_->next_ = this;
1297 }
1298 next_ = cursor;
1299 cursor->previous_ = this;
1300 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001301
1302 if (block_->instructions_.first_instruction_ == cursor) {
1303 block_->instructions_.first_instruction_ = this;
1304 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001305}
1306
Vladimir Markofb337ea2015-11-25 15:25:10 +00001307void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1308 DCHECK(!CanThrow());
1309 DCHECK(!HasSideEffects());
1310 DCHECK(!HasEnvironmentUses());
1311 DCHECK(HasNonEnvironmentUses());
1312 DCHECK(!IsPhi()); // Makes no sense for Phi.
1313 DCHECK_EQ(InputCount(), 0u);
1314
1315 // Find the target block.
1316 HUseIterator<HInstruction*> uses_it(GetUses());
1317 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1318 uses_it.Advance();
1319 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1320 uses_it.Advance();
1321 }
1322 if (!uses_it.Done()) {
1323 // This instruction has uses in two or more blocks. Find the common dominator.
1324 CommonDominator finder(target_block);
1325 for (; !uses_it.Done(); uses_it.Advance()) {
1326 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1327 }
1328 target_block = finder.Get();
1329 DCHECK(target_block != nullptr);
1330 }
1331 // Move to the first dominator not in a loop.
1332 while (target_block->IsInLoop()) {
1333 target_block = target_block->GetDominator();
1334 DCHECK(target_block != nullptr);
1335 }
1336
1337 // Find insertion position.
1338 HInstruction* insert_pos = nullptr;
1339 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1340 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1341 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1342 insert_pos = uses_it2.Current()->GetUser();
1343 }
1344 }
1345 if (insert_pos == nullptr) {
1346 // No user in `target_block`, insert before the control flow instruction.
1347 insert_pos = target_block->GetLastInstruction();
1348 DCHECK(insert_pos->IsControlFlow());
1349 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1350 if (insert_pos->IsIf()) {
1351 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1352 if (if_input == insert_pos->GetPrevious()) {
1353 insert_pos = if_input;
1354 }
1355 }
1356 }
1357 MoveBefore(insert_pos);
1358}
1359
David Brazdilfc6a86a2015-06-26 10:33:45 +00001360HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001361 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001362 DCHECK_EQ(cursor->GetBlock(), this);
1363
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001364 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1365 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001366 new_block->instructions_.first_instruction_ = cursor;
1367 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1368 instructions_.last_instruction_ = cursor->previous_;
1369 if (cursor->previous_ == nullptr) {
1370 instructions_.first_instruction_ = nullptr;
1371 } else {
1372 cursor->previous_->next_ = nullptr;
1373 cursor->previous_ = nullptr;
1374 }
1375
1376 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001377 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001378
Vladimir Marko60584552015-09-03 13:35:12 +00001379 for (HBasicBlock* successor : GetSuccessors()) {
1380 new_block->successors_.push_back(successor);
1381 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001382 }
Vladimir Marko60584552015-09-03 13:35:12 +00001383 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001384 AddSuccessor(new_block);
1385
David Brazdil56e1acc2015-06-30 15:41:36 +01001386 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001387 return new_block;
1388}
1389
David Brazdild7558da2015-09-22 13:04:14 +01001390HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001391 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001392 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1393
1394 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1395
1396 for (HBasicBlock* predecessor : GetPredecessors()) {
1397 new_block->predecessors_.push_back(predecessor);
1398 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1399 }
1400 predecessors_.clear();
1401 AddPredecessor(new_block);
1402
1403 GetGraph()->AddBlock(new_block);
1404 return new_block;
1405}
1406
David Brazdil9bc43612015-11-05 21:25:24 +00001407HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1408 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1409 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1410
1411 HInstruction* first_insn = GetFirstInstruction();
1412 HInstruction* split_before = nullptr;
1413
1414 if (first_insn != nullptr && first_insn->IsLoadException()) {
1415 // Catch block starts with a LoadException. Split the block after
1416 // the StoreLocal and ClearException which must come after the load.
1417 DCHECK(first_insn->GetNext()->IsStoreLocal());
1418 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1419 split_before = first_insn->GetNext()->GetNext()->GetNext();
1420 } else {
1421 // Catch block does not load the exception. Split at the beginning
1422 // to create an empty catch block.
1423 split_before = first_insn;
1424 }
1425
1426 if (split_before == nullptr) {
1427 // Catch block has no instructions after the split point (must be dead).
1428 // Do not split it but rather signal error by returning nullptr.
1429 return nullptr;
1430 } else {
1431 return SplitBefore(split_before);
1432 }
1433}
1434
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001435HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1436 DCHECK_EQ(cursor->GetBlock(), this);
1437
1438 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1439 cursor->GetDexPc());
1440 new_block->instructions_.first_instruction_ = cursor;
1441 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1442 instructions_.last_instruction_ = cursor->previous_;
1443 if (cursor->previous_ == nullptr) {
1444 instructions_.first_instruction_ = nullptr;
1445 } else {
1446 cursor->previous_->next_ = nullptr;
1447 cursor->previous_ = nullptr;
1448 }
1449
1450 new_block->instructions_.SetBlockOfInstructions(new_block);
1451
1452 for (HBasicBlock* successor : GetSuccessors()) {
1453 new_block->successors_.push_back(successor);
1454 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1455 }
1456 successors_.clear();
1457
1458 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1459 dominated->dominator_ = new_block;
1460 new_block->dominated_blocks_.push_back(dominated);
1461 }
1462 dominated_blocks_.clear();
1463 return new_block;
1464}
1465
1466HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001467 DCHECK(!cursor->IsControlFlow());
1468 DCHECK_NE(instructions_.last_instruction_, cursor);
1469 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001470
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001471 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1472 new_block->instructions_.first_instruction_ = cursor->GetNext();
1473 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1474 cursor->next_->previous_ = nullptr;
1475 cursor->next_ = nullptr;
1476 instructions_.last_instruction_ = cursor;
1477
1478 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001479 for (HBasicBlock* successor : GetSuccessors()) {
1480 new_block->successors_.push_back(successor);
1481 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001482 }
Vladimir Marko60584552015-09-03 13:35:12 +00001483 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001484
Vladimir Marko60584552015-09-03 13:35:12 +00001485 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001486 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001487 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001488 }
Vladimir Marko60584552015-09-03 13:35:12 +00001489 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001490 return new_block;
1491}
1492
David Brazdilec16f792015-08-19 15:04:01 +01001493const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001494 if (EndsWithTryBoundary()) {
1495 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1496 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001497 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001498 return try_boundary;
1499 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001500 DCHECK(IsTryBlock());
1501 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001502 return nullptr;
1503 }
David Brazdilec16f792015-08-19 15:04:01 +01001504 } else if (IsTryBlock()) {
1505 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001506 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001507 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001508 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001509}
1510
David Brazdild7558da2015-09-22 13:04:14 +01001511bool HBasicBlock::HasThrowingInstructions() const {
1512 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1513 if (it.Current()->CanThrow()) {
1514 return true;
1515 }
1516 }
1517 return false;
1518}
1519
David Brazdilfc6a86a2015-06-26 10:33:45 +00001520static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1521 return block.GetPhis().IsEmpty()
1522 && !block.GetInstructions().IsEmpty()
1523 && block.GetFirstInstruction() == block.GetLastInstruction();
1524}
1525
David Brazdil46e2a392015-03-16 17:31:52 +00001526bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001527 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1528}
1529
1530bool HBasicBlock::IsSingleTryBoundary() const {
1531 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001532}
1533
David Brazdil8d5b8b22015-03-24 10:51:52 +00001534bool HBasicBlock::EndsWithControlFlowInstruction() const {
1535 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1536}
1537
David Brazdilb2bd1c52015-03-25 11:17:37 +00001538bool HBasicBlock::EndsWithIf() const {
1539 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1540}
1541
David Brazdilffee3d32015-07-06 11:48:53 +01001542bool HBasicBlock::EndsWithTryBoundary() const {
1543 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1544}
1545
David Brazdilb2bd1c52015-03-25 11:17:37 +00001546bool HBasicBlock::HasSinglePhi() const {
1547 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1548}
1549
David Brazdild26a4112015-11-10 11:07:31 +00001550ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1551 if (EndsWithTryBoundary()) {
1552 // The normal-flow successor of HTryBoundary is always stored at index zero.
1553 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1554 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1555 } else {
1556 // All successors of blocks not ending with TryBoundary are normal.
1557 return ArrayRef<HBasicBlock* const>(successors_);
1558 }
1559}
1560
1561ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1562 if (EndsWithTryBoundary()) {
1563 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1564 } else {
1565 // Blocks not ending with TryBoundary do not have exceptional successors.
1566 return ArrayRef<HBasicBlock* const>();
1567 }
1568}
1569
David Brazdilffee3d32015-07-06 11:48:53 +01001570bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001571 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1572 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1573
1574 size_t length = handlers1.size();
1575 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001576 return false;
1577 }
1578
David Brazdilb618ade2015-07-29 10:31:29 +01001579 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001580 for (size_t i = 0; i < length; ++i) {
1581 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001582 return false;
1583 }
1584 }
1585 return true;
1586}
1587
David Brazdil2d7352b2015-04-20 14:52:42 +01001588size_t HInstructionList::CountSize() const {
1589 size_t size = 0;
1590 HInstruction* current = first_instruction_;
1591 for (; current != nullptr; current = current->GetNext()) {
1592 size++;
1593 }
1594 return size;
1595}
1596
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001597void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1598 for (HInstruction* current = first_instruction_;
1599 current != nullptr;
1600 current = current->GetNext()) {
1601 current->SetBlock(block);
1602 }
1603}
1604
1605void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1606 DCHECK(Contains(cursor));
1607 if (!instruction_list.IsEmpty()) {
1608 if (cursor == last_instruction_) {
1609 last_instruction_ = instruction_list.last_instruction_;
1610 } else {
1611 cursor->next_->previous_ = instruction_list.last_instruction_;
1612 }
1613 instruction_list.last_instruction_->next_ = cursor->next_;
1614 cursor->next_ = instruction_list.first_instruction_;
1615 instruction_list.first_instruction_->previous_ = cursor;
1616 }
1617}
1618
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001619void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1620 DCHECK(Contains(cursor));
1621 if (!instruction_list.IsEmpty()) {
1622 if (cursor == first_instruction_) {
1623 first_instruction_ = instruction_list.first_instruction_;
1624 } else {
1625 cursor->previous_->next_ = instruction_list.first_instruction_;
1626 }
1627 instruction_list.last_instruction_->next_ = cursor;
1628 instruction_list.first_instruction_->previous_ = cursor->previous_;
1629 cursor->previous_ = instruction_list.last_instruction_;
1630 }
1631}
1632
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001633void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001634 if (IsEmpty()) {
1635 first_instruction_ = instruction_list.first_instruction_;
1636 last_instruction_ = instruction_list.last_instruction_;
1637 } else {
1638 AddAfter(last_instruction_, instruction_list);
1639 }
1640}
1641
David Brazdil04ff4e82015-12-10 13:54:52 +00001642// Should be called on instructions in a dead block in post order. This method
1643// assumes `insn` has been removed from all users with the exception of catch
1644// phis because of missing exceptional edges in the graph. It removes the
1645// instruction from catch phi uses, together with inputs of other catch phis in
1646// the catch block at the same index, as these must be dead too.
1647static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1648 DCHECK(!insn->HasEnvironmentUses());
1649 while (insn->HasNonEnvironmentUses()) {
1650 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1651 size_t use_index = use->GetIndex();
1652 HBasicBlock* user_block = use->GetUser()->GetBlock();
1653 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1654 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1655 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1656 }
1657 }
1658}
1659
David Brazdil2d7352b2015-04-20 14:52:42 +01001660void HBasicBlock::DisconnectAndDelete() {
1661 // Dominators must be removed after all the blocks they dominate. This way
1662 // a loop header is removed last, a requirement for correct loop information
1663 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001664 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001665
David Brazdil9eeebf62016-03-24 11:18:15 +00001666 // The following steps gradually remove the block from all its dependants in
1667 // post order (b/27683071).
1668
1669 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1670 // We need to do this before step (4) which destroys the predecessor list.
1671 HBasicBlock* loop_update_start = this;
1672 if (IsLoopHeader()) {
1673 HLoopInformation* loop_info = GetLoopInformation();
1674 // All other blocks in this loop should have been removed because the header
1675 // was their dominator.
1676 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1677 DCHECK(!loop_info->IsIrreducible());
1678 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1679 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1680 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001681 }
1682
David Brazdil9eeebf62016-03-24 11:18:15 +00001683 // (2) Disconnect the block from its successors and update their phis.
1684 for (HBasicBlock* successor : successors_) {
1685 // Delete this block from the list of predecessors.
1686 size_t this_index = successor->GetPredecessorIndexOf(this);
1687 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1688
1689 // Check that `successor` has other predecessors, otherwise `this` is the
1690 // dominator of `successor` which violates the order DCHECKed at the top.
1691 DCHECK(!successor->predecessors_.empty());
1692
1693 // Remove this block's entries in the successor's phis. Skip exceptional
1694 // successors because catch phi inputs do not correspond to predecessor
1695 // blocks but throwing instructions. The inputs of the catch phis will be
1696 // updated in step (3).
1697 if (!successor->IsCatchBlock()) {
1698 if (successor->predecessors_.size() == 1u) {
1699 // The successor has just one predecessor left. Replace phis with the only
1700 // remaining input.
1701 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1702 HPhi* phi = phi_it.Current()->AsPhi();
1703 phi->ReplaceWith(phi->InputAt(1 - this_index));
1704 successor->RemovePhi(phi);
1705 }
1706 } else {
1707 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1708 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1709 }
1710 }
1711 }
1712 }
1713 successors_.clear();
1714
1715 // (3) Remove instructions and phis. Instructions should have no remaining uses
1716 // except in catch phis. If an instruction is used by a catch phi at `index`,
1717 // remove `index`-th input of all phis in the catch block since they are
1718 // guaranteed dead. Note that we may miss dead inputs this way but the
1719 // graph will always remain consistent.
1720 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1721 HInstruction* insn = it.Current();
1722 RemoveUsesOfDeadInstruction(insn);
1723 RemoveInstruction(insn);
1724 }
1725 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1726 HPhi* insn = it.Current()->AsPhi();
1727 RemoveUsesOfDeadInstruction(insn);
1728 RemovePhi(insn);
1729 }
1730
1731 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001732 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001733 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001734 // We should not see any back edges as they would have been removed by step (3).
1735 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1736
David Brazdil2d7352b2015-04-20 14:52:42 +01001737 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001738 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1739 // This block is the only normal-flow successor of the TryBoundary which
1740 // makes `predecessor` dead. Since DCE removes blocks in post order,
1741 // exception handlers of this TryBoundary were already visited and any
1742 // remaining handlers therefore must be live. We remove `predecessor` from
1743 // their list of predecessors.
1744 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1745 while (predecessor->GetSuccessors().size() > 1) {
1746 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1747 DCHECK(handler->IsCatchBlock());
1748 predecessor->RemoveSuccessor(handler);
1749 handler->RemovePredecessor(predecessor);
1750 }
1751 }
1752
David Brazdil2d7352b2015-04-20 14:52:42 +01001753 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001754 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1755 if (num_pred_successors == 1u) {
1756 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001757 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1758 // successor. Replace those with a HGoto.
1759 DCHECK(last_instruction->IsIf() ||
1760 last_instruction->IsPackedSwitch() ||
1761 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001762 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001763 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001764 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001765 // The predecessor has no remaining successors and therefore must be dead.
1766 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001767 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001768 predecessor->RemoveInstruction(last_instruction);
1769 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001770 // There are multiple successors left. The removed block might be a successor
1771 // of a PackedSwitch which will be completely removed (perhaps replaced with
1772 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1773 // case, leave `last_instruction` as is for now.
1774 DCHECK(last_instruction->IsPackedSwitch() ||
1775 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001776 }
David Brazdil46e2a392015-03-16 17:31:52 +00001777 }
Vladimir Marko60584552015-09-03 13:35:12 +00001778 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001779
David Brazdil9eeebf62016-03-24 11:18:15 +00001780 // (5) Remove the block from all loops it is included in. Skip the inner-most
1781 // loop if this is the loop header (see definition of `loop_update_start`)
1782 // because the loop header's predecessor list has been destroyed in step (4).
1783 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1784 HLoopInformation* loop_info = it.Current();
1785 loop_info->Remove(this);
1786 if (loop_info->IsBackEdge(*this)) {
1787 // If this was the last back edge of the loop, we deliberately leave the
1788 // loop in an inconsistent state and will fail GraphChecker unless the
1789 // entire loop is removed during the pass.
1790 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001791 }
1792 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001793
David Brazdil9eeebf62016-03-24 11:18:15 +00001794 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001795 dominator_->RemoveDominatedBlock(this);
1796 SetDominator(nullptr);
1797
David Brazdil9eeebf62016-03-24 11:18:15 +00001798 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001799 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001800 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001801}
1802
1803void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001804 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001805 DCHECK(ContainsElement(dominated_blocks_, other));
1806 DCHECK_EQ(GetSingleSuccessor(), other);
1807 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001808 DCHECK(other->GetPhis().IsEmpty());
1809
David Brazdil2d7352b2015-04-20 14:52:42 +01001810 // Move instructions from `other` to `this`.
1811 DCHECK(EndsWithControlFlowInstruction());
1812 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001813 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001814 other->instructions_.SetBlockOfInstructions(this);
1815 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001816
David Brazdil2d7352b2015-04-20 14:52:42 +01001817 // Remove `other` from the loops it is included in.
1818 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1819 HLoopInformation* loop_info = it.Current();
1820 loop_info->Remove(other);
1821 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001822 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001823 }
1824 }
1825
1826 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001827 successors_.clear();
1828 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001829 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001830 successor->ReplacePredecessor(other, this);
1831 }
1832
David Brazdil2d7352b2015-04-20 14:52:42 +01001833 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001834 RemoveDominatedBlock(other);
1835 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1836 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001837 dominated->SetDominator(this);
1838 }
Vladimir Marko60584552015-09-03 13:35:12 +00001839 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001840 other->dominator_ = nullptr;
1841
1842 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001843 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001844
1845 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001846 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001847 other->SetGraph(nullptr);
1848}
1849
1850void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1851 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001852 DCHECK(GetDominatedBlocks().empty());
1853 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001854 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001855 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001856 DCHECK(other->GetPhis().IsEmpty());
1857 DCHECK(!other->IsInLoop());
1858
1859 // Move instructions from `other` to `this`.
1860 instructions_.Add(other->GetInstructions());
1861 other->instructions_.SetBlockOfInstructions(this);
1862
1863 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001864 successors_.clear();
1865 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001866 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001867 successor->ReplacePredecessor(other, this);
1868 }
1869
1870 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001871 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1872 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001873 dominated->SetDominator(this);
1874 }
Vladimir Marko60584552015-09-03 13:35:12 +00001875 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001876 other->dominator_ = nullptr;
1877 other->graph_ = nullptr;
1878}
1879
1880void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001881 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001882 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001883 predecessor->ReplaceSuccessor(this, other);
1884 }
Vladimir Marko60584552015-09-03 13:35:12 +00001885 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001886 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001887 successor->ReplacePredecessor(this, other);
1888 }
Vladimir Marko60584552015-09-03 13:35:12 +00001889 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1890 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001891 }
1892 GetDominator()->ReplaceDominatedBlock(this, other);
1893 other->SetDominator(GetDominator());
1894 dominator_ = nullptr;
1895 graph_ = nullptr;
1896}
1897
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001898void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001899 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001900 DCHECK(block->GetSuccessors().empty());
1901 DCHECK(block->GetPredecessors().empty());
1902 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001903 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001904 DCHECK(block->GetInstructions().IsEmpty());
1905 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001906
David Brazdilc7af85d2015-05-26 12:05:55 +01001907 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001908 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001909 }
1910
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001911 RemoveElement(reverse_post_order_, block);
1912 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001913}
1914
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001915void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1916 HBasicBlock* reference,
1917 bool replace_if_back_edge) {
1918 if (block->IsLoopHeader()) {
1919 // Clear the information of which blocks are contained in that loop. Since the
1920 // information is stored as a bit vector based on block ids, we have to update
1921 // it, as those block ids were specific to the callee graph and we are now adding
1922 // these blocks to the caller graph.
1923 block->GetLoopInformation()->ClearAllBlocks();
1924 }
1925
1926 // If not already in a loop, update the loop information.
1927 if (!block->IsInLoop()) {
1928 block->SetLoopInformation(reference->GetLoopInformation());
1929 }
1930
1931 // If the block is in a loop, update all its outward loops.
1932 HLoopInformation* loop_info = block->GetLoopInformation();
1933 if (loop_info != nullptr) {
1934 for (HLoopInformationOutwardIterator loop_it(*block);
1935 !loop_it.Done();
1936 loop_it.Advance()) {
1937 loop_it.Current()->Add(block);
1938 }
1939 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1940 loop_info->ReplaceBackEdge(reference, block);
1941 }
1942 }
1943
1944 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1945 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1946 ? reference->GetTryCatchInformation()
1947 : nullptr;
1948 block->SetTryCatchInformation(try_catch_info);
1949}
1950
Calin Juravle2e768302015-07-28 14:41:11 +00001951HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001952 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001953 // Update the environments in this graph to have the invoke's environment
1954 // as parent.
1955 {
1956 HReversePostOrderIterator it(*this);
1957 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1958 for (; !it.Done(); it.Advance()) {
1959 HBasicBlock* block = it.Current();
1960 for (HInstructionIterator instr_it(block->GetInstructions());
1961 !instr_it.Done();
1962 instr_it.Advance()) {
1963 HInstruction* current = instr_it.Current();
1964 if (current->NeedsEnvironment()) {
1965 current->GetEnvironment()->SetAndCopyParentChain(
1966 outer_graph->GetArena(), invoke->GetEnvironment());
1967 }
1968 }
1969 }
1970 }
1971 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1972 if (HasBoundsChecks()) {
1973 outer_graph->SetHasBoundsChecks(true);
1974 }
1975
Calin Juravle2e768302015-07-28 14:41:11 +00001976 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001977 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001978 // Simple case of an entry block, a body block, and an exit block.
1979 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001980 HBasicBlock* body = GetBlocks()[1];
1981 DCHECK(GetBlocks()[0]->IsEntryBlock());
1982 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001983 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001984 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001985 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001986
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001987 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1988 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001990
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001991 // Replace the invoke with the return value of the inlined graph.
1992 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001993 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001994 } else {
1995 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001996 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001997
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001998 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001999 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002000 // Need to inline multiple blocks. We split `invoke`'s block
2001 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002002 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002003 // with the second half.
2004 ArenaAllocator* allocator = outer_graph->GetArena();
2005 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002006 // Note that we split before the invoke only to simplify polymorphic inlining.
2007 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002008
Vladimir Markoec7802a2015-10-01 20:57:57 +01002009 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002010 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002011 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002012 exit_block_->ReplaceWith(to);
2013
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002014 // Update the meta information surrounding blocks:
2015 // (1) the graph they are now in,
2016 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002017 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002018 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002019 // Note that we do not need to update catch phi inputs because they
2020 // correspond to the register file of the outer method which the inlinee
2021 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002022
2023 // We don't add the entry block, the exit block, and the first block, which
2024 // has been merged with `at`.
2025 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2026
2027 // We add the `to` block.
2028 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002029 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002030 + kNumberOfNewBlocksInCaller;
2031
2032 // Find the location of `at` in the outer graph's reverse post order. The new
2033 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002034 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002035 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2036
David Brazdil95177982015-10-30 12:56:58 -05002037 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2038 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002039 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2040 HBasicBlock* current = it.Current();
2041 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002042 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002043 DCHECK(current->GetGraph() == this);
2044 current->SetGraph(outer_graph);
2045 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002046 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002047 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002048 }
2049 }
2050
David Brazdil95177982015-10-30 12:56:58 -05002051 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002052 to->SetGraph(outer_graph);
2053 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002054 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002055 // Only `to` can become a back edge, as the inlined blocks
2056 // are predecessors of `to`.
2057 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002058
David Brazdil3f523062016-02-29 16:53:33 +00002059 // Update all predecessors of the exit block (now the `to` block)
2060 // to not `HReturn` but `HGoto` instead.
2061 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2062 if (to->GetPredecessors().size() == 1) {
2063 HBasicBlock* predecessor = to->GetPredecessors()[0];
2064 HInstruction* last = predecessor->GetLastInstruction();
2065 if (!returns_void) {
2066 return_value = last->InputAt(0);
2067 }
2068 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2069 predecessor->RemoveInstruction(last);
2070 } else {
2071 if (!returns_void) {
2072 // There will be multiple returns.
2073 return_value = new (allocator) HPhi(
2074 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2075 to->AddPhi(return_value->AsPhi());
2076 }
2077 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2078 HInstruction* last = predecessor->GetLastInstruction();
2079 if (!returns_void) {
2080 DCHECK(last->IsReturn());
2081 return_value->AsPhi()->AddInput(last->InputAt(0));
2082 }
2083 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2084 predecessor->RemoveInstruction(last);
2085 }
2086 }
2087 }
David Brazdil05144f42015-04-16 15:18:00 +01002088
2089 // Walk over the entry block and:
2090 // - Move constants from the entry block to the outer_graph's entry block,
2091 // - Replace HParameterValue instructions with their real value.
2092 // - Remove suspend checks, that hold an environment.
2093 // We must do this after the other blocks have been inlined, otherwise ids of
2094 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002095 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002096 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2097 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002098 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002099 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002100 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002101 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002102 replacement = outer_graph->GetIntConstant(
2103 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002104 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002105 replacement = outer_graph->GetLongConstant(
2106 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002107 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002108 replacement = outer_graph->GetFloatConstant(
2109 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002110 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002111 replacement = outer_graph->GetDoubleConstant(
2112 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002113 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002114 if (kIsDebugBuild
2115 && invoke->IsInvokeStaticOrDirect()
2116 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2117 // Ensure we do not use the last input of `invoke`, as it
2118 // contains a clinit check which is not an actual argument.
2119 size_t last_input_index = invoke->InputCount() - 1;
2120 DCHECK(parameter_index != last_input_index);
2121 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002122 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002123 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002124 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002125 } else {
2126 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2127 entry_block_->RemoveInstruction(current);
2128 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002129 if (replacement != nullptr) {
2130 current->ReplaceWith(replacement);
2131 // If the current is the return value then we need to update the latter.
2132 if (current == return_value) {
2133 DCHECK_EQ(entry_block_, return_value->GetBlock());
2134 return_value = replacement;
2135 }
2136 }
2137 }
2138
Calin Juravle2e768302015-07-28 14:41:11 +00002139 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002140}
2141
Mingyao Yang3584bce2015-05-19 16:01:59 -07002142/*
2143 * Loop will be transformed to:
2144 * old_pre_header
2145 * |
2146 * if_block
2147 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002148 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002149 * \ /
2150 * new_pre_header
2151 * |
2152 * header
2153 */
2154void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2155 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002156 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002157
Aart Bik3fc7f352015-11-20 22:03:03 -08002158 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002159 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002160 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2161 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002162 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2163 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002164 AddBlock(true_block);
2165 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002166 AddBlock(new_pre_header);
2167
Aart Bik3fc7f352015-11-20 22:03:03 -08002168 header->ReplacePredecessor(old_pre_header, new_pre_header);
2169 old_pre_header->successors_.clear();
2170 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002171
Aart Bik3fc7f352015-11-20 22:03:03 -08002172 old_pre_header->AddSuccessor(if_block);
2173 if_block->AddSuccessor(true_block); // True successor
2174 if_block->AddSuccessor(false_block); // False successor
2175 true_block->AddSuccessor(new_pre_header);
2176 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002177
Aart Bik3fc7f352015-11-20 22:03:03 -08002178 old_pre_header->dominated_blocks_.push_back(if_block);
2179 if_block->SetDominator(old_pre_header);
2180 if_block->dominated_blocks_.push_back(true_block);
2181 true_block->SetDominator(if_block);
2182 if_block->dominated_blocks_.push_back(false_block);
2183 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002184 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002185 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002186 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002187 header->SetDominator(new_pre_header);
2188
Aart Bik3fc7f352015-11-20 22:03:03 -08002189 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002190 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002191 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002192 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002193 reverse_post_order_[index_of_header++] = true_block;
2194 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002195 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002196
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002197 // The pre_header can never be a back edge of a loop.
2198 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2199 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2200 UpdateLoopAndTryInformationOfNewBlock(
2201 if_block, old_pre_header, /* replace_if_back_edge */ false);
2202 UpdateLoopAndTryInformationOfNewBlock(
2203 true_block, old_pre_header, /* replace_if_back_edge */ false);
2204 UpdateLoopAndTryInformationOfNewBlock(
2205 false_block, old_pre_header, /* replace_if_back_edge */ false);
2206 UpdateLoopAndTryInformationOfNewBlock(
2207 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002208}
2209
David Brazdilf5552582015-12-27 13:36:12 +00002210static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2211 SHARED_REQUIRES(Locks::mutator_lock_) {
2212 if (rti.IsValid()) {
2213 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2214 << " upper_bound_rti: " << upper_bound_rti
2215 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002216 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2217 << " upper_bound_rti: " << upper_bound_rti
2218 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002219 }
2220}
2221
Calin Juravle2e768302015-07-28 14:41:11 +00002222void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2223 if (kIsDebugBuild) {
2224 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2225 ScopedObjectAccess soa(Thread::Current());
2226 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2227 if (IsBoundType()) {
2228 // Having the test here spares us from making the method virtual just for
2229 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002230 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002231 }
2232 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002233 reference_type_handle_ = rti.GetTypeHandle();
2234 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002235}
2236
David Brazdilf5552582015-12-27 13:36:12 +00002237void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2238 if (kIsDebugBuild) {
2239 ScopedObjectAccess soa(Thread::Current());
2240 DCHECK(upper_bound.IsValid());
2241 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2242 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2243 }
2244 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002245 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002246}
2247
Vladimir Markoa1de9182016-02-25 11:37:38 +00002248ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002249 if (kIsDebugBuild) {
2250 ScopedObjectAccess soa(Thread::Current());
2251 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002252 if (!is_exact) {
2253 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2254 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2255 }
Calin Juravle2e768302015-07-28 14:41:11 +00002256 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002257 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002258}
2259
Calin Juravleacf735c2015-02-12 15:25:22 +00002260std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2261 ScopedObjectAccess soa(Thread::Current());
2262 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002263 << " is_valid=" << rhs.IsValid()
2264 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002265 << " is_exact=" << rhs.IsExact()
2266 << " ]";
2267 return os;
2268}
2269
Mark Mendellc4701932015-04-10 13:18:51 -04002270bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2271 // For now, assume that instructions in different blocks may use the
2272 // environment.
2273 // TODO: Use the control flow to decide if this is true.
2274 if (GetBlock() != other->GetBlock()) {
2275 return true;
2276 }
2277
2278 // We know that we are in the same block. Walk from 'this' to 'other',
2279 // checking to see if there is any instruction with an environment.
2280 HInstruction* current = this;
2281 for (; current != other && current != nullptr; current = current->GetNext()) {
2282 // This is a conservative check, as the instruction result may not be in
2283 // the referenced environment.
2284 if (current->HasEnvironment()) {
2285 return true;
2286 }
2287 }
2288
2289 // We should have been called with 'this' before 'other' in the block.
2290 // Just confirm this.
2291 DCHECK(current != nullptr);
2292 return false;
2293}
2294
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002295void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002296 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2297 IntrinsicSideEffects side_effects,
2298 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002299 intrinsic_ = intrinsic;
2300 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002301
Aart Bik5d75afe2015-12-14 11:57:01 -08002302 // Adjust method's side effects from intrinsic table.
2303 switch (side_effects) {
2304 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2305 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2306 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2307 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2308 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002309
2310 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2311 opt.SetDoesNotNeedDexCache();
2312 opt.SetDoesNotNeedEnvironment();
2313 } else {
2314 // If we need an environment, that means there will be a call, which can trigger GC.
2315 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2316 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002317 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002318 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002319}
2320
David Brazdil6de19382016-01-08 17:37:10 +00002321bool HNewInstance::IsStringAlloc() const {
2322 ScopedObjectAccess soa(Thread::Current());
2323 return GetReferenceTypeInfo().IsStringClass();
2324}
2325
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002326bool HInvoke::NeedsEnvironment() const {
2327 if (!IsIntrinsic()) {
2328 return true;
2329 }
2330 IntrinsicOptimizations opt(*this);
2331 return !opt.GetDoesNotNeedEnvironment();
2332}
2333
Vladimir Markodc151b22015-10-15 18:02:30 +01002334bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2335 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002336 return false;
2337 }
2338 if (!IsIntrinsic()) {
2339 return true;
2340 }
2341 IntrinsicOptimizations opt(*this);
2342 return !opt.GetDoesNotNeedDexCache();
2343}
2344
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002345void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2346 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2347 input->AddUseAt(this, index);
2348 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2349 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2350 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2351 InputRecordAt(i).GetUseNode()->SetIndex(i);
2352 }
2353}
2354
Vladimir Markob554b5a2015-11-06 12:57:55 +00002355void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2356 RemoveAsUserOfInput(index);
2357 inputs_.erase(inputs_.begin() + index);
2358 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2359 for (size_t i = index, e = InputCount(); i < e; ++i) {
2360 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2361 InputRecordAt(i).GetUseNode()->SetIndex(i);
2362 }
2363}
2364
Vladimir Markof64242a2015-12-01 14:58:23 +00002365std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2366 switch (rhs) {
2367 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2368 return os << "string_init";
2369 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2370 return os << "recursive";
2371 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2372 return os << "direct";
2373 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2374 return os << "direct_fixup";
2375 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2376 return os << "dex_cache_pc_relative";
2377 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2378 return os << "dex_cache_via_method";
2379 default:
2380 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2381 UNREACHABLE();
2382 }
2383}
2384
Vladimir Markofbb184a2015-11-13 14:47:00 +00002385std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2386 switch (rhs) {
2387 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2388 return os << "explicit";
2389 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2390 return os << "implicit";
2391 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2392 return os << "none";
2393 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002394 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2395 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002396 }
2397}
2398
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002399bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2400 HLoadString* other_load_string = other->AsLoadString();
2401 if (string_index_ != other_load_string->string_index_ ||
2402 GetPackedFields() != other_load_string->GetPackedFields()) {
2403 return false;
2404 }
2405 LoadKind load_kind = GetLoadKind();
2406 if (HasAddress(load_kind)) {
2407 return GetAddress() == other_load_string->GetAddress();
2408 } else if (HasStringReference(load_kind)) {
2409 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2410 } else {
2411 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2412 // If the string indexes and dex files are the same, dex cache element offsets
2413 // must also be the same, so we don't need to compare them.
2414 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2415 }
2416}
2417
2418void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2419 // Once sharpened, the load kind should not be changed again.
2420 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2421 SetPackedField<LoadKindField>(load_kind);
2422
2423 if (load_kind != LoadKind::kDexCacheViaMethod) {
2424 RemoveAsUserOfInput(0u);
2425 SetRawInputAt(0u, nullptr);
2426 }
2427 if (!NeedsEnvironment()) {
2428 RemoveEnvironment();
2429 }
2430}
2431
2432std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2433 switch (rhs) {
2434 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2435 return os << "BootImageLinkTimeAddress";
2436 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2437 return os << "BootImageLinkTimePcRelative";
2438 case HLoadString::LoadKind::kBootImageAddress:
2439 return os << "BootImageAddress";
2440 case HLoadString::LoadKind::kDexCacheAddress:
2441 return os << "DexCacheAddress";
2442 case HLoadString::LoadKind::kDexCachePcRelative:
2443 return os << "DexCachePcRelative";
2444 case HLoadString::LoadKind::kDexCacheViaMethod:
2445 return os << "DexCacheViaMethod";
2446 default:
2447 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2448 UNREACHABLE();
2449 }
2450}
2451
Mark Mendellc4701932015-04-10 13:18:51 -04002452void HInstruction::RemoveEnvironmentUsers() {
2453 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2454 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2455 HEnvironment* user = user_node->GetUser();
2456 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2457 }
2458 env_uses_.Clear();
2459}
2460
Roland Levillainc9b21f82016-03-23 16:36:59 +00002461// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002462HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2463 ArenaAllocator* allocator = GetArena();
2464
2465 if (cond->IsCondition() &&
2466 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2467 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2468 HInstruction* lhs = cond->InputAt(0);
2469 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002470 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002471 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2472 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2473 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2474 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2475 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2476 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2477 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2478 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2479 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2480 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2481 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002482 default:
2483 LOG(FATAL) << "Unexpected condition";
2484 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002485 }
2486 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2487 return replacement;
2488 } else if (cond->IsIntConstant()) {
2489 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002490 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002491 return GetIntConstant(1);
2492 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002493 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002494 return GetIntConstant(0);
2495 }
2496 } else {
2497 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2498 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2499 return replacement;
2500 }
2501}
2502
Roland Levillainc9285912015-12-18 10:38:42 +00002503std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2504 os << "["
2505 << " source=" << rhs.GetSource()
2506 << " destination=" << rhs.GetDestination()
2507 << " type=" << rhs.GetType()
2508 << " instruction=";
2509 if (rhs.GetInstruction() != nullptr) {
2510 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2511 } else {
2512 os << "null";
2513 }
2514 os << " ]";
2515 return os;
2516}
2517
Roland Levillain86503782016-02-11 19:07:30 +00002518std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2519 switch (rhs) {
2520 case TypeCheckKind::kUnresolvedCheck:
2521 return os << "unresolved_check";
2522 case TypeCheckKind::kExactCheck:
2523 return os << "exact_check";
2524 case TypeCheckKind::kClassHierarchyCheck:
2525 return os << "class_hierarchy_check";
2526 case TypeCheckKind::kAbstractClassCheck:
2527 return os << "abstract_class_check";
2528 case TypeCheckKind::kInterfaceCheck:
2529 return os << "interface_check";
2530 case TypeCheckKind::kArrayObjectCheck:
2531 return os << "array_object_check";
2532 case TypeCheckKind::kArrayCheck:
2533 return os << "array_check";
2534 default:
2535 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2536 UNREACHABLE();
2537 }
2538}
2539
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002540} // namespace art