blob: 39c1b4eea307bd08d592cd698fba7d378df130dc [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
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000346void HLoopInformation::Add(HBasicBlock* block) {
347 blocks_.SetBit(block->GetBlockId());
348}
349
David Brazdil46e2a392015-03-16 17:31:52 +0000350void HLoopInformation::Remove(HBasicBlock* block) {
351 blocks_.ClearBit(block->GetBlockId());
352}
353
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100354void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
355 if (blocks_.IsBitSet(block->GetBlockId())) {
356 return;
357 }
358
359 blocks_.SetBit(block->GetBlockId());
360 block->SetInLoop(this);
361 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
362 PopulateRecursive(block->GetPredecessors().Get(i));
363 }
364}
365
366bool HLoopInformation::Populate() {
367 DCHECK_EQ(GetBackEdges().Size(), 1u);
368 HBasicBlock* back_edge = GetBackEdges().Get(0);
369 DCHECK(back_edge->GetDominator() != nullptr);
370 if (!header_->Dominates(back_edge)) {
371 // This loop is not natural. Do not bother going further.
372 return false;
373 }
374
375 // Populate this loop: starting with the back edge, recursively add predecessors
376 // that are not already part of that loop. Set the header as part of the loop
377 // to end the recursion.
378 // This is a recursive implementation of the algorithm described in
379 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
380 blocks_.SetBit(header_->GetBlockId());
381 PopulateRecursive(back_edge);
382 return true;
383}
384
385HBasicBlock* HLoopInformation::GetPreHeader() const {
386 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
387 return header_->GetDominator();
388}
389
390bool HLoopInformation::Contains(const HBasicBlock& block) const {
391 return blocks_.IsBitSet(block.GetBlockId());
392}
393
394bool HLoopInformation::IsIn(const HLoopInformation& other) const {
395 return other.blocks_.IsBitSet(header_->GetBlockId());
396}
397
398bool HBasicBlock::Dominates(HBasicBlock* other) const {
399 // Walk up the dominator tree from `other`, to find out if `this`
400 // is an ancestor.
401 HBasicBlock* current = other;
402 while (current != nullptr) {
403 if (current == this) {
404 return true;
405 }
406 current = current->GetDominator();
407 }
408 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100409}
410
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100411static void UpdateInputsUsers(HInstruction* instruction) {
412 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
413 instruction->InputAt(i)->AddUseAt(instruction, i);
414 }
415 // Environment should be created later.
416 DCHECK(!instruction->HasEnvironment());
417}
418
Roland Levillainccc07a92014-09-16 14:48:16 +0100419void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
420 HInstruction* replacement) {
421 DCHECK(initial->GetBlock() == this);
422 InsertInstructionBefore(replacement, initial);
423 initial->ReplaceWith(replacement);
424 RemoveInstruction(initial);
425}
426
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100427static void Add(HInstructionList* instruction_list,
428 HBasicBlock* block,
429 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000430 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000431 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100432 instruction->SetBlock(block);
433 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100434 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100435 instruction_list->AddInstruction(instruction);
436}
437
438void HBasicBlock::AddInstruction(HInstruction* instruction) {
439 Add(&instructions_, this, instruction);
440}
441
442void HBasicBlock::AddPhi(HPhi* phi) {
443 Add(&phis_, this, phi);
444}
445
David Brazdilc3d743f2015-04-22 13:40:50 +0100446void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
447 DCHECK(!cursor->IsPhi());
448 DCHECK(!instruction->IsPhi());
449 DCHECK_EQ(instruction->GetId(), -1);
450 DCHECK_NE(cursor->GetId(), -1);
451 DCHECK_EQ(cursor->GetBlock(), this);
452 DCHECK(!instruction->IsControlFlow());
453 instruction->SetBlock(this);
454 instruction->SetId(GetGraph()->GetNextInstructionId());
455 UpdateInputsUsers(instruction);
456 instructions_.InsertInstructionBefore(instruction, cursor);
457}
458
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100459void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
460 DCHECK(!cursor->IsPhi());
461 DCHECK(!instruction->IsPhi());
462 DCHECK_EQ(instruction->GetId(), -1);
463 DCHECK_NE(cursor->GetId(), -1);
464 DCHECK_EQ(cursor->GetBlock(), this);
465 DCHECK(!instruction->IsControlFlow());
466 DCHECK(!cursor->IsControlFlow());
467 instruction->SetBlock(this);
468 instruction->SetId(GetGraph()->GetNextInstructionId());
469 UpdateInputsUsers(instruction);
470 instructions_.InsertInstructionAfter(instruction, cursor);
471}
472
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100473void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
474 DCHECK_EQ(phi->GetId(), -1);
475 DCHECK_NE(cursor->GetId(), -1);
476 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100477 phi->SetBlock(this);
478 phi->SetId(GetGraph()->GetNextInstructionId());
479 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100480 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100481}
482
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100483static void Remove(HInstructionList* instruction_list,
484 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000485 HInstruction* instruction,
486 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100487 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100488 instruction->SetBlock(nullptr);
489 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000490 if (ensure_safety) {
491 DCHECK(instruction->GetUses().IsEmpty());
492 DCHECK(instruction->GetEnvUses().IsEmpty());
493 RemoveAsUser(instruction);
494 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100495}
496
David Brazdil1abb4192015-02-17 18:33:36 +0000497void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
498 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100499}
500
David Brazdil1abb4192015-02-17 18:33:36 +0000501void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
502 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100503}
504
David Brazdiled596192015-01-23 10:39:45 +0000505void HEnvironment::CopyFrom(HEnvironment* env) {
506 for (size_t i = 0; i < env->Size(); i++) {
507 HInstruction* instruction = env->GetInstructionAt(i);
508 SetRawEnvAt(i, instruction);
509 if (instruction != nullptr) {
510 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100511 }
David Brazdiled596192015-01-23 10:39:45 +0000512 }
513}
514
David Brazdil1abb4192015-02-17 18:33:36 +0000515void HEnvironment::RemoveAsUserOfInput(size_t index) const {
516 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
517 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100518}
519
Calin Juravle77520bc2015-01-12 18:45:46 +0000520HInstruction* HInstruction::GetNextDisregardingMoves() const {
521 HInstruction* next = GetNext();
522 while (next != nullptr && next->IsParallelMove()) {
523 next = next->GetNext();
524 }
525 return next;
526}
527
528HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
529 HInstruction* previous = GetPrevious();
530 while (previous != nullptr && previous->IsParallelMove()) {
531 previous = previous->GetPrevious();
532 }
533 return previous;
534}
535
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100536void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000537 if (first_instruction_ == nullptr) {
538 DCHECK(last_instruction_ == nullptr);
539 first_instruction_ = last_instruction_ = instruction;
540 } else {
541 last_instruction_->next_ = instruction;
542 instruction->previous_ = last_instruction_;
543 last_instruction_ = instruction;
544 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000545}
546
David Brazdilc3d743f2015-04-22 13:40:50 +0100547void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
548 DCHECK(Contains(cursor));
549 if (cursor == first_instruction_) {
550 cursor->previous_ = instruction;
551 instruction->next_ = cursor;
552 first_instruction_ = instruction;
553 } else {
554 instruction->previous_ = cursor->previous_;
555 instruction->next_ = cursor;
556 cursor->previous_ = instruction;
557 instruction->previous_->next_ = instruction;
558 }
559}
560
561void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
562 DCHECK(Contains(cursor));
563 if (cursor == last_instruction_) {
564 cursor->next_ = instruction;
565 instruction->previous_ = cursor;
566 last_instruction_ = instruction;
567 } else {
568 instruction->next_ = cursor->next_;
569 instruction->previous_ = cursor;
570 cursor->next_ = instruction;
571 instruction->next_->previous_ = instruction;
572 }
573}
574
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100575void HInstructionList::RemoveInstruction(HInstruction* instruction) {
576 if (instruction->previous_ != nullptr) {
577 instruction->previous_->next_ = instruction->next_;
578 }
579 if (instruction->next_ != nullptr) {
580 instruction->next_->previous_ = instruction->previous_;
581 }
582 if (instruction == first_instruction_) {
583 first_instruction_ = instruction->next_;
584 }
585 if (instruction == last_instruction_) {
586 last_instruction_ = instruction->previous_;
587 }
588}
589
Roland Levillain6b469232014-09-25 10:10:38 +0100590bool HInstructionList::Contains(HInstruction* instruction) const {
591 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
592 if (it.Current() == instruction) {
593 return true;
594 }
595 }
596 return false;
597}
598
Roland Levillainccc07a92014-09-16 14:48:16 +0100599bool HInstructionList::FoundBefore(const HInstruction* instruction1,
600 const HInstruction* instruction2) const {
601 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
602 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
603 if (it.Current() == instruction1) {
604 return true;
605 }
606 if (it.Current() == instruction2) {
607 return false;
608 }
609 }
610 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
611 return true;
612}
613
Roland Levillain6c82d402014-10-13 16:10:27 +0100614bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
615 if (other_instruction == this) {
616 // An instruction does not strictly dominate itself.
617 return false;
618 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100619 HBasicBlock* block = GetBlock();
620 HBasicBlock* other_block = other_instruction->GetBlock();
621 if (block != other_block) {
622 return GetBlock()->Dominates(other_instruction->GetBlock());
623 } else {
624 // If both instructions are in the same block, ensure this
625 // instruction comes before `other_instruction`.
626 if (IsPhi()) {
627 if (!other_instruction->IsPhi()) {
628 // Phis appear before non phi-instructions so this instruction
629 // dominates `other_instruction`.
630 return true;
631 } else {
632 // There is no order among phis.
633 LOG(FATAL) << "There is no dominance between phis of a same block.";
634 return false;
635 }
636 } else {
637 // `this` is not a phi.
638 if (other_instruction->IsPhi()) {
639 // Phis appear before non phi-instructions so this instruction
640 // does not dominate `other_instruction`.
641 return false;
642 } else {
643 // Check whether this instruction comes before
644 // `other_instruction` in the instruction list.
645 return block->GetInstructions().FoundBefore(this, other_instruction);
646 }
647 }
648 }
649}
650
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100651void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100652 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000653 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
654 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100655 HInstruction* user = current->GetUser();
656 size_t input_index = current->GetIndex();
657 user->SetRawInputAt(input_index, other);
658 other->AddUseAt(user, input_index);
659 }
660
David Brazdiled596192015-01-23 10:39:45 +0000661 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
662 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100663 HEnvironment* user = current->GetUser();
664 size_t input_index = current->GetIndex();
665 user->SetRawEnvAt(input_index, other);
666 other->AddEnvUseAt(user, input_index);
667 }
668
David Brazdiled596192015-01-23 10:39:45 +0000669 uses_.Clear();
670 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100671}
672
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100673void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000674 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100675 SetRawInputAt(index, replacement);
676 replacement->AddUseAt(this, index);
677}
678
Nicolas Geoffray39468442014-09-02 15:17:15 +0100679size_t HInstruction::EnvironmentSize() const {
680 return HasEnvironment() ? environment_->Size() : 0;
681}
682
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100683void HPhi::AddInput(HInstruction* input) {
684 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000685 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100686 input->AddUseAt(this, inputs_.Size() - 1);
687}
688
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100689#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000690void H##name::Accept(HGraphVisitor* visitor) { \
691 visitor->Visit##name(this); \
692}
693
694FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
695
696#undef DEFINE_ACCEPT
697
698void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100699 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
700 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000701 HBasicBlock* block = blocks.Get(i);
702 if (block != nullptr) {
703 VisitBasicBlock(block);
704 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000705 }
706}
707
Roland Levillain633021e2014-10-01 14:12:25 +0100708void HGraphVisitor::VisitReversePostOrder() {
709 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
710 VisitBasicBlock(it.Current());
711 }
712}
713
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000714void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100715 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100716 it.Current()->Accept(this);
717 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100718 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000719 it.Current()->Accept(this);
720 }
721}
722
Roland Levillain9240d6a2014-10-20 16:47:04 +0100723HConstant* HUnaryOperation::TryStaticEvaluation() const {
724 if (GetInput()->IsIntConstant()) {
725 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000726 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100727 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100728 // TODO: Implement static evaluation of long unary operations.
729 //
730 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700731 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100732 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100733 return nullptr;
734 }
735 return nullptr;
736}
737
738HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100739 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
740 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
741 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000742 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100743 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
744 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
745 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000746 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000747 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000748 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000749 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000750 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000751 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100752 }
753 return nullptr;
754}
Dave Allison20dfc792014-06-16 20:44:29 -0700755
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000756HConstant* HBinaryOperation::GetConstantRight() const {
757 if (GetRight()->IsConstant()) {
758 return GetRight()->AsConstant();
759 } else if (IsCommutative() && GetLeft()->IsConstant()) {
760 return GetLeft()->AsConstant();
761 } else {
762 return nullptr;
763 }
764}
765
766// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700767// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000768HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
769 HInstruction* most_constant_right = GetConstantRight();
770 if (most_constant_right == nullptr) {
771 return nullptr;
772 } else if (most_constant_right == GetLeft()) {
773 return GetRight();
774 } else {
775 return GetLeft();
776 }
777}
778
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700779bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
780 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100781}
782
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100783bool HInstruction::Equals(HInstruction* other) const {
784 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100785 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100786 if (!InstructionDataEquals(other)) return false;
787 if (GetType() != other->GetType()) return false;
788 if (InputCount() != other->InputCount()) return false;
789
790 for (size_t i = 0, e = InputCount(); i < e; ++i) {
791 if (InputAt(i) != other->InputAt(i)) return false;
792 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100793 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100794 return true;
795}
796
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700797std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
798#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
799 switch (rhs) {
800 FOR_EACH_INSTRUCTION(DECLARE_CASE)
801 default:
802 os << "Unknown instruction kind " << static_cast<int>(rhs);
803 break;
804 }
805#undef DECLARE_CASE
806 return os;
807}
808
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000809void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000810 next_->previous_ = previous_;
811 if (previous_ != nullptr) {
812 previous_->next_ = next_;
813 }
814 if (block_->instructions_.first_instruction_ == this) {
815 block_->instructions_.first_instruction_ = next_;
816 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000817 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000818
819 previous_ = cursor->previous_;
820 if (previous_ != nullptr) {
821 previous_->next_ = this;
822 }
823 next_ = cursor;
824 cursor->previous_ = this;
825 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000826
827 if (block_->instructions_.first_instruction_ == cursor) {
828 block_->instructions_.first_instruction_ = this;
829 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000830}
831
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000832HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
833 DCHECK(!cursor->IsControlFlow());
834 DCHECK_NE(instructions_.last_instruction_, cursor);
835 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000836
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000837 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
838 new_block->instructions_.first_instruction_ = cursor->GetNext();
839 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
840 cursor->next_->previous_ = nullptr;
841 cursor->next_ = nullptr;
842 instructions_.last_instruction_ = cursor;
843
844 new_block->instructions_.SetBlockOfInstructions(new_block);
845 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
846 HBasicBlock* successor = GetSuccessors().Get(i);
847 new_block->successors_.Add(successor);
848 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
849 }
850 successors_.Reset();
851
852 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
853 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
854 dominated->dominator_ = new_block;
855 new_block->dominated_blocks_.Add(dominated);
856 }
857 dominated_blocks_.Reset();
858 return new_block;
859}
860
David Brazdil46e2a392015-03-16 17:31:52 +0000861bool HBasicBlock::IsSingleGoto() const {
862 HLoopInformation* loop_info = GetLoopInformation();
863 // TODO: Remove the null check b/19084197.
864 return GetFirstInstruction() != nullptr
865 && GetPhis().IsEmpty()
866 && GetFirstInstruction() == GetLastInstruction()
867 && GetLastInstruction()->IsGoto()
868 // Back edges generate the suspend check.
869 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
870}
871
David Brazdil8d5b8b22015-03-24 10:51:52 +0000872bool HBasicBlock::EndsWithControlFlowInstruction() const {
873 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
874}
875
David Brazdilb2bd1c52015-03-25 11:17:37 +0000876bool HBasicBlock::EndsWithIf() const {
877 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
878}
879
880bool HBasicBlock::HasSinglePhi() const {
881 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
882}
883
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000884void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
885 for (HInstruction* current = first_instruction_;
886 current != nullptr;
887 current = current->GetNext()) {
888 current->SetBlock(block);
889 }
890}
891
892void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
893 DCHECK(Contains(cursor));
894 if (!instruction_list.IsEmpty()) {
895 if (cursor == last_instruction_) {
896 last_instruction_ = instruction_list.last_instruction_;
897 } else {
898 cursor->next_->previous_ = instruction_list.last_instruction_;
899 }
900 instruction_list.last_instruction_->next_ = cursor->next_;
901 cursor->next_ = instruction_list.first_instruction_;
902 instruction_list.first_instruction_->previous_ = cursor;
903 }
904}
905
906void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +0000907 if (IsEmpty()) {
908 first_instruction_ = instruction_list.first_instruction_;
909 last_instruction_ = instruction_list.last_instruction_;
910 } else {
911 AddAfter(last_instruction_, instruction_list);
912 }
913}
914
915void HBasicBlock::DisconnectFromAll() {
916 DCHECK(dominated_blocks_.IsEmpty()) << "Unimplemented scenario";
917
918 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
919 predecessors_.Get(i)->successors_.Delete(this);
920 }
921 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
922 successors_.Get(i)->predecessors_.Delete(this);
923 }
924 dominator_->dominated_blocks_.Delete(this);
925
926 predecessors_.Reset();
927 successors_.Reset();
928 dominator_ = nullptr;
929 graph_ = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000930}
931
932void HBasicBlock::MergeWith(HBasicBlock* other) {
933 DCHECK(successors_.IsEmpty()) << "Unimplemented block merge scenario";
David Brazdil46e2a392015-03-16 17:31:52 +0000934 DCHECK(dominated_blocks_.IsEmpty()
935 || (dominated_blocks_.Size() == 1 && dominated_blocks_.Get(0) == other))
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000936 << "Unimplemented block merge scenario";
937 DCHECK(other->GetPhis().IsEmpty());
938
939 successors_.Reset();
940 dominated_blocks_.Reset();
941 instructions_.Add(other->GetInstructions());
942 other->GetInstructions().SetBlockOfInstructions(this);
943
944 while (!other->GetSuccessors().IsEmpty()) {
945 HBasicBlock* successor = other->GetSuccessors().Get(0);
946 successor->ReplacePredecessor(other, this);
947 }
948
949 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
950 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
951 dominated_blocks_.Add(dominated);
952 dominated->SetDominator(this);
953 }
954 other->dominated_blocks_.Reset();
955 other->dominator_ = nullptr;
956 other->graph_ = nullptr;
957}
958
959void HBasicBlock::ReplaceWith(HBasicBlock* other) {
960 while (!GetPredecessors().IsEmpty()) {
961 HBasicBlock* predecessor = GetPredecessors().Get(0);
962 predecessor->ReplaceSuccessor(this, other);
963 }
964 while (!GetSuccessors().IsEmpty()) {
965 HBasicBlock* successor = GetSuccessors().Get(0);
966 successor->ReplacePredecessor(this, other);
967 }
968 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
969 other->AddDominatedBlock(dominated_blocks_.Get(i));
970 }
971 GetDominator()->ReplaceDominatedBlock(this, other);
972 other->SetDominator(GetDominator());
973 dominator_ = nullptr;
974 graph_ = nullptr;
975}
976
977// Create space in `blocks` for adding `number_of_new_blocks` entries
978// starting at location `at`. Blocks after `at` are moved accordingly.
979static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
980 size_t number_of_new_blocks,
981 size_t at) {
982 size_t old_size = blocks->Size();
983 size_t new_size = old_size + number_of_new_blocks;
984 blocks->SetSize(new_size);
985 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
986 blocks->Put(j, blocks->Get(i));
987 }
988}
989
990void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000991 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000992 // Simple case of an entry block, a body block, and an exit block.
993 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000994 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000995 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
996 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000997 DCHECK(!body->IsExitBlock());
998 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000999
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001000 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1001 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001002
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001003 // Replace the invoke with the return value of the inlined graph.
1004 if (last->IsReturn()) {
1005 invoke->ReplaceWith(last->InputAt(0));
1006 } else {
1007 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001008 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001009
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001010 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001011 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001012 // Need to inline multiple blocks. We split `invoke`'s block
1013 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001014 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001015 // with the second half.
1016 ArenaAllocator* allocator = outer_graph->GetArena();
1017 HBasicBlock* at = invoke->GetBlock();
1018 HBasicBlock* to = at->SplitAfter(invoke);
1019
1020 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1021 DCHECK(!first->IsInLoop());
1022 at->MergeWith(first);
1023 exit_block_->ReplaceWith(to);
1024
1025 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001026 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001027 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001028 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1029 if (to->GetPredecessors().Size() == 1) {
1030 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001031 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001032 if (!returns_void) {
1033 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001034 }
1035 predecessor->AddInstruction(new (allocator) HGoto());
1036 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001037 } else {
1038 if (!returns_void) {
1039 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001040 return_value = new (allocator) HPhi(
1041 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001042 to->AddPhi(return_value->AsPhi());
1043 }
1044 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1045 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1046 HInstruction* last = predecessor->GetLastInstruction();
1047 if (!returns_void) {
1048 return_value->AsPhi()->AddInput(last->InputAt(0));
1049 }
1050 predecessor->AddInstruction(new (allocator) HGoto());
1051 predecessor->RemoveInstruction(last);
1052 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001053 }
1054
1055 if (return_value != nullptr) {
1056 invoke->ReplaceWith(return_value);
1057 }
1058
1059 // Update the meta information surrounding blocks:
1060 // (1) the graph they are now in,
1061 // (2) the reverse post order of that graph,
1062 // (3) the potential loop information they are now in.
1063
1064 // We don't add the entry block, the exit block, and the first block, which
1065 // has been merged with `at`.
1066 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1067
1068 // We add the `to` block.
1069 static constexpr int kNumberOfNewBlocksInCaller = 1;
1070 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1071 + kNumberOfNewBlocksInCaller;
1072
1073 // Find the location of `at` in the outer graph's reverse post order. The new
1074 // blocks will be added after it.
1075 size_t index_of_at = 0;
1076 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1077 index_of_at++;
1078 }
1079 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1080
1081 // Do a reverse post order of the blocks in the callee and do (1), (2),
1082 // and (3) to the blocks that apply.
1083 HLoopInformation* info = at->GetLoopInformation();
1084 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1085 HBasicBlock* current = it.Current();
1086 if (current != exit_block_ && current != entry_block_ && current != first) {
1087 DCHECK(!current->IsInLoop());
1088 DCHECK(current->GetGraph() == this);
1089 current->SetGraph(outer_graph);
1090 outer_graph->AddBlock(current);
1091 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1092 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001093 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001094 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1095 loop_it.Current()->Add(current);
1096 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001097 }
1098 }
1099 }
1100
1101 // Do (1), (2), and (3) to `to`.
1102 to->SetGraph(outer_graph);
1103 outer_graph->AddBlock(to);
1104 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1105 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001106 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001107 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1108 loop_it.Current()->Add(to);
1109 }
David Brazdil46e2a392015-03-16 17:31:52 +00001110 if (info->IsBackEdge(*at)) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001111 // Only `at` can become a back edge, as the inlined blocks
1112 // are predecessors of `at`.
1113 DCHECK_EQ(1u, info->NumberOfBackEdges());
1114 info->ClearBackEdges();
1115 info->AddBackEdge(to);
1116 }
1117 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001118 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001119
David Brazdil05144f42015-04-16 15:18:00 +01001120 // Update the next instruction id of the outer graph, so that instructions
1121 // added later get bigger ids than those in the inner graph.
1122 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1123
1124 // Walk over the entry block and:
1125 // - Move constants from the entry block to the outer_graph's entry block,
1126 // - Replace HParameterValue instructions with their real value.
1127 // - Remove suspend checks, that hold an environment.
1128 // We must do this after the other blocks have been inlined, otherwise ids of
1129 // constants could overlap with the inner graph.
1130 int parameter_index = 0;
1131 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1132 HInstruction* current = it.Current();
1133 if (current->IsNullConstant()) {
1134 current->ReplaceWith(outer_graph->GetNullConstant());
1135 } else if (current->IsIntConstant()) {
1136 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1137 } else if (current->IsLongConstant()) {
1138 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
1139 } else if (current->IsFloatConstant() || current->IsDoubleConstant()) {
1140 // TODO: Don't duplicate floating-point constants.
1141 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
1142 } else if (current->IsParameterValue()) {
1143 current->ReplaceWith(invoke->InputAt(parameter_index++));
1144 } else {
1145 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1146 entry_block_->RemoveInstruction(current);
1147 }
1148 }
1149
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001150 // Finally remove the invoke from the caller.
1151 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001152}
1153
David Brazdil46e2a392015-03-16 17:31:52 +00001154void HGraph::MergeEmptyBranches(HBasicBlock* start_block, HBasicBlock* end_block) {
David Brazdilb2bd1c52015-03-25 11:17:37 +00001155 // Find the two branches of an If.
David Brazdil46e2a392015-03-16 17:31:52 +00001156 DCHECK_EQ(start_block->GetSuccessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001157 HBasicBlock* left_branch = start_block->GetSuccessors().Get(0);
1158 HBasicBlock* right_branch = start_block->GetSuccessors().Get(1);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001159
1160 // Make sure this is a diamond control-flow path.
David Brazdil46e2a392015-03-16 17:31:52 +00001161 DCHECK_EQ(left_branch->GetSuccessors().Get(0), end_block);
1162 DCHECK_EQ(right_branch->GetSuccessors().Get(0), end_block);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001163 DCHECK_EQ(end_block->GetPredecessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001164 DCHECK_EQ(start_block, end_block->GetDominator());
1165
1166 // Disconnect the branches and merge the two blocks. This will move
1167 // all instructions from 'end_block' to 'start_block'.
1168 DCHECK(left_branch->IsSingleGoto());
1169 DCHECK(right_branch->IsSingleGoto());
1170 left_branch->DisconnectFromAll();
1171 right_branch->DisconnectFromAll();
1172 start_block->RemoveInstruction(start_block->GetLastInstruction());
1173 start_block->MergeWith(end_block);
1174
1175 // Delete the now redundant blocks from the graph.
1176 blocks_.Put(left_branch->GetBlockId(), nullptr);
1177 blocks_.Put(right_branch->GetBlockId(), nullptr);
1178 blocks_.Put(end_block->GetBlockId(), nullptr);
1179
1180 // Update reverse post order.
1181 reverse_post_order_.Delete(left_branch);
1182 reverse_post_order_.Delete(right_branch);
1183 reverse_post_order_.Delete(end_block);
1184
David Brazdilb2bd1c52015-03-25 11:17:37 +00001185 // Update loops which contain the code.
1186 for (HLoopInformationOutwardIterator it(*start_block); !it.Done(); it.Advance()) {
1187 HLoopInformation* loop_info = it.Current();
1188 DCHECK(loop_info->Contains(*left_branch));
1189 DCHECK(loop_info->Contains(*right_branch));
1190 DCHECK(loop_info->Contains(*end_block));
David Brazdil46e2a392015-03-16 17:31:52 +00001191 loop_info->Remove(left_branch);
1192 loop_info->Remove(right_branch);
1193 loop_info->Remove(end_block);
1194 if (loop_info->IsBackEdge(*end_block)) {
1195 loop_info->RemoveBackEdge(end_block);
1196 loop_info->AddBackEdge(start_block);
1197 }
David Brazdil46e2a392015-03-16 17:31:52 +00001198 }
1199}
1200
Calin Juravleacf735c2015-02-12 15:25:22 +00001201std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1202 ScopedObjectAccess soa(Thread::Current());
1203 os << "["
1204 << " is_top=" << rhs.IsTop()
1205 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1206 << " is_exact=" << rhs.IsExact()
1207 << " ]";
1208 return os;
1209}
1210
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001211} // namespace art