blob: 9f448af73a346e96031a7940b77063f3d520ea03 [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 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
59 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
60 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
61 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
62 constexpr size_t kDefaultWorklistSize = 8;
63 worklist.reserve(kDefaultWorklistSize);
64 visited->SetBit(entry_block_->GetBlockId());
65 visiting.SetBit(entry_block_->GetBlockId());
66 worklist.push_back(entry_block_);
67
68 while (!worklist.empty()) {
69 HBasicBlock* current = worklist.back();
70 uint32_t current_id = current->GetBlockId();
71 if (successors_visited[current_id] == current->GetSuccessors().size()) {
72 visiting.ClearBit(current_id);
73 worklist.pop_back();
74 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010075 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
76 uint32_t successor_id = successor->GetBlockId();
77 if (visiting.IsBitSet(successor_id)) {
78 DCHECK(ContainsElement(worklist, successor));
79 successor->AddBackEdge(current);
80 } else if (!visited->IsBitSet(successor_id)) {
81 visited->SetBit(successor_id);
82 visiting.SetBit(successor_id);
83 worklist.push_back(successor);
84 }
85 }
86 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000087}
88
Vladimir Markocac5a7e2016-02-22 10:39:50 +000089static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010090 for (HEnvironment* environment = instruction->GetEnvironment();
91 environment != nullptr;
92 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000094 if (environment->GetInstructionAt(i) != nullptr) {
95 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000096 }
97 }
98 }
99}
100
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000101static void RemoveAsUser(HInstruction* instruction) {
102 for (size_t i = 0; i < instruction->InputCount(); i++) {
103 instruction->RemoveAsUserOfInput(i);
104 }
105
106 RemoveEnvironmentUses(instruction);
107}
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100112 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000113 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100114 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000115 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
116 RemoveAsUser(it.Current());
117 }
118 }
119 }
120}
121
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100122void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100125 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000128 for (HBasicBlock* successor : block->GetSuccessors()) {
129 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000130 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100131 // Remove the block from the list of blocks, so that further analyses
132 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600134 if (block->IsExitBlock()) {
135 SetExitBlock(nullptr);
136 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000137 // Mark the block as removed. This is used by the HGraphBuilder to discard
138 // the block as a branch target.
139 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 }
142}
143
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000145 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000146
David Brazdil86ea7ee2016-02-16 09:26:07 +0000147 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 FindBackEdges(&visited);
149
David Brazdil86ea7ee2016-02-16 09:26:07 +0000150 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000151 // the initial DFS as users from other instructions, so that
152 // users can be safely removed before uses later.
153 RemoveInstructionsAsUsersFromDeadBlocks(visited);
154
David Brazdil86ea7ee2016-02-16 09:26:07 +0000155 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000156 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 // predecessors list of live blocks.
158 RemoveDeadBlocks(visited);
159
David Brazdil86ea7ee2016-02-16 09:26:07 +0000160 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100161 // dominators and the reverse post order.
162 SimplifyCFG();
163
David Brazdil86ea7ee2016-02-16 09:26:07 +0000164 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000166
David Brazdil86ea7ee2016-02-16 09:26:07 +0000167 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168 // set the loop information on each block.
169 GraphAnalysisResult result = AnalyzeLoops();
170 if (result != kAnalysisSuccess) {
171 return result;
172 }
173
David Brazdil86ea7ee2016-02-16 09:26:07 +0000174 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175 // which needs the information to build catch block phis from values of
176 // locals at throwing instructions inside try blocks.
177 ComputeTryBlockInformation();
178
179 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100180}
181
182void HGraph::ClearDominanceInformation() {
183 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
184 it.Current()->ClearDominanceInformation();
185 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100186 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187}
188
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000189void HGraph::ClearLoopInformation() {
190 SetHasIrreducibleLoops(false);
191 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000192 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000193 }
194}
195
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000197 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198 dominator_ = nullptr;
199}
200
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000201HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
202 HInstruction* instruction = GetFirstInstruction();
203 while (instruction->IsParallelMove()) {
204 instruction = instruction->GetNext();
205 }
206 return instruction;
207}
208
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100209void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100210 DCHECK(reverse_post_order_.empty());
211 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100212 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100213
214 // Number of visits of a given node, indexed by block id.
215 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
216 // Number of successors visited from a given node, indexed by block id.
217 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
218 // Nodes for which we need to visit successors.
219 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
220 constexpr size_t kDefaultWorklistSize = 8;
221 worklist.reserve(kDefaultWorklistSize);
222 worklist.push_back(entry_block_);
223
224 while (!worklist.empty()) {
225 HBasicBlock* current = worklist.back();
226 uint32_t current_id = current->GetBlockId();
227 if (successors_visited[current_id] == current->GetSuccessors().size()) {
228 worklist.pop_back();
229 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100230 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
231
232 if (successor->GetDominator() == nullptr) {
233 successor->SetDominator(current);
234 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000235 // The CommonDominator can work for multiple blocks as long as the
236 // domination information doesn't change. However, since we're changing
237 // that information here, we can use the finder only for pairs of blocks.
238 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100239 }
240
241 // Once all the forward edges have been visited, we know the immediate
242 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100243 if (++visits[successor->GetBlockId()] ==
244 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100245 reverse_post_order_.push_back(successor);
246 worklist.push_back(successor);
247 }
248 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000249 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000250
251 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000252 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000253 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
254 HBasicBlock* block = it.Current();
255 if (!block->IsEntryBlock()) {
256 block->GetDominator()->AddDominatedBlock(block);
257 }
258 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000259}
260
David Brazdilfc6a86a2015-06-26 10:33:45 +0000261HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000262 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
263 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000264 // Use `InsertBetween` to ensure the predecessor index and successor index of
265 // `block` and `successor` are preserved.
266 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000267 return new_block;
268}
269
270void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
271 // Insert a new node between `block` and `successor` to split the
272 // critical edge.
273 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600274 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100275 if (successor->IsLoopHeader()) {
276 // If we split at a back edge boundary, make the new block the back edge.
277 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000278 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100279 info->RemoveBackEdge(block);
280 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100281 }
282 }
283}
284
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100285void HGraph::SimplifyLoop(HBasicBlock* header) {
286 HLoopInformation* info = header->GetLoopInformation();
287
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100288 // Make sure the loop has only one pre header. This simplifies SSA building by having
289 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000290 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
291 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000292 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000293 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100294 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100295 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600296 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100299 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100300 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100301 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100302 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 }
304 }
305 pre_header->AddSuccessor(header);
306 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100307
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100308 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100309 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
310 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000311 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100312 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100313 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000314 header->predecessors_[pred] = to_swap;
315 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100316 break;
317 }
318 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100319 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100320
321 // Place the suspend check at the beginning of the header, so that live registers
322 // will be known when allocating registers. Note that code generation can still
323 // generate the suspend check at the back edge, but needs to be careful with
324 // loop phi spill slots (which are not written to at back edge).
325 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdil86ea7ee2016-02-16 09:26:07 +0000326 if (first_instruction == nullptr) {
327 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
328 header->AddInstruction(check);
329 first_instruction = check;
330 } else if (!first_instruction->IsSuspendCheck()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100331 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
332 header->InsertInstructionBefore(check, first_instruction);
333 first_instruction = check;
334 }
335 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100336}
337
David Brazdilffee3d32015-07-06 11:48:53 +0100338void HGraph::ComputeTryBlockInformation() {
339 // Iterate in reverse post order to propagate try membership information from
340 // predecessors to their successors.
341 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
342 HBasicBlock* block = it.Current();
343 if (block->IsEntryBlock() || block->IsCatchBlock()) {
344 // Catch blocks after simplification have only exceptional predecessors
345 // and hence are never in tries.
346 continue;
347 }
348
349 // Infer try membership from the first predecessor. Having simplified loops,
350 // the first predecessor can never be a back edge and therefore it must have
351 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100352 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100353 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100354 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000355 if (try_entry != nullptr &&
356 (block->GetTryCatchInformation() == nullptr ||
357 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
358 // We are either setting try block membership for the first time or it
359 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100360 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
361 }
David Brazdilffee3d32015-07-06 11:48:53 +0100362 }
363}
364
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100365void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000366// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100367 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000368 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100369 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
370 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
371 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
372 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100373 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000374 if (block->GetSuccessors().size() > 1) {
375 // Only split normal-flow edges. We cannot split exceptional edges as they
376 // are synthesized (approximate real control flow), and we do not need to
377 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000378 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
379 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
380 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100381 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000382 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000383 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
384 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000385 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000386 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100387 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000388 // SplitCriticalEdge could have invalidated the `normal_successors`
389 // ArrayRef. We must re-acquire it.
390 normal_successors = block->GetNormalSuccessors();
391 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
392 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100393 }
394 }
395 }
396 if (block->IsLoopHeader()) {
397 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000398 } else if (!block->IsEntryBlock() &&
399 block->GetFirstInstruction() != nullptr &&
400 block->GetFirstInstruction()->IsSuspendCheck()) {
401 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000402 // a loop got dismantled. Just remove the suspend check.
403 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 }
405 }
406}
407
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000408GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100409 // Order does not matter.
410 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
411 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100412 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100413 if (block->IsCatchBlock()) {
414 // TODO: Dealing with exceptional back edges could be tricky because
415 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000416 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100417 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000418 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100419 }
420 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000421 return kAnalysisSuccess;
422}
423
424void HLoopInformation::Dump(std::ostream& os) {
425 os << "header: " << header_->GetBlockId() << std::endl;
426 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
427 for (HBasicBlock* block : back_edges_) {
428 os << "back edge: " << block->GetBlockId() << std::endl;
429 }
430 for (HBasicBlock* block : header_->GetPredecessors()) {
431 os << "predecessor: " << block->GetBlockId() << std::endl;
432 }
433 for (uint32_t idx : blocks_.Indexes()) {
434 os << " in loop: " << idx << std::endl;
435 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100436}
437
David Brazdil8d5b8b22015-03-24 10:51:52 +0000438void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000439 // New constants are inserted before the SuspendCheck at the bottom of the
440 // entry block. Note that this method can be called from the graph builder and
441 // the entry block therefore may not end with SuspendCheck->Goto yet.
442 HInstruction* insert_before = nullptr;
443
444 HInstruction* gota = entry_block_->GetLastInstruction();
445 if (gota != nullptr && gota->IsGoto()) {
446 HInstruction* suspend_check = gota->GetPrevious();
447 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
448 insert_before = suspend_check;
449 } else {
450 insert_before = gota;
451 }
452 }
453
454 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000455 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000456 } else {
457 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000458 }
459}
460
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600461HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100462 // For simplicity, don't bother reviving the cached null constant if it is
463 // not null and not in a block. Otherwise, we need to clear the instruction
464 // id and/or any invariants the graph is assuming when adding new instructions.
465 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600466 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000467 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000468 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000469 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000470 if (kIsDebugBuild) {
471 ScopedObjectAccess soa(Thread::Current());
472 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
473 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000474 return cached_null_constant_;
475}
476
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100477HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100478 // For simplicity, don't bother reviving the cached current method if it is
479 // not null and not in a block. Otherwise, we need to clear the instruction
480 // id and/or any invariants the graph is assuming when adding new instructions.
481 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700482 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600483 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
484 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100485 if (entry_block_->GetFirstInstruction() == nullptr) {
486 entry_block_->AddInstruction(cached_current_method_);
487 } else {
488 entry_block_->InsertInstructionBefore(
489 cached_current_method_, entry_block_->GetFirstInstruction());
490 }
491 }
492 return cached_current_method_;
493}
494
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600495HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000496 switch (type) {
497 case Primitive::Type::kPrimBoolean:
498 DCHECK(IsUint<1>(value));
499 FALLTHROUGH_INTENDED;
500 case Primitive::Type::kPrimByte:
501 case Primitive::Type::kPrimChar:
502 case Primitive::Type::kPrimShort:
503 case Primitive::Type::kPrimInt:
504 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600505 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000506
507 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600508 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000509
510 default:
511 LOG(FATAL) << "Unsupported constant type";
512 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000513 }
David Brazdil46e2a392015-03-16 17:31:52 +0000514}
515
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000516void HGraph::CacheFloatConstant(HFloatConstant* constant) {
517 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
518 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
519 cached_float_constants_.Overwrite(value, constant);
520}
521
522void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
523 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
524 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
525 cached_double_constants_.Overwrite(value, constant);
526}
527
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000528void HLoopInformation::Add(HBasicBlock* block) {
529 blocks_.SetBit(block->GetBlockId());
530}
531
David Brazdil46e2a392015-03-16 17:31:52 +0000532void HLoopInformation::Remove(HBasicBlock* block) {
533 blocks_.ClearBit(block->GetBlockId());
534}
535
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100536void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
537 if (blocks_.IsBitSet(block->GetBlockId())) {
538 return;
539 }
540
541 blocks_.SetBit(block->GetBlockId());
542 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000543 for (HBasicBlock* predecessor : block->GetPredecessors()) {
544 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100545 }
546}
547
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000548void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
549 if (blocks_.IsBitSet(block->GetBlockId())) {
550 return;
551 }
552
553 if (block->IsLoopHeader()) {
554 // If we hit a loop header in an irreducible loop, we first check if the
555 // pre header of that loop belongs to the currently analyzed loop. If it does,
556 // then we visit the back edges.
557 // Note that we cannot use GetPreHeader, as the loop may have not been populated
558 // yet.
559 HBasicBlock* pre_header = block->GetPredecessors()[0];
560 PopulateIrreducibleRecursive(pre_header);
561 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
562 blocks_.SetBit(block->GetBlockId());
563 block->SetInLoop(this);
564 HLoopInformation* info = block->GetLoopInformation();
565 for (HBasicBlock* back_edge : info->GetBackEdges()) {
566 PopulateIrreducibleRecursive(back_edge);
567 }
568 }
569 } else {
570 // Visit all predecessors. If one predecessor is part of the loop, this
571 // block is also part of this loop.
572 for (HBasicBlock* predecessor : block->GetPredecessors()) {
573 PopulateIrreducibleRecursive(predecessor);
574 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
575 blocks_.SetBit(block->GetBlockId());
576 block->SetInLoop(this);
577 }
578 }
579 }
580}
581
582void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100583 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000584 // Populate this loop: starting with the back edge, recursively add predecessors
585 // that are not already part of that loop. Set the header as part of the loop
586 // to end the recursion.
587 // This is a recursive implementation of the algorithm described in
588 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
589 blocks_.SetBit(header_->GetBlockId());
590 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100591 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100592 DCHECK(back_edge->GetDominator() != nullptr);
593 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594 irreducible_ = true;
595 header_->GetGraph()->SetHasIrreducibleLoops(true);
596 PopulateIrreducibleRecursive(back_edge);
597 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000598 if (header_->GetGraph()->IsCompilingOsr()) {
599 irreducible_ = true;
600 header_->GetGraph()->SetHasIrreducibleLoops(true);
601 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000602 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100603 }
David Brazdila4b8c212015-05-07 09:59:30 +0100604 }
605}
606
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100607HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 HBasicBlock* block = header_->GetPredecessors()[0];
609 DCHECK(irreducible_ || (block == header_->GetDominator()));
610 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100611}
612
613bool HLoopInformation::Contains(const HBasicBlock& block) const {
614 return blocks_.IsBitSet(block.GetBlockId());
615}
616
617bool HLoopInformation::IsIn(const HLoopInformation& other) const {
618 return other.blocks_.IsBitSet(header_->GetBlockId());
619}
620
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800621bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
622 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700623}
624
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100625size_t HLoopInformation::GetLifetimeEnd() const {
626 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100627 for (HBasicBlock* back_edge : GetBackEdges()) {
628 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100629 }
630 return last_position;
631}
632
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100633bool HBasicBlock::Dominates(HBasicBlock* other) const {
634 // Walk up the dominator tree from `other`, to find out if `this`
635 // is an ancestor.
636 HBasicBlock* current = other;
637 while (current != nullptr) {
638 if (current == this) {
639 return true;
640 }
641 current = current->GetDominator();
642 }
643 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100644}
645
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100646static void UpdateInputsUsers(HInstruction* instruction) {
647 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
648 instruction->InputAt(i)->AddUseAt(instruction, i);
649 }
650 // Environment should be created later.
651 DCHECK(!instruction->HasEnvironment());
652}
653
Roland Levillainccc07a92014-09-16 14:48:16 +0100654void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
655 HInstruction* replacement) {
656 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400657 if (initial->IsControlFlow()) {
658 // We can only replace a control flow instruction with another control flow instruction.
659 DCHECK(replacement->IsControlFlow());
660 DCHECK_EQ(replacement->GetId(), -1);
661 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
662 DCHECK_EQ(initial->GetBlock(), this);
663 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
664 DCHECK(initial->GetUses().IsEmpty());
665 DCHECK(initial->GetEnvUses().IsEmpty());
666 replacement->SetBlock(this);
667 replacement->SetId(GetGraph()->GetNextInstructionId());
668 instructions_.InsertInstructionBefore(replacement, initial);
669 UpdateInputsUsers(replacement);
670 } else {
671 InsertInstructionBefore(replacement, initial);
672 initial->ReplaceWith(replacement);
673 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100674 RemoveInstruction(initial);
675}
676
David Brazdil74eb1b22015-12-14 11:44:01 +0000677void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
678 DCHECK(!cursor->IsPhi());
679 DCHECK(!insn->IsPhi());
680 DCHECK(!insn->IsControlFlow());
681 DCHECK(insn->CanBeMoved());
682 DCHECK(!insn->HasSideEffects());
683
684 HBasicBlock* from_block = insn->GetBlock();
685 HBasicBlock* to_block = cursor->GetBlock();
686 DCHECK(from_block != to_block);
687
688 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
689 insn->SetBlock(to_block);
690 to_block->instructions_.InsertInstructionBefore(insn, cursor);
691}
692
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100693static void Add(HInstructionList* instruction_list,
694 HBasicBlock* block,
695 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000696 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000697 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100698 instruction->SetBlock(block);
699 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100700 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100701 instruction_list->AddInstruction(instruction);
702}
703
704void HBasicBlock::AddInstruction(HInstruction* instruction) {
705 Add(&instructions_, this, instruction);
706}
707
708void HBasicBlock::AddPhi(HPhi* phi) {
709 Add(&phis_, this, phi);
710}
711
David Brazdilc3d743f2015-04-22 13:40:50 +0100712void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
713 DCHECK(!cursor->IsPhi());
714 DCHECK(!instruction->IsPhi());
715 DCHECK_EQ(instruction->GetId(), -1);
716 DCHECK_NE(cursor->GetId(), -1);
717 DCHECK_EQ(cursor->GetBlock(), this);
718 DCHECK(!instruction->IsControlFlow());
719 instruction->SetBlock(this);
720 instruction->SetId(GetGraph()->GetNextInstructionId());
721 UpdateInputsUsers(instruction);
722 instructions_.InsertInstructionBefore(instruction, cursor);
723}
724
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100725void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
726 DCHECK(!cursor->IsPhi());
727 DCHECK(!instruction->IsPhi());
728 DCHECK_EQ(instruction->GetId(), -1);
729 DCHECK_NE(cursor->GetId(), -1);
730 DCHECK_EQ(cursor->GetBlock(), this);
731 DCHECK(!instruction->IsControlFlow());
732 DCHECK(!cursor->IsControlFlow());
733 instruction->SetBlock(this);
734 instruction->SetId(GetGraph()->GetNextInstructionId());
735 UpdateInputsUsers(instruction);
736 instructions_.InsertInstructionAfter(instruction, cursor);
737}
738
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100739void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
740 DCHECK_EQ(phi->GetId(), -1);
741 DCHECK_NE(cursor->GetId(), -1);
742 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100743 phi->SetBlock(this);
744 phi->SetId(GetGraph()->GetNextInstructionId());
745 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100746 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100747}
748
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100749static void Remove(HInstructionList* instruction_list,
750 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000751 HInstruction* instruction,
752 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100753 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100754 instruction->SetBlock(nullptr);
755 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000756 if (ensure_safety) {
757 DCHECK(instruction->GetUses().IsEmpty());
758 DCHECK(instruction->GetEnvUses().IsEmpty());
759 RemoveAsUser(instruction);
760 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100761}
762
David Brazdil1abb4192015-02-17 18:33:36 +0000763void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100764 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000765 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100766}
767
David Brazdil1abb4192015-02-17 18:33:36 +0000768void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
769 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100770}
771
David Brazdilc7508e92015-04-27 13:28:57 +0100772void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
773 if (instruction->IsPhi()) {
774 RemovePhi(instruction->AsPhi(), ensure_safety);
775 } else {
776 RemoveInstruction(instruction, ensure_safety);
777 }
778}
779
Vladimir Marko71bf8092015-09-15 15:33:14 +0100780void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
781 for (size_t i = 0; i < locals.size(); i++) {
782 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100783 SetRawEnvAt(i, instruction);
784 if (instruction != nullptr) {
785 instruction->AddEnvUseAt(this, i);
786 }
787 }
788}
789
David Brazdiled596192015-01-23 10:39:45 +0000790void HEnvironment::CopyFrom(HEnvironment* env) {
791 for (size_t i = 0; i < env->Size(); i++) {
792 HInstruction* instruction = env->GetInstructionAt(i);
793 SetRawEnvAt(i, instruction);
794 if (instruction != nullptr) {
795 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100796 }
David Brazdiled596192015-01-23 10:39:45 +0000797 }
798}
799
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700800void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
801 HBasicBlock* loop_header) {
802 DCHECK(loop_header->IsLoopHeader());
803 for (size_t i = 0; i < env->Size(); i++) {
804 HInstruction* instruction = env->GetInstructionAt(i);
805 SetRawEnvAt(i, instruction);
806 if (instruction == nullptr) {
807 continue;
808 }
809 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
810 // At the end of the loop pre-header, the corresponding value for instruction
811 // is the first input of the phi.
812 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700813 SetRawEnvAt(i, initial);
814 initial->AddEnvUseAt(this, i);
815 } else {
816 instruction->AddEnvUseAt(this, i);
817 }
818 }
819}
820
David Brazdil1abb4192015-02-17 18:33:36 +0000821void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100822 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000823 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100824}
825
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000826HInstruction::InstructionKind HInstruction::GetKind() const {
827 return GetKindInternal();
828}
829
Calin Juravle77520bc2015-01-12 18:45:46 +0000830HInstruction* HInstruction::GetNextDisregardingMoves() const {
831 HInstruction* next = GetNext();
832 while (next != nullptr && next->IsParallelMove()) {
833 next = next->GetNext();
834 }
835 return next;
836}
837
838HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
839 HInstruction* previous = GetPrevious();
840 while (previous != nullptr && previous->IsParallelMove()) {
841 previous = previous->GetPrevious();
842 }
843 return previous;
844}
845
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100846void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000847 if (first_instruction_ == nullptr) {
848 DCHECK(last_instruction_ == nullptr);
849 first_instruction_ = last_instruction_ = instruction;
850 } else {
851 last_instruction_->next_ = instruction;
852 instruction->previous_ = last_instruction_;
853 last_instruction_ = instruction;
854 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000855}
856
David Brazdilc3d743f2015-04-22 13:40:50 +0100857void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
858 DCHECK(Contains(cursor));
859 if (cursor == first_instruction_) {
860 cursor->previous_ = instruction;
861 instruction->next_ = cursor;
862 first_instruction_ = instruction;
863 } else {
864 instruction->previous_ = cursor->previous_;
865 instruction->next_ = cursor;
866 cursor->previous_ = instruction;
867 instruction->previous_->next_ = instruction;
868 }
869}
870
871void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
872 DCHECK(Contains(cursor));
873 if (cursor == last_instruction_) {
874 cursor->next_ = instruction;
875 instruction->previous_ = cursor;
876 last_instruction_ = instruction;
877 } else {
878 instruction->next_ = cursor->next_;
879 instruction->previous_ = cursor;
880 cursor->next_ = instruction;
881 instruction->next_->previous_ = instruction;
882 }
883}
884
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100885void HInstructionList::RemoveInstruction(HInstruction* instruction) {
886 if (instruction->previous_ != nullptr) {
887 instruction->previous_->next_ = instruction->next_;
888 }
889 if (instruction->next_ != nullptr) {
890 instruction->next_->previous_ = instruction->previous_;
891 }
892 if (instruction == first_instruction_) {
893 first_instruction_ = instruction->next_;
894 }
895 if (instruction == last_instruction_) {
896 last_instruction_ = instruction->previous_;
897 }
898}
899
Roland Levillain6b469232014-09-25 10:10:38 +0100900bool HInstructionList::Contains(HInstruction* instruction) const {
901 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
902 if (it.Current() == instruction) {
903 return true;
904 }
905 }
906 return false;
907}
908
Roland Levillainccc07a92014-09-16 14:48:16 +0100909bool HInstructionList::FoundBefore(const HInstruction* instruction1,
910 const HInstruction* instruction2) const {
911 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
912 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
913 if (it.Current() == instruction1) {
914 return true;
915 }
916 if (it.Current() == instruction2) {
917 return false;
918 }
919 }
920 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
921 return true;
922}
923
Roland Levillain6c82d402014-10-13 16:10:27 +0100924bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
925 if (other_instruction == this) {
926 // An instruction does not strictly dominate itself.
927 return false;
928 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100929 HBasicBlock* block = GetBlock();
930 HBasicBlock* other_block = other_instruction->GetBlock();
931 if (block != other_block) {
932 return GetBlock()->Dominates(other_instruction->GetBlock());
933 } else {
934 // If both instructions are in the same block, ensure this
935 // instruction comes before `other_instruction`.
936 if (IsPhi()) {
937 if (!other_instruction->IsPhi()) {
938 // Phis appear before non phi-instructions so this instruction
939 // dominates `other_instruction`.
940 return true;
941 } else {
942 // There is no order among phis.
943 LOG(FATAL) << "There is no dominance between phis of a same block.";
944 return false;
945 }
946 } else {
947 // `this` is not a phi.
948 if (other_instruction->IsPhi()) {
949 // Phis appear before non phi-instructions so this instruction
950 // does not dominate `other_instruction`.
951 return false;
952 } else {
953 // Check whether this instruction comes before
954 // `other_instruction` in the instruction list.
955 return block->GetInstructions().FoundBefore(this, other_instruction);
956 }
957 }
958 }
959}
960
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000961void HInstruction::RemoveEnvironment() {
962 RemoveEnvironmentUses(this);
963 environment_ = nullptr;
964}
965
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100966void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100967 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000968 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
969 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100970 HInstruction* user = current->GetUser();
971 size_t input_index = current->GetIndex();
972 user->SetRawInputAt(input_index, other);
973 other->AddUseAt(user, input_index);
974 }
975
David Brazdiled596192015-01-23 10:39:45 +0000976 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
977 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100978 HEnvironment* user = current->GetUser();
979 size_t input_index = current->GetIndex();
980 user->SetRawEnvAt(input_index, other);
981 other->AddEnvUseAt(user, input_index);
982 }
983
David Brazdiled596192015-01-23 10:39:45 +0000984 uses_.Clear();
985 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100986}
987
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100988void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000989 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100990 SetRawInputAt(index, replacement);
991 replacement->AddUseAt(this, index);
992}
993
Nicolas Geoffray39468442014-09-02 15:17:15 +0100994size_t HInstruction::EnvironmentSize() const {
995 return HasEnvironment() ? environment_->Size() : 0;
996}
997
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100998void HPhi::AddInput(HInstruction* input) {
999 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001000 inputs_.push_back(HUserRecord<HInstruction*>(input));
1001 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001002}
1003
David Brazdil2d7352b2015-04-20 14:52:42 +01001004void HPhi::RemoveInputAt(size_t index) {
1005 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001006 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001007 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001008 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001009 InputRecordAt(i).GetUseNode()->SetIndex(i);
1010 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001011}
1012
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001013#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001014void H##name::Accept(HGraphVisitor* visitor) { \
1015 visitor->Visit##name(this); \
1016}
1017
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001018FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001019
1020#undef DEFINE_ACCEPT
1021
1022void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001023 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1024 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001025 if (block != nullptr) {
1026 VisitBasicBlock(block);
1027 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001028 }
1029}
1030
Roland Levillain633021e2014-10-01 14:12:25 +01001031void HGraphVisitor::VisitReversePostOrder() {
1032 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1033 VisitBasicBlock(it.Current());
1034 }
1035}
1036
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001037void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001038 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039 it.Current()->Accept(this);
1040 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001041 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001042 it.Current()->Accept(this);
1043 }
1044}
1045
Mark Mendelle82549b2015-05-06 10:55:34 -04001046HConstant* HTypeConversion::TryStaticEvaluation() const {
1047 HGraph* graph = GetBlock()->GetGraph();
1048 if (GetInput()->IsIntConstant()) {
1049 int32_t value = GetInput()->AsIntConstant()->GetValue();
1050 switch (GetResultType()) {
1051 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001052 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001053 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001054 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001055 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001056 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001057 default:
1058 return nullptr;
1059 }
1060 } else if (GetInput()->IsLongConstant()) {
1061 int64_t value = GetInput()->AsLongConstant()->GetValue();
1062 switch (GetResultType()) {
1063 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001064 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001065 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001066 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001067 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001068 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001069 default:
1070 return nullptr;
1071 }
1072 } else if (GetInput()->IsFloatConstant()) {
1073 float value = GetInput()->AsFloatConstant()->GetValue();
1074 switch (GetResultType()) {
1075 case Primitive::kPrimInt:
1076 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001077 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001078 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001079 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001080 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001081 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1082 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001083 case Primitive::kPrimLong:
1084 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001085 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001086 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001087 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001088 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001089 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1090 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001091 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001092 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001093 default:
1094 return nullptr;
1095 }
1096 } else if (GetInput()->IsDoubleConstant()) {
1097 double value = GetInput()->AsDoubleConstant()->GetValue();
1098 switch (GetResultType()) {
1099 case Primitive::kPrimInt:
1100 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001102 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001103 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001104 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1106 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001107 case Primitive::kPrimLong:
1108 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001110 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001111 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001112 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001113 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1114 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001115 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001116 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001117 default:
1118 return nullptr;
1119 }
1120 }
1121 return nullptr;
1122}
1123
Roland Levillain9240d6a2014-10-20 16:47:04 +01001124HConstant* HUnaryOperation::TryStaticEvaluation() const {
1125 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001126 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001127 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001128 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001129 } else if (kEnableFloatingPointStaticEvaluation) {
1130 if (GetInput()->IsFloatConstant()) {
1131 return Evaluate(GetInput()->AsFloatConstant());
1132 } else if (GetInput()->IsDoubleConstant()) {
1133 return Evaluate(GetInput()->AsDoubleConstant());
1134 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001135 }
1136 return nullptr;
1137}
1138
1139HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001140 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1141 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001142 } else if (GetLeft()->IsLongConstant()) {
1143 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001144 // The binop(long, int) case is only valid for shifts and rotations.
1145 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001146 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1147 } else if (GetRight()->IsLongConstant()) {
1148 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001149 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001150 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001151 // The binop(null, null) case is only valid for equal and not-equal conditions.
1152 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001153 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001154 } else if (kEnableFloatingPointStaticEvaluation) {
1155 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1156 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1157 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1158 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1159 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001160 }
1161 return nullptr;
1162}
Dave Allison20dfc792014-06-16 20:44:29 -07001163
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001164HConstant* HBinaryOperation::GetConstantRight() const {
1165 if (GetRight()->IsConstant()) {
1166 return GetRight()->AsConstant();
1167 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1168 return GetLeft()->AsConstant();
1169 } else {
1170 return nullptr;
1171 }
1172}
1173
1174// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001175// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001176HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1177 HInstruction* most_constant_right = GetConstantRight();
1178 if (most_constant_right == nullptr) {
1179 return nullptr;
1180 } else if (most_constant_right == GetLeft()) {
1181 return GetRight();
1182 } else {
1183 return GetLeft();
1184 }
1185}
1186
Roland Levillain31dd3d62016-02-16 12:21:02 +00001187std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1188 switch (rhs) {
1189 case ComparisonBias::kNoBias:
1190 return os << "no_bias";
1191 case ComparisonBias::kGtBias:
1192 return os << "gt_bias";
1193 case ComparisonBias::kLtBias:
1194 return os << "lt_bias";
1195 default:
1196 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1197 UNREACHABLE();
1198 }
1199}
1200
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001201bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1202 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001203}
1204
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001205bool HInstruction::Equals(HInstruction* other) const {
1206 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001207 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001208 if (!InstructionDataEquals(other)) return false;
1209 if (GetType() != other->GetType()) return false;
1210 if (InputCount() != other->InputCount()) return false;
1211
1212 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1213 if (InputAt(i) != other->InputAt(i)) return false;
1214 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001215 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001216 return true;
1217}
1218
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001219std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1220#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1221 switch (rhs) {
1222 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1223 default:
1224 os << "Unknown instruction kind " << static_cast<int>(rhs);
1225 break;
1226 }
1227#undef DECLARE_CASE
1228 return os;
1229}
1230
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001231void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001232 next_->previous_ = previous_;
1233 if (previous_ != nullptr) {
1234 previous_->next_ = next_;
1235 }
1236 if (block_->instructions_.first_instruction_ == this) {
1237 block_->instructions_.first_instruction_ = next_;
1238 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001239 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001240
1241 previous_ = cursor->previous_;
1242 if (previous_ != nullptr) {
1243 previous_->next_ = this;
1244 }
1245 next_ = cursor;
1246 cursor->previous_ = this;
1247 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001248
1249 if (block_->instructions_.first_instruction_ == cursor) {
1250 block_->instructions_.first_instruction_ = this;
1251 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001252}
1253
Vladimir Markofb337ea2015-11-25 15:25:10 +00001254void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1255 DCHECK(!CanThrow());
1256 DCHECK(!HasSideEffects());
1257 DCHECK(!HasEnvironmentUses());
1258 DCHECK(HasNonEnvironmentUses());
1259 DCHECK(!IsPhi()); // Makes no sense for Phi.
1260 DCHECK_EQ(InputCount(), 0u);
1261
1262 // Find the target block.
1263 HUseIterator<HInstruction*> uses_it(GetUses());
1264 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1265 uses_it.Advance();
1266 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1267 uses_it.Advance();
1268 }
1269 if (!uses_it.Done()) {
1270 // This instruction has uses in two or more blocks. Find the common dominator.
1271 CommonDominator finder(target_block);
1272 for (; !uses_it.Done(); uses_it.Advance()) {
1273 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1274 }
1275 target_block = finder.Get();
1276 DCHECK(target_block != nullptr);
1277 }
1278 // Move to the first dominator not in a loop.
1279 while (target_block->IsInLoop()) {
1280 target_block = target_block->GetDominator();
1281 DCHECK(target_block != nullptr);
1282 }
1283
1284 // Find insertion position.
1285 HInstruction* insert_pos = nullptr;
1286 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1287 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1288 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1289 insert_pos = uses_it2.Current()->GetUser();
1290 }
1291 }
1292 if (insert_pos == nullptr) {
1293 // No user in `target_block`, insert before the control flow instruction.
1294 insert_pos = target_block->GetLastInstruction();
1295 DCHECK(insert_pos->IsControlFlow());
1296 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1297 if (insert_pos->IsIf()) {
1298 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1299 if (if_input == insert_pos->GetPrevious()) {
1300 insert_pos = if_input;
1301 }
1302 }
1303 }
1304 MoveBefore(insert_pos);
1305}
1306
David Brazdilfc6a86a2015-06-26 10:33:45 +00001307HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001308 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001309 DCHECK_EQ(cursor->GetBlock(), this);
1310
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001311 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1312 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001313 new_block->instructions_.first_instruction_ = cursor;
1314 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1315 instructions_.last_instruction_ = cursor->previous_;
1316 if (cursor->previous_ == nullptr) {
1317 instructions_.first_instruction_ = nullptr;
1318 } else {
1319 cursor->previous_->next_ = nullptr;
1320 cursor->previous_ = nullptr;
1321 }
1322
1323 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001324 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001325
Vladimir Marko60584552015-09-03 13:35:12 +00001326 for (HBasicBlock* successor : GetSuccessors()) {
1327 new_block->successors_.push_back(successor);
1328 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001329 }
Vladimir Marko60584552015-09-03 13:35:12 +00001330 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001331 AddSuccessor(new_block);
1332
David Brazdil56e1acc2015-06-30 15:41:36 +01001333 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001334 return new_block;
1335}
1336
David Brazdild7558da2015-09-22 13:04:14 +01001337HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001338 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001339 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1340
1341 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1342
1343 for (HBasicBlock* predecessor : GetPredecessors()) {
1344 new_block->predecessors_.push_back(predecessor);
1345 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1346 }
1347 predecessors_.clear();
1348 AddPredecessor(new_block);
1349
1350 GetGraph()->AddBlock(new_block);
1351 return new_block;
1352}
1353
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001354HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1355 DCHECK_EQ(cursor->GetBlock(), this);
1356
1357 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1358 cursor->GetDexPc());
1359 new_block->instructions_.first_instruction_ = cursor;
1360 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1361 instructions_.last_instruction_ = cursor->previous_;
1362 if (cursor->previous_ == nullptr) {
1363 instructions_.first_instruction_ = nullptr;
1364 } else {
1365 cursor->previous_->next_ = nullptr;
1366 cursor->previous_ = nullptr;
1367 }
1368
1369 new_block->instructions_.SetBlockOfInstructions(new_block);
1370
1371 for (HBasicBlock* successor : GetSuccessors()) {
1372 new_block->successors_.push_back(successor);
1373 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1374 }
1375 successors_.clear();
1376
1377 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1378 dominated->dominator_ = new_block;
1379 new_block->dominated_blocks_.push_back(dominated);
1380 }
1381 dominated_blocks_.clear();
1382 return new_block;
1383}
1384
1385HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001386 DCHECK(!cursor->IsControlFlow());
1387 DCHECK_NE(instructions_.last_instruction_, cursor);
1388 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001389
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001390 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1391 new_block->instructions_.first_instruction_ = cursor->GetNext();
1392 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1393 cursor->next_->previous_ = nullptr;
1394 cursor->next_ = nullptr;
1395 instructions_.last_instruction_ = cursor;
1396
1397 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001398 for (HBasicBlock* successor : GetSuccessors()) {
1399 new_block->successors_.push_back(successor);
1400 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001401 }
Vladimir Marko60584552015-09-03 13:35:12 +00001402 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001403
Vladimir Marko60584552015-09-03 13:35:12 +00001404 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001406 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001407 }
Vladimir Marko60584552015-09-03 13:35:12 +00001408 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001409 return new_block;
1410}
1411
David Brazdilec16f792015-08-19 15:04:01 +01001412const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001413 if (EndsWithTryBoundary()) {
1414 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1415 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001416 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001417 return try_boundary;
1418 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001419 DCHECK(IsTryBlock());
1420 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001421 return nullptr;
1422 }
David Brazdilec16f792015-08-19 15:04:01 +01001423 } else if (IsTryBlock()) {
1424 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001425 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001426 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001427 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001428}
1429
David Brazdild7558da2015-09-22 13:04:14 +01001430bool HBasicBlock::HasThrowingInstructions() const {
1431 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1432 if (it.Current()->CanThrow()) {
1433 return true;
1434 }
1435 }
1436 return false;
1437}
1438
David Brazdilfc6a86a2015-06-26 10:33:45 +00001439static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1440 return block.GetPhis().IsEmpty()
1441 && !block.GetInstructions().IsEmpty()
1442 && block.GetFirstInstruction() == block.GetLastInstruction();
1443}
1444
David Brazdil46e2a392015-03-16 17:31:52 +00001445bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001446 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1447}
1448
1449bool HBasicBlock::IsSingleTryBoundary() const {
1450 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001451}
1452
David Brazdil8d5b8b22015-03-24 10:51:52 +00001453bool HBasicBlock::EndsWithControlFlowInstruction() const {
1454 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1455}
1456
David Brazdilb2bd1c52015-03-25 11:17:37 +00001457bool HBasicBlock::EndsWithIf() const {
1458 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1459}
1460
David Brazdilffee3d32015-07-06 11:48:53 +01001461bool HBasicBlock::EndsWithTryBoundary() const {
1462 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1463}
1464
David Brazdilb2bd1c52015-03-25 11:17:37 +00001465bool HBasicBlock::HasSinglePhi() const {
1466 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1467}
1468
David Brazdild26a4112015-11-10 11:07:31 +00001469ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1470 if (EndsWithTryBoundary()) {
1471 // The normal-flow successor of HTryBoundary is always stored at index zero.
1472 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1473 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1474 } else {
1475 // All successors of blocks not ending with TryBoundary are normal.
1476 return ArrayRef<HBasicBlock* const>(successors_);
1477 }
1478}
1479
1480ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1481 if (EndsWithTryBoundary()) {
1482 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1483 } else {
1484 // Blocks not ending with TryBoundary do not have exceptional successors.
1485 return ArrayRef<HBasicBlock* const>();
1486 }
1487}
1488
David Brazdilffee3d32015-07-06 11:48:53 +01001489bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001490 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1491 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1492
1493 size_t length = handlers1.size();
1494 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001495 return false;
1496 }
1497
David Brazdilb618ade2015-07-29 10:31:29 +01001498 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001499 for (size_t i = 0; i < length; ++i) {
1500 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001501 return false;
1502 }
1503 }
1504 return true;
1505}
1506
David Brazdil2d7352b2015-04-20 14:52:42 +01001507size_t HInstructionList::CountSize() const {
1508 size_t size = 0;
1509 HInstruction* current = first_instruction_;
1510 for (; current != nullptr; current = current->GetNext()) {
1511 size++;
1512 }
1513 return size;
1514}
1515
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001516void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1517 for (HInstruction* current = first_instruction_;
1518 current != nullptr;
1519 current = current->GetNext()) {
1520 current->SetBlock(block);
1521 }
1522}
1523
1524void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1525 DCHECK(Contains(cursor));
1526 if (!instruction_list.IsEmpty()) {
1527 if (cursor == last_instruction_) {
1528 last_instruction_ = instruction_list.last_instruction_;
1529 } else {
1530 cursor->next_->previous_ = instruction_list.last_instruction_;
1531 }
1532 instruction_list.last_instruction_->next_ = cursor->next_;
1533 cursor->next_ = instruction_list.first_instruction_;
1534 instruction_list.first_instruction_->previous_ = cursor;
1535 }
1536}
1537
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001538void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1539 DCHECK(Contains(cursor));
1540 if (!instruction_list.IsEmpty()) {
1541 if (cursor == first_instruction_) {
1542 first_instruction_ = instruction_list.first_instruction_;
1543 } else {
1544 cursor->previous_->next_ = instruction_list.first_instruction_;
1545 }
1546 instruction_list.last_instruction_->next_ = cursor;
1547 instruction_list.first_instruction_->previous_ = cursor->previous_;
1548 cursor->previous_ = instruction_list.last_instruction_;
1549 }
1550}
1551
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001552void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001553 if (IsEmpty()) {
1554 first_instruction_ = instruction_list.first_instruction_;
1555 last_instruction_ = instruction_list.last_instruction_;
1556 } else {
1557 AddAfter(last_instruction_, instruction_list);
1558 }
1559}
1560
David Brazdil04ff4e82015-12-10 13:54:52 +00001561// Should be called on instructions in a dead block in post order. This method
1562// assumes `insn` has been removed from all users with the exception of catch
1563// phis because of missing exceptional edges in the graph. It removes the
1564// instruction from catch phi uses, together with inputs of other catch phis in
1565// the catch block at the same index, as these must be dead too.
1566static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1567 DCHECK(!insn->HasEnvironmentUses());
1568 while (insn->HasNonEnvironmentUses()) {
1569 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1570 size_t use_index = use->GetIndex();
1571 HBasicBlock* user_block = use->GetUser()->GetBlock();
1572 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1573 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1574 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1575 }
1576 }
1577}
1578
David Brazdil2d7352b2015-04-20 14:52:42 +01001579void HBasicBlock::DisconnectAndDelete() {
1580 // Dominators must be removed after all the blocks they dominate. This way
1581 // a loop header is removed last, a requirement for correct loop information
1582 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001583 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001584
David Brazdil9eeebf62016-03-24 11:18:15 +00001585 // The following steps gradually remove the block from all its dependants in
1586 // post order (b/27683071).
1587
1588 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1589 // We need to do this before step (4) which destroys the predecessor list.
1590 HBasicBlock* loop_update_start = this;
1591 if (IsLoopHeader()) {
1592 HLoopInformation* loop_info = GetLoopInformation();
1593 // All other blocks in this loop should have been removed because the header
1594 // was their dominator.
1595 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1596 DCHECK(!loop_info->IsIrreducible());
1597 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1598 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1599 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001600 }
1601
David Brazdil9eeebf62016-03-24 11:18:15 +00001602 // (2) Disconnect the block from its successors and update their phis.
1603 for (HBasicBlock* successor : successors_) {
1604 // Delete this block from the list of predecessors.
1605 size_t this_index = successor->GetPredecessorIndexOf(this);
1606 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1607
1608 // Check that `successor` has other predecessors, otherwise `this` is the
1609 // dominator of `successor` which violates the order DCHECKed at the top.
1610 DCHECK(!successor->predecessors_.empty());
1611
1612 // Remove this block's entries in the successor's phis. Skip exceptional
1613 // successors because catch phi inputs do not correspond to predecessor
1614 // blocks but throwing instructions. The inputs of the catch phis will be
1615 // updated in step (3).
1616 if (!successor->IsCatchBlock()) {
1617 if (successor->predecessors_.size() == 1u) {
1618 // The successor has just one predecessor left. Replace phis with the only
1619 // remaining input.
1620 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1621 HPhi* phi = phi_it.Current()->AsPhi();
1622 phi->ReplaceWith(phi->InputAt(1 - this_index));
1623 successor->RemovePhi(phi);
1624 }
1625 } else {
1626 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1627 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1628 }
1629 }
1630 }
1631 }
1632 successors_.clear();
1633
1634 // (3) Remove instructions and phis. Instructions should have no remaining uses
1635 // except in catch phis. If an instruction is used by a catch phi at `index`,
1636 // remove `index`-th input of all phis in the catch block since they are
1637 // guaranteed dead. Note that we may miss dead inputs this way but the
1638 // graph will always remain consistent.
1639 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1640 HInstruction* insn = it.Current();
1641 RemoveUsesOfDeadInstruction(insn);
1642 RemoveInstruction(insn);
1643 }
1644 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1645 HPhi* insn = it.Current()->AsPhi();
1646 RemoveUsesOfDeadInstruction(insn);
1647 RemovePhi(insn);
1648 }
1649
1650 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001651 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001652 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001653 // We should not see any back edges as they would have been removed by step (3).
1654 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1655
David Brazdil2d7352b2015-04-20 14:52:42 +01001656 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001657 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1658 // This block is the only normal-flow successor of the TryBoundary which
1659 // makes `predecessor` dead. Since DCE removes blocks in post order,
1660 // exception handlers of this TryBoundary were already visited and any
1661 // remaining handlers therefore must be live. We remove `predecessor` from
1662 // their list of predecessors.
1663 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1664 while (predecessor->GetSuccessors().size() > 1) {
1665 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1666 DCHECK(handler->IsCatchBlock());
1667 predecessor->RemoveSuccessor(handler);
1668 handler->RemovePredecessor(predecessor);
1669 }
1670 }
1671
David Brazdil2d7352b2015-04-20 14:52:42 +01001672 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001673 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1674 if (num_pred_successors == 1u) {
1675 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001676 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1677 // successor. Replace those with a HGoto.
1678 DCHECK(last_instruction->IsIf() ||
1679 last_instruction->IsPackedSwitch() ||
1680 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001681 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001682 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001683 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001684 // The predecessor has no remaining successors and therefore must be dead.
1685 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001686 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001687 predecessor->RemoveInstruction(last_instruction);
1688 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001689 // There are multiple successors left. The removed block might be a successor
1690 // of a PackedSwitch which will be completely removed (perhaps replaced with
1691 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1692 // case, leave `last_instruction` as is for now.
1693 DCHECK(last_instruction->IsPackedSwitch() ||
1694 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001695 }
David Brazdil46e2a392015-03-16 17:31:52 +00001696 }
Vladimir Marko60584552015-09-03 13:35:12 +00001697 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001698
David Brazdil9eeebf62016-03-24 11:18:15 +00001699 // (5) Remove the block from all loops it is included in. Skip the inner-most
1700 // loop if this is the loop header (see definition of `loop_update_start`)
1701 // because the loop header's predecessor list has been destroyed in step (4).
1702 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1703 HLoopInformation* loop_info = it.Current();
1704 loop_info->Remove(this);
1705 if (loop_info->IsBackEdge(*this)) {
1706 // If this was the last back edge of the loop, we deliberately leave the
1707 // loop in an inconsistent state and will fail GraphChecker unless the
1708 // entire loop is removed during the pass.
1709 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001710 }
1711 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001712
David Brazdil9eeebf62016-03-24 11:18:15 +00001713 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 dominator_->RemoveDominatedBlock(this);
1715 SetDominator(nullptr);
1716
David Brazdil9eeebf62016-03-24 11:18:15 +00001717 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001718 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001719 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001720}
1721
1722void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001723 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001724 DCHECK(ContainsElement(dominated_blocks_, other));
1725 DCHECK_EQ(GetSingleSuccessor(), other);
1726 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001727 DCHECK(other->GetPhis().IsEmpty());
1728
David Brazdil2d7352b2015-04-20 14:52:42 +01001729 // Move instructions from `other` to `this`.
1730 DCHECK(EndsWithControlFlowInstruction());
1731 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001732 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001733 other->instructions_.SetBlockOfInstructions(this);
1734 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001735
David Brazdil2d7352b2015-04-20 14:52:42 +01001736 // Remove `other` from the loops it is included in.
1737 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1738 HLoopInformation* loop_info = it.Current();
1739 loop_info->Remove(other);
1740 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001741 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001742 }
1743 }
1744
1745 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001746 successors_.clear();
1747 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001748 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001749 successor->ReplacePredecessor(other, this);
1750 }
1751
David Brazdil2d7352b2015-04-20 14:52:42 +01001752 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001753 RemoveDominatedBlock(other);
1754 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1755 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001756 dominated->SetDominator(this);
1757 }
Vladimir Marko60584552015-09-03 13:35:12 +00001758 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001759 other->dominator_ = nullptr;
1760
1761 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001762 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001763
1764 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001765 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001766 other->SetGraph(nullptr);
1767}
1768
1769void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1770 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001771 DCHECK(GetDominatedBlocks().empty());
1772 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001773 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001774 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001775 DCHECK(other->GetPhis().IsEmpty());
1776 DCHECK(!other->IsInLoop());
1777
1778 // Move instructions from `other` to `this`.
1779 instructions_.Add(other->GetInstructions());
1780 other->instructions_.SetBlockOfInstructions(this);
1781
1782 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001783 successors_.clear();
1784 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001785 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 successor->ReplacePredecessor(other, this);
1787 }
1788
1789 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001790 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1791 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001792 dominated->SetDominator(this);
1793 }
Vladimir Marko60584552015-09-03 13:35:12 +00001794 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001795 other->dominator_ = nullptr;
1796 other->graph_ = nullptr;
1797}
1798
1799void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001800 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001801 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001802 predecessor->ReplaceSuccessor(this, other);
1803 }
Vladimir Marko60584552015-09-03 13:35:12 +00001804 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001805 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001806 successor->ReplacePredecessor(this, other);
1807 }
Vladimir Marko60584552015-09-03 13:35:12 +00001808 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1809 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001810 }
1811 GetDominator()->ReplaceDominatedBlock(this, other);
1812 other->SetDominator(GetDominator());
1813 dominator_ = nullptr;
1814 graph_ = nullptr;
1815}
1816
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001817void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001818 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001819 DCHECK(block->GetSuccessors().empty());
1820 DCHECK(block->GetPredecessors().empty());
1821 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001822 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001823 DCHECK(block->GetInstructions().IsEmpty());
1824 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001825
David Brazdilc7af85d2015-05-26 12:05:55 +01001826 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001827 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001828 }
1829
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001830 RemoveElement(reverse_post_order_, block);
1831 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001832 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001833}
1834
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001835void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1836 HBasicBlock* reference,
1837 bool replace_if_back_edge) {
1838 if (block->IsLoopHeader()) {
1839 // Clear the information of which blocks are contained in that loop. Since the
1840 // information is stored as a bit vector based on block ids, we have to update
1841 // it, as those block ids were specific to the callee graph and we are now adding
1842 // these blocks to the caller graph.
1843 block->GetLoopInformation()->ClearAllBlocks();
1844 }
1845
1846 // If not already in a loop, update the loop information.
1847 if (!block->IsInLoop()) {
1848 block->SetLoopInformation(reference->GetLoopInformation());
1849 }
1850
1851 // If the block is in a loop, update all its outward loops.
1852 HLoopInformation* loop_info = block->GetLoopInformation();
1853 if (loop_info != nullptr) {
1854 for (HLoopInformationOutwardIterator loop_it(*block);
1855 !loop_it.Done();
1856 loop_it.Advance()) {
1857 loop_it.Current()->Add(block);
1858 }
1859 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1860 loop_info->ReplaceBackEdge(reference, block);
1861 }
1862 }
1863
1864 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1865 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1866 ? reference->GetTryCatchInformation()
1867 : nullptr;
1868 block->SetTryCatchInformation(try_catch_info);
1869}
1870
Calin Juravle2e768302015-07-28 14:41:11 +00001871HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001872 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001873 // Update the environments in this graph to have the invoke's environment
1874 // as parent.
1875 {
1876 HReversePostOrderIterator it(*this);
1877 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1878 for (; !it.Done(); it.Advance()) {
1879 HBasicBlock* block = it.Current();
1880 for (HInstructionIterator instr_it(block->GetInstructions());
1881 !instr_it.Done();
1882 instr_it.Advance()) {
1883 HInstruction* current = instr_it.Current();
1884 if (current->NeedsEnvironment()) {
1885 current->GetEnvironment()->SetAndCopyParentChain(
1886 outer_graph->GetArena(), invoke->GetEnvironment());
1887 }
1888 }
1889 }
1890 }
1891 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1892 if (HasBoundsChecks()) {
1893 outer_graph->SetHasBoundsChecks(true);
1894 }
1895
Calin Juravle2e768302015-07-28 14:41:11 +00001896 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001897 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001898 // Simple case of an entry block, a body block, and an exit block.
1899 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001900 HBasicBlock* body = GetBlocks()[1];
1901 DCHECK(GetBlocks()[0]->IsEntryBlock());
1902 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001904 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001905 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001906
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001907 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1908 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001909 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001910
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001911 // Replace the invoke with the return value of the inlined graph.
1912 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001913 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001914 } else {
1915 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001916 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001917
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001919 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001920 // Need to inline multiple blocks. We split `invoke`'s block
1921 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001922 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001923 // with the second half.
1924 ArenaAllocator* allocator = outer_graph->GetArena();
1925 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001926 // Note that we split before the invoke only to simplify polymorphic inlining.
1927 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001928
Vladimir Markoec7802a2015-10-01 20:57:57 +01001929 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001931 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001932 exit_block_->ReplaceWith(to);
1933
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001934 // Update the meta information surrounding blocks:
1935 // (1) the graph they are now in,
1936 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001937 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001938 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001939 // Note that we do not need to update catch phi inputs because they
1940 // correspond to the register file of the outer method which the inlinee
1941 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001942
1943 // We don't add the entry block, the exit block, and the first block, which
1944 // has been merged with `at`.
1945 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1946
1947 // We add the `to` block.
1948 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001949 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001950 + kNumberOfNewBlocksInCaller;
1951
1952 // Find the location of `at` in the outer graph's reverse post order. The new
1953 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001954 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001955 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1956
David Brazdil95177982015-10-30 12:56:58 -05001957 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1958 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001959 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1960 HBasicBlock* current = it.Current();
1961 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001962 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001963 DCHECK(current->GetGraph() == this);
1964 current->SetGraph(outer_graph);
1965 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001966 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001967 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001968 }
1969 }
1970
David Brazdil95177982015-10-30 12:56:58 -05001971 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001972 to->SetGraph(outer_graph);
1973 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001974 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001975 // Only `to` can become a back edge, as the inlined blocks
1976 // are predecessors of `to`.
1977 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001978
David Brazdil3f523062016-02-29 16:53:33 +00001979 // Update all predecessors of the exit block (now the `to` block)
1980 // to not `HReturn` but `HGoto` instead.
1981 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
1982 if (to->GetPredecessors().size() == 1) {
1983 HBasicBlock* predecessor = to->GetPredecessors()[0];
1984 HInstruction* last = predecessor->GetLastInstruction();
1985 if (!returns_void) {
1986 return_value = last->InputAt(0);
1987 }
1988 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
1989 predecessor->RemoveInstruction(last);
1990 } else {
1991 if (!returns_void) {
1992 // There will be multiple returns.
1993 return_value = new (allocator) HPhi(
1994 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
1995 to->AddPhi(return_value->AsPhi());
1996 }
1997 for (HBasicBlock* predecessor : to->GetPredecessors()) {
1998 HInstruction* last = predecessor->GetLastInstruction();
1999 if (!returns_void) {
2000 DCHECK(last->IsReturn());
2001 return_value->AsPhi()->AddInput(last->InputAt(0));
2002 }
2003 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2004 predecessor->RemoveInstruction(last);
2005 }
2006 }
2007 }
David Brazdil05144f42015-04-16 15:18:00 +01002008
2009 // Walk over the entry block and:
2010 // - Move constants from the entry block to the outer_graph's entry block,
2011 // - Replace HParameterValue instructions with their real value.
2012 // - Remove suspend checks, that hold an environment.
2013 // We must do this after the other blocks have been inlined, otherwise ids of
2014 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002015 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002016 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2017 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002018 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002019 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002020 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002021 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002022 replacement = outer_graph->GetIntConstant(
2023 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002024 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002025 replacement = outer_graph->GetLongConstant(
2026 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002027 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002028 replacement = outer_graph->GetFloatConstant(
2029 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002030 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002031 replacement = outer_graph->GetDoubleConstant(
2032 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002033 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002034 if (kIsDebugBuild
2035 && invoke->IsInvokeStaticOrDirect()
2036 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2037 // Ensure we do not use the last input of `invoke`, as it
2038 // contains a clinit check which is not an actual argument.
2039 size_t last_input_index = invoke->InputCount() - 1;
2040 DCHECK(parameter_index != last_input_index);
2041 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002042 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002043 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002044 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002045 } else {
2046 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2047 entry_block_->RemoveInstruction(current);
2048 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002049 if (replacement != nullptr) {
2050 current->ReplaceWith(replacement);
2051 // If the current is the return value then we need to update the latter.
2052 if (current == return_value) {
2053 DCHECK_EQ(entry_block_, return_value->GetBlock());
2054 return_value = replacement;
2055 }
2056 }
2057 }
2058
Calin Juravle2e768302015-07-28 14:41:11 +00002059 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002060}
2061
Mingyao Yang3584bce2015-05-19 16:01:59 -07002062/*
2063 * Loop will be transformed to:
2064 * old_pre_header
2065 * |
2066 * if_block
2067 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002068 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002069 * \ /
2070 * new_pre_header
2071 * |
2072 * header
2073 */
2074void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2075 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002076 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002077
Aart Bik3fc7f352015-11-20 22:03:03 -08002078 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002079 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002080 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2081 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002082 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2083 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002084 AddBlock(true_block);
2085 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002086 AddBlock(new_pre_header);
2087
Aart Bik3fc7f352015-11-20 22:03:03 -08002088 header->ReplacePredecessor(old_pre_header, new_pre_header);
2089 old_pre_header->successors_.clear();
2090 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002091
Aart Bik3fc7f352015-11-20 22:03:03 -08002092 old_pre_header->AddSuccessor(if_block);
2093 if_block->AddSuccessor(true_block); // True successor
2094 if_block->AddSuccessor(false_block); // False successor
2095 true_block->AddSuccessor(new_pre_header);
2096 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002097
Aart Bik3fc7f352015-11-20 22:03:03 -08002098 old_pre_header->dominated_blocks_.push_back(if_block);
2099 if_block->SetDominator(old_pre_header);
2100 if_block->dominated_blocks_.push_back(true_block);
2101 true_block->SetDominator(if_block);
2102 if_block->dominated_blocks_.push_back(false_block);
2103 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002104 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002105 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002106 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107 header->SetDominator(new_pre_header);
2108
Aart Bik3fc7f352015-11-20 22:03:03 -08002109 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002110 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002111 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002112 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002113 reverse_post_order_[index_of_header++] = true_block;
2114 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002115 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002116
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002117 // The pre_header can never be a back edge of a loop.
2118 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2119 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2120 UpdateLoopAndTryInformationOfNewBlock(
2121 if_block, old_pre_header, /* replace_if_back_edge */ false);
2122 UpdateLoopAndTryInformationOfNewBlock(
2123 true_block, old_pre_header, /* replace_if_back_edge */ false);
2124 UpdateLoopAndTryInformationOfNewBlock(
2125 false_block, old_pre_header, /* replace_if_back_edge */ false);
2126 UpdateLoopAndTryInformationOfNewBlock(
2127 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002128}
2129
David Brazdilf5552582015-12-27 13:36:12 +00002130static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2131 SHARED_REQUIRES(Locks::mutator_lock_) {
2132 if (rti.IsValid()) {
2133 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2134 << " upper_bound_rti: " << upper_bound_rti
2135 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002136 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2137 << " upper_bound_rti: " << upper_bound_rti
2138 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002139 }
2140}
2141
Calin Juravle2e768302015-07-28 14:41:11 +00002142void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2143 if (kIsDebugBuild) {
2144 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2145 ScopedObjectAccess soa(Thread::Current());
2146 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2147 if (IsBoundType()) {
2148 // Having the test here spares us from making the method virtual just for
2149 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002150 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002151 }
2152 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002153 reference_type_handle_ = rti.GetTypeHandle();
2154 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002155}
2156
David Brazdilf5552582015-12-27 13:36:12 +00002157void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2158 if (kIsDebugBuild) {
2159 ScopedObjectAccess soa(Thread::Current());
2160 DCHECK(upper_bound.IsValid());
2161 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2162 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2163 }
2164 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002165 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002166}
2167
Vladimir Markoa1de9182016-02-25 11:37:38 +00002168ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002169 if (kIsDebugBuild) {
2170 ScopedObjectAccess soa(Thread::Current());
2171 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002172 if (!is_exact) {
2173 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2174 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2175 }
Calin Juravle2e768302015-07-28 14:41:11 +00002176 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002177 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002178}
2179
Calin Juravleacf735c2015-02-12 15:25:22 +00002180std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2181 ScopedObjectAccess soa(Thread::Current());
2182 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002183 << " is_valid=" << rhs.IsValid()
2184 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002185 << " is_exact=" << rhs.IsExact()
2186 << " ]";
2187 return os;
2188}
2189
Mark Mendellc4701932015-04-10 13:18:51 -04002190bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2191 // For now, assume that instructions in different blocks may use the
2192 // environment.
2193 // TODO: Use the control flow to decide if this is true.
2194 if (GetBlock() != other->GetBlock()) {
2195 return true;
2196 }
2197
2198 // We know that we are in the same block. Walk from 'this' to 'other',
2199 // checking to see if there is any instruction with an environment.
2200 HInstruction* current = this;
2201 for (; current != other && current != nullptr; current = current->GetNext()) {
2202 // This is a conservative check, as the instruction result may not be in
2203 // the referenced environment.
2204 if (current->HasEnvironment()) {
2205 return true;
2206 }
2207 }
2208
2209 // We should have been called with 'this' before 'other' in the block.
2210 // Just confirm this.
2211 DCHECK(current != nullptr);
2212 return false;
2213}
2214
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002215void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002216 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2217 IntrinsicSideEffects side_effects,
2218 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002219 intrinsic_ = intrinsic;
2220 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002221
Aart Bik5d75afe2015-12-14 11:57:01 -08002222 // Adjust method's side effects from intrinsic table.
2223 switch (side_effects) {
2224 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2225 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2226 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2227 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2228 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002229
2230 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2231 opt.SetDoesNotNeedDexCache();
2232 opt.SetDoesNotNeedEnvironment();
2233 } else {
2234 // If we need an environment, that means there will be a call, which can trigger GC.
2235 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2236 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002237 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002238 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002239}
2240
David Brazdil6de19382016-01-08 17:37:10 +00002241bool HNewInstance::IsStringAlloc() const {
2242 ScopedObjectAccess soa(Thread::Current());
2243 return GetReferenceTypeInfo().IsStringClass();
2244}
2245
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002246bool HInvoke::NeedsEnvironment() const {
2247 if (!IsIntrinsic()) {
2248 return true;
2249 }
2250 IntrinsicOptimizations opt(*this);
2251 return !opt.GetDoesNotNeedEnvironment();
2252}
2253
Vladimir Markodc151b22015-10-15 18:02:30 +01002254bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2255 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002256 return false;
2257 }
2258 if (!IsIntrinsic()) {
2259 return true;
2260 }
2261 IntrinsicOptimizations opt(*this);
2262 return !opt.GetDoesNotNeedDexCache();
2263}
2264
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002265void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2266 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2267 input->AddUseAt(this, index);
2268 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2269 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2270 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2271 InputRecordAt(i).GetUseNode()->SetIndex(i);
2272 }
2273}
2274
Vladimir Markob554b5a2015-11-06 12:57:55 +00002275void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2276 RemoveAsUserOfInput(index);
2277 inputs_.erase(inputs_.begin() + index);
2278 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2279 for (size_t i = index, e = InputCount(); i < e; ++i) {
2280 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2281 InputRecordAt(i).GetUseNode()->SetIndex(i);
2282 }
2283}
2284
Vladimir Markof64242a2015-12-01 14:58:23 +00002285std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2286 switch (rhs) {
2287 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2288 return os << "string_init";
2289 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2290 return os << "recursive";
2291 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2292 return os << "direct";
2293 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2294 return os << "direct_fixup";
2295 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2296 return os << "dex_cache_pc_relative";
2297 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2298 return os << "dex_cache_via_method";
2299 default:
2300 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2301 UNREACHABLE();
2302 }
2303}
2304
Vladimir Markofbb184a2015-11-13 14:47:00 +00002305std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2306 switch (rhs) {
2307 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2308 return os << "explicit";
2309 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2310 return os << "implicit";
2311 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2312 return os << "none";
2313 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002314 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2315 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002316 }
2317}
2318
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002319bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2320 HLoadString* other_load_string = other->AsLoadString();
2321 if (string_index_ != other_load_string->string_index_ ||
2322 GetPackedFields() != other_load_string->GetPackedFields()) {
2323 return false;
2324 }
2325 LoadKind load_kind = GetLoadKind();
2326 if (HasAddress(load_kind)) {
2327 return GetAddress() == other_load_string->GetAddress();
2328 } else if (HasStringReference(load_kind)) {
2329 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2330 } else {
2331 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2332 // If the string indexes and dex files are the same, dex cache element offsets
2333 // must also be the same, so we don't need to compare them.
2334 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2335 }
2336}
2337
2338void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2339 // Once sharpened, the load kind should not be changed again.
2340 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2341 SetPackedField<LoadKindField>(load_kind);
2342
2343 if (load_kind != LoadKind::kDexCacheViaMethod) {
2344 RemoveAsUserOfInput(0u);
2345 SetRawInputAt(0u, nullptr);
2346 }
2347 if (!NeedsEnvironment()) {
2348 RemoveEnvironment();
2349 }
2350}
2351
2352std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2353 switch (rhs) {
2354 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2355 return os << "BootImageLinkTimeAddress";
2356 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2357 return os << "BootImageLinkTimePcRelative";
2358 case HLoadString::LoadKind::kBootImageAddress:
2359 return os << "BootImageAddress";
2360 case HLoadString::LoadKind::kDexCacheAddress:
2361 return os << "DexCacheAddress";
2362 case HLoadString::LoadKind::kDexCachePcRelative:
2363 return os << "DexCachePcRelative";
2364 case HLoadString::LoadKind::kDexCacheViaMethod:
2365 return os << "DexCacheViaMethod";
2366 default:
2367 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2368 UNREACHABLE();
2369 }
2370}
2371
Mark Mendellc4701932015-04-10 13:18:51 -04002372void HInstruction::RemoveEnvironmentUsers() {
2373 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2374 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2375 HEnvironment* user = user_node->GetUser();
2376 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2377 }
2378 env_uses_.Clear();
2379}
2380
Roland Levillainc9b21f82016-03-23 16:36:59 +00002381// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002382HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2383 ArenaAllocator* allocator = GetArena();
2384
2385 if (cond->IsCondition() &&
2386 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2387 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2388 HInstruction* lhs = cond->InputAt(0);
2389 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002390 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002391 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2392 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2393 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2394 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2395 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2396 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2397 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2398 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2399 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2400 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2401 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002402 default:
2403 LOG(FATAL) << "Unexpected condition";
2404 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002405 }
2406 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2407 return replacement;
2408 } else if (cond->IsIntConstant()) {
2409 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002410 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002411 return GetIntConstant(1);
2412 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002413 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002414 return GetIntConstant(0);
2415 }
2416 } else {
2417 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2418 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2419 return replacement;
2420 }
2421}
2422
Roland Levillainc9285912015-12-18 10:38:42 +00002423std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2424 os << "["
2425 << " source=" << rhs.GetSource()
2426 << " destination=" << rhs.GetDestination()
2427 << " type=" << rhs.GetType()
2428 << " instruction=";
2429 if (rhs.GetInstruction() != nullptr) {
2430 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2431 } else {
2432 os << "null";
2433 }
2434 os << " ]";
2435 return os;
2436}
2437
Roland Levillain86503782016-02-11 19:07:30 +00002438std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2439 switch (rhs) {
2440 case TypeCheckKind::kUnresolvedCheck:
2441 return os << "unresolved_check";
2442 case TypeCheckKind::kExactCheck:
2443 return os << "exact_check";
2444 case TypeCheckKind::kClassHierarchyCheck:
2445 return os << "class_hierarchy_check";
2446 case TypeCheckKind::kAbstractClassCheck:
2447 return os << "abstract_class_check";
2448 case TypeCheckKind::kInterfaceCheck:
2449 return os << "interface_check";
2450 case TypeCheckKind::kArrayObjectCheck:
2451 return os << "array_object_check";
2452 case TypeCheckKind::kArrayCheck:
2453 return os << "array_check";
2454 default:
2455 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2456 UNREACHABLE();
2457 }
2458}
2459
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002460} // namespace art