blob: 60201964936a873d0b8657e6d316a711a1cbd6cc [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
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010019#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000020#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000021#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000022
23namespace art {
24
25void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000026 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027 blocks_.Add(block);
28}
29
Nicolas Geoffray804d0932014-05-02 08:46:00 +010030void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000031 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000032 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000033}
34
Roland Levillainfc600dc2014-12-02 17:16:31 +000035static void RemoveAsUser(HInstruction* instruction) {
36 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000037 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000038 }
39
40 HEnvironment* environment = instruction->GetEnvironment();
41 if (environment != nullptr) {
42 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000043 if (environment->GetInstructionAt(i) != nullptr) {
44 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000045 }
46 }
47 }
48}
49
50void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
51 for (size_t i = 0; i < blocks_.Size(); ++i) {
52 if (!visited.IsBitSet(i)) {
53 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010054 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000055 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
56 RemoveAsUser(it.Current());
57 }
58 }
59 }
60}
61
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010062void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010063 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000064 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000065 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000067 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
68 block->GetSuccessors().Get(j)->RemovePredecessor(block);
69 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // Remove the block from the list of blocks, so that further analyses
71 // never see it.
72 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000073 }
74 }
75}
76
77void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
78 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010079 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000080 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000081 if (visited->IsBitSet(id)) return;
82
83 visited->SetBit(id);
84 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010085 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
86 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000087 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000088 successor->AddBackEdge(block);
89 } else {
90 VisitBlockForBackEdges(successor, visited, visiting);
91 }
92 }
93 visiting->ClearBit(id);
94}
95
96void HGraph::BuildDominatorTree() {
97 ArenaBitVector visited(arena_, blocks_.Size(), false);
98
99 // (1) Find the back edges in the graph doing a DFS traversal.
100 FindBackEdges(&visited);
101
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 // (2) Remove instructions and phis from blocks not visited during
103 // the initial DFS as users from other instructions, so that
104 // users can be safely removed before uses later.
105 RemoveInstructionsAsUsersFromDeadBlocks(visited);
106
107 // (3) Remove blocks not visited during the initial DFS.
108 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 // predecessors list of live blocks.
110 RemoveDeadBlocks(visited);
111
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100113 // dominators and the reverse post order.
114 SimplifyCFG();
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000117 // the successors of a block only when all its forward branches
118 // have been processed.
119 GrowableArray<size_t> visits(arena_, blocks_.Size());
120 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100121 reverse_post_order_.Add(entry_block_);
122 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
123 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 }
125}
126
127HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
128 ArenaBitVector visited(arena_, blocks_.Size(), false);
129 // Walk the dominator tree of the first block and mark the visited blocks.
130 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000131 visited.SetBit(first->GetBlockId());
132 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 }
134 // Walk the dominator tree of the second block until a marked block is found.
135 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000136 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 return second;
138 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000139 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 LOG(ERROR) << "Could not find common dominator";
142 return nullptr;
143}
144
145void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
146 HBasicBlock* predecessor,
147 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000148 if (block->GetDominator() == nullptr) {
149 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000151 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000154 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 // Once all the forward edges have been visited, we know the immediate
156 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000157 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100158 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100159 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100160 reverse_post_order_.Add(block);
161 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
162 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000163 }
164 }
165}
166
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000167void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100168 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100169 SsaBuilder ssa_builder(this);
170 ssa_builder.BuildSsa();
171}
172
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100173void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
174 // Insert a new node between `block` and `successor` to split the
175 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100176 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 AddBlock(new_block);
178 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100179 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100180 new_block->AddSuccessor(successor);
181 if (successor->IsLoopHeader()) {
182 // If we split at a back edge boundary, make the new block the back edge.
183 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000184 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100185 info->RemoveBackEdge(block);
186 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100187 }
188 }
189}
190
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100191void HGraph::SimplifyLoop(HBasicBlock* header) {
192 HLoopInformation* info = header->GetLoopInformation();
193
194 // If there are more than one back edge, make them branch to the same block that
195 // will become the only back edge. This simplifies finding natural loops in the
196 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100197 // Also, if the loop is a do/while (that is the back edge is an if), change the
198 // back edge to be a goto. This simplifies code generation of suspend cheks.
199 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
200 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100201 AddBlock(new_back_edge);
202 new_back_edge->AddInstruction(new (arena_) HGoto());
203 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
204 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100205 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100206 }
207 info->ClearBackEdges();
208 info->AddBackEdge(new_back_edge);
209 new_back_edge->AddSuccessor(header);
210 }
211
212 // Make sure the loop has only one pre header. This simplifies SSA building by having
213 // to just look at the pre header to know which locals are initialized at entry of the
214 // loop.
215 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
216 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100217 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100218 AddBlock(pre_header);
219 pre_header->AddInstruction(new (arena_) HGoto());
220
221 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
222 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
223 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
224 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
225 if (predecessor != back_edge) {
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
233 // Make sure the second predecessor of a loop header is the back edge.
234 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
235 header->SwapPredecessors();
236 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100237
238 // Place the suspend check at the beginning of the header, so that live registers
239 // will be known when allocating registers. Note that code generation can still
240 // generate the suspend check at the back edge, but needs to be careful with
241 // loop phi spill slots (which are not written to at back edge).
242 HInstruction* first_instruction = header->GetFirstInstruction();
243 if (!first_instruction->IsSuspendCheck()) {
244 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
245 header->InsertInstructionBefore(check, first_instruction);
246 first_instruction = check;
247 }
248 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100249}
250
251void HGraph::SimplifyCFG() {
252 // Simplify the CFG for future analysis, and code generation:
253 // (1): Split critical edges.
254 // (2): Simplify loops by having only one back edge, and one preheader.
255 for (size_t i = 0; i < blocks_.Size(); ++i) {
256 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100257 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100258 if (block->GetSuccessors().Size() > 1) {
259 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
260 HBasicBlock* successor = block->GetSuccessors().Get(j);
261 if (successor->GetPredecessors().Size() > 1) {
262 SplitCriticalEdge(block, successor);
263 --j;
264 }
265 }
266 }
267 if (block->IsLoopHeader()) {
268 SimplifyLoop(block);
269 }
270 }
271}
272
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000273bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100274 // Order does not matter.
275 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
276 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 if (block->IsLoopHeader()) {
278 HLoopInformation* info = block->GetLoopInformation();
279 if (!info->Populate()) {
280 // Abort if the loop is non natural. We currently bailout in such cases.
281 return false;
282 }
283 }
284 }
285 return true;
286}
287
David Brazdil8d5b8b22015-03-24 10:51:52 +0000288void HGraph::InsertConstant(HConstant* constant) {
289 // New constants are inserted before the final control-flow instruction
290 // of the graph, or at its end if called from the graph builder.
291 if (entry_block_->EndsWithControlFlowInstruction()) {
292 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000293 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000294 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000295 }
296}
297
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000298HNullConstant* HGraph::GetNullConstant() {
299 if (cached_null_constant_ == nullptr) {
300 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000301 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000302 }
303 return cached_null_constant_;
304}
305
David Brazdil8d5b8b22015-03-24 10:51:52 +0000306template <class InstructionType, typename ValueType>
307InstructionType* HGraph::CreateConstant(ValueType value,
308 ArenaSafeMap<ValueType, InstructionType*>* cache) {
309 // Try to find an existing constant of the given value.
310 InstructionType* constant = nullptr;
311 auto cached_constant = cache->find(value);
312 if (cached_constant != cache->end()) {
313 constant = cached_constant->second;
David Brazdil46e2a392015-03-16 17:31:52 +0000314 }
David Brazdil8d5b8b22015-03-24 10:51:52 +0000315
316 // If not found or previously deleted, create and cache a new instruction.
317 if (constant == nullptr || constant->GetBlock() == nullptr) {
318 constant = new (arena_) InstructionType(value);
319 cache->Overwrite(value, constant);
320 InsertConstant(constant);
321 }
322 return constant;
David Brazdil46e2a392015-03-16 17:31:52 +0000323}
324
David Brazdil8d5b8b22015-03-24 10:51:52 +0000325HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
326 switch (type) {
327 case Primitive::Type::kPrimBoolean:
328 DCHECK(IsUint<1>(value));
329 FALLTHROUGH_INTENDED;
330 case Primitive::Type::kPrimByte:
331 case Primitive::Type::kPrimChar:
332 case Primitive::Type::kPrimShort:
333 case Primitive::Type::kPrimInt:
334 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
335 return GetIntConstant(static_cast<int32_t>(value));
336
337 case Primitive::Type::kPrimLong:
338 return GetLongConstant(value);
339
340 default:
341 LOG(FATAL) << "Unsupported constant type";
342 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000343 }
David Brazdil46e2a392015-03-16 17:31:52 +0000344}
345
Mark Mendellb0bd8912015-04-15 19:57:22 -0400346HFloatConstant* HGraph::GetFloatConstant(float value) {
347 HFloatConstant *constant = new (arena_) HFloatConstant(value);
348 InsertConstant(constant);
349 return constant;
350}
351
352HDoubleConstant* HGraph::GetDoubleConstant(double value) {
353 HDoubleConstant *constant = new (arena_) HDoubleConstant(value);
354 InsertConstant(constant);
355 return constant;
356}
357
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000358void HLoopInformation::Add(HBasicBlock* block) {
359 blocks_.SetBit(block->GetBlockId());
360}
361
David Brazdil46e2a392015-03-16 17:31:52 +0000362void HLoopInformation::Remove(HBasicBlock* block) {
363 blocks_.ClearBit(block->GetBlockId());
364}
365
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100366void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
367 if (blocks_.IsBitSet(block->GetBlockId())) {
368 return;
369 }
370
371 blocks_.SetBit(block->GetBlockId());
372 block->SetInLoop(this);
373 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
374 PopulateRecursive(block->GetPredecessors().Get(i));
375 }
376}
377
378bool HLoopInformation::Populate() {
379 DCHECK_EQ(GetBackEdges().Size(), 1u);
380 HBasicBlock* back_edge = GetBackEdges().Get(0);
381 DCHECK(back_edge->GetDominator() != nullptr);
382 if (!header_->Dominates(back_edge)) {
383 // This loop is not natural. Do not bother going further.
384 return false;
385 }
386
387 // Populate this loop: starting with the back edge, recursively add predecessors
388 // that are not already part of that loop. Set the header as part of the loop
389 // to end the recursion.
390 // This is a recursive implementation of the algorithm described in
391 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
392 blocks_.SetBit(header_->GetBlockId());
393 PopulateRecursive(back_edge);
394 return true;
395}
396
397HBasicBlock* HLoopInformation::GetPreHeader() const {
398 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
399 return header_->GetDominator();
400}
401
402bool HLoopInformation::Contains(const HBasicBlock& block) const {
403 return blocks_.IsBitSet(block.GetBlockId());
404}
405
406bool HLoopInformation::IsIn(const HLoopInformation& other) const {
407 return other.blocks_.IsBitSet(header_->GetBlockId());
408}
409
410bool HBasicBlock::Dominates(HBasicBlock* other) const {
411 // Walk up the dominator tree from `other`, to find out if `this`
412 // is an ancestor.
413 HBasicBlock* current = other;
414 while (current != nullptr) {
415 if (current == this) {
416 return true;
417 }
418 current = current->GetDominator();
419 }
420 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100421}
422
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100423static void UpdateInputsUsers(HInstruction* instruction) {
424 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
425 instruction->InputAt(i)->AddUseAt(instruction, i);
426 }
427 // Environment should be created later.
428 DCHECK(!instruction->HasEnvironment());
429}
430
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100431void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100432 DCHECK(!cursor->IsPhi());
433 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100434 DCHECK_EQ(instruction->GetId(), -1);
435 DCHECK_NE(cursor->GetId(), -1);
436 DCHECK_EQ(cursor->GetBlock(), this);
437 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100438 instruction->next_ = cursor;
439 instruction->previous_ = cursor->previous_;
440 cursor->previous_ = instruction;
441 if (GetFirstInstruction() == cursor) {
442 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100443 } else {
444 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100445 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100446 instruction->SetBlock(this);
447 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100448 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100449}
450
Roland Levillainccc07a92014-09-16 14:48:16 +0100451void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
452 HInstruction* replacement) {
453 DCHECK(initial->GetBlock() == this);
454 InsertInstructionBefore(replacement, initial);
455 initial->ReplaceWith(replacement);
456 RemoveInstruction(initial);
457}
458
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100459static void Add(HInstructionList* instruction_list,
460 HBasicBlock* block,
461 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000462 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000463 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100464 instruction->SetBlock(block);
465 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100466 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100467 instruction_list->AddInstruction(instruction);
468}
469
470void HBasicBlock::AddInstruction(HInstruction* instruction) {
471 Add(&instructions_, this, instruction);
472}
473
474void HBasicBlock::AddPhi(HPhi* phi) {
475 Add(&phis_, this, phi);
476}
477
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100478void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
479 DCHECK_EQ(phi->GetId(), -1);
480 DCHECK_NE(cursor->GetId(), -1);
481 DCHECK_EQ(cursor->GetBlock(), this);
482 if (cursor->next_ == nullptr) {
483 cursor->next_ = phi;
484 phi->previous_ = cursor;
485 DCHECK(phi->next_ == nullptr);
486 } else {
487 phi->next_ = cursor->next_;
488 phi->previous_ = cursor;
489 cursor->next_ = phi;
490 phi->next_->previous_ = phi;
491 }
492 phi->SetBlock(this);
493 phi->SetId(GetGraph()->GetNextInstructionId());
494 UpdateInputsUsers(phi);
495}
496
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100497static void Remove(HInstructionList* instruction_list,
498 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000499 HInstruction* instruction,
500 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100501 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100502 instruction->SetBlock(nullptr);
503 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000504 if (ensure_safety) {
505 DCHECK(instruction->GetUses().IsEmpty());
506 DCHECK(instruction->GetEnvUses().IsEmpty());
507 RemoveAsUser(instruction);
508 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100509}
510
David Brazdil1abb4192015-02-17 18:33:36 +0000511void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
512 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100513}
514
David Brazdil1abb4192015-02-17 18:33:36 +0000515void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
516 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100517}
518
David Brazdiled596192015-01-23 10:39:45 +0000519void HEnvironment::CopyFrom(HEnvironment* env) {
520 for (size_t i = 0; i < env->Size(); i++) {
521 HInstruction* instruction = env->GetInstructionAt(i);
522 SetRawEnvAt(i, instruction);
523 if (instruction != nullptr) {
524 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100525 }
David Brazdiled596192015-01-23 10:39:45 +0000526 }
527}
528
David Brazdil1abb4192015-02-17 18:33:36 +0000529void HEnvironment::RemoveAsUserOfInput(size_t index) const {
530 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
531 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100532}
533
Calin Juravle77520bc2015-01-12 18:45:46 +0000534HInstruction* HInstruction::GetNextDisregardingMoves() const {
535 HInstruction* next = GetNext();
536 while (next != nullptr && next->IsParallelMove()) {
537 next = next->GetNext();
538 }
539 return next;
540}
541
542HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
543 HInstruction* previous = GetPrevious();
544 while (previous != nullptr && previous->IsParallelMove()) {
545 previous = previous->GetPrevious();
546 }
547 return previous;
548}
549
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100550void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000551 if (first_instruction_ == nullptr) {
552 DCHECK(last_instruction_ == nullptr);
553 first_instruction_ = last_instruction_ = instruction;
554 } else {
555 last_instruction_->next_ = instruction;
556 instruction->previous_ = last_instruction_;
557 last_instruction_ = instruction;
558 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000559}
560
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100561void HInstructionList::RemoveInstruction(HInstruction* instruction) {
562 if (instruction->previous_ != nullptr) {
563 instruction->previous_->next_ = instruction->next_;
564 }
565 if (instruction->next_ != nullptr) {
566 instruction->next_->previous_ = instruction->previous_;
567 }
568 if (instruction == first_instruction_) {
569 first_instruction_ = instruction->next_;
570 }
571 if (instruction == last_instruction_) {
572 last_instruction_ = instruction->previous_;
573 }
574}
575
Roland Levillain6b469232014-09-25 10:10:38 +0100576bool HInstructionList::Contains(HInstruction* instruction) const {
577 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
578 if (it.Current() == instruction) {
579 return true;
580 }
581 }
582 return false;
583}
584
Roland Levillainccc07a92014-09-16 14:48:16 +0100585bool HInstructionList::FoundBefore(const HInstruction* instruction1,
586 const HInstruction* instruction2) const {
587 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
588 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
589 if (it.Current() == instruction1) {
590 return true;
591 }
592 if (it.Current() == instruction2) {
593 return false;
594 }
595 }
596 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
597 return true;
598}
599
Roland Levillain6c82d402014-10-13 16:10:27 +0100600bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
601 if (other_instruction == this) {
602 // An instruction does not strictly dominate itself.
603 return false;
604 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100605 HBasicBlock* block = GetBlock();
606 HBasicBlock* other_block = other_instruction->GetBlock();
607 if (block != other_block) {
608 return GetBlock()->Dominates(other_instruction->GetBlock());
609 } else {
610 // If both instructions are in the same block, ensure this
611 // instruction comes before `other_instruction`.
612 if (IsPhi()) {
613 if (!other_instruction->IsPhi()) {
614 // Phis appear before non phi-instructions so this instruction
615 // dominates `other_instruction`.
616 return true;
617 } else {
618 // There is no order among phis.
619 LOG(FATAL) << "There is no dominance between phis of a same block.";
620 return false;
621 }
622 } else {
623 // `this` is not a phi.
624 if (other_instruction->IsPhi()) {
625 // Phis appear before non phi-instructions so this instruction
626 // does not dominate `other_instruction`.
627 return false;
628 } else {
629 // Check whether this instruction comes before
630 // `other_instruction` in the instruction list.
631 return block->GetInstructions().FoundBefore(this, other_instruction);
632 }
633 }
634 }
635}
636
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100637void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100638 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000639 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
640 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100641 HInstruction* user = current->GetUser();
642 size_t input_index = current->GetIndex();
643 user->SetRawInputAt(input_index, other);
644 other->AddUseAt(user, input_index);
645 }
646
David Brazdiled596192015-01-23 10:39:45 +0000647 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
648 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100649 HEnvironment* user = current->GetUser();
650 size_t input_index = current->GetIndex();
651 user->SetRawEnvAt(input_index, other);
652 other->AddEnvUseAt(user, input_index);
653 }
654
David Brazdiled596192015-01-23 10:39:45 +0000655 uses_.Clear();
656 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657}
658
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100659void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000660 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100661 SetRawInputAt(index, replacement);
662 replacement->AddUseAt(this, index);
663}
664
Nicolas Geoffray39468442014-09-02 15:17:15 +0100665size_t HInstruction::EnvironmentSize() const {
666 return HasEnvironment() ? environment_->Size() : 0;
667}
668
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100669void HPhi::AddInput(HInstruction* input) {
670 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000671 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100672 input->AddUseAt(this, inputs_.Size() - 1);
673}
674
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100675#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000676void H##name::Accept(HGraphVisitor* visitor) { \
677 visitor->Visit##name(this); \
678}
679
680FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
681
682#undef DEFINE_ACCEPT
683
684void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100685 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
686 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000687 HBasicBlock* block = blocks.Get(i);
688 if (block != nullptr) {
689 VisitBasicBlock(block);
690 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000691 }
692}
693
Roland Levillain633021e2014-10-01 14:12:25 +0100694void HGraphVisitor::VisitReversePostOrder() {
695 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
696 VisitBasicBlock(it.Current());
697 }
698}
699
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000700void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100701 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100702 it.Current()->Accept(this);
703 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100704 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000705 it.Current()->Accept(this);
706 }
707}
708
Roland Levillain9240d6a2014-10-20 16:47:04 +0100709HConstant* HUnaryOperation::TryStaticEvaluation() const {
710 if (GetInput()->IsIntConstant()) {
711 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000712 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100713 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100714 // TODO: Implement static evaluation of long unary operations.
715 //
716 // Do not exit with a fatal condition here. Instead, simply
717 // return `nullptr' to notify the caller that this instruction
718 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100719 return nullptr;
720 }
721 return nullptr;
722}
723
724HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100725 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
726 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
727 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000728 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100729 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
730 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
731 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000732 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000733 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000734 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000735 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000736 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000737 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100738 }
739 return nullptr;
740}
Dave Allison20dfc792014-06-16 20:44:29 -0700741
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000742HConstant* HBinaryOperation::GetConstantRight() const {
743 if (GetRight()->IsConstant()) {
744 return GetRight()->AsConstant();
745 } else if (IsCommutative() && GetLeft()->IsConstant()) {
746 return GetLeft()->AsConstant();
747 } else {
748 return nullptr;
749 }
750}
751
752// If `GetConstantRight()` returns one of the input, this returns the other
753// one. Otherwise it returns nullptr.
754HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
755 HInstruction* most_constant_right = GetConstantRight();
756 if (most_constant_right == nullptr) {
757 return nullptr;
758 } else if (most_constant_right == GetLeft()) {
759 return GetRight();
760 } else {
761 return GetLeft();
762 }
763}
764
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700765bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
766 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100767}
768
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100769bool HInstruction::Equals(HInstruction* other) const {
770 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100771 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100772 if (!InstructionDataEquals(other)) return false;
773 if (GetType() != other->GetType()) return false;
774 if (InputCount() != other->InputCount()) return false;
775
776 for (size_t i = 0, e = InputCount(); i < e; ++i) {
777 if (InputAt(i) != other->InputAt(i)) return false;
778 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100779 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100780 return true;
781}
782
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700783std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
784#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
785 switch (rhs) {
786 FOR_EACH_INSTRUCTION(DECLARE_CASE)
787 default:
788 os << "Unknown instruction kind " << static_cast<int>(rhs);
789 break;
790 }
791#undef DECLARE_CASE
792 return os;
793}
794
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000795void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000796 next_->previous_ = previous_;
797 if (previous_ != nullptr) {
798 previous_->next_ = next_;
799 }
800 if (block_->instructions_.first_instruction_ == this) {
801 block_->instructions_.first_instruction_ = next_;
802 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000803 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000804
805 previous_ = cursor->previous_;
806 if (previous_ != nullptr) {
807 previous_->next_ = this;
808 }
809 next_ = cursor;
810 cursor->previous_ = this;
811 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000812
813 if (block_->instructions_.first_instruction_ == cursor) {
814 block_->instructions_.first_instruction_ = this;
815 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000816}
817
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000818HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
819 DCHECK(!cursor->IsControlFlow());
820 DCHECK_NE(instructions_.last_instruction_, cursor);
821 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000822
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000823 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
824 new_block->instructions_.first_instruction_ = cursor->GetNext();
825 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
826 cursor->next_->previous_ = nullptr;
827 cursor->next_ = nullptr;
828 instructions_.last_instruction_ = cursor;
829
830 new_block->instructions_.SetBlockOfInstructions(new_block);
831 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
832 HBasicBlock* successor = GetSuccessors().Get(i);
833 new_block->successors_.Add(successor);
834 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
835 }
836 successors_.Reset();
837
838 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
839 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
840 dominated->dominator_ = new_block;
841 new_block->dominated_blocks_.Add(dominated);
842 }
843 dominated_blocks_.Reset();
844 return new_block;
845}
846
David Brazdil46e2a392015-03-16 17:31:52 +0000847bool HBasicBlock::IsSingleGoto() const {
848 HLoopInformation* loop_info = GetLoopInformation();
849 // TODO: Remove the null check b/19084197.
850 return GetFirstInstruction() != nullptr
851 && GetPhis().IsEmpty()
852 && GetFirstInstruction() == GetLastInstruction()
853 && GetLastInstruction()->IsGoto()
854 // Back edges generate the suspend check.
855 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
856}
857
David Brazdil8d5b8b22015-03-24 10:51:52 +0000858bool HBasicBlock::EndsWithControlFlowInstruction() const {
859 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
860}
861
David Brazdilb2bd1c52015-03-25 11:17:37 +0000862bool HBasicBlock::EndsWithIf() const {
863 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
864}
865
866bool HBasicBlock::HasSinglePhi() const {
867 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
868}
869
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000870void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
871 for (HInstruction* current = first_instruction_;
872 current != nullptr;
873 current = current->GetNext()) {
874 current->SetBlock(block);
875 }
876}
877
878void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
879 DCHECK(Contains(cursor));
880 if (!instruction_list.IsEmpty()) {
881 if (cursor == last_instruction_) {
882 last_instruction_ = instruction_list.last_instruction_;
883 } else {
884 cursor->next_->previous_ = instruction_list.last_instruction_;
885 }
886 instruction_list.last_instruction_->next_ = cursor->next_;
887 cursor->next_ = instruction_list.first_instruction_;
888 instruction_list.first_instruction_->previous_ = cursor;
889 }
890}
891
892void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +0000893 if (IsEmpty()) {
894 first_instruction_ = instruction_list.first_instruction_;
895 last_instruction_ = instruction_list.last_instruction_;
896 } else {
897 AddAfter(last_instruction_, instruction_list);
898 }
899}
900
901void HBasicBlock::DisconnectFromAll() {
902 DCHECK(dominated_blocks_.IsEmpty()) << "Unimplemented scenario";
903
904 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
905 predecessors_.Get(i)->successors_.Delete(this);
906 }
907 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
908 successors_.Get(i)->predecessors_.Delete(this);
909 }
910 dominator_->dominated_blocks_.Delete(this);
911
912 predecessors_.Reset();
913 successors_.Reset();
914 dominator_ = nullptr;
915 graph_ = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000916}
917
918void HBasicBlock::MergeWith(HBasicBlock* other) {
919 DCHECK(successors_.IsEmpty()) << "Unimplemented block merge scenario";
David Brazdil46e2a392015-03-16 17:31:52 +0000920 DCHECK(dominated_blocks_.IsEmpty()
921 || (dominated_blocks_.Size() == 1 && dominated_blocks_.Get(0) == other))
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000922 << "Unimplemented block merge scenario";
923 DCHECK(other->GetPhis().IsEmpty());
924
925 successors_.Reset();
926 dominated_blocks_.Reset();
927 instructions_.Add(other->GetInstructions());
928 other->GetInstructions().SetBlockOfInstructions(this);
929
930 while (!other->GetSuccessors().IsEmpty()) {
931 HBasicBlock* successor = other->GetSuccessors().Get(0);
932 successor->ReplacePredecessor(other, this);
933 }
934
935 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
936 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
937 dominated_blocks_.Add(dominated);
938 dominated->SetDominator(this);
939 }
940 other->dominated_blocks_.Reset();
941 other->dominator_ = nullptr;
942 other->graph_ = nullptr;
943}
944
945void HBasicBlock::ReplaceWith(HBasicBlock* other) {
946 while (!GetPredecessors().IsEmpty()) {
947 HBasicBlock* predecessor = GetPredecessors().Get(0);
948 predecessor->ReplaceSuccessor(this, other);
949 }
950 while (!GetSuccessors().IsEmpty()) {
951 HBasicBlock* successor = GetSuccessors().Get(0);
952 successor->ReplacePredecessor(this, other);
953 }
954 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
955 other->AddDominatedBlock(dominated_blocks_.Get(i));
956 }
957 GetDominator()->ReplaceDominatedBlock(this, other);
958 other->SetDominator(GetDominator());
959 dominator_ = nullptr;
960 graph_ = nullptr;
961}
962
963// Create space in `blocks` for adding `number_of_new_blocks` entries
964// starting at location `at`. Blocks after `at` are moved accordingly.
965static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
966 size_t number_of_new_blocks,
967 size_t at) {
968 size_t old_size = blocks->Size();
969 size_t new_size = old_size + number_of_new_blocks;
970 blocks->SetSize(new_size);
971 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
972 blocks->Put(j, blocks->Get(i));
973 }
974}
975
976void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000977 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000978 // Simple case of an entry block, a body block, and an exit block.
979 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000980 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000981 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
982 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000983 DCHECK(!body->IsExitBlock());
984 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000985
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000986 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
987 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000988
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000989 // Replace the invoke with the return value of the inlined graph.
990 if (last->IsReturn()) {
991 invoke->ReplaceWith(last->InputAt(0));
992 } else {
993 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000994 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000995
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000996 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000997 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000998 // Need to inline multiple blocks. We split `invoke`'s block
999 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001000 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001001 // with the second half.
1002 ArenaAllocator* allocator = outer_graph->GetArena();
1003 HBasicBlock* at = invoke->GetBlock();
1004 HBasicBlock* to = at->SplitAfter(invoke);
1005
1006 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1007 DCHECK(!first->IsInLoop());
1008 at->MergeWith(first);
1009 exit_block_->ReplaceWith(to);
1010
1011 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001012 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001013 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001014 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1015 if (to->GetPredecessors().Size() == 1) {
1016 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001017 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001018 if (!returns_void) {
1019 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001020 }
1021 predecessor->AddInstruction(new (allocator) HGoto());
1022 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001023 } else {
1024 if (!returns_void) {
1025 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001026 return_value = new (allocator) HPhi(
1027 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001028 to->AddPhi(return_value->AsPhi());
1029 }
1030 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1031 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1032 HInstruction* last = predecessor->GetLastInstruction();
1033 if (!returns_void) {
1034 return_value->AsPhi()->AddInput(last->InputAt(0));
1035 }
1036 predecessor->AddInstruction(new (allocator) HGoto());
1037 predecessor->RemoveInstruction(last);
1038 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001039 }
1040
1041 if (return_value != nullptr) {
1042 invoke->ReplaceWith(return_value);
1043 }
1044
1045 // Update the meta information surrounding blocks:
1046 // (1) the graph they are now in,
1047 // (2) the reverse post order of that graph,
1048 // (3) the potential loop information they are now in.
1049
1050 // We don't add the entry block, the exit block, and the first block, which
1051 // has been merged with `at`.
1052 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1053
1054 // We add the `to` block.
1055 static constexpr int kNumberOfNewBlocksInCaller = 1;
1056 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1057 + kNumberOfNewBlocksInCaller;
1058
1059 // Find the location of `at` in the outer graph's reverse post order. The new
1060 // blocks will be added after it.
1061 size_t index_of_at = 0;
1062 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1063 index_of_at++;
1064 }
1065 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1066
1067 // Do a reverse post order of the blocks in the callee and do (1), (2),
1068 // and (3) to the blocks that apply.
1069 HLoopInformation* info = at->GetLoopInformation();
1070 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1071 HBasicBlock* current = it.Current();
1072 if (current != exit_block_ && current != entry_block_ && current != first) {
1073 DCHECK(!current->IsInLoop());
1074 DCHECK(current->GetGraph() == this);
1075 current->SetGraph(outer_graph);
1076 outer_graph->AddBlock(current);
1077 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1078 if (info != nullptr) {
1079 info->Add(current);
1080 current->SetLoopInformation(info);
1081 }
1082 }
1083 }
1084
1085 // Do (1), (2), and (3) to `to`.
1086 to->SetGraph(outer_graph);
1087 outer_graph->AddBlock(to);
1088 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1089 if (info != nullptr) {
1090 info->Add(to);
1091 to->SetLoopInformation(info);
David Brazdil46e2a392015-03-16 17:31:52 +00001092 if (info->IsBackEdge(*at)) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001093 // Only `at` can become a back edge, as the inlined blocks
1094 // are predecessors of `at`.
1095 DCHECK_EQ(1u, info->NumberOfBackEdges());
1096 info->ClearBackEdges();
1097 info->AddBackEdge(to);
1098 }
1099 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001100 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001101
David Brazdil05144f42015-04-16 15:18:00 +01001102 // Update the next instruction id of the outer graph, so that instructions
1103 // added later get bigger ids than those in the inner graph.
1104 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1105
1106 // Walk over the entry block and:
1107 // - Move constants from the entry block to the outer_graph's entry block,
1108 // - Replace HParameterValue instructions with their real value.
1109 // - Remove suspend checks, that hold an environment.
1110 // We must do this after the other blocks have been inlined, otherwise ids of
1111 // constants could overlap with the inner graph.
1112 int parameter_index = 0;
1113 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1114 HInstruction* current = it.Current();
1115 if (current->IsNullConstant()) {
1116 current->ReplaceWith(outer_graph->GetNullConstant());
1117 } else if (current->IsIntConstant()) {
1118 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1119 } else if (current->IsLongConstant()) {
1120 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
1121 } else if (current->IsFloatConstant() || current->IsDoubleConstant()) {
1122 // TODO: Don't duplicate floating-point constants.
1123 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
1124 } else if (current->IsParameterValue()) {
1125 current->ReplaceWith(invoke->InputAt(parameter_index++));
1126 } else {
1127 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1128 entry_block_->RemoveInstruction(current);
1129 }
1130 }
1131
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001132 // Finally remove the invoke from the caller.
1133 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001134}
1135
David Brazdil46e2a392015-03-16 17:31:52 +00001136void HGraph::MergeEmptyBranches(HBasicBlock* start_block, HBasicBlock* end_block) {
David Brazdilb2bd1c52015-03-25 11:17:37 +00001137 // Find the two branches of an If.
David Brazdil46e2a392015-03-16 17:31:52 +00001138 DCHECK_EQ(start_block->GetSuccessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001139 HBasicBlock* left_branch = start_block->GetSuccessors().Get(0);
1140 HBasicBlock* right_branch = start_block->GetSuccessors().Get(1);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001141
1142 // Make sure this is a diamond control-flow path.
David Brazdil46e2a392015-03-16 17:31:52 +00001143 DCHECK_EQ(left_branch->GetSuccessors().Get(0), end_block);
1144 DCHECK_EQ(right_branch->GetSuccessors().Get(0), end_block);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001145 DCHECK_EQ(end_block->GetPredecessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001146 DCHECK_EQ(start_block, end_block->GetDominator());
1147
1148 // Disconnect the branches and merge the two blocks. This will move
1149 // all instructions from 'end_block' to 'start_block'.
1150 DCHECK(left_branch->IsSingleGoto());
1151 DCHECK(right_branch->IsSingleGoto());
1152 left_branch->DisconnectFromAll();
1153 right_branch->DisconnectFromAll();
1154 start_block->RemoveInstruction(start_block->GetLastInstruction());
1155 start_block->MergeWith(end_block);
1156
1157 // Delete the now redundant blocks from the graph.
1158 blocks_.Put(left_branch->GetBlockId(), nullptr);
1159 blocks_.Put(right_branch->GetBlockId(), nullptr);
1160 blocks_.Put(end_block->GetBlockId(), nullptr);
1161
1162 // Update reverse post order.
1163 reverse_post_order_.Delete(left_branch);
1164 reverse_post_order_.Delete(right_branch);
1165 reverse_post_order_.Delete(end_block);
1166
David Brazdilb2bd1c52015-03-25 11:17:37 +00001167 // Update loops which contain the code.
1168 for (HLoopInformationOutwardIterator it(*start_block); !it.Done(); it.Advance()) {
1169 HLoopInformation* loop_info = it.Current();
1170 DCHECK(loop_info->Contains(*left_branch));
1171 DCHECK(loop_info->Contains(*right_branch));
1172 DCHECK(loop_info->Contains(*end_block));
David Brazdil46e2a392015-03-16 17:31:52 +00001173 loop_info->Remove(left_branch);
1174 loop_info->Remove(right_branch);
1175 loop_info->Remove(end_block);
1176 if (loop_info->IsBackEdge(*end_block)) {
1177 loop_info->RemoveBackEdge(end_block);
1178 loop_info->AddBackEdge(start_block);
1179 }
David Brazdil46e2a392015-03-16 17:31:52 +00001180 }
1181}
1182
Calin Juravleacf735c2015-02-12 15:25:22 +00001183std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1184 ScopedObjectAccess soa(Thread::Current());
1185 os << "["
1186 << " is_top=" << rhs.IsTop()
1187 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1188 << " is_exact=" << rhs.IsExact()
1189 << " ]";
1190 return os;
1191}
1192
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001193} // namespace art