blob: b82e37cb4e330986111f8ef5b4063dad0c378087 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000023#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000025
26namespace art {
27
28void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000029 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000030 blocks_.Add(block);
31}
32
Nicolas Geoffray804d0932014-05-02 08:46:00 +010033void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000034 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000035 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000036}
37
Roland Levillainfc600dc2014-12-02 17:16:31 +000038static void RemoveAsUser(HInstruction* instruction) {
39 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000040 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000041 }
42
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010043 for (HEnvironment* environment = instruction->GetEnvironment();
44 environment != nullptr;
45 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000046 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000047 if (environment->GetInstructionAt(i) != nullptr) {
48 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000049 }
50 }
51 }
52}
53
54void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
55 for (size_t i = 0; i < blocks_.Size(); ++i) {
56 if (!visited.IsBitSet(i)) {
57 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010058 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000059 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
60 RemoveAsUser(it.Current());
61 }
62 }
63 }
64}
65
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010067 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000068 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000069 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000071 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
72 block->GetSuccessors().Get(j)->RemovePredecessor(block);
73 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010074 // Remove the block from the list of blocks, so that further analyses
75 // never see it.
76 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010089 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
90 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
101 ArenaBitVector visited(arena_, blocks_.Size(), false);
102
103 // (1) Find the back edges in the graph doing a DFS traversal.
104 FindBackEdges(&visited);
105
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 // (2) Remove instructions and phis from blocks not visited during
107 // the initial DFS as users from other instructions, so that
108 // users can be safely removed before uses later.
109 RemoveInstructionsAsUsersFromDeadBlocks(visited);
110
111 // (3) Remove blocks not visited during the initial DFS.
112 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 // predecessors list of live blocks.
114 RemoveDeadBlocks(visited);
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100117 // dominators and the reverse post order.
118 SimplifyCFG();
119
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100120 // (5) Compute the dominance information and the reverse post order.
121 ComputeDominanceInformation();
122}
123
124void HGraph::ClearDominanceInformation() {
125 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
126 it.Current()->ClearDominanceInformation();
127 }
128 reverse_post_order_.Reset();
129}
130
131void HBasicBlock::ClearDominanceInformation() {
132 dominated_blocks_.Reset();
133 dominator_ = nullptr;
134}
135
136void HGraph::ComputeDominanceInformation() {
137 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000138 GrowableArray<size_t> visits(arena_, blocks_.Size());
139 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100140 reverse_post_order_.Add(entry_block_);
141 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
142 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 }
144}
145
146HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
147 ArenaBitVector visited(arena_, blocks_.Size(), false);
148 // Walk the dominator tree of the first block and mark the visited blocks.
149 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000150 visited.SetBit(first->GetBlockId());
151 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153 // Walk the dominator tree of the second block until a marked block is found.
154 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 return second;
157 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 }
160 LOG(ERROR) << "Could not find common dominator";
161 return nullptr;
162}
163
164void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
165 HBasicBlock* predecessor,
166 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000167 if (block->GetDominator() == nullptr) {
168 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000169 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000170 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000173 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 // Once all the forward edges have been visited, we know the immediate
175 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000176 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100178 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100179 reverse_post_order_.Add(block);
180 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
181 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000182 }
183 }
184}
185
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100187 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100188 SsaBuilder ssa_builder(this);
189 ssa_builder.BuildSsa();
190}
191
David Brazdilfc6a86a2015-06-26 10:33:45 +0000192HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000193 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
194 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000195 // Use `InsertBetween` to ensure the predecessor index and successor index of
196 // `block` and `successor` are preserved.
197 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000198 return new_block;
199}
200
201void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
202 // Insert a new node between `block` and `successor` to split the
203 // critical edge.
204 HBasicBlock* new_block = SplitEdge(block, successor);
205 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100206 if (successor->IsLoopHeader()) {
207 // If we split at a back edge boundary, make the new block the back edge.
208 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000209 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 info->RemoveBackEdge(block);
211 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100212 }
213 }
214}
215
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100216void HGraph::SimplifyLoop(HBasicBlock* header) {
217 HLoopInformation* info = header->GetLoopInformation();
218
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100219 // Make sure the loop has only one pre header. This simplifies SSA building by having
220 // to just look at the pre header to know which locals are initialized at entry of the
221 // loop.
222 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
223 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100224 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100225 AddBlock(pre_header);
226 pre_header->AddInstruction(new (arena_) HGoto());
227
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
229 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100230 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100231 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100233 }
234 }
235 pre_header->AddSuccessor(header);
236 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100237
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100238 // Make sure the first predecessor of a loop header is the incoming block.
239 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
240 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
241 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
242 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
243 if (!info->IsBackEdge(*predecessor)) {
244 header->predecessors_.Put(pred, to_swap);
245 header->predecessors_.Put(0, predecessor);
246 break;
247 }
248 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100249 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100250
251 // Place the suspend check at the beginning of the header, so that live registers
252 // will be known when allocating registers. Note that code generation can still
253 // generate the suspend check at the back edge, but needs to be careful with
254 // loop phi spill slots (which are not written to at back edge).
255 HInstruction* first_instruction = header->GetFirstInstruction();
256 if (!first_instruction->IsSuspendCheck()) {
257 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
258 header->InsertInstructionBefore(check, first_instruction);
259 first_instruction = check;
260 }
261 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100262}
263
264void HGraph::SimplifyCFG() {
265 // Simplify the CFG for future analysis, and code generation:
266 // (1): Split critical edges.
267 // (2): Simplify loops by having only one back edge, and one preheader.
268 for (size_t i = 0; i < blocks_.Size(); ++i) {
269 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100270 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100271 if (block->GetSuccessors().Size() > 1) {
272 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
273 HBasicBlock* successor = block->GetSuccessors().Get(j);
274 if (successor->GetPredecessors().Size() > 1) {
275 SplitCriticalEdge(block, successor);
276 --j;
277 }
278 }
279 }
280 if (block->IsLoopHeader()) {
281 SimplifyLoop(block);
282 }
283 }
284}
285
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000286bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100287 // Order does not matter.
288 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
289 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 if (block->IsLoopHeader()) {
291 HLoopInformation* info = block->GetLoopInformation();
292 if (!info->Populate()) {
293 // Abort if the loop is non natural. We currently bailout in such cases.
294 return false;
295 }
296 }
297 }
298 return true;
299}
300
David Brazdil8d5b8b22015-03-24 10:51:52 +0000301void HGraph::InsertConstant(HConstant* constant) {
302 // New constants are inserted before the final control-flow instruction
303 // of the graph, or at its end if called from the graph builder.
304 if (entry_block_->EndsWithControlFlowInstruction()) {
305 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000306 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000307 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000308 }
309}
310
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000311HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100312 // For simplicity, don't bother reviving the cached null constant if it is
313 // not null and not in a block. Otherwise, we need to clear the instruction
314 // id and/or any invariants the graph is assuming when adding new instructions.
315 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000316 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000317 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000318 }
319 return cached_null_constant_;
320}
321
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100322HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100323 // For simplicity, don't bother reviving the cached current method if it is
324 // not null and not in a block. Otherwise, we need to clear the instruction
325 // id and/or any invariants the graph is assuming when adding new instructions.
326 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700327 cached_current_method_ = new (arena_) HCurrentMethod(
328 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100329 if (entry_block_->GetFirstInstruction() == nullptr) {
330 entry_block_->AddInstruction(cached_current_method_);
331 } else {
332 entry_block_->InsertInstructionBefore(
333 cached_current_method_, entry_block_->GetFirstInstruction());
334 }
335 }
336 return cached_current_method_;
337}
338
David Brazdil8d5b8b22015-03-24 10:51:52 +0000339HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
340 switch (type) {
341 case Primitive::Type::kPrimBoolean:
342 DCHECK(IsUint<1>(value));
343 FALLTHROUGH_INTENDED;
344 case Primitive::Type::kPrimByte:
345 case Primitive::Type::kPrimChar:
346 case Primitive::Type::kPrimShort:
347 case Primitive::Type::kPrimInt:
348 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
349 return GetIntConstant(static_cast<int32_t>(value));
350
351 case Primitive::Type::kPrimLong:
352 return GetLongConstant(value);
353
354 default:
355 LOG(FATAL) << "Unsupported constant type";
356 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000357 }
David Brazdil46e2a392015-03-16 17:31:52 +0000358}
359
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000360void HGraph::CacheFloatConstant(HFloatConstant* constant) {
361 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
362 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
363 cached_float_constants_.Overwrite(value, constant);
364}
365
366void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
367 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
368 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
369 cached_double_constants_.Overwrite(value, constant);
370}
371
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000372void HLoopInformation::Add(HBasicBlock* block) {
373 blocks_.SetBit(block->GetBlockId());
374}
375
David Brazdil46e2a392015-03-16 17:31:52 +0000376void HLoopInformation::Remove(HBasicBlock* block) {
377 blocks_.ClearBit(block->GetBlockId());
378}
379
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100380void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
381 if (blocks_.IsBitSet(block->GetBlockId())) {
382 return;
383 }
384
385 blocks_.SetBit(block->GetBlockId());
386 block->SetInLoop(this);
387 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
388 PopulateRecursive(block->GetPredecessors().Get(i));
389 }
390}
391
392bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100393 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100394 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
395 HBasicBlock* back_edge = GetBackEdges().Get(i);
396 DCHECK(back_edge->GetDominator() != nullptr);
397 if (!header_->Dominates(back_edge)) {
398 // This loop is not natural. Do not bother going further.
399 return false;
400 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100401
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100402 // Populate this loop: starting with the back edge, recursively add predecessors
403 // that are not already part of that loop. Set the header as part of the loop
404 // to end the recursion.
405 // This is a recursive implementation of the algorithm described in
406 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
407 blocks_.SetBit(header_->GetBlockId());
408 PopulateRecursive(back_edge);
409 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100410 return true;
411}
412
David Brazdila4b8c212015-05-07 09:59:30 +0100413void HLoopInformation::Update() {
414 HGraph* graph = header_->GetGraph();
415 for (uint32_t id : blocks_.Indexes()) {
416 HBasicBlock* block = graph->GetBlocks().Get(id);
417 // Reset loop information of non-header blocks inside the loop, except
418 // members of inner nested loops because those should already have been
419 // updated by their own LoopInformation.
420 if (block->GetLoopInformation() == this && block != header_) {
421 block->SetLoopInformation(nullptr);
422 }
423 }
424 blocks_.ClearAllBits();
425
426 if (back_edges_.IsEmpty()) {
427 // The loop has been dismantled, delete its suspend check and remove info
428 // from the header.
429 DCHECK(HasSuspendCheck());
430 header_->RemoveInstruction(suspend_check_);
431 header_->SetLoopInformation(nullptr);
432 header_ = nullptr;
433 suspend_check_ = nullptr;
434 } else {
435 if (kIsDebugBuild) {
436 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
437 DCHECK(header_->Dominates(back_edges_.Get(i)));
438 }
439 }
440 // This loop still has reachable back edges. Repopulate the list of blocks.
441 bool populate_successful = Populate();
442 DCHECK(populate_successful);
443 }
444}
445
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100447 return header_->GetDominator();
448}
449
450bool HLoopInformation::Contains(const HBasicBlock& block) const {
451 return blocks_.IsBitSet(block.GetBlockId());
452}
453
454bool HLoopInformation::IsIn(const HLoopInformation& other) const {
455 return other.blocks_.IsBitSet(header_->GetBlockId());
456}
457
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100458size_t HLoopInformation::GetLifetimeEnd() const {
459 size_t last_position = 0;
460 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
461 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
462 }
463 return last_position;
464}
465
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100466bool HBasicBlock::Dominates(HBasicBlock* other) const {
467 // Walk up the dominator tree from `other`, to find out if `this`
468 // is an ancestor.
469 HBasicBlock* current = other;
470 while (current != nullptr) {
471 if (current == this) {
472 return true;
473 }
474 current = current->GetDominator();
475 }
476 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100477}
478
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100479static void UpdateInputsUsers(HInstruction* instruction) {
480 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
481 instruction->InputAt(i)->AddUseAt(instruction, i);
482 }
483 // Environment should be created later.
484 DCHECK(!instruction->HasEnvironment());
485}
486
Roland Levillainccc07a92014-09-16 14:48:16 +0100487void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
488 HInstruction* replacement) {
489 DCHECK(initial->GetBlock() == this);
490 InsertInstructionBefore(replacement, initial);
491 initial->ReplaceWith(replacement);
492 RemoveInstruction(initial);
493}
494
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100495static void Add(HInstructionList* instruction_list,
496 HBasicBlock* block,
497 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000498 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000499 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100500 instruction->SetBlock(block);
501 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100502 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100503 instruction_list->AddInstruction(instruction);
504}
505
506void HBasicBlock::AddInstruction(HInstruction* instruction) {
507 Add(&instructions_, this, instruction);
508}
509
510void HBasicBlock::AddPhi(HPhi* phi) {
511 Add(&phis_, this, phi);
512}
513
David Brazdilc3d743f2015-04-22 13:40:50 +0100514void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
515 DCHECK(!cursor->IsPhi());
516 DCHECK(!instruction->IsPhi());
517 DCHECK_EQ(instruction->GetId(), -1);
518 DCHECK_NE(cursor->GetId(), -1);
519 DCHECK_EQ(cursor->GetBlock(), this);
520 DCHECK(!instruction->IsControlFlow());
521 instruction->SetBlock(this);
522 instruction->SetId(GetGraph()->GetNextInstructionId());
523 UpdateInputsUsers(instruction);
524 instructions_.InsertInstructionBefore(instruction, cursor);
525}
526
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100527void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
528 DCHECK(!cursor->IsPhi());
529 DCHECK(!instruction->IsPhi());
530 DCHECK_EQ(instruction->GetId(), -1);
531 DCHECK_NE(cursor->GetId(), -1);
532 DCHECK_EQ(cursor->GetBlock(), this);
533 DCHECK(!instruction->IsControlFlow());
534 DCHECK(!cursor->IsControlFlow());
535 instruction->SetBlock(this);
536 instruction->SetId(GetGraph()->GetNextInstructionId());
537 UpdateInputsUsers(instruction);
538 instructions_.InsertInstructionAfter(instruction, cursor);
539}
540
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100541void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
542 DCHECK_EQ(phi->GetId(), -1);
543 DCHECK_NE(cursor->GetId(), -1);
544 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100545 phi->SetBlock(this);
546 phi->SetId(GetGraph()->GetNextInstructionId());
547 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100548 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100549}
550
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100551static void Remove(HInstructionList* instruction_list,
552 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000553 HInstruction* instruction,
554 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100555 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100556 instruction->SetBlock(nullptr);
557 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000558 if (ensure_safety) {
559 DCHECK(instruction->GetUses().IsEmpty());
560 DCHECK(instruction->GetEnvUses().IsEmpty());
561 RemoveAsUser(instruction);
562 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100563}
564
David Brazdil1abb4192015-02-17 18:33:36 +0000565void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100566 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000567 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100568}
569
David Brazdil1abb4192015-02-17 18:33:36 +0000570void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
571 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100572}
573
David Brazdilc7508e92015-04-27 13:28:57 +0100574void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
575 if (instruction->IsPhi()) {
576 RemovePhi(instruction->AsPhi(), ensure_safety);
577 } else {
578 RemoveInstruction(instruction, ensure_safety);
579 }
580}
581
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100582void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
583 for (size_t i = 0; i < locals.Size(); i++) {
584 HInstruction* instruction = locals.Get(i);
585 SetRawEnvAt(i, instruction);
586 if (instruction != nullptr) {
587 instruction->AddEnvUseAt(this, i);
588 }
589 }
590}
591
David Brazdiled596192015-01-23 10:39:45 +0000592void HEnvironment::CopyFrom(HEnvironment* env) {
593 for (size_t i = 0; i < env->Size(); i++) {
594 HInstruction* instruction = env->GetInstructionAt(i);
595 SetRawEnvAt(i, instruction);
596 if (instruction != nullptr) {
597 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100598 }
David Brazdiled596192015-01-23 10:39:45 +0000599 }
600}
601
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700602void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
603 HBasicBlock* loop_header) {
604 DCHECK(loop_header->IsLoopHeader());
605 for (size_t i = 0; i < env->Size(); i++) {
606 HInstruction* instruction = env->GetInstructionAt(i);
607 SetRawEnvAt(i, instruction);
608 if (instruction == nullptr) {
609 continue;
610 }
611 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
612 // At the end of the loop pre-header, the corresponding value for instruction
613 // is the first input of the phi.
614 HInstruction* initial = instruction->AsPhi()->InputAt(0);
615 DCHECK(initial->GetBlock()->Dominates(loop_header));
616 SetRawEnvAt(i, initial);
617 initial->AddEnvUseAt(this, i);
618 } else {
619 instruction->AddEnvUseAt(this, i);
620 }
621 }
622}
623
David Brazdil1abb4192015-02-17 18:33:36 +0000624void HEnvironment::RemoveAsUserOfInput(size_t index) const {
625 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
626 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100627}
628
Calin Juravle77520bc2015-01-12 18:45:46 +0000629HInstruction* HInstruction::GetNextDisregardingMoves() const {
630 HInstruction* next = GetNext();
631 while (next != nullptr && next->IsParallelMove()) {
632 next = next->GetNext();
633 }
634 return next;
635}
636
637HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
638 HInstruction* previous = GetPrevious();
639 while (previous != nullptr && previous->IsParallelMove()) {
640 previous = previous->GetPrevious();
641 }
642 return previous;
643}
644
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100645void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000646 if (first_instruction_ == nullptr) {
647 DCHECK(last_instruction_ == nullptr);
648 first_instruction_ = last_instruction_ = instruction;
649 } else {
650 last_instruction_->next_ = instruction;
651 instruction->previous_ = last_instruction_;
652 last_instruction_ = instruction;
653 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000654}
655
David Brazdilc3d743f2015-04-22 13:40:50 +0100656void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
657 DCHECK(Contains(cursor));
658 if (cursor == first_instruction_) {
659 cursor->previous_ = instruction;
660 instruction->next_ = cursor;
661 first_instruction_ = instruction;
662 } else {
663 instruction->previous_ = cursor->previous_;
664 instruction->next_ = cursor;
665 cursor->previous_ = instruction;
666 instruction->previous_->next_ = instruction;
667 }
668}
669
670void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
671 DCHECK(Contains(cursor));
672 if (cursor == last_instruction_) {
673 cursor->next_ = instruction;
674 instruction->previous_ = cursor;
675 last_instruction_ = instruction;
676 } else {
677 instruction->next_ = cursor->next_;
678 instruction->previous_ = cursor;
679 cursor->next_ = instruction;
680 instruction->next_->previous_ = instruction;
681 }
682}
683
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100684void HInstructionList::RemoveInstruction(HInstruction* instruction) {
685 if (instruction->previous_ != nullptr) {
686 instruction->previous_->next_ = instruction->next_;
687 }
688 if (instruction->next_ != nullptr) {
689 instruction->next_->previous_ = instruction->previous_;
690 }
691 if (instruction == first_instruction_) {
692 first_instruction_ = instruction->next_;
693 }
694 if (instruction == last_instruction_) {
695 last_instruction_ = instruction->previous_;
696 }
697}
698
Roland Levillain6b469232014-09-25 10:10:38 +0100699bool HInstructionList::Contains(HInstruction* instruction) const {
700 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
701 if (it.Current() == instruction) {
702 return true;
703 }
704 }
705 return false;
706}
707
Roland Levillainccc07a92014-09-16 14:48:16 +0100708bool HInstructionList::FoundBefore(const HInstruction* instruction1,
709 const HInstruction* instruction2) const {
710 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
711 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
712 if (it.Current() == instruction1) {
713 return true;
714 }
715 if (it.Current() == instruction2) {
716 return false;
717 }
718 }
719 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
720 return true;
721}
722
Roland Levillain6c82d402014-10-13 16:10:27 +0100723bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
724 if (other_instruction == this) {
725 // An instruction does not strictly dominate itself.
726 return false;
727 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100728 HBasicBlock* block = GetBlock();
729 HBasicBlock* other_block = other_instruction->GetBlock();
730 if (block != other_block) {
731 return GetBlock()->Dominates(other_instruction->GetBlock());
732 } else {
733 // If both instructions are in the same block, ensure this
734 // instruction comes before `other_instruction`.
735 if (IsPhi()) {
736 if (!other_instruction->IsPhi()) {
737 // Phis appear before non phi-instructions so this instruction
738 // dominates `other_instruction`.
739 return true;
740 } else {
741 // There is no order among phis.
742 LOG(FATAL) << "There is no dominance between phis of a same block.";
743 return false;
744 }
745 } else {
746 // `this` is not a phi.
747 if (other_instruction->IsPhi()) {
748 // Phis appear before non phi-instructions so this instruction
749 // does not dominate `other_instruction`.
750 return false;
751 } else {
752 // Check whether this instruction comes before
753 // `other_instruction` in the instruction list.
754 return block->GetInstructions().FoundBefore(this, other_instruction);
755 }
756 }
757 }
758}
759
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100760void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100761 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000762 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
763 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100764 HInstruction* user = current->GetUser();
765 size_t input_index = current->GetIndex();
766 user->SetRawInputAt(input_index, other);
767 other->AddUseAt(user, input_index);
768 }
769
David Brazdiled596192015-01-23 10:39:45 +0000770 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
771 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100772 HEnvironment* user = current->GetUser();
773 size_t input_index = current->GetIndex();
774 user->SetRawEnvAt(input_index, other);
775 other->AddEnvUseAt(user, input_index);
776 }
777
David Brazdiled596192015-01-23 10:39:45 +0000778 uses_.Clear();
779 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100780}
781
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100782void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000783 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100784 SetRawInputAt(index, replacement);
785 replacement->AddUseAt(this, index);
786}
787
Nicolas Geoffray39468442014-09-02 15:17:15 +0100788size_t HInstruction::EnvironmentSize() const {
789 return HasEnvironment() ? environment_->Size() : 0;
790}
791
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100792void HPhi::AddInput(HInstruction* input) {
793 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000794 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100795 input->AddUseAt(this, inputs_.Size() - 1);
796}
797
David Brazdil2d7352b2015-04-20 14:52:42 +0100798void HPhi::RemoveInputAt(size_t index) {
799 RemoveAsUserOfInput(index);
800 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100801 for (size_t i = index, e = InputCount(); i < e; ++i) {
802 InputRecordAt(i).GetUseNode()->SetIndex(i);
803 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100804}
805
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100806#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000807void H##name::Accept(HGraphVisitor* visitor) { \
808 visitor->Visit##name(this); \
809}
810
811FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
812
813#undef DEFINE_ACCEPT
814
815void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100816 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
817 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000818 HBasicBlock* block = blocks.Get(i);
819 if (block != nullptr) {
820 VisitBasicBlock(block);
821 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000822 }
823}
824
Roland Levillain633021e2014-10-01 14:12:25 +0100825void HGraphVisitor::VisitReversePostOrder() {
826 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
827 VisitBasicBlock(it.Current());
828 }
829}
830
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000831void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100832 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100833 it.Current()->Accept(this);
834 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100835 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000836 it.Current()->Accept(this);
837 }
838}
839
Mark Mendelle82549b2015-05-06 10:55:34 -0400840HConstant* HTypeConversion::TryStaticEvaluation() const {
841 HGraph* graph = GetBlock()->GetGraph();
842 if (GetInput()->IsIntConstant()) {
843 int32_t value = GetInput()->AsIntConstant()->GetValue();
844 switch (GetResultType()) {
845 case Primitive::kPrimLong:
846 return graph->GetLongConstant(static_cast<int64_t>(value));
847 case Primitive::kPrimFloat:
848 return graph->GetFloatConstant(static_cast<float>(value));
849 case Primitive::kPrimDouble:
850 return graph->GetDoubleConstant(static_cast<double>(value));
851 default:
852 return nullptr;
853 }
854 } else if (GetInput()->IsLongConstant()) {
855 int64_t value = GetInput()->AsLongConstant()->GetValue();
856 switch (GetResultType()) {
857 case Primitive::kPrimInt:
858 return graph->GetIntConstant(static_cast<int32_t>(value));
859 case Primitive::kPrimFloat:
860 return graph->GetFloatConstant(static_cast<float>(value));
861 case Primitive::kPrimDouble:
862 return graph->GetDoubleConstant(static_cast<double>(value));
863 default:
864 return nullptr;
865 }
866 } else if (GetInput()->IsFloatConstant()) {
867 float value = GetInput()->AsFloatConstant()->GetValue();
868 switch (GetResultType()) {
869 case Primitive::kPrimInt:
870 if (std::isnan(value))
871 return graph->GetIntConstant(0);
872 if (value >= kPrimIntMax)
873 return graph->GetIntConstant(kPrimIntMax);
874 if (value <= kPrimIntMin)
875 return graph->GetIntConstant(kPrimIntMin);
876 return graph->GetIntConstant(static_cast<int32_t>(value));
877 case Primitive::kPrimLong:
878 if (std::isnan(value))
879 return graph->GetLongConstant(0);
880 if (value >= kPrimLongMax)
881 return graph->GetLongConstant(kPrimLongMax);
882 if (value <= kPrimLongMin)
883 return graph->GetLongConstant(kPrimLongMin);
884 return graph->GetLongConstant(static_cast<int64_t>(value));
885 case Primitive::kPrimDouble:
886 return graph->GetDoubleConstant(static_cast<double>(value));
887 default:
888 return nullptr;
889 }
890 } else if (GetInput()->IsDoubleConstant()) {
891 double value = GetInput()->AsDoubleConstant()->GetValue();
892 switch (GetResultType()) {
893 case Primitive::kPrimInt:
894 if (std::isnan(value))
895 return graph->GetIntConstant(0);
896 if (value >= kPrimIntMax)
897 return graph->GetIntConstant(kPrimIntMax);
898 if (value <= kPrimLongMin)
899 return graph->GetIntConstant(kPrimIntMin);
900 return graph->GetIntConstant(static_cast<int32_t>(value));
901 case Primitive::kPrimLong:
902 if (std::isnan(value))
903 return graph->GetLongConstant(0);
904 if (value >= kPrimLongMax)
905 return graph->GetLongConstant(kPrimLongMax);
906 if (value <= kPrimLongMin)
907 return graph->GetLongConstant(kPrimLongMin);
908 return graph->GetLongConstant(static_cast<int64_t>(value));
909 case Primitive::kPrimFloat:
910 return graph->GetFloatConstant(static_cast<float>(value));
911 default:
912 return nullptr;
913 }
914 }
915 return nullptr;
916}
917
Roland Levillain9240d6a2014-10-20 16:47:04 +0100918HConstant* HUnaryOperation::TryStaticEvaluation() const {
919 if (GetInput()->IsIntConstant()) {
920 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000921 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100922 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100923 // TODO: Implement static evaluation of long unary operations.
924 //
925 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700926 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100927 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100928 return nullptr;
929 }
930 return nullptr;
931}
932
933HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100934 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
935 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
936 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000937 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100938 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
939 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
940 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000941 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000942 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000943 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000944 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000945 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000946 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100947 }
948 return nullptr;
949}
Dave Allison20dfc792014-06-16 20:44:29 -0700950
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000951HConstant* HBinaryOperation::GetConstantRight() const {
952 if (GetRight()->IsConstant()) {
953 return GetRight()->AsConstant();
954 } else if (IsCommutative() && GetLeft()->IsConstant()) {
955 return GetLeft()->AsConstant();
956 } else {
957 return nullptr;
958 }
959}
960
961// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700962// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000963HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
964 HInstruction* most_constant_right = GetConstantRight();
965 if (most_constant_right == nullptr) {
966 return nullptr;
967 } else if (most_constant_right == GetLeft()) {
968 return GetRight();
969 } else {
970 return GetLeft();
971 }
972}
973
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700974bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
975 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100976}
977
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100978bool HInstruction::Equals(HInstruction* other) const {
979 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100980 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100981 if (!InstructionDataEquals(other)) return false;
982 if (GetType() != other->GetType()) return false;
983 if (InputCount() != other->InputCount()) return false;
984
985 for (size_t i = 0, e = InputCount(); i < e; ++i) {
986 if (InputAt(i) != other->InputAt(i)) return false;
987 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100988 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100989 return true;
990}
991
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700992std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
993#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
994 switch (rhs) {
995 FOR_EACH_INSTRUCTION(DECLARE_CASE)
996 default:
997 os << "Unknown instruction kind " << static_cast<int>(rhs);
998 break;
999 }
1000#undef DECLARE_CASE
1001 return os;
1002}
1003
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001004void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001005 next_->previous_ = previous_;
1006 if (previous_ != nullptr) {
1007 previous_->next_ = next_;
1008 }
1009 if (block_->instructions_.first_instruction_ == this) {
1010 block_->instructions_.first_instruction_ = next_;
1011 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001012 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001013
1014 previous_ = cursor->previous_;
1015 if (previous_ != nullptr) {
1016 previous_->next_ = this;
1017 }
1018 next_ = cursor;
1019 cursor->previous_ = this;
1020 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001021
1022 if (block_->instructions_.first_instruction_ == cursor) {
1023 block_->instructions_.first_instruction_ = this;
1024 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001025}
1026
David Brazdilfc6a86a2015-06-26 10:33:45 +00001027HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1028 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1029 DCHECK_EQ(cursor->GetBlock(), this);
1030
1031 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1032 new_block->instructions_.first_instruction_ = cursor;
1033 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1034 instructions_.last_instruction_ = cursor->previous_;
1035 if (cursor->previous_ == nullptr) {
1036 instructions_.first_instruction_ = nullptr;
1037 } else {
1038 cursor->previous_->next_ = nullptr;
1039 cursor->previous_ = nullptr;
1040 }
1041
1042 new_block->instructions_.SetBlockOfInstructions(new_block);
1043 AddInstruction(new (GetGraph()->GetArena()) HGoto());
1044
1045 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1046 HBasicBlock* successor = GetSuccessors().Get(i);
1047 new_block->successors_.Add(successor);
1048 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1049 }
1050 successors_.Reset();
1051 AddSuccessor(new_block);
1052
David Brazdil56e1acc2015-06-30 15:41:36 +01001053 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001054 return new_block;
1055}
1056
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001057HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1058 DCHECK(!cursor->IsControlFlow());
1059 DCHECK_NE(instructions_.last_instruction_, cursor);
1060 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001061
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001062 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1063 new_block->instructions_.first_instruction_ = cursor->GetNext();
1064 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1065 cursor->next_->previous_ = nullptr;
1066 cursor->next_ = nullptr;
1067 instructions_.last_instruction_ = cursor;
1068
1069 new_block->instructions_.SetBlockOfInstructions(new_block);
1070 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1071 HBasicBlock* successor = GetSuccessors().Get(i);
1072 new_block->successors_.Add(successor);
1073 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1074 }
1075 successors_.Reset();
1076
1077 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1078 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1079 dominated->dominator_ = new_block;
1080 new_block->dominated_blocks_.Add(dominated);
1081 }
1082 dominated_blocks_.Reset();
1083 return new_block;
1084}
1085
David Brazdilfc6a86a2015-06-26 10:33:45 +00001086bool HBasicBlock::IsExceptionalSuccessor(size_t idx) const {
1087 return !GetInstructions().IsEmpty()
1088 && GetLastInstruction()->IsTryBoundary()
1089 && GetLastInstruction()->AsTryBoundary()->IsExceptionalSuccessor(idx);
1090}
1091
1092static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1093 return block.GetPhis().IsEmpty()
1094 && !block.GetInstructions().IsEmpty()
1095 && block.GetFirstInstruction() == block.GetLastInstruction();
1096}
1097
David Brazdil46e2a392015-03-16 17:31:52 +00001098bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001099 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1100}
1101
1102bool HBasicBlock::IsSingleTryBoundary() const {
1103 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001104}
1105
David Brazdil8d5b8b22015-03-24 10:51:52 +00001106bool HBasicBlock::EndsWithControlFlowInstruction() const {
1107 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1108}
1109
David Brazdilb2bd1c52015-03-25 11:17:37 +00001110bool HBasicBlock::EndsWithIf() const {
1111 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1112}
1113
1114bool HBasicBlock::HasSinglePhi() const {
1115 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1116}
1117
David Brazdil2d7352b2015-04-20 14:52:42 +01001118size_t HInstructionList::CountSize() const {
1119 size_t size = 0;
1120 HInstruction* current = first_instruction_;
1121 for (; current != nullptr; current = current->GetNext()) {
1122 size++;
1123 }
1124 return size;
1125}
1126
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001127void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1128 for (HInstruction* current = first_instruction_;
1129 current != nullptr;
1130 current = current->GetNext()) {
1131 current->SetBlock(block);
1132 }
1133}
1134
1135void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1136 DCHECK(Contains(cursor));
1137 if (!instruction_list.IsEmpty()) {
1138 if (cursor == last_instruction_) {
1139 last_instruction_ = instruction_list.last_instruction_;
1140 } else {
1141 cursor->next_->previous_ = instruction_list.last_instruction_;
1142 }
1143 instruction_list.last_instruction_->next_ = cursor->next_;
1144 cursor->next_ = instruction_list.first_instruction_;
1145 instruction_list.first_instruction_->previous_ = cursor;
1146 }
1147}
1148
1149void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001150 if (IsEmpty()) {
1151 first_instruction_ = instruction_list.first_instruction_;
1152 last_instruction_ = instruction_list.last_instruction_;
1153 } else {
1154 AddAfter(last_instruction_, instruction_list);
1155 }
1156}
1157
David Brazdil2d7352b2015-04-20 14:52:42 +01001158void HBasicBlock::DisconnectAndDelete() {
1159 // Dominators must be removed after all the blocks they dominate. This way
1160 // a loop header is removed last, a requirement for correct loop information
1161 // iteration.
1162 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001163
David Brazdil2d7352b2015-04-20 14:52:42 +01001164 // Remove the block from all loops it is included in.
1165 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1166 HLoopInformation* loop_info = it.Current();
1167 loop_info->Remove(this);
1168 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001169 // If this was the last back edge of the loop, we deliberately leave the
1170 // loop in an inconsistent state and will fail SSAChecker unless the
1171 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001172 loop_info->RemoveBackEdge(this);
1173 }
1174 }
1175
1176 // Disconnect the block from its predecessors and update their control-flow
1177 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001178 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001179 HBasicBlock* predecessor = predecessors_.Get(i);
1180 HInstruction* last_instruction = predecessor->GetLastInstruction();
1181 predecessor->RemoveInstruction(last_instruction);
1182 predecessor->RemoveSuccessor(this);
1183 if (predecessor->GetSuccessors().Size() == 1u) {
1184 DCHECK(last_instruction->IsIf());
1185 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1186 } else {
1187 // The predecessor has no remaining successors and therefore must be dead.
1188 // We deliberately leave it without a control-flow instruction so that the
1189 // SSAChecker fails unless it is not removed during the pass too.
1190 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1191 }
David Brazdil46e2a392015-03-16 17:31:52 +00001192 }
David Brazdil46e2a392015-03-16 17:31:52 +00001193 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001194
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001195 // Disconnect the block from its successors and update their phis.
David Brazdil2d7352b2015-04-20 14:52:42 +01001196 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1197 HBasicBlock* successor = successors_.Get(i);
1198 // Delete this block from the list of predecessors.
1199 size_t this_index = successor->GetPredecessorIndexOf(this);
1200 successor->predecessors_.DeleteAt(this_index);
1201
1202 // Check that `successor` has other predecessors, otherwise `this` is the
1203 // dominator of `successor` which violates the order DCHECKed at the top.
1204 DCHECK(!successor->predecessors_.IsEmpty());
1205
David Brazdil2d7352b2015-04-20 14:52:42 +01001206 // Remove this block's entries in the successor's phis.
1207 if (successor->predecessors_.Size() == 1u) {
1208 // The successor has just one predecessor left. Replace phis with the only
1209 // remaining input.
1210 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1211 HPhi* phi = phi_it.Current()->AsPhi();
1212 phi->ReplaceWith(phi->InputAt(1 - this_index));
1213 successor->RemovePhi(phi);
1214 }
1215 } else {
1216 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1217 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1218 }
1219 }
1220 }
David Brazdil46e2a392015-03-16 17:31:52 +00001221 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001222
1223 // Disconnect from the dominator.
1224 dominator_->RemoveDominatedBlock(this);
1225 SetDominator(nullptr);
1226
1227 // Delete from the graph. The function safely deletes remaining instructions
1228 // and updates the reverse post order.
1229 graph_->DeleteDeadBlock(this);
1230 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001231}
1232
1233void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001234 DCHECK_EQ(GetGraph(), other->GetGraph());
1235 DCHECK(GetDominatedBlocks().Contains(other));
1236 DCHECK_EQ(GetSuccessors().Size(), 1u);
1237 DCHECK_EQ(GetSuccessors().Get(0), other);
1238 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1239 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001240 DCHECK(other->GetPhis().IsEmpty());
1241
David Brazdil2d7352b2015-04-20 14:52:42 +01001242 // Move instructions from `other` to `this`.
1243 DCHECK(EndsWithControlFlowInstruction());
1244 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001245 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001246 other->instructions_.SetBlockOfInstructions(this);
1247 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001248
David Brazdil2d7352b2015-04-20 14:52:42 +01001249 // Remove `other` from the loops it is included in.
1250 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1251 HLoopInformation* loop_info = it.Current();
1252 loop_info->Remove(other);
1253 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001254 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001255 }
1256 }
1257
1258 // Update links to the successors of `other`.
1259 successors_.Reset();
1260 while (!other->successors_.IsEmpty()) {
1261 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001262 successor->ReplacePredecessor(other, this);
1263 }
1264
David Brazdil2d7352b2015-04-20 14:52:42 +01001265 // Update the dominator tree.
1266 dominated_blocks_.Delete(other);
1267 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1268 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1269 dominated_blocks_.Add(dominated);
1270 dominated->SetDominator(this);
1271 }
1272 other->dominated_blocks_.Reset();
1273 other->dominator_ = nullptr;
1274
1275 // Clear the list of predecessors of `other` in preparation of deleting it.
1276 other->predecessors_.Reset();
1277
1278 // Delete `other` from the graph. The function updates reverse post order.
1279 graph_->DeleteDeadBlock(other);
1280 other->SetGraph(nullptr);
1281}
1282
1283void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1284 DCHECK_NE(GetGraph(), other->GetGraph());
1285 DCHECK(GetDominatedBlocks().IsEmpty());
1286 DCHECK(GetSuccessors().IsEmpty());
1287 DCHECK(!EndsWithControlFlowInstruction());
1288 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1289 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1290 DCHECK(other->GetPhis().IsEmpty());
1291 DCHECK(!other->IsInLoop());
1292
1293 // Move instructions from `other` to `this`.
1294 instructions_.Add(other->GetInstructions());
1295 other->instructions_.SetBlockOfInstructions(this);
1296
1297 // Update links to the successors of `other`.
1298 successors_.Reset();
1299 while (!other->successors_.IsEmpty()) {
1300 HBasicBlock* successor = other->successors_.Get(0);
1301 successor->ReplacePredecessor(other, this);
1302 }
1303
1304 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001305 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1306 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1307 dominated_blocks_.Add(dominated);
1308 dominated->SetDominator(this);
1309 }
1310 other->dominated_blocks_.Reset();
1311 other->dominator_ = nullptr;
1312 other->graph_ = nullptr;
1313}
1314
1315void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1316 while (!GetPredecessors().IsEmpty()) {
1317 HBasicBlock* predecessor = GetPredecessors().Get(0);
1318 predecessor->ReplaceSuccessor(this, other);
1319 }
1320 while (!GetSuccessors().IsEmpty()) {
1321 HBasicBlock* successor = GetSuccessors().Get(0);
1322 successor->ReplacePredecessor(this, other);
1323 }
1324 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1325 other->AddDominatedBlock(dominated_blocks_.Get(i));
1326 }
1327 GetDominator()->ReplaceDominatedBlock(this, other);
1328 other->SetDominator(GetDominator());
1329 dominator_ = nullptr;
1330 graph_ = nullptr;
1331}
1332
1333// Create space in `blocks` for adding `number_of_new_blocks` entries
1334// starting at location `at`. Blocks after `at` are moved accordingly.
1335static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1336 size_t number_of_new_blocks,
1337 size_t at) {
1338 size_t old_size = blocks->Size();
1339 size_t new_size = old_size + number_of_new_blocks;
1340 blocks->SetSize(new_size);
1341 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1342 blocks->Put(j, blocks->Get(i));
1343 }
1344}
1345
David Brazdil2d7352b2015-04-20 14:52:42 +01001346void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1347 DCHECK_EQ(block->GetGraph(), this);
1348 DCHECK(block->GetSuccessors().IsEmpty());
1349 DCHECK(block->GetPredecessors().IsEmpty());
1350 DCHECK(block->GetDominatedBlocks().IsEmpty());
1351 DCHECK(block->GetDominator() == nullptr);
1352
1353 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1354 block->RemoveInstruction(it.Current());
1355 }
1356 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1357 block->RemovePhi(it.Current()->AsPhi());
1358 }
1359
David Brazdilc7af85d2015-05-26 12:05:55 +01001360 if (block->IsExitBlock()) {
1361 exit_block_ = nullptr;
1362 }
1363
David Brazdil2d7352b2015-04-20 14:52:42 +01001364 reverse_post_order_.Delete(block);
1365 blocks_.Put(block->GetBlockId(), nullptr);
1366}
1367
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001368void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001369 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001370 // Update the environments in this graph to have the invoke's environment
1371 // as parent.
1372 {
1373 HReversePostOrderIterator it(*this);
1374 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1375 for (; !it.Done(); it.Advance()) {
1376 HBasicBlock* block = it.Current();
1377 for (HInstructionIterator instr_it(block->GetInstructions());
1378 !instr_it.Done();
1379 instr_it.Advance()) {
1380 HInstruction* current = instr_it.Current();
1381 if (current->NeedsEnvironment()) {
1382 current->GetEnvironment()->SetAndCopyParentChain(
1383 outer_graph->GetArena(), invoke->GetEnvironment());
1384 }
1385 }
1386 }
1387 }
1388 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1389 if (HasBoundsChecks()) {
1390 outer_graph->SetHasBoundsChecks(true);
1391 }
1392
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001393 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001394 // Simple case of an entry block, a body block, and an exit block.
1395 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001396 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001397 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1398 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001399 DCHECK(!body->IsExitBlock());
1400 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001401
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001402 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1403 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001404
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 // Replace the invoke with the return value of the inlined graph.
1406 if (last->IsReturn()) {
1407 invoke->ReplaceWith(last->InputAt(0));
1408 } else {
1409 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001410 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001411
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001412 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001413 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001414 // Need to inline multiple blocks. We split `invoke`'s block
1415 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001416 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001417 // with the second half.
1418 ArenaAllocator* allocator = outer_graph->GetArena();
1419 HBasicBlock* at = invoke->GetBlock();
1420 HBasicBlock* to = at->SplitAfter(invoke);
1421
1422 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1423 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001424 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001425 exit_block_->ReplaceWith(to);
1426
1427 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001428 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001429 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001430 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1431 if (to->GetPredecessors().Size() == 1) {
1432 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001433 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001434 if (!returns_void) {
1435 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 }
1437 predecessor->AddInstruction(new (allocator) HGoto());
1438 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001439 } else {
1440 if (!returns_void) {
1441 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001442 return_value = new (allocator) HPhi(
1443 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001444 to->AddPhi(return_value->AsPhi());
1445 }
1446 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1447 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1448 HInstruction* last = predecessor->GetLastInstruction();
1449 if (!returns_void) {
1450 return_value->AsPhi()->AddInput(last->InputAt(0));
1451 }
1452 predecessor->AddInstruction(new (allocator) HGoto());
1453 predecessor->RemoveInstruction(last);
1454 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001455 }
1456
1457 if (return_value != nullptr) {
1458 invoke->ReplaceWith(return_value);
1459 }
1460
1461 // Update the meta information surrounding blocks:
1462 // (1) the graph they are now in,
1463 // (2) the reverse post order of that graph,
1464 // (3) the potential loop information they are now in.
1465
1466 // We don't add the entry block, the exit block, and the first block, which
1467 // has been merged with `at`.
1468 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1469
1470 // We add the `to` block.
1471 static constexpr int kNumberOfNewBlocksInCaller = 1;
1472 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1473 + kNumberOfNewBlocksInCaller;
1474
1475 // Find the location of `at` in the outer graph's reverse post order. The new
1476 // blocks will be added after it.
1477 size_t index_of_at = 0;
1478 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1479 index_of_at++;
1480 }
1481 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1482
1483 // Do a reverse post order of the blocks in the callee and do (1), (2),
1484 // and (3) to the blocks that apply.
1485 HLoopInformation* info = at->GetLoopInformation();
1486 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1487 HBasicBlock* current = it.Current();
1488 if (current != exit_block_ && current != entry_block_ && current != first) {
1489 DCHECK(!current->IsInLoop());
1490 DCHECK(current->GetGraph() == this);
1491 current->SetGraph(outer_graph);
1492 outer_graph->AddBlock(current);
1493 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1494 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001495 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001496 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1497 loop_it.Current()->Add(current);
1498 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001499 }
1500 }
1501 }
1502
1503 // Do (1), (2), and (3) to `to`.
1504 to->SetGraph(outer_graph);
1505 outer_graph->AddBlock(to);
1506 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1507 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001508 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001509 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1510 loop_it.Current()->Add(to);
1511 }
David Brazdil46e2a392015-03-16 17:31:52 +00001512 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001513 // Only `to` can become a back edge, as the inlined blocks
1514 // are predecessors of `to`.
1515 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001516 }
1517 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001519
David Brazdil05144f42015-04-16 15:18:00 +01001520 // Update the next instruction id of the outer graph, so that instructions
1521 // added later get bigger ids than those in the inner graph.
1522 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1523
1524 // Walk over the entry block and:
1525 // - Move constants from the entry block to the outer_graph's entry block,
1526 // - Replace HParameterValue instructions with their real value.
1527 // - Remove suspend checks, that hold an environment.
1528 // We must do this after the other blocks have been inlined, otherwise ids of
1529 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001530 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001531 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1532 HInstruction* current = it.Current();
1533 if (current->IsNullConstant()) {
1534 current->ReplaceWith(outer_graph->GetNullConstant());
1535 } else if (current->IsIntConstant()) {
1536 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1537 } else if (current->IsLongConstant()) {
1538 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001539 } else if (current->IsFloatConstant()) {
1540 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1541 } else if (current->IsDoubleConstant()) {
1542 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001543 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001544 if (kIsDebugBuild
1545 && invoke->IsInvokeStaticOrDirect()
1546 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1547 // Ensure we do not use the last input of `invoke`, as it
1548 // contains a clinit check which is not an actual argument.
1549 size_t last_input_index = invoke->InputCount() - 1;
1550 DCHECK(parameter_index != last_input_index);
1551 }
David Brazdil05144f42015-04-16 15:18:00 +01001552 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001553 } else if (current->IsCurrentMethod()) {
1554 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001555 } else {
1556 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1557 entry_block_->RemoveInstruction(current);
1558 }
1559 }
1560
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001561 // Finally remove the invoke from the caller.
1562 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001563}
1564
Mingyao Yang3584bce2015-05-19 16:01:59 -07001565/*
1566 * Loop will be transformed to:
1567 * old_pre_header
1568 * |
1569 * if_block
1570 * / \
1571 * dummy_block deopt_block
1572 * \ /
1573 * new_pre_header
1574 * |
1575 * header
1576 */
1577void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1578 DCHECK(header->IsLoopHeader());
1579 HBasicBlock* pre_header = header->GetDominator();
1580
1581 // Need this to avoid critical edge.
1582 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1583 // Need this to avoid critical edge.
1584 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1585 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1586 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1587 AddBlock(if_block);
1588 AddBlock(dummy_block);
1589 AddBlock(deopt_block);
1590 AddBlock(new_pre_header);
1591
1592 header->ReplacePredecessor(pre_header, new_pre_header);
1593 pre_header->successors_.Reset();
1594 pre_header->dominated_blocks_.Reset();
1595
1596 pre_header->AddSuccessor(if_block);
1597 if_block->AddSuccessor(dummy_block); // True successor
1598 if_block->AddSuccessor(deopt_block); // False successor
1599 dummy_block->AddSuccessor(new_pre_header);
1600 deopt_block->AddSuccessor(new_pre_header);
1601
1602 pre_header->dominated_blocks_.Add(if_block);
1603 if_block->SetDominator(pre_header);
1604 if_block->dominated_blocks_.Add(dummy_block);
1605 dummy_block->SetDominator(if_block);
1606 if_block->dominated_blocks_.Add(deopt_block);
1607 deopt_block->SetDominator(if_block);
1608 if_block->dominated_blocks_.Add(new_pre_header);
1609 new_pre_header->SetDominator(if_block);
1610 new_pre_header->dominated_blocks_.Add(header);
1611 header->SetDominator(new_pre_header);
1612
1613 size_t index_of_header = 0;
1614 while (reverse_post_order_.Get(index_of_header) != header) {
1615 index_of_header++;
1616 }
1617 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1618 reverse_post_order_.Put(index_of_header++, if_block);
1619 reverse_post_order_.Put(index_of_header++, dummy_block);
1620 reverse_post_order_.Put(index_of_header++, deopt_block);
1621 reverse_post_order_.Put(index_of_header++, new_pre_header);
1622
1623 HLoopInformation* info = pre_header->GetLoopInformation();
1624 if (info != nullptr) {
1625 if_block->SetLoopInformation(info);
1626 dummy_block->SetLoopInformation(info);
1627 deopt_block->SetLoopInformation(info);
1628 new_pre_header->SetLoopInformation(info);
1629 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1630 !loop_it.Done();
1631 loop_it.Advance()) {
1632 loop_it.Current()->Add(if_block);
1633 loop_it.Current()->Add(dummy_block);
1634 loop_it.Current()->Add(deopt_block);
1635 loop_it.Current()->Add(new_pre_header);
1636 }
1637 }
1638}
1639
Calin Juravleacf735c2015-02-12 15:25:22 +00001640std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1641 ScopedObjectAccess soa(Thread::Current());
1642 os << "["
1643 << " is_top=" << rhs.IsTop()
1644 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1645 << " is_exact=" << rhs.IsExact()
1646 << " ]";
1647 return os;
1648}
1649
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001650} // namespace art