blob: cd91d2c87b7c52bb75414c4b73e420b66edcbbe7 [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
Roland Levillainfc600dc2014-12-02 17:16:31 +0000120 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000121 // the successors of a block only when all its forward branches
122 // have been processed.
123 GrowableArray<size_t> visits(arena_, blocks_.Size());
124 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100125 reverse_post_order_.Add(entry_block_);
126 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
127 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000128 }
129}
130
131HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
132 ArenaBitVector visited(arena_, blocks_.Size(), false);
133 // Walk the dominator tree of the first block and mark the visited blocks.
134 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000135 visited.SetBit(first->GetBlockId());
136 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 }
138 // Walk the dominator tree of the second block until a marked block is found.
139 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000140 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 return second;
142 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000143 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 }
145 LOG(ERROR) << "Could not find common dominator";
146 return nullptr;
147}
148
149void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
150 HBasicBlock* predecessor,
151 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000152 if (block->GetDominator() == nullptr) {
153 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000154 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // Once all the forward edges have been visited, we know the immediate
160 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000161 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100163 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100164 reverse_post_order_.Add(block);
165 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
166 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000167 }
168 }
169}
170
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000171void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100172 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100173 SsaBuilder ssa_builder(this);
174 ssa_builder.BuildSsa();
175}
176
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
178 // Insert a new node between `block` and `successor` to split the
179 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100181 AddBlock(new_block);
182 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100183 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 new_block->AddSuccessor(successor);
185 if (successor->IsLoopHeader()) {
186 // If we split at a back edge boundary, make the new block the back edge.
187 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000188 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100189 info->RemoveBackEdge(block);
190 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100191 }
192 }
193}
194
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100195void HGraph::SimplifyLoop(HBasicBlock* header) {
196 HLoopInformation* info = header->GetLoopInformation();
197
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100198 // Make sure the loop has only one pre header. This simplifies SSA building by having
199 // to just look at the pre header to know which locals are initialized at entry of the
200 // loop.
201 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
202 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100203 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100204 AddBlock(pre_header);
205 pre_header->AddInstruction(new (arena_) HGoto());
206
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100207 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
208 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100209 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100210 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100212 }
213 }
214 pre_header->AddSuccessor(header);
215 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100216
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100217 // Make sure the first predecessor of a loop header is the incoming block.
218 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
219 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
220 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
221 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
222 if (!info->IsBackEdge(*predecessor)) {
223 header->predecessors_.Put(pred, to_swap);
224 header->predecessors_.Put(0, predecessor);
225 break;
226 }
227 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100228 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100229
230 // Place the suspend check at the beginning of the header, so that live registers
231 // will be known when allocating registers. Note that code generation can still
232 // generate the suspend check at the back edge, but needs to be careful with
233 // loop phi spill slots (which are not written to at back edge).
234 HInstruction* first_instruction = header->GetFirstInstruction();
235 if (!first_instruction->IsSuspendCheck()) {
236 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
237 header->InsertInstructionBefore(check, first_instruction);
238 first_instruction = check;
239 }
240 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100241}
242
243void HGraph::SimplifyCFG() {
244 // Simplify the CFG for future analysis, and code generation:
245 // (1): Split critical edges.
246 // (2): Simplify loops by having only one back edge, and one preheader.
247 for (size_t i = 0; i < blocks_.Size(); ++i) {
248 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100249 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100250 if (block->GetSuccessors().Size() > 1) {
251 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
252 HBasicBlock* successor = block->GetSuccessors().Get(j);
253 if (successor->GetPredecessors().Size() > 1) {
254 SplitCriticalEdge(block, successor);
255 --j;
256 }
257 }
258 }
259 if (block->IsLoopHeader()) {
260 SimplifyLoop(block);
261 }
262 }
263}
264
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000265bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100266 // Order does not matter.
267 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
268 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100269 if (block->IsLoopHeader()) {
270 HLoopInformation* info = block->GetLoopInformation();
271 if (!info->Populate()) {
272 // Abort if the loop is non natural. We currently bailout in such cases.
273 return false;
274 }
275 }
276 }
277 return true;
278}
279
David Brazdil8d5b8b22015-03-24 10:51:52 +0000280void HGraph::InsertConstant(HConstant* constant) {
281 // New constants are inserted before the final control-flow instruction
282 // of the graph, or at its end if called from the graph builder.
283 if (entry_block_->EndsWithControlFlowInstruction()) {
284 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000285 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000286 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000287 }
288}
289
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000290HNullConstant* HGraph::GetNullConstant() {
291 if (cached_null_constant_ == nullptr) {
292 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000293 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000294 }
295 return cached_null_constant_;
296}
297
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100298HCurrentMethod* HGraph::GetCurrentMethod() {
299 if (cached_current_method_ == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700300 cached_current_method_ = new (arena_) HCurrentMethod(
301 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100302 if (entry_block_->GetFirstInstruction() == nullptr) {
303 entry_block_->AddInstruction(cached_current_method_);
304 } else {
305 entry_block_->InsertInstructionBefore(
306 cached_current_method_, entry_block_->GetFirstInstruction());
307 }
308 }
309 return cached_current_method_;
310}
311
David Brazdil8d5b8b22015-03-24 10:51:52 +0000312HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
313 switch (type) {
314 case Primitive::Type::kPrimBoolean:
315 DCHECK(IsUint<1>(value));
316 FALLTHROUGH_INTENDED;
317 case Primitive::Type::kPrimByte:
318 case Primitive::Type::kPrimChar:
319 case Primitive::Type::kPrimShort:
320 case Primitive::Type::kPrimInt:
321 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
322 return GetIntConstant(static_cast<int32_t>(value));
323
324 case Primitive::Type::kPrimLong:
325 return GetLongConstant(value);
326
327 default:
328 LOG(FATAL) << "Unsupported constant type";
329 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000330 }
David Brazdil46e2a392015-03-16 17:31:52 +0000331}
332
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000333void HGraph::CacheFloatConstant(HFloatConstant* constant) {
334 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
335 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
336 cached_float_constants_.Overwrite(value, constant);
337}
338
339void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
340 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
341 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
342 cached_double_constants_.Overwrite(value, constant);
343}
344
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000345void HLoopInformation::Add(HBasicBlock* block) {
346 blocks_.SetBit(block->GetBlockId());
347}
348
David Brazdil46e2a392015-03-16 17:31:52 +0000349void HLoopInformation::Remove(HBasicBlock* block) {
350 blocks_.ClearBit(block->GetBlockId());
351}
352
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100353void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
354 if (blocks_.IsBitSet(block->GetBlockId())) {
355 return;
356 }
357
358 blocks_.SetBit(block->GetBlockId());
359 block->SetInLoop(this);
360 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
361 PopulateRecursive(block->GetPredecessors().Get(i));
362 }
363}
364
365bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100366 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100367 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
368 HBasicBlock* back_edge = GetBackEdges().Get(i);
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 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100374
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100375 // 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 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100383 return true;
384}
385
David Brazdila4b8c212015-05-07 09:59:30 +0100386void HLoopInformation::Update() {
387 HGraph* graph = header_->GetGraph();
388 for (uint32_t id : blocks_.Indexes()) {
389 HBasicBlock* block = graph->GetBlocks().Get(id);
390 // Reset loop information of non-header blocks inside the loop, except
391 // members of inner nested loops because those should already have been
392 // updated by their own LoopInformation.
393 if (block->GetLoopInformation() == this && block != header_) {
394 block->SetLoopInformation(nullptr);
395 }
396 }
397 blocks_.ClearAllBits();
398
399 if (back_edges_.IsEmpty()) {
400 // The loop has been dismantled, delete its suspend check and remove info
401 // from the header.
402 DCHECK(HasSuspendCheck());
403 header_->RemoveInstruction(suspend_check_);
404 header_->SetLoopInformation(nullptr);
405 header_ = nullptr;
406 suspend_check_ = nullptr;
407 } else {
408 if (kIsDebugBuild) {
409 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
410 DCHECK(header_->Dominates(back_edges_.Get(i)));
411 }
412 }
413 // This loop still has reachable back edges. Repopulate the list of blocks.
414 bool populate_successful = Populate();
415 DCHECK(populate_successful);
416 }
417}
418
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100419HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420 return header_->GetDominator();
421}
422
423bool HLoopInformation::Contains(const HBasicBlock& block) const {
424 return blocks_.IsBitSet(block.GetBlockId());
425}
426
427bool HLoopInformation::IsIn(const HLoopInformation& other) const {
428 return other.blocks_.IsBitSet(header_->GetBlockId());
429}
430
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100431size_t HLoopInformation::GetLifetimeEnd() const {
432 size_t last_position = 0;
433 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
434 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
435 }
436 return last_position;
437}
438
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100439bool HBasicBlock::Dominates(HBasicBlock* other) const {
440 // Walk up the dominator tree from `other`, to find out if `this`
441 // is an ancestor.
442 HBasicBlock* current = other;
443 while (current != nullptr) {
444 if (current == this) {
445 return true;
446 }
447 current = current->GetDominator();
448 }
449 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100450}
451
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100452static void UpdateInputsUsers(HInstruction* instruction) {
453 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
454 instruction->InputAt(i)->AddUseAt(instruction, i);
455 }
456 // Environment should be created later.
457 DCHECK(!instruction->HasEnvironment());
458}
459
Roland Levillainccc07a92014-09-16 14:48:16 +0100460void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
461 HInstruction* replacement) {
462 DCHECK(initial->GetBlock() == this);
463 InsertInstructionBefore(replacement, initial);
464 initial->ReplaceWith(replacement);
465 RemoveInstruction(initial);
466}
467
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100468static void Add(HInstructionList* instruction_list,
469 HBasicBlock* block,
470 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000471 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000472 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100473 instruction->SetBlock(block);
474 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100475 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100476 instruction_list->AddInstruction(instruction);
477}
478
479void HBasicBlock::AddInstruction(HInstruction* instruction) {
480 Add(&instructions_, this, instruction);
481}
482
483void HBasicBlock::AddPhi(HPhi* phi) {
484 Add(&phis_, this, phi);
485}
486
David Brazdilc3d743f2015-04-22 13:40:50 +0100487void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
488 DCHECK(!cursor->IsPhi());
489 DCHECK(!instruction->IsPhi());
490 DCHECK_EQ(instruction->GetId(), -1);
491 DCHECK_NE(cursor->GetId(), -1);
492 DCHECK_EQ(cursor->GetBlock(), this);
493 DCHECK(!instruction->IsControlFlow());
494 instruction->SetBlock(this);
495 instruction->SetId(GetGraph()->GetNextInstructionId());
496 UpdateInputsUsers(instruction);
497 instructions_.InsertInstructionBefore(instruction, cursor);
498}
499
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100500void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
501 DCHECK(!cursor->IsPhi());
502 DCHECK(!instruction->IsPhi());
503 DCHECK_EQ(instruction->GetId(), -1);
504 DCHECK_NE(cursor->GetId(), -1);
505 DCHECK_EQ(cursor->GetBlock(), this);
506 DCHECK(!instruction->IsControlFlow());
507 DCHECK(!cursor->IsControlFlow());
508 instruction->SetBlock(this);
509 instruction->SetId(GetGraph()->GetNextInstructionId());
510 UpdateInputsUsers(instruction);
511 instructions_.InsertInstructionAfter(instruction, cursor);
512}
513
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100514void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
515 DCHECK_EQ(phi->GetId(), -1);
516 DCHECK_NE(cursor->GetId(), -1);
517 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100518 phi->SetBlock(this);
519 phi->SetId(GetGraph()->GetNextInstructionId());
520 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100521 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100522}
523
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100524static void Remove(HInstructionList* instruction_list,
525 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000526 HInstruction* instruction,
527 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100528 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100529 instruction->SetBlock(nullptr);
530 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000531 if (ensure_safety) {
532 DCHECK(instruction->GetUses().IsEmpty());
533 DCHECK(instruction->GetEnvUses().IsEmpty());
534 RemoveAsUser(instruction);
535 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100536}
537
David Brazdil1abb4192015-02-17 18:33:36 +0000538void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100539 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000540 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100541}
542
David Brazdil1abb4192015-02-17 18:33:36 +0000543void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
544 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100545}
546
David Brazdilc7508e92015-04-27 13:28:57 +0100547void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
548 if (instruction->IsPhi()) {
549 RemovePhi(instruction->AsPhi(), ensure_safety);
550 } else {
551 RemoveInstruction(instruction, ensure_safety);
552 }
553}
554
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100555void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
556 for (size_t i = 0; i < locals.Size(); i++) {
557 HInstruction* instruction = locals.Get(i);
558 SetRawEnvAt(i, instruction);
559 if (instruction != nullptr) {
560 instruction->AddEnvUseAt(this, i);
561 }
562 }
563}
564
David Brazdiled596192015-01-23 10:39:45 +0000565void HEnvironment::CopyFrom(HEnvironment* env) {
566 for (size_t i = 0; i < env->Size(); i++) {
567 HInstruction* instruction = env->GetInstructionAt(i);
568 SetRawEnvAt(i, instruction);
569 if (instruction != nullptr) {
570 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100571 }
David Brazdiled596192015-01-23 10:39:45 +0000572 }
573}
574
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700575void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
576 HBasicBlock* loop_header) {
577 DCHECK(loop_header->IsLoopHeader());
578 for (size_t i = 0; i < env->Size(); i++) {
579 HInstruction* instruction = env->GetInstructionAt(i);
580 SetRawEnvAt(i, instruction);
581 if (instruction == nullptr) {
582 continue;
583 }
584 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
585 // At the end of the loop pre-header, the corresponding value for instruction
586 // is the first input of the phi.
587 HInstruction* initial = instruction->AsPhi()->InputAt(0);
588 DCHECK(initial->GetBlock()->Dominates(loop_header));
589 SetRawEnvAt(i, initial);
590 initial->AddEnvUseAt(this, i);
591 } else {
592 instruction->AddEnvUseAt(this, i);
593 }
594 }
595}
596
David Brazdil1abb4192015-02-17 18:33:36 +0000597void HEnvironment::RemoveAsUserOfInput(size_t index) const {
598 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
599 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100600}
601
Calin Juravle77520bc2015-01-12 18:45:46 +0000602HInstruction* HInstruction::GetNextDisregardingMoves() const {
603 HInstruction* next = GetNext();
604 while (next != nullptr && next->IsParallelMove()) {
605 next = next->GetNext();
606 }
607 return next;
608}
609
610HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
611 HInstruction* previous = GetPrevious();
612 while (previous != nullptr && previous->IsParallelMove()) {
613 previous = previous->GetPrevious();
614 }
615 return previous;
616}
617
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100618void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000619 if (first_instruction_ == nullptr) {
620 DCHECK(last_instruction_ == nullptr);
621 first_instruction_ = last_instruction_ = instruction;
622 } else {
623 last_instruction_->next_ = instruction;
624 instruction->previous_ = last_instruction_;
625 last_instruction_ = instruction;
626 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000627}
628
David Brazdilc3d743f2015-04-22 13:40:50 +0100629void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
630 DCHECK(Contains(cursor));
631 if (cursor == first_instruction_) {
632 cursor->previous_ = instruction;
633 instruction->next_ = cursor;
634 first_instruction_ = instruction;
635 } else {
636 instruction->previous_ = cursor->previous_;
637 instruction->next_ = cursor;
638 cursor->previous_ = instruction;
639 instruction->previous_->next_ = instruction;
640 }
641}
642
643void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
644 DCHECK(Contains(cursor));
645 if (cursor == last_instruction_) {
646 cursor->next_ = instruction;
647 instruction->previous_ = cursor;
648 last_instruction_ = instruction;
649 } else {
650 instruction->next_ = cursor->next_;
651 instruction->previous_ = cursor;
652 cursor->next_ = instruction;
653 instruction->next_->previous_ = instruction;
654 }
655}
656
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657void HInstructionList::RemoveInstruction(HInstruction* instruction) {
658 if (instruction->previous_ != nullptr) {
659 instruction->previous_->next_ = instruction->next_;
660 }
661 if (instruction->next_ != nullptr) {
662 instruction->next_->previous_ = instruction->previous_;
663 }
664 if (instruction == first_instruction_) {
665 first_instruction_ = instruction->next_;
666 }
667 if (instruction == last_instruction_) {
668 last_instruction_ = instruction->previous_;
669 }
670}
671
Roland Levillain6b469232014-09-25 10:10:38 +0100672bool HInstructionList::Contains(HInstruction* instruction) const {
673 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
674 if (it.Current() == instruction) {
675 return true;
676 }
677 }
678 return false;
679}
680
Roland Levillainccc07a92014-09-16 14:48:16 +0100681bool HInstructionList::FoundBefore(const HInstruction* instruction1,
682 const HInstruction* instruction2) const {
683 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
684 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
685 if (it.Current() == instruction1) {
686 return true;
687 }
688 if (it.Current() == instruction2) {
689 return false;
690 }
691 }
692 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
693 return true;
694}
695
Roland Levillain6c82d402014-10-13 16:10:27 +0100696bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
697 if (other_instruction == this) {
698 // An instruction does not strictly dominate itself.
699 return false;
700 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100701 HBasicBlock* block = GetBlock();
702 HBasicBlock* other_block = other_instruction->GetBlock();
703 if (block != other_block) {
704 return GetBlock()->Dominates(other_instruction->GetBlock());
705 } else {
706 // If both instructions are in the same block, ensure this
707 // instruction comes before `other_instruction`.
708 if (IsPhi()) {
709 if (!other_instruction->IsPhi()) {
710 // Phis appear before non phi-instructions so this instruction
711 // dominates `other_instruction`.
712 return true;
713 } else {
714 // There is no order among phis.
715 LOG(FATAL) << "There is no dominance between phis of a same block.";
716 return false;
717 }
718 } else {
719 // `this` is not a phi.
720 if (other_instruction->IsPhi()) {
721 // Phis appear before non phi-instructions so this instruction
722 // does not dominate `other_instruction`.
723 return false;
724 } else {
725 // Check whether this instruction comes before
726 // `other_instruction` in the instruction list.
727 return block->GetInstructions().FoundBefore(this, other_instruction);
728 }
729 }
730 }
731}
732
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100733void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100734 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000735 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
736 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100737 HInstruction* user = current->GetUser();
738 size_t input_index = current->GetIndex();
739 user->SetRawInputAt(input_index, other);
740 other->AddUseAt(user, input_index);
741 }
742
David Brazdiled596192015-01-23 10:39:45 +0000743 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
744 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100745 HEnvironment* user = current->GetUser();
746 size_t input_index = current->GetIndex();
747 user->SetRawEnvAt(input_index, other);
748 other->AddEnvUseAt(user, input_index);
749 }
750
David Brazdiled596192015-01-23 10:39:45 +0000751 uses_.Clear();
752 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100753}
754
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100755void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000756 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100757 SetRawInputAt(index, replacement);
758 replacement->AddUseAt(this, index);
759}
760
Nicolas Geoffray39468442014-09-02 15:17:15 +0100761size_t HInstruction::EnvironmentSize() const {
762 return HasEnvironment() ? environment_->Size() : 0;
763}
764
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100765void HPhi::AddInput(HInstruction* input) {
766 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000767 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100768 input->AddUseAt(this, inputs_.Size() - 1);
769}
770
David Brazdil2d7352b2015-04-20 14:52:42 +0100771void HPhi::RemoveInputAt(size_t index) {
772 RemoveAsUserOfInput(index);
773 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100774 for (size_t i = index, e = InputCount(); i < e; ++i) {
775 InputRecordAt(i).GetUseNode()->SetIndex(i);
776 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100777}
778
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100779#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000780void H##name::Accept(HGraphVisitor* visitor) { \
781 visitor->Visit##name(this); \
782}
783
784FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
785
786#undef DEFINE_ACCEPT
787
788void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100789 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
790 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000791 HBasicBlock* block = blocks.Get(i);
792 if (block != nullptr) {
793 VisitBasicBlock(block);
794 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000795 }
796}
797
Roland Levillain633021e2014-10-01 14:12:25 +0100798void HGraphVisitor::VisitReversePostOrder() {
799 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
800 VisitBasicBlock(it.Current());
801 }
802}
803
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000804void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100805 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806 it.Current()->Accept(this);
807 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100808 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000809 it.Current()->Accept(this);
810 }
811}
812
Mark Mendelle82549b2015-05-06 10:55:34 -0400813HConstant* HTypeConversion::TryStaticEvaluation() const {
814 HGraph* graph = GetBlock()->GetGraph();
815 if (GetInput()->IsIntConstant()) {
816 int32_t value = GetInput()->AsIntConstant()->GetValue();
817 switch (GetResultType()) {
818 case Primitive::kPrimLong:
819 return graph->GetLongConstant(static_cast<int64_t>(value));
820 case Primitive::kPrimFloat:
821 return graph->GetFloatConstant(static_cast<float>(value));
822 case Primitive::kPrimDouble:
823 return graph->GetDoubleConstant(static_cast<double>(value));
824 default:
825 return nullptr;
826 }
827 } else if (GetInput()->IsLongConstant()) {
828 int64_t value = GetInput()->AsLongConstant()->GetValue();
829 switch (GetResultType()) {
830 case Primitive::kPrimInt:
831 return graph->GetIntConstant(static_cast<int32_t>(value));
832 case Primitive::kPrimFloat:
833 return graph->GetFloatConstant(static_cast<float>(value));
834 case Primitive::kPrimDouble:
835 return graph->GetDoubleConstant(static_cast<double>(value));
836 default:
837 return nullptr;
838 }
839 } else if (GetInput()->IsFloatConstant()) {
840 float value = GetInput()->AsFloatConstant()->GetValue();
841 switch (GetResultType()) {
842 case Primitive::kPrimInt:
843 if (std::isnan(value))
844 return graph->GetIntConstant(0);
845 if (value >= kPrimIntMax)
846 return graph->GetIntConstant(kPrimIntMax);
847 if (value <= kPrimIntMin)
848 return graph->GetIntConstant(kPrimIntMin);
849 return graph->GetIntConstant(static_cast<int32_t>(value));
850 case Primitive::kPrimLong:
851 if (std::isnan(value))
852 return graph->GetLongConstant(0);
853 if (value >= kPrimLongMax)
854 return graph->GetLongConstant(kPrimLongMax);
855 if (value <= kPrimLongMin)
856 return graph->GetLongConstant(kPrimLongMin);
857 return graph->GetLongConstant(static_cast<int64_t>(value));
858 case Primitive::kPrimDouble:
859 return graph->GetDoubleConstant(static_cast<double>(value));
860 default:
861 return nullptr;
862 }
863 } else if (GetInput()->IsDoubleConstant()) {
864 double value = GetInput()->AsDoubleConstant()->GetValue();
865 switch (GetResultType()) {
866 case Primitive::kPrimInt:
867 if (std::isnan(value))
868 return graph->GetIntConstant(0);
869 if (value >= kPrimIntMax)
870 return graph->GetIntConstant(kPrimIntMax);
871 if (value <= kPrimLongMin)
872 return graph->GetIntConstant(kPrimIntMin);
873 return graph->GetIntConstant(static_cast<int32_t>(value));
874 case Primitive::kPrimLong:
875 if (std::isnan(value))
876 return graph->GetLongConstant(0);
877 if (value >= kPrimLongMax)
878 return graph->GetLongConstant(kPrimLongMax);
879 if (value <= kPrimLongMin)
880 return graph->GetLongConstant(kPrimLongMin);
881 return graph->GetLongConstant(static_cast<int64_t>(value));
882 case Primitive::kPrimFloat:
883 return graph->GetFloatConstant(static_cast<float>(value));
884 default:
885 return nullptr;
886 }
887 }
888 return nullptr;
889}
890
Roland Levillain9240d6a2014-10-20 16:47:04 +0100891HConstant* HUnaryOperation::TryStaticEvaluation() const {
892 if (GetInput()->IsIntConstant()) {
893 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000894 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100895 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100896 // TODO: Implement static evaluation of long unary operations.
897 //
898 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700899 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100900 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100901 return nullptr;
902 }
903 return nullptr;
904}
905
906HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100907 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
908 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
909 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000910 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100911 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
912 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
913 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000914 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000915 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000916 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000917 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000918 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000919 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100920 }
921 return nullptr;
922}
Dave Allison20dfc792014-06-16 20:44:29 -0700923
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000924HConstant* HBinaryOperation::GetConstantRight() const {
925 if (GetRight()->IsConstant()) {
926 return GetRight()->AsConstant();
927 } else if (IsCommutative() && GetLeft()->IsConstant()) {
928 return GetLeft()->AsConstant();
929 } else {
930 return nullptr;
931 }
932}
933
934// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700935// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000936HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
937 HInstruction* most_constant_right = GetConstantRight();
938 if (most_constant_right == nullptr) {
939 return nullptr;
940 } else if (most_constant_right == GetLeft()) {
941 return GetRight();
942 } else {
943 return GetLeft();
944 }
945}
946
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700947bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
948 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100949}
950
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100951bool HInstruction::Equals(HInstruction* other) const {
952 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100953 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100954 if (!InstructionDataEquals(other)) return false;
955 if (GetType() != other->GetType()) return false;
956 if (InputCount() != other->InputCount()) return false;
957
958 for (size_t i = 0, e = InputCount(); i < e; ++i) {
959 if (InputAt(i) != other->InputAt(i)) return false;
960 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100961 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100962 return true;
963}
964
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700965std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
966#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
967 switch (rhs) {
968 FOR_EACH_INSTRUCTION(DECLARE_CASE)
969 default:
970 os << "Unknown instruction kind " << static_cast<int>(rhs);
971 break;
972 }
973#undef DECLARE_CASE
974 return os;
975}
976
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000977void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000978 next_->previous_ = previous_;
979 if (previous_ != nullptr) {
980 previous_->next_ = next_;
981 }
982 if (block_->instructions_.first_instruction_ == this) {
983 block_->instructions_.first_instruction_ = next_;
984 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000985 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000986
987 previous_ = cursor->previous_;
988 if (previous_ != nullptr) {
989 previous_->next_ = this;
990 }
991 next_ = cursor;
992 cursor->previous_ = this;
993 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000994
995 if (block_->instructions_.first_instruction_ == cursor) {
996 block_->instructions_.first_instruction_ = this;
997 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000998}
999
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001000HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1001 DCHECK(!cursor->IsControlFlow());
1002 DCHECK_NE(instructions_.last_instruction_, cursor);
1003 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001004
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001005 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1006 new_block->instructions_.first_instruction_ = cursor->GetNext();
1007 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1008 cursor->next_->previous_ = nullptr;
1009 cursor->next_ = nullptr;
1010 instructions_.last_instruction_ = cursor;
1011
1012 new_block->instructions_.SetBlockOfInstructions(new_block);
1013 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1014 HBasicBlock* successor = GetSuccessors().Get(i);
1015 new_block->successors_.Add(successor);
1016 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1017 }
1018 successors_.Reset();
1019
1020 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1021 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1022 dominated->dominator_ = new_block;
1023 new_block->dominated_blocks_.Add(dominated);
1024 }
1025 dominated_blocks_.Reset();
1026 return new_block;
1027}
1028
David Brazdil46e2a392015-03-16 17:31:52 +00001029bool HBasicBlock::IsSingleGoto() const {
1030 HLoopInformation* loop_info = GetLoopInformation();
1031 // TODO: Remove the null check b/19084197.
1032 return GetFirstInstruction() != nullptr
1033 && GetPhis().IsEmpty()
1034 && GetFirstInstruction() == GetLastInstruction()
1035 && GetLastInstruction()->IsGoto()
1036 // Back edges generate the suspend check.
1037 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
1038}
1039
David Brazdil8d5b8b22015-03-24 10:51:52 +00001040bool HBasicBlock::EndsWithControlFlowInstruction() const {
1041 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1042}
1043
David Brazdilb2bd1c52015-03-25 11:17:37 +00001044bool HBasicBlock::EndsWithIf() const {
1045 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1046}
1047
1048bool HBasicBlock::HasSinglePhi() const {
1049 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1050}
1051
David Brazdil2d7352b2015-04-20 14:52:42 +01001052size_t HInstructionList::CountSize() const {
1053 size_t size = 0;
1054 HInstruction* current = first_instruction_;
1055 for (; current != nullptr; current = current->GetNext()) {
1056 size++;
1057 }
1058 return size;
1059}
1060
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001061void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1062 for (HInstruction* current = first_instruction_;
1063 current != nullptr;
1064 current = current->GetNext()) {
1065 current->SetBlock(block);
1066 }
1067}
1068
1069void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1070 DCHECK(Contains(cursor));
1071 if (!instruction_list.IsEmpty()) {
1072 if (cursor == last_instruction_) {
1073 last_instruction_ = instruction_list.last_instruction_;
1074 } else {
1075 cursor->next_->previous_ = instruction_list.last_instruction_;
1076 }
1077 instruction_list.last_instruction_->next_ = cursor->next_;
1078 cursor->next_ = instruction_list.first_instruction_;
1079 instruction_list.first_instruction_->previous_ = cursor;
1080 }
1081}
1082
1083void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001084 if (IsEmpty()) {
1085 first_instruction_ = instruction_list.first_instruction_;
1086 last_instruction_ = instruction_list.last_instruction_;
1087 } else {
1088 AddAfter(last_instruction_, instruction_list);
1089 }
1090}
1091
David Brazdil2d7352b2015-04-20 14:52:42 +01001092void HBasicBlock::DisconnectAndDelete() {
1093 // Dominators must be removed after all the blocks they dominate. This way
1094 // a loop header is removed last, a requirement for correct loop information
1095 // iteration.
1096 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001097
David Brazdil2d7352b2015-04-20 14:52:42 +01001098 // Remove the block from all loops it is included in.
1099 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1100 HLoopInformation* loop_info = it.Current();
1101 loop_info->Remove(this);
1102 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001103 // If this was the last back edge of the loop, we deliberately leave the
1104 // loop in an inconsistent state and will fail SSAChecker unless the
1105 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001106 loop_info->RemoveBackEdge(this);
1107 }
1108 }
1109
1110 // Disconnect the block from its predecessors and update their control-flow
1111 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001112 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001113 HBasicBlock* predecessor = predecessors_.Get(i);
1114 HInstruction* last_instruction = predecessor->GetLastInstruction();
1115 predecessor->RemoveInstruction(last_instruction);
1116 predecessor->RemoveSuccessor(this);
1117 if (predecessor->GetSuccessors().Size() == 1u) {
1118 DCHECK(last_instruction->IsIf());
1119 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1120 } else {
1121 // The predecessor has no remaining successors and therefore must be dead.
1122 // We deliberately leave it without a control-flow instruction so that the
1123 // SSAChecker fails unless it is not removed during the pass too.
1124 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1125 }
David Brazdil46e2a392015-03-16 17:31:52 +00001126 }
David Brazdil46e2a392015-03-16 17:31:52 +00001127 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001128
1129 // Disconnect the block from its successors and update their dominators
1130 // and phis.
1131 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1132 HBasicBlock* successor = successors_.Get(i);
1133 // Delete this block from the list of predecessors.
1134 size_t this_index = successor->GetPredecessorIndexOf(this);
1135 successor->predecessors_.DeleteAt(this_index);
1136
1137 // Check that `successor` has other predecessors, otherwise `this` is the
1138 // dominator of `successor` which violates the order DCHECKed at the top.
1139 DCHECK(!successor->predecessors_.IsEmpty());
1140
1141 // Recompute the successor's dominator.
1142 HBasicBlock* old_dominator = successor->GetDominator();
1143 HBasicBlock* new_dominator = successor->predecessors_.Get(0);
1144 for (size_t j = 1, f = successor->predecessors_.Size(); j < f; ++j) {
1145 new_dominator = graph_->FindCommonDominator(
1146 new_dominator, successor->predecessors_.Get(j));
1147 }
1148 if (old_dominator != new_dominator) {
1149 successor->SetDominator(new_dominator);
1150 old_dominator->RemoveDominatedBlock(successor);
1151 new_dominator->AddDominatedBlock(successor);
1152 }
1153
1154 // Remove this block's entries in the successor's phis.
1155 if (successor->predecessors_.Size() == 1u) {
1156 // The successor has just one predecessor left. Replace phis with the only
1157 // remaining input.
1158 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1159 HPhi* phi = phi_it.Current()->AsPhi();
1160 phi->ReplaceWith(phi->InputAt(1 - this_index));
1161 successor->RemovePhi(phi);
1162 }
1163 } else {
1164 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1165 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1166 }
1167 }
1168 }
David Brazdil46e2a392015-03-16 17:31:52 +00001169 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001170
1171 // Disconnect from the dominator.
1172 dominator_->RemoveDominatedBlock(this);
1173 SetDominator(nullptr);
1174
1175 // Delete from the graph. The function safely deletes remaining instructions
1176 // and updates the reverse post order.
1177 graph_->DeleteDeadBlock(this);
1178 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001179}
1180
1181void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001182 DCHECK_EQ(GetGraph(), other->GetGraph());
1183 DCHECK(GetDominatedBlocks().Contains(other));
1184 DCHECK_EQ(GetSuccessors().Size(), 1u);
1185 DCHECK_EQ(GetSuccessors().Get(0), other);
1186 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1187 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001188 DCHECK(other->GetPhis().IsEmpty());
1189
David Brazdil2d7352b2015-04-20 14:52:42 +01001190 // Move instructions from `other` to `this`.
1191 DCHECK(EndsWithControlFlowInstruction());
1192 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001193 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001194 other->instructions_.SetBlockOfInstructions(this);
1195 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001196
David Brazdil2d7352b2015-04-20 14:52:42 +01001197 // Remove `other` from the loops it is included in.
1198 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1199 HLoopInformation* loop_info = it.Current();
1200 loop_info->Remove(other);
1201 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001202 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001203 }
1204 }
1205
1206 // Update links to the successors of `other`.
1207 successors_.Reset();
1208 while (!other->successors_.IsEmpty()) {
1209 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001210 successor->ReplacePredecessor(other, this);
1211 }
1212
David Brazdil2d7352b2015-04-20 14:52:42 +01001213 // Update the dominator tree.
1214 dominated_blocks_.Delete(other);
1215 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1216 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1217 dominated_blocks_.Add(dominated);
1218 dominated->SetDominator(this);
1219 }
1220 other->dominated_blocks_.Reset();
1221 other->dominator_ = nullptr;
1222
1223 // Clear the list of predecessors of `other` in preparation of deleting it.
1224 other->predecessors_.Reset();
1225
1226 // Delete `other` from the graph. The function updates reverse post order.
1227 graph_->DeleteDeadBlock(other);
1228 other->SetGraph(nullptr);
1229}
1230
1231void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1232 DCHECK_NE(GetGraph(), other->GetGraph());
1233 DCHECK(GetDominatedBlocks().IsEmpty());
1234 DCHECK(GetSuccessors().IsEmpty());
1235 DCHECK(!EndsWithControlFlowInstruction());
1236 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1237 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1238 DCHECK(other->GetPhis().IsEmpty());
1239 DCHECK(!other->IsInLoop());
1240
1241 // Move instructions from `other` to `this`.
1242 instructions_.Add(other->GetInstructions());
1243 other->instructions_.SetBlockOfInstructions(this);
1244
1245 // Update links to the successors of `other`.
1246 successors_.Reset();
1247 while (!other->successors_.IsEmpty()) {
1248 HBasicBlock* successor = other->successors_.Get(0);
1249 successor->ReplacePredecessor(other, this);
1250 }
1251
1252 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001253 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1254 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1255 dominated_blocks_.Add(dominated);
1256 dominated->SetDominator(this);
1257 }
1258 other->dominated_blocks_.Reset();
1259 other->dominator_ = nullptr;
1260 other->graph_ = nullptr;
1261}
1262
1263void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1264 while (!GetPredecessors().IsEmpty()) {
1265 HBasicBlock* predecessor = GetPredecessors().Get(0);
1266 predecessor->ReplaceSuccessor(this, other);
1267 }
1268 while (!GetSuccessors().IsEmpty()) {
1269 HBasicBlock* successor = GetSuccessors().Get(0);
1270 successor->ReplacePredecessor(this, other);
1271 }
1272 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1273 other->AddDominatedBlock(dominated_blocks_.Get(i));
1274 }
1275 GetDominator()->ReplaceDominatedBlock(this, other);
1276 other->SetDominator(GetDominator());
1277 dominator_ = nullptr;
1278 graph_ = nullptr;
1279}
1280
1281// Create space in `blocks` for adding `number_of_new_blocks` entries
1282// starting at location `at`. Blocks after `at` are moved accordingly.
1283static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1284 size_t number_of_new_blocks,
1285 size_t at) {
1286 size_t old_size = blocks->Size();
1287 size_t new_size = old_size + number_of_new_blocks;
1288 blocks->SetSize(new_size);
1289 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1290 blocks->Put(j, blocks->Get(i));
1291 }
1292}
1293
David Brazdil2d7352b2015-04-20 14:52:42 +01001294void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1295 DCHECK_EQ(block->GetGraph(), this);
1296 DCHECK(block->GetSuccessors().IsEmpty());
1297 DCHECK(block->GetPredecessors().IsEmpty());
1298 DCHECK(block->GetDominatedBlocks().IsEmpty());
1299 DCHECK(block->GetDominator() == nullptr);
1300
1301 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1302 block->RemoveInstruction(it.Current());
1303 }
1304 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1305 block->RemovePhi(it.Current()->AsPhi());
1306 }
1307
David Brazdilc7af85d2015-05-26 12:05:55 +01001308 if (block->IsExitBlock()) {
1309 exit_block_ = nullptr;
1310 }
1311
David Brazdil2d7352b2015-04-20 14:52:42 +01001312 reverse_post_order_.Delete(block);
1313 blocks_.Put(block->GetBlockId(), nullptr);
1314}
1315
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001316void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001317 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001318 // Update the environments in this graph to have the invoke's environment
1319 // as parent.
1320 {
1321 HReversePostOrderIterator it(*this);
1322 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1323 for (; !it.Done(); it.Advance()) {
1324 HBasicBlock* block = it.Current();
1325 for (HInstructionIterator instr_it(block->GetInstructions());
1326 !instr_it.Done();
1327 instr_it.Advance()) {
1328 HInstruction* current = instr_it.Current();
1329 if (current->NeedsEnvironment()) {
1330 current->GetEnvironment()->SetAndCopyParentChain(
1331 outer_graph->GetArena(), invoke->GetEnvironment());
1332 }
1333 }
1334 }
1335 }
1336 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1337 if (HasBoundsChecks()) {
1338 outer_graph->SetHasBoundsChecks(true);
1339 }
1340
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001341 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001342 // Simple case of an entry block, a body block, and an exit block.
1343 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001344 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001345 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1346 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001347 DCHECK(!body->IsExitBlock());
1348 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001349
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001350 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1351 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001352
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001353 // Replace the invoke with the return value of the inlined graph.
1354 if (last->IsReturn()) {
1355 invoke->ReplaceWith(last->InputAt(0));
1356 } else {
1357 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001358 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001359
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001360 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001361 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001362 // Need to inline multiple blocks. We split `invoke`'s block
1363 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001364 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001365 // with the second half.
1366 ArenaAllocator* allocator = outer_graph->GetArena();
1367 HBasicBlock* at = invoke->GetBlock();
1368 HBasicBlock* to = at->SplitAfter(invoke);
1369
1370 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1371 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001372 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001373 exit_block_->ReplaceWith(to);
1374
1375 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001376 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001377 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001378 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1379 if (to->GetPredecessors().Size() == 1) {
1380 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001381 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001382 if (!returns_void) {
1383 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001384 }
1385 predecessor->AddInstruction(new (allocator) HGoto());
1386 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001387 } else {
1388 if (!returns_void) {
1389 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001390 return_value = new (allocator) HPhi(
1391 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001392 to->AddPhi(return_value->AsPhi());
1393 }
1394 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1395 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1396 HInstruction* last = predecessor->GetLastInstruction();
1397 if (!returns_void) {
1398 return_value->AsPhi()->AddInput(last->InputAt(0));
1399 }
1400 predecessor->AddInstruction(new (allocator) HGoto());
1401 predecessor->RemoveInstruction(last);
1402 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001403 }
1404
1405 if (return_value != nullptr) {
1406 invoke->ReplaceWith(return_value);
1407 }
1408
1409 // Update the meta information surrounding blocks:
1410 // (1) the graph they are now in,
1411 // (2) the reverse post order of that graph,
1412 // (3) the potential loop information they are now in.
1413
1414 // We don't add the entry block, the exit block, and the first block, which
1415 // has been merged with `at`.
1416 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1417
1418 // We add the `to` block.
1419 static constexpr int kNumberOfNewBlocksInCaller = 1;
1420 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1421 + kNumberOfNewBlocksInCaller;
1422
1423 // Find the location of `at` in the outer graph's reverse post order. The new
1424 // blocks will be added after it.
1425 size_t index_of_at = 0;
1426 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1427 index_of_at++;
1428 }
1429 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1430
1431 // Do a reverse post order of the blocks in the callee and do (1), (2),
1432 // and (3) to the blocks that apply.
1433 HLoopInformation* info = at->GetLoopInformation();
1434 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1435 HBasicBlock* current = it.Current();
1436 if (current != exit_block_ && current != entry_block_ && current != first) {
1437 DCHECK(!current->IsInLoop());
1438 DCHECK(current->GetGraph() == this);
1439 current->SetGraph(outer_graph);
1440 outer_graph->AddBlock(current);
1441 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1442 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001443 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001444 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1445 loop_it.Current()->Add(current);
1446 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001447 }
1448 }
1449 }
1450
1451 // Do (1), (2), and (3) to `to`.
1452 to->SetGraph(outer_graph);
1453 outer_graph->AddBlock(to);
1454 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1455 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001456 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001457 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1458 loop_it.Current()->Add(to);
1459 }
David Brazdil46e2a392015-03-16 17:31:52 +00001460 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001461 // Only `to` can become a back edge, as the inlined blocks
1462 // are predecessors of `to`.
1463 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001464 }
1465 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001466 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001467
David Brazdil05144f42015-04-16 15:18:00 +01001468 // Update the next instruction id of the outer graph, so that instructions
1469 // added later get bigger ids than those in the inner graph.
1470 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1471
1472 // Walk over the entry block and:
1473 // - Move constants from the entry block to the outer_graph's entry block,
1474 // - Replace HParameterValue instructions with their real value.
1475 // - Remove suspend checks, that hold an environment.
1476 // We must do this after the other blocks have been inlined, otherwise ids of
1477 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001478 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001479 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1480 HInstruction* current = it.Current();
1481 if (current->IsNullConstant()) {
1482 current->ReplaceWith(outer_graph->GetNullConstant());
1483 } else if (current->IsIntConstant()) {
1484 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1485 } else if (current->IsLongConstant()) {
1486 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001487 } else if (current->IsFloatConstant()) {
1488 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1489 } else if (current->IsDoubleConstant()) {
1490 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001491 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001492 if (kIsDebugBuild
1493 && invoke->IsInvokeStaticOrDirect()
1494 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1495 // Ensure we do not use the last input of `invoke`, as it
1496 // contains a clinit check which is not an actual argument.
1497 size_t last_input_index = invoke->InputCount() - 1;
1498 DCHECK(parameter_index != last_input_index);
1499 }
David Brazdil05144f42015-04-16 15:18:00 +01001500 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001501 } else if (current->IsCurrentMethod()) {
1502 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001503 } else {
1504 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1505 entry_block_->RemoveInstruction(current);
1506 }
1507 }
1508
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001509 // Finally remove the invoke from the caller.
1510 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001511}
1512
Calin Juravleacf735c2015-02-12 15:25:22 +00001513std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1514 ScopedObjectAccess soa(Thread::Current());
1515 os << "["
1516 << " is_top=" << rhs.IsTop()
1517 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1518 << " is_exact=" << rhs.IsExact()
1519 << " ]";
1520 return os;
1521}
1522
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001523} // namespace art