blob: a6390af1f24084fbc2cff5b474fc0374a15c1884 [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 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000023#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000025
26namespace art {
27
28void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000029 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000030 blocks_.Add(block);
31}
32
Nicolas Geoffray804d0932014-05-02 08:46:00 +010033void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000034 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000035 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000036}
37
Roland Levillainfc600dc2014-12-02 17:16:31 +000038static void RemoveAsUser(HInstruction* instruction) {
39 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000040 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000041 }
42
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010043 for (HEnvironment* environment = instruction->GetEnvironment();
44 environment != nullptr;
45 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000046 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000047 if (environment->GetInstructionAt(i) != nullptr) {
48 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000049 }
50 }
51 }
52}
53
54void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
55 for (size_t i = 0; i < blocks_.Size(); ++i) {
56 if (!visited.IsBitSet(i)) {
57 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010058 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000059 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
60 RemoveAsUser(it.Current());
61 }
62 }
63 }
64}
65
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010067 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000068 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000069 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000071 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
72 block->GetSuccessors().Get(j)->RemovePredecessor(block);
73 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010074 // Remove the block from the list of blocks, so that further analyses
75 // never see it.
76 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010089 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
90 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
101 ArenaBitVector visited(arena_, blocks_.Size(), false);
102
103 // (1) Find the back edges in the graph doing a DFS traversal.
104 FindBackEdges(&visited);
105
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 // (2) Remove instructions and phis from blocks not visited during
107 // the initial DFS as users from other instructions, so that
108 // users can be safely removed before uses later.
109 RemoveInstructionsAsUsersFromDeadBlocks(visited);
110
111 // (3) Remove blocks not visited during the initial DFS.
112 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 // predecessors list of live blocks.
114 RemoveDeadBlocks(visited);
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100117 // dominators and the reverse post order.
118 SimplifyCFG();
119
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100120 // (5) Compute the dominance information and the reverse post order.
121 ComputeDominanceInformation();
122}
123
124void HGraph::ClearDominanceInformation() {
125 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
126 it.Current()->ClearDominanceInformation();
127 }
128 reverse_post_order_.Reset();
129}
130
131void HBasicBlock::ClearDominanceInformation() {
132 dominated_blocks_.Reset();
133 dominator_ = nullptr;
134}
135
136void HGraph::ComputeDominanceInformation() {
137 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000138 GrowableArray<size_t> visits(arena_, blocks_.Size());
139 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100140 reverse_post_order_.Add(entry_block_);
141 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
142 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 }
144}
145
146HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
147 ArenaBitVector visited(arena_, blocks_.Size(), false);
148 // Walk the dominator tree of the first block and mark the visited blocks.
149 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000150 visited.SetBit(first->GetBlockId());
151 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153 // Walk the dominator tree of the second block until a marked block is found.
154 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 return second;
157 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 }
160 LOG(ERROR) << "Could not find common dominator";
161 return nullptr;
162}
163
164void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
165 HBasicBlock* predecessor,
166 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000167 if (block->GetDominator() == nullptr) {
168 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000169 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000170 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000173 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 // Once all the forward edges have been visited, we know the immediate
175 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000176 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100178 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100179 reverse_post_order_.Add(block);
180 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
181 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000182 }
183 }
184}
185
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100187 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100188 SsaBuilder ssa_builder(this);
189 ssa_builder.BuildSsa();
190}
191
David Brazdil0b5c7d12015-06-11 11:17:49 +0100192void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
193 // Insert a new node between `block` and `successor` to split the
194 // critical edge.
David Brazdil3e187382015-06-26 09:59:52 +0000195 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
196 AddBlock(new_block);
David Brazdil0b5c7d12015-06-11 11:17:49 +0100197 new_block->AddInstruction(new (arena_) HGoto());
David Brazdil3e187382015-06-26 09:59:52 +0000198 // Use `InsertBetween` to ensure the predecessor index and successor index of
199 // `block` and `successor` are preserved.
200 new_block->InsertBetween(block, successor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100201 if (successor->IsLoopHeader()) {
202 // If we split at a back edge boundary, make the new block the back edge.
203 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000204 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100205 info->RemoveBackEdge(block);
206 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100207 }
208 }
209}
210
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211void HGraph::SimplifyLoop(HBasicBlock* header) {
212 HLoopInformation* info = header->GetLoopInformation();
213
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100214 // Make sure the loop has only one pre header. This simplifies SSA building by having
215 // to just look at the pre header to know which locals are initialized at entry of the
216 // loop.
217 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
218 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100219 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100220 AddBlock(pre_header);
221 pre_header->AddInstruction(new (arena_) HGoto());
222
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100223 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
224 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100225 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100226 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100227 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 }
229 }
230 pre_header->AddSuccessor(header);
231 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100232
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100233 // Make sure the first predecessor of a loop header is the incoming block.
234 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
235 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
236 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
237 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
238 if (!info->IsBackEdge(*predecessor)) {
239 header->predecessors_.Put(pred, to_swap);
240 header->predecessors_.Put(0, predecessor);
241 break;
242 }
243 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100244 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100245
246 // Place the suspend check at the beginning of the header, so that live registers
247 // will be known when allocating registers. Note that code generation can still
248 // generate the suspend check at the back edge, but needs to be careful with
249 // loop phi spill slots (which are not written to at back edge).
250 HInstruction* first_instruction = header->GetFirstInstruction();
251 if (!first_instruction->IsSuspendCheck()) {
252 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
253 header->InsertInstructionBefore(check, first_instruction);
254 first_instruction = check;
255 }
256 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100257}
258
259void HGraph::SimplifyCFG() {
260 // Simplify the CFG for future analysis, and code generation:
261 // (1): Split critical edges.
262 // (2): Simplify loops by having only one back edge, and one preheader.
263 for (size_t i = 0; i < blocks_.Size(); ++i) {
264 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100265 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100266 if (block->GetSuccessors().Size() > 1) {
267 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
268 HBasicBlock* successor = block->GetSuccessors().Get(j);
269 if (successor->GetPredecessors().Size() > 1) {
270 SplitCriticalEdge(block, successor);
271 --j;
272 }
273 }
274 }
275 if (block->IsLoopHeader()) {
276 SimplifyLoop(block);
277 }
278 }
279}
280
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000281bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100282 // Order does not matter.
283 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
284 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100285 if (block->IsLoopHeader()) {
286 HLoopInformation* info = block->GetLoopInformation();
287 if (!info->Populate()) {
288 // Abort if the loop is non natural. We currently bailout in such cases.
289 return false;
290 }
291 }
292 }
293 return true;
294}
295
David Brazdil8d5b8b22015-03-24 10:51:52 +0000296void HGraph::InsertConstant(HConstant* constant) {
297 // New constants are inserted before the final control-flow instruction
298 // of the graph, or at its end if called from the graph builder.
299 if (entry_block_->EndsWithControlFlowInstruction()) {
300 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000301 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000302 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000303 }
304}
305
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000306HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100307 // For simplicity, don't bother reviving the cached null constant if it is
308 // not null and not in a block. Otherwise, we need to clear the instruction
309 // id and/or any invariants the graph is assuming when adding new instructions.
310 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000311 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000312 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000313 }
314 return cached_null_constant_;
315}
316
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100317HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100318 // For simplicity, don't bother reviving the cached current method if it is
319 // not null and not in a block. Otherwise, we need to clear the instruction
320 // id and/or any invariants the graph is assuming when adding new instructions.
321 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700322 cached_current_method_ = new (arena_) HCurrentMethod(
323 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100324 if (entry_block_->GetFirstInstruction() == nullptr) {
325 entry_block_->AddInstruction(cached_current_method_);
326 } else {
327 entry_block_->InsertInstructionBefore(
328 cached_current_method_, entry_block_->GetFirstInstruction());
329 }
330 }
331 return cached_current_method_;
332}
333
David Brazdil8d5b8b22015-03-24 10:51:52 +0000334HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
335 switch (type) {
336 case Primitive::Type::kPrimBoolean:
337 DCHECK(IsUint<1>(value));
338 FALLTHROUGH_INTENDED;
339 case Primitive::Type::kPrimByte:
340 case Primitive::Type::kPrimChar:
341 case Primitive::Type::kPrimShort:
342 case Primitive::Type::kPrimInt:
343 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
344 return GetIntConstant(static_cast<int32_t>(value));
345
346 case Primitive::Type::kPrimLong:
347 return GetLongConstant(value);
348
349 default:
350 LOG(FATAL) << "Unsupported constant type";
351 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000352 }
David Brazdil46e2a392015-03-16 17:31:52 +0000353}
354
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000355void HGraph::CacheFloatConstant(HFloatConstant* constant) {
356 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
357 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
358 cached_float_constants_.Overwrite(value, constant);
359}
360
361void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
362 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
363 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
364 cached_double_constants_.Overwrite(value, constant);
365}
366
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000367void HLoopInformation::Add(HBasicBlock* block) {
368 blocks_.SetBit(block->GetBlockId());
369}
370
David Brazdil46e2a392015-03-16 17:31:52 +0000371void HLoopInformation::Remove(HBasicBlock* block) {
372 blocks_.ClearBit(block->GetBlockId());
373}
374
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100375void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
376 if (blocks_.IsBitSet(block->GetBlockId())) {
377 return;
378 }
379
380 blocks_.SetBit(block->GetBlockId());
381 block->SetInLoop(this);
382 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
383 PopulateRecursive(block->GetPredecessors().Get(i));
384 }
385}
386
387bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100388 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100389 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
390 HBasicBlock* back_edge = GetBackEdges().Get(i);
391 DCHECK(back_edge->GetDominator() != nullptr);
392 if (!header_->Dominates(back_edge)) {
393 // This loop is not natural. Do not bother going further.
394 return false;
395 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100396
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100397 // Populate this loop: starting with the back edge, recursively add predecessors
398 // that are not already part of that loop. Set the header as part of the loop
399 // to end the recursion.
400 // This is a recursive implementation of the algorithm described in
401 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
402 blocks_.SetBit(header_->GetBlockId());
403 PopulateRecursive(back_edge);
404 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100405 return true;
406}
407
David Brazdila4b8c212015-05-07 09:59:30 +0100408void HLoopInformation::Update() {
409 HGraph* graph = header_->GetGraph();
410 for (uint32_t id : blocks_.Indexes()) {
411 HBasicBlock* block = graph->GetBlocks().Get(id);
412 // Reset loop information of non-header blocks inside the loop, except
413 // members of inner nested loops because those should already have been
414 // updated by their own LoopInformation.
415 if (block->GetLoopInformation() == this && block != header_) {
416 block->SetLoopInformation(nullptr);
417 }
418 }
419 blocks_.ClearAllBits();
420
421 if (back_edges_.IsEmpty()) {
422 // The loop has been dismantled, delete its suspend check and remove info
423 // from the header.
424 DCHECK(HasSuspendCheck());
425 header_->RemoveInstruction(suspend_check_);
426 header_->SetLoopInformation(nullptr);
427 header_ = nullptr;
428 suspend_check_ = nullptr;
429 } else {
430 if (kIsDebugBuild) {
431 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
432 DCHECK(header_->Dominates(back_edges_.Get(i)));
433 }
434 }
435 // This loop still has reachable back edges. Repopulate the list of blocks.
436 bool populate_successful = Populate();
437 DCHECK(populate_successful);
438 }
439}
440
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100441HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100442 return header_->GetDominator();
443}
444
445bool HLoopInformation::Contains(const HBasicBlock& block) const {
446 return blocks_.IsBitSet(block.GetBlockId());
447}
448
449bool HLoopInformation::IsIn(const HLoopInformation& other) const {
450 return other.blocks_.IsBitSet(header_->GetBlockId());
451}
452
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100453size_t HLoopInformation::GetLifetimeEnd() const {
454 size_t last_position = 0;
455 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
456 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
457 }
458 return last_position;
459}
460
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100461bool HBasicBlock::Dominates(HBasicBlock* other) const {
462 // Walk up the dominator tree from `other`, to find out if `this`
463 // is an ancestor.
464 HBasicBlock* current = other;
465 while (current != nullptr) {
466 if (current == this) {
467 return true;
468 }
469 current = current->GetDominator();
470 }
471 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100472}
473
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100474static void UpdateInputsUsers(HInstruction* instruction) {
475 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
476 instruction->InputAt(i)->AddUseAt(instruction, i);
477 }
478 // Environment should be created later.
479 DCHECK(!instruction->HasEnvironment());
480}
481
Roland Levillainccc07a92014-09-16 14:48:16 +0100482void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
483 HInstruction* replacement) {
484 DCHECK(initial->GetBlock() == this);
485 InsertInstructionBefore(replacement, initial);
486 initial->ReplaceWith(replacement);
487 RemoveInstruction(initial);
488}
489
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100490static void Add(HInstructionList* instruction_list,
491 HBasicBlock* block,
492 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000493 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000494 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100495 instruction->SetBlock(block);
496 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100497 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100498 instruction_list->AddInstruction(instruction);
499}
500
501void HBasicBlock::AddInstruction(HInstruction* instruction) {
502 Add(&instructions_, this, instruction);
503}
504
505void HBasicBlock::AddPhi(HPhi* phi) {
506 Add(&phis_, this, phi);
507}
508
David Brazdilc3d743f2015-04-22 13:40:50 +0100509void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
510 DCHECK(!cursor->IsPhi());
511 DCHECK(!instruction->IsPhi());
512 DCHECK_EQ(instruction->GetId(), -1);
513 DCHECK_NE(cursor->GetId(), -1);
514 DCHECK_EQ(cursor->GetBlock(), this);
515 DCHECK(!instruction->IsControlFlow());
516 instruction->SetBlock(this);
517 instruction->SetId(GetGraph()->GetNextInstructionId());
518 UpdateInputsUsers(instruction);
519 instructions_.InsertInstructionBefore(instruction, cursor);
520}
521
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100522void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
523 DCHECK(!cursor->IsPhi());
524 DCHECK(!instruction->IsPhi());
525 DCHECK_EQ(instruction->GetId(), -1);
526 DCHECK_NE(cursor->GetId(), -1);
527 DCHECK_EQ(cursor->GetBlock(), this);
528 DCHECK(!instruction->IsControlFlow());
529 DCHECK(!cursor->IsControlFlow());
530 instruction->SetBlock(this);
531 instruction->SetId(GetGraph()->GetNextInstructionId());
532 UpdateInputsUsers(instruction);
533 instructions_.InsertInstructionAfter(instruction, cursor);
534}
535
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100536void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
537 DCHECK_EQ(phi->GetId(), -1);
538 DCHECK_NE(cursor->GetId(), -1);
539 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100540 phi->SetBlock(this);
541 phi->SetId(GetGraph()->GetNextInstructionId());
542 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100543 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100544}
545
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100546static void Remove(HInstructionList* instruction_list,
547 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000548 HInstruction* instruction,
549 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100550 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100551 instruction->SetBlock(nullptr);
552 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000553 if (ensure_safety) {
554 DCHECK(instruction->GetUses().IsEmpty());
555 DCHECK(instruction->GetEnvUses().IsEmpty());
556 RemoveAsUser(instruction);
557 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100558}
559
David Brazdil1abb4192015-02-17 18:33:36 +0000560void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100561 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000562 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100563}
564
David Brazdil1abb4192015-02-17 18:33:36 +0000565void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
566 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100567}
568
David Brazdilc7508e92015-04-27 13:28:57 +0100569void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
570 if (instruction->IsPhi()) {
571 RemovePhi(instruction->AsPhi(), ensure_safety);
572 } else {
573 RemoveInstruction(instruction, ensure_safety);
574 }
575}
576
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100577void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
578 for (size_t i = 0; i < locals.Size(); i++) {
579 HInstruction* instruction = locals.Get(i);
580 SetRawEnvAt(i, instruction);
581 if (instruction != nullptr) {
582 instruction->AddEnvUseAt(this, i);
583 }
584 }
585}
586
David Brazdiled596192015-01-23 10:39:45 +0000587void HEnvironment::CopyFrom(HEnvironment* env) {
588 for (size_t i = 0; i < env->Size(); i++) {
589 HInstruction* instruction = env->GetInstructionAt(i);
590 SetRawEnvAt(i, instruction);
591 if (instruction != nullptr) {
592 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100593 }
David Brazdiled596192015-01-23 10:39:45 +0000594 }
595}
596
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700597void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
598 HBasicBlock* loop_header) {
599 DCHECK(loop_header->IsLoopHeader());
600 for (size_t i = 0; i < env->Size(); i++) {
601 HInstruction* instruction = env->GetInstructionAt(i);
602 SetRawEnvAt(i, instruction);
603 if (instruction == nullptr) {
604 continue;
605 }
606 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
607 // At the end of the loop pre-header, the corresponding value for instruction
608 // is the first input of the phi.
609 HInstruction* initial = instruction->AsPhi()->InputAt(0);
610 DCHECK(initial->GetBlock()->Dominates(loop_header));
611 SetRawEnvAt(i, initial);
612 initial->AddEnvUseAt(this, i);
613 } else {
614 instruction->AddEnvUseAt(this, i);
615 }
616 }
617}
618
David Brazdil1abb4192015-02-17 18:33:36 +0000619void HEnvironment::RemoveAsUserOfInput(size_t index) const {
620 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
621 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100622}
623
Calin Juravle77520bc2015-01-12 18:45:46 +0000624HInstruction* HInstruction::GetNextDisregardingMoves() const {
625 HInstruction* next = GetNext();
626 while (next != nullptr && next->IsParallelMove()) {
627 next = next->GetNext();
628 }
629 return next;
630}
631
632HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
633 HInstruction* previous = GetPrevious();
634 while (previous != nullptr && previous->IsParallelMove()) {
635 previous = previous->GetPrevious();
636 }
637 return previous;
638}
639
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100640void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000641 if (first_instruction_ == nullptr) {
642 DCHECK(last_instruction_ == nullptr);
643 first_instruction_ = last_instruction_ = instruction;
644 } else {
645 last_instruction_->next_ = instruction;
646 instruction->previous_ = last_instruction_;
647 last_instruction_ = instruction;
648 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000649}
650
David Brazdilc3d743f2015-04-22 13:40:50 +0100651void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
652 DCHECK(Contains(cursor));
653 if (cursor == first_instruction_) {
654 cursor->previous_ = instruction;
655 instruction->next_ = cursor;
656 first_instruction_ = instruction;
657 } else {
658 instruction->previous_ = cursor->previous_;
659 instruction->next_ = cursor;
660 cursor->previous_ = instruction;
661 instruction->previous_->next_ = instruction;
662 }
663}
664
665void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
666 DCHECK(Contains(cursor));
667 if (cursor == last_instruction_) {
668 cursor->next_ = instruction;
669 instruction->previous_ = cursor;
670 last_instruction_ = instruction;
671 } else {
672 instruction->next_ = cursor->next_;
673 instruction->previous_ = cursor;
674 cursor->next_ = instruction;
675 instruction->next_->previous_ = instruction;
676 }
677}
678
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100679void HInstructionList::RemoveInstruction(HInstruction* instruction) {
680 if (instruction->previous_ != nullptr) {
681 instruction->previous_->next_ = instruction->next_;
682 }
683 if (instruction->next_ != nullptr) {
684 instruction->next_->previous_ = instruction->previous_;
685 }
686 if (instruction == first_instruction_) {
687 first_instruction_ = instruction->next_;
688 }
689 if (instruction == last_instruction_) {
690 last_instruction_ = instruction->previous_;
691 }
692}
693
Roland Levillain6b469232014-09-25 10:10:38 +0100694bool HInstructionList::Contains(HInstruction* instruction) const {
695 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
696 if (it.Current() == instruction) {
697 return true;
698 }
699 }
700 return false;
701}
702
Roland Levillainccc07a92014-09-16 14:48:16 +0100703bool HInstructionList::FoundBefore(const HInstruction* instruction1,
704 const HInstruction* instruction2) const {
705 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
706 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
707 if (it.Current() == instruction1) {
708 return true;
709 }
710 if (it.Current() == instruction2) {
711 return false;
712 }
713 }
714 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
715 return true;
716}
717
Roland Levillain6c82d402014-10-13 16:10:27 +0100718bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
719 if (other_instruction == this) {
720 // An instruction does not strictly dominate itself.
721 return false;
722 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100723 HBasicBlock* block = GetBlock();
724 HBasicBlock* other_block = other_instruction->GetBlock();
725 if (block != other_block) {
726 return GetBlock()->Dominates(other_instruction->GetBlock());
727 } else {
728 // If both instructions are in the same block, ensure this
729 // instruction comes before `other_instruction`.
730 if (IsPhi()) {
731 if (!other_instruction->IsPhi()) {
732 // Phis appear before non phi-instructions so this instruction
733 // dominates `other_instruction`.
734 return true;
735 } else {
736 // There is no order among phis.
737 LOG(FATAL) << "There is no dominance between phis of a same block.";
738 return false;
739 }
740 } else {
741 // `this` is not a phi.
742 if (other_instruction->IsPhi()) {
743 // Phis appear before non phi-instructions so this instruction
744 // does not dominate `other_instruction`.
745 return false;
746 } else {
747 // Check whether this instruction comes before
748 // `other_instruction` in the instruction list.
749 return block->GetInstructions().FoundBefore(this, other_instruction);
750 }
751 }
752 }
753}
754
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100755void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100756 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000757 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
758 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100759 HInstruction* user = current->GetUser();
760 size_t input_index = current->GetIndex();
761 user->SetRawInputAt(input_index, other);
762 other->AddUseAt(user, input_index);
763 }
764
David Brazdiled596192015-01-23 10:39:45 +0000765 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
766 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100767 HEnvironment* user = current->GetUser();
768 size_t input_index = current->GetIndex();
769 user->SetRawEnvAt(input_index, other);
770 other->AddEnvUseAt(user, input_index);
771 }
772
David Brazdiled596192015-01-23 10:39:45 +0000773 uses_.Clear();
774 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100775}
776
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100777void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000778 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100779 SetRawInputAt(index, replacement);
780 replacement->AddUseAt(this, index);
781}
782
Nicolas Geoffray39468442014-09-02 15:17:15 +0100783size_t HInstruction::EnvironmentSize() const {
784 return HasEnvironment() ? environment_->Size() : 0;
785}
786
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100787void HPhi::AddInput(HInstruction* input) {
788 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000789 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100790 input->AddUseAt(this, inputs_.Size() - 1);
791}
792
David Brazdil2d7352b2015-04-20 14:52:42 +0100793void HPhi::RemoveInputAt(size_t index) {
794 RemoveAsUserOfInput(index);
795 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100796 for (size_t i = index, e = InputCount(); i < e; ++i) {
797 InputRecordAt(i).GetUseNode()->SetIndex(i);
798 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100799}
800
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100801#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000802void H##name::Accept(HGraphVisitor* visitor) { \
803 visitor->Visit##name(this); \
804}
805
806FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
807
808#undef DEFINE_ACCEPT
809
810void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100811 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
812 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000813 HBasicBlock* block = blocks.Get(i);
814 if (block != nullptr) {
815 VisitBasicBlock(block);
816 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000817 }
818}
819
Roland Levillain633021e2014-10-01 14:12:25 +0100820void HGraphVisitor::VisitReversePostOrder() {
821 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
822 VisitBasicBlock(it.Current());
823 }
824}
825
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000826void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100827 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100828 it.Current()->Accept(this);
829 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100830 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000831 it.Current()->Accept(this);
832 }
833}
834
Mark Mendelle82549b2015-05-06 10:55:34 -0400835HConstant* HTypeConversion::TryStaticEvaluation() const {
836 HGraph* graph = GetBlock()->GetGraph();
837 if (GetInput()->IsIntConstant()) {
838 int32_t value = GetInput()->AsIntConstant()->GetValue();
839 switch (GetResultType()) {
840 case Primitive::kPrimLong:
841 return graph->GetLongConstant(static_cast<int64_t>(value));
842 case Primitive::kPrimFloat:
843 return graph->GetFloatConstant(static_cast<float>(value));
844 case Primitive::kPrimDouble:
845 return graph->GetDoubleConstant(static_cast<double>(value));
846 default:
847 return nullptr;
848 }
849 } else if (GetInput()->IsLongConstant()) {
850 int64_t value = GetInput()->AsLongConstant()->GetValue();
851 switch (GetResultType()) {
852 case Primitive::kPrimInt:
853 return graph->GetIntConstant(static_cast<int32_t>(value));
854 case Primitive::kPrimFloat:
855 return graph->GetFloatConstant(static_cast<float>(value));
856 case Primitive::kPrimDouble:
857 return graph->GetDoubleConstant(static_cast<double>(value));
858 default:
859 return nullptr;
860 }
861 } else if (GetInput()->IsFloatConstant()) {
862 float value = GetInput()->AsFloatConstant()->GetValue();
863 switch (GetResultType()) {
864 case Primitive::kPrimInt:
865 if (std::isnan(value))
866 return graph->GetIntConstant(0);
867 if (value >= kPrimIntMax)
868 return graph->GetIntConstant(kPrimIntMax);
869 if (value <= kPrimIntMin)
870 return graph->GetIntConstant(kPrimIntMin);
871 return graph->GetIntConstant(static_cast<int32_t>(value));
872 case Primitive::kPrimLong:
873 if (std::isnan(value))
874 return graph->GetLongConstant(0);
875 if (value >= kPrimLongMax)
876 return graph->GetLongConstant(kPrimLongMax);
877 if (value <= kPrimLongMin)
878 return graph->GetLongConstant(kPrimLongMin);
879 return graph->GetLongConstant(static_cast<int64_t>(value));
880 case Primitive::kPrimDouble:
881 return graph->GetDoubleConstant(static_cast<double>(value));
882 default:
883 return nullptr;
884 }
885 } else if (GetInput()->IsDoubleConstant()) {
886 double value = GetInput()->AsDoubleConstant()->GetValue();
887 switch (GetResultType()) {
888 case Primitive::kPrimInt:
889 if (std::isnan(value))
890 return graph->GetIntConstant(0);
891 if (value >= kPrimIntMax)
892 return graph->GetIntConstant(kPrimIntMax);
893 if (value <= kPrimLongMin)
894 return graph->GetIntConstant(kPrimIntMin);
895 return graph->GetIntConstant(static_cast<int32_t>(value));
896 case Primitive::kPrimLong:
897 if (std::isnan(value))
898 return graph->GetLongConstant(0);
899 if (value >= kPrimLongMax)
900 return graph->GetLongConstant(kPrimLongMax);
901 if (value <= kPrimLongMin)
902 return graph->GetLongConstant(kPrimLongMin);
903 return graph->GetLongConstant(static_cast<int64_t>(value));
904 case Primitive::kPrimFloat:
905 return graph->GetFloatConstant(static_cast<float>(value));
906 default:
907 return nullptr;
908 }
909 }
910 return nullptr;
911}
912
Roland Levillain9240d6a2014-10-20 16:47:04 +0100913HConstant* HUnaryOperation::TryStaticEvaluation() const {
914 if (GetInput()->IsIntConstant()) {
915 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000916 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100917 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100918 // TODO: Implement static evaluation of long unary operations.
919 //
920 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700921 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100922 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100923 return nullptr;
924 }
925 return nullptr;
926}
927
928HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100929 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
930 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
931 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000932 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100933 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
934 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
935 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000936 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000937 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000938 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000939 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000940 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000941 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100942 }
943 return nullptr;
944}
Dave Allison20dfc792014-06-16 20:44:29 -0700945
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000946HConstant* HBinaryOperation::GetConstantRight() const {
947 if (GetRight()->IsConstant()) {
948 return GetRight()->AsConstant();
949 } else if (IsCommutative() && GetLeft()->IsConstant()) {
950 return GetLeft()->AsConstant();
951 } else {
952 return nullptr;
953 }
954}
955
956// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700957// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000958HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
959 HInstruction* most_constant_right = GetConstantRight();
960 if (most_constant_right == nullptr) {
961 return nullptr;
962 } else if (most_constant_right == GetLeft()) {
963 return GetRight();
964 } else {
965 return GetLeft();
966 }
967}
968
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700969bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
970 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100971}
972
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100973bool HInstruction::Equals(HInstruction* other) const {
974 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100975 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100976 if (!InstructionDataEquals(other)) return false;
977 if (GetType() != other->GetType()) return false;
978 if (InputCount() != other->InputCount()) return false;
979
980 for (size_t i = 0, e = InputCount(); i < e; ++i) {
981 if (InputAt(i) != other->InputAt(i)) return false;
982 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100983 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100984 return true;
985}
986
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700987std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
988#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
989 switch (rhs) {
990 FOR_EACH_INSTRUCTION(DECLARE_CASE)
991 default:
992 os << "Unknown instruction kind " << static_cast<int>(rhs);
993 break;
994 }
995#undef DECLARE_CASE
996 return os;
997}
998
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000999void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001000 next_->previous_ = previous_;
1001 if (previous_ != nullptr) {
1002 previous_->next_ = next_;
1003 }
1004 if (block_->instructions_.first_instruction_ == this) {
1005 block_->instructions_.first_instruction_ = next_;
1006 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001007 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001008
1009 previous_ = cursor->previous_;
1010 if (previous_ != nullptr) {
1011 previous_->next_ = this;
1012 }
1013 next_ = cursor;
1014 cursor->previous_ = this;
1015 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001016
1017 if (block_->instructions_.first_instruction_ == cursor) {
1018 block_->instructions_.first_instruction_ = this;
1019 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001020}
1021
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001022HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1023 DCHECK(!cursor->IsControlFlow());
1024 DCHECK_NE(instructions_.last_instruction_, cursor);
1025 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001026
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001027 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1028 new_block->instructions_.first_instruction_ = cursor->GetNext();
1029 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1030 cursor->next_->previous_ = nullptr;
1031 cursor->next_ = nullptr;
1032 instructions_.last_instruction_ = cursor;
1033
1034 new_block->instructions_.SetBlockOfInstructions(new_block);
1035 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1036 HBasicBlock* successor = GetSuccessors().Get(i);
1037 new_block->successors_.Add(successor);
1038 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1039 }
1040 successors_.Reset();
1041
1042 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1043 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1044 dominated->dominator_ = new_block;
1045 new_block->dominated_blocks_.Add(dominated);
1046 }
1047 dominated_blocks_.Reset();
1048 return new_block;
1049}
1050
David Brazdil46e2a392015-03-16 17:31:52 +00001051bool HBasicBlock::IsSingleGoto() const {
David Brazdil3e187382015-06-26 09:59:52 +00001052 HLoopInformation* loop_info = GetLoopInformation();
1053 DCHECK(EndsWithControlFlowInstruction());
1054 return GetPhis().IsEmpty()
1055 && GetFirstInstruction() == GetLastInstruction()
1056 && GetLastInstruction()->IsGoto()
1057 // Back edges generate the suspend check.
1058 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
David Brazdil46e2a392015-03-16 17:31:52 +00001059}
1060
David Brazdil8d5b8b22015-03-24 10:51:52 +00001061bool HBasicBlock::EndsWithControlFlowInstruction() const {
1062 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1063}
1064
David Brazdilb2bd1c52015-03-25 11:17:37 +00001065bool HBasicBlock::EndsWithIf() const {
1066 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1067}
1068
1069bool HBasicBlock::HasSinglePhi() const {
1070 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1071}
1072
David Brazdil2d7352b2015-04-20 14:52:42 +01001073size_t HInstructionList::CountSize() const {
1074 size_t size = 0;
1075 HInstruction* current = first_instruction_;
1076 for (; current != nullptr; current = current->GetNext()) {
1077 size++;
1078 }
1079 return size;
1080}
1081
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001082void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1083 for (HInstruction* current = first_instruction_;
1084 current != nullptr;
1085 current = current->GetNext()) {
1086 current->SetBlock(block);
1087 }
1088}
1089
1090void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1091 DCHECK(Contains(cursor));
1092 if (!instruction_list.IsEmpty()) {
1093 if (cursor == last_instruction_) {
1094 last_instruction_ = instruction_list.last_instruction_;
1095 } else {
1096 cursor->next_->previous_ = instruction_list.last_instruction_;
1097 }
1098 instruction_list.last_instruction_->next_ = cursor->next_;
1099 cursor->next_ = instruction_list.first_instruction_;
1100 instruction_list.first_instruction_->previous_ = cursor;
1101 }
1102}
1103
1104void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001105 if (IsEmpty()) {
1106 first_instruction_ = instruction_list.first_instruction_;
1107 last_instruction_ = instruction_list.last_instruction_;
1108 } else {
1109 AddAfter(last_instruction_, instruction_list);
1110 }
1111}
1112
David Brazdil2d7352b2015-04-20 14:52:42 +01001113void HBasicBlock::DisconnectAndDelete() {
1114 // Dominators must be removed after all the blocks they dominate. This way
1115 // a loop header is removed last, a requirement for correct loop information
1116 // iteration.
1117 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001118
David Brazdil2d7352b2015-04-20 14:52:42 +01001119 // Remove the block from all loops it is included in.
1120 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1121 HLoopInformation* loop_info = it.Current();
1122 loop_info->Remove(this);
1123 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001124 // If this was the last back edge of the loop, we deliberately leave the
1125 // loop in an inconsistent state and will fail SSAChecker unless the
1126 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001127 loop_info->RemoveBackEdge(this);
1128 }
1129 }
1130
1131 // Disconnect the block from its predecessors and update their control-flow
1132 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001133 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001134 HBasicBlock* predecessor = predecessors_.Get(i);
1135 HInstruction* last_instruction = predecessor->GetLastInstruction();
1136 predecessor->RemoveInstruction(last_instruction);
1137 predecessor->RemoveSuccessor(this);
1138 if (predecessor->GetSuccessors().Size() == 1u) {
1139 DCHECK(last_instruction->IsIf());
1140 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1141 } else {
1142 // The predecessor has no remaining successors and therefore must be dead.
1143 // We deliberately leave it without a control-flow instruction so that the
1144 // SSAChecker fails unless it is not removed during the pass too.
1145 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1146 }
David Brazdil46e2a392015-03-16 17:31:52 +00001147 }
David Brazdil46e2a392015-03-16 17:31:52 +00001148 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001149
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001150 // Disconnect the block from its successors and update their phis.
David Brazdil2d7352b2015-04-20 14:52:42 +01001151 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1152 HBasicBlock* successor = successors_.Get(i);
1153 // Delete this block from the list of predecessors.
1154 size_t this_index = successor->GetPredecessorIndexOf(this);
1155 successor->predecessors_.DeleteAt(this_index);
1156
1157 // Check that `successor` has other predecessors, otherwise `this` is the
1158 // dominator of `successor` which violates the order DCHECKed at the top.
1159 DCHECK(!successor->predecessors_.IsEmpty());
1160
David Brazdil2d7352b2015-04-20 14:52:42 +01001161 // Remove this block's entries in the successor's phis.
1162 if (successor->predecessors_.Size() == 1u) {
1163 // The successor has just one predecessor left. Replace phis with the only
1164 // remaining input.
1165 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1166 HPhi* phi = phi_it.Current()->AsPhi();
1167 phi->ReplaceWith(phi->InputAt(1 - this_index));
1168 successor->RemovePhi(phi);
1169 }
1170 } else {
1171 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1172 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1173 }
1174 }
1175 }
David Brazdil46e2a392015-03-16 17:31:52 +00001176 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001177
1178 // Disconnect from the dominator.
1179 dominator_->RemoveDominatedBlock(this);
1180 SetDominator(nullptr);
1181
1182 // Delete from the graph. The function safely deletes remaining instructions
1183 // and updates the reverse post order.
1184 graph_->DeleteDeadBlock(this);
1185 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001186}
1187
1188void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001189 DCHECK_EQ(GetGraph(), other->GetGraph());
1190 DCHECK(GetDominatedBlocks().Contains(other));
1191 DCHECK_EQ(GetSuccessors().Size(), 1u);
1192 DCHECK_EQ(GetSuccessors().Get(0), other);
1193 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1194 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001195 DCHECK(other->GetPhis().IsEmpty());
1196
David Brazdil2d7352b2015-04-20 14:52:42 +01001197 // Move instructions from `other` to `this`.
1198 DCHECK(EndsWithControlFlowInstruction());
1199 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001200 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001201 other->instructions_.SetBlockOfInstructions(this);
1202 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001203
David Brazdil2d7352b2015-04-20 14:52:42 +01001204 // Remove `other` from the loops it is included in.
1205 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1206 HLoopInformation* loop_info = it.Current();
1207 loop_info->Remove(other);
1208 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001209 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001210 }
1211 }
1212
1213 // Update links to the successors of `other`.
1214 successors_.Reset();
1215 while (!other->successors_.IsEmpty()) {
1216 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001217 successor->ReplacePredecessor(other, this);
1218 }
1219
David Brazdil2d7352b2015-04-20 14:52:42 +01001220 // Update the dominator tree.
1221 dominated_blocks_.Delete(other);
1222 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1223 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1224 dominated_blocks_.Add(dominated);
1225 dominated->SetDominator(this);
1226 }
1227 other->dominated_blocks_.Reset();
1228 other->dominator_ = nullptr;
1229
1230 // Clear the list of predecessors of `other` in preparation of deleting it.
1231 other->predecessors_.Reset();
1232
1233 // Delete `other` from the graph. The function updates reverse post order.
1234 graph_->DeleteDeadBlock(other);
1235 other->SetGraph(nullptr);
1236}
1237
1238void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1239 DCHECK_NE(GetGraph(), other->GetGraph());
1240 DCHECK(GetDominatedBlocks().IsEmpty());
1241 DCHECK(GetSuccessors().IsEmpty());
1242 DCHECK(!EndsWithControlFlowInstruction());
1243 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1244 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1245 DCHECK(other->GetPhis().IsEmpty());
1246 DCHECK(!other->IsInLoop());
1247
1248 // Move instructions from `other` to `this`.
1249 instructions_.Add(other->GetInstructions());
1250 other->instructions_.SetBlockOfInstructions(this);
1251
1252 // Update links to the successors of `other`.
1253 successors_.Reset();
1254 while (!other->successors_.IsEmpty()) {
1255 HBasicBlock* successor = other->successors_.Get(0);
1256 successor->ReplacePredecessor(other, this);
1257 }
1258
1259 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001260 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1261 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1262 dominated_blocks_.Add(dominated);
1263 dominated->SetDominator(this);
1264 }
1265 other->dominated_blocks_.Reset();
1266 other->dominator_ = nullptr;
1267 other->graph_ = nullptr;
1268}
1269
1270void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1271 while (!GetPredecessors().IsEmpty()) {
1272 HBasicBlock* predecessor = GetPredecessors().Get(0);
1273 predecessor->ReplaceSuccessor(this, other);
1274 }
1275 while (!GetSuccessors().IsEmpty()) {
1276 HBasicBlock* successor = GetSuccessors().Get(0);
1277 successor->ReplacePredecessor(this, other);
1278 }
1279 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1280 other->AddDominatedBlock(dominated_blocks_.Get(i));
1281 }
1282 GetDominator()->ReplaceDominatedBlock(this, other);
1283 other->SetDominator(GetDominator());
1284 dominator_ = nullptr;
1285 graph_ = nullptr;
1286}
1287
1288// Create space in `blocks` for adding `number_of_new_blocks` entries
1289// starting at location `at`. Blocks after `at` are moved accordingly.
1290static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1291 size_t number_of_new_blocks,
1292 size_t at) {
1293 size_t old_size = blocks->Size();
1294 size_t new_size = old_size + number_of_new_blocks;
1295 blocks->SetSize(new_size);
1296 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1297 blocks->Put(j, blocks->Get(i));
1298 }
1299}
1300
David Brazdil2d7352b2015-04-20 14:52:42 +01001301void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1302 DCHECK_EQ(block->GetGraph(), this);
1303 DCHECK(block->GetSuccessors().IsEmpty());
1304 DCHECK(block->GetPredecessors().IsEmpty());
1305 DCHECK(block->GetDominatedBlocks().IsEmpty());
1306 DCHECK(block->GetDominator() == nullptr);
1307
1308 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1309 block->RemoveInstruction(it.Current());
1310 }
1311 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1312 block->RemovePhi(it.Current()->AsPhi());
1313 }
1314
David Brazdilc7af85d2015-05-26 12:05:55 +01001315 if (block->IsExitBlock()) {
1316 exit_block_ = nullptr;
1317 }
1318
David Brazdil2d7352b2015-04-20 14:52:42 +01001319 reverse_post_order_.Delete(block);
1320 blocks_.Put(block->GetBlockId(), nullptr);
1321}
1322
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001323void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001324 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001325 // Update the environments in this graph to have the invoke's environment
1326 // as parent.
1327 {
1328 HReversePostOrderIterator it(*this);
1329 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1330 for (; !it.Done(); it.Advance()) {
1331 HBasicBlock* block = it.Current();
1332 for (HInstructionIterator instr_it(block->GetInstructions());
1333 !instr_it.Done();
1334 instr_it.Advance()) {
1335 HInstruction* current = instr_it.Current();
1336 if (current->NeedsEnvironment()) {
1337 current->GetEnvironment()->SetAndCopyParentChain(
1338 outer_graph->GetArena(), invoke->GetEnvironment());
1339 }
1340 }
1341 }
1342 }
1343 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1344 if (HasBoundsChecks()) {
1345 outer_graph->SetHasBoundsChecks(true);
1346 }
1347
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001348 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001349 // Simple case of an entry block, a body block, and an exit block.
1350 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001351 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001352 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1353 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001354 DCHECK(!body->IsExitBlock());
1355 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001356
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001357 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1358 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001359
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001360 // Replace the invoke with the return value of the inlined graph.
1361 if (last->IsReturn()) {
1362 invoke->ReplaceWith(last->InputAt(0));
1363 } else {
1364 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001365 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001366
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001367 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001368 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001369 // Need to inline multiple blocks. We split `invoke`'s block
1370 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001371 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001372 // with the second half.
1373 ArenaAllocator* allocator = outer_graph->GetArena();
1374 HBasicBlock* at = invoke->GetBlock();
1375 HBasicBlock* to = at->SplitAfter(invoke);
1376
1377 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1378 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001379 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001380 exit_block_->ReplaceWith(to);
1381
1382 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001383 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001384 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001385 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1386 if (to->GetPredecessors().Size() == 1) {
1387 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001388 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001389 if (!returns_void) {
1390 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001391 }
1392 predecessor->AddInstruction(new (allocator) HGoto());
1393 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001394 } else {
1395 if (!returns_void) {
1396 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001397 return_value = new (allocator) HPhi(
1398 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001399 to->AddPhi(return_value->AsPhi());
1400 }
1401 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1402 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1403 HInstruction* last = predecessor->GetLastInstruction();
1404 if (!returns_void) {
1405 return_value->AsPhi()->AddInput(last->InputAt(0));
1406 }
1407 predecessor->AddInstruction(new (allocator) HGoto());
1408 predecessor->RemoveInstruction(last);
1409 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001410 }
1411
1412 if (return_value != nullptr) {
1413 invoke->ReplaceWith(return_value);
1414 }
1415
1416 // Update the meta information surrounding blocks:
1417 // (1) the graph they are now in,
1418 // (2) the reverse post order of that graph,
1419 // (3) the potential loop information they are now in.
1420
1421 // We don't add the entry block, the exit block, and the first block, which
1422 // has been merged with `at`.
1423 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1424
1425 // We add the `to` block.
1426 static constexpr int kNumberOfNewBlocksInCaller = 1;
1427 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1428 + kNumberOfNewBlocksInCaller;
1429
1430 // Find the location of `at` in the outer graph's reverse post order. The new
1431 // blocks will be added after it.
1432 size_t index_of_at = 0;
1433 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1434 index_of_at++;
1435 }
1436 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1437
1438 // Do a reverse post order of the blocks in the callee and do (1), (2),
1439 // and (3) to the blocks that apply.
1440 HLoopInformation* info = at->GetLoopInformation();
1441 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1442 HBasicBlock* current = it.Current();
1443 if (current != exit_block_ && current != entry_block_ && current != first) {
1444 DCHECK(!current->IsInLoop());
1445 DCHECK(current->GetGraph() == this);
1446 current->SetGraph(outer_graph);
1447 outer_graph->AddBlock(current);
1448 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1449 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001450 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001451 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1452 loop_it.Current()->Add(current);
1453 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001454 }
1455 }
1456 }
1457
1458 // Do (1), (2), and (3) to `to`.
1459 to->SetGraph(outer_graph);
1460 outer_graph->AddBlock(to);
1461 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1462 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001463 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001464 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1465 loop_it.Current()->Add(to);
1466 }
David Brazdil46e2a392015-03-16 17:31:52 +00001467 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001468 // Only `to` can become a back edge, as the inlined blocks
1469 // are predecessors of `to`.
1470 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001471 }
1472 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001473 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001474
David Brazdil05144f42015-04-16 15:18:00 +01001475 // Update the next instruction id of the outer graph, so that instructions
1476 // added later get bigger ids than those in the inner graph.
1477 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1478
1479 // Walk over the entry block and:
1480 // - Move constants from the entry block to the outer_graph's entry block,
1481 // - Replace HParameterValue instructions with their real value.
1482 // - Remove suspend checks, that hold an environment.
1483 // We must do this after the other blocks have been inlined, otherwise ids of
1484 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001485 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001486 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1487 HInstruction* current = it.Current();
1488 if (current->IsNullConstant()) {
1489 current->ReplaceWith(outer_graph->GetNullConstant());
1490 } else if (current->IsIntConstant()) {
1491 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1492 } else if (current->IsLongConstant()) {
1493 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001494 } else if (current->IsFloatConstant()) {
1495 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1496 } else if (current->IsDoubleConstant()) {
1497 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001498 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001499 if (kIsDebugBuild
1500 && invoke->IsInvokeStaticOrDirect()
1501 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1502 // Ensure we do not use the last input of `invoke`, as it
1503 // contains a clinit check which is not an actual argument.
1504 size_t last_input_index = invoke->InputCount() - 1;
1505 DCHECK(parameter_index != last_input_index);
1506 }
David Brazdil05144f42015-04-16 15:18:00 +01001507 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001508 } else if (current->IsCurrentMethod()) {
1509 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001510 } else {
1511 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1512 entry_block_->RemoveInstruction(current);
1513 }
1514 }
1515
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001516 // Finally remove the invoke from the caller.
1517 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518}
1519
Mingyao Yang3584bce2015-05-19 16:01:59 -07001520/*
1521 * Loop will be transformed to:
1522 * old_pre_header
1523 * |
1524 * if_block
1525 * / \
1526 * dummy_block deopt_block
1527 * \ /
1528 * new_pre_header
1529 * |
1530 * header
1531 */
1532void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1533 DCHECK(header->IsLoopHeader());
1534 HBasicBlock* pre_header = header->GetDominator();
1535
1536 // Need this to avoid critical edge.
1537 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1538 // Need this to avoid critical edge.
1539 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1540 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1541 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1542 AddBlock(if_block);
1543 AddBlock(dummy_block);
1544 AddBlock(deopt_block);
1545 AddBlock(new_pre_header);
1546
1547 header->ReplacePredecessor(pre_header, new_pre_header);
1548 pre_header->successors_.Reset();
1549 pre_header->dominated_blocks_.Reset();
1550
1551 pre_header->AddSuccessor(if_block);
1552 if_block->AddSuccessor(dummy_block); // True successor
1553 if_block->AddSuccessor(deopt_block); // False successor
1554 dummy_block->AddSuccessor(new_pre_header);
1555 deopt_block->AddSuccessor(new_pre_header);
1556
1557 pre_header->dominated_blocks_.Add(if_block);
1558 if_block->SetDominator(pre_header);
1559 if_block->dominated_blocks_.Add(dummy_block);
1560 dummy_block->SetDominator(if_block);
1561 if_block->dominated_blocks_.Add(deopt_block);
1562 deopt_block->SetDominator(if_block);
1563 if_block->dominated_blocks_.Add(new_pre_header);
1564 new_pre_header->SetDominator(if_block);
1565 new_pre_header->dominated_blocks_.Add(header);
1566 header->SetDominator(new_pre_header);
1567
1568 size_t index_of_header = 0;
1569 while (reverse_post_order_.Get(index_of_header) != header) {
1570 index_of_header++;
1571 }
1572 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1573 reverse_post_order_.Put(index_of_header++, if_block);
1574 reverse_post_order_.Put(index_of_header++, dummy_block);
1575 reverse_post_order_.Put(index_of_header++, deopt_block);
1576 reverse_post_order_.Put(index_of_header++, new_pre_header);
1577
1578 HLoopInformation* info = pre_header->GetLoopInformation();
1579 if (info != nullptr) {
1580 if_block->SetLoopInformation(info);
1581 dummy_block->SetLoopInformation(info);
1582 deopt_block->SetLoopInformation(info);
1583 new_pre_header->SetLoopInformation(info);
1584 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1585 !loop_it.Done();
1586 loop_it.Advance()) {
1587 loop_it.Current()->Add(if_block);
1588 loop_it.Current()->Add(dummy_block);
1589 loop_it.Current()->Add(deopt_block);
1590 loop_it.Current()->Add(new_pre_header);
1591 }
1592 }
1593}
1594
Calin Juravleacf735c2015-02-12 15:25:22 +00001595std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1596 ScopedObjectAccess soa(Thread::Current());
1597 os << "["
1598 << " is_top=" << rhs.IsTop()
1599 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1600 << " is_exact=" << rhs.IsExact()
1601 << " ]";
1602 return os;
1603}
1604
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001605} // namespace art