blob: d7e4c53df0d27a4d71c02393d254da1d87cb3880 [file] [log] [blame]
David Brazdildee58d62016-04-07 09:54:26 +00001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "instruction_builder.h"
18
Matthew Gharrity465ecc82016-07-19 21:32:52 +000019#include "art_method-inl.h"
David Brazdildee58d62016-04-07 09:54:26 +000020#include "bytecode_utils.h"
21#include "class_linker.h"
Andreas Gampe26de38b2016-07-27 17:53:11 -070022#include "dex_instruction-inl.h"
David Brazdildee58d62016-04-07 09:54:26 +000023#include "driver/compiler_options.h"
24#include "scoped_thread_state_change.h"
25
26namespace art {
27
28void HInstructionBuilder::MaybeRecordStat(MethodCompilationStat compilation_stat) {
29 if (compilation_stats_ != nullptr) {
30 compilation_stats_->RecordStat(compilation_stat);
31 }
32}
33
34HBasicBlock* HInstructionBuilder::FindBlockStartingAt(uint32_t dex_pc) const {
35 return block_builder_->GetBlockAt(dex_pc);
36}
37
38ArenaVector<HInstruction*>* HInstructionBuilder::GetLocalsFor(HBasicBlock* block) {
39 ArenaVector<HInstruction*>* locals = &locals_for_[block->GetBlockId()];
40 const size_t vregs = graph_->GetNumberOfVRegs();
41 if (locals->size() != vregs) {
42 locals->resize(vregs, nullptr);
43
44 if (block->IsCatchBlock()) {
45 // We record incoming inputs of catch phis at throwing instructions and
46 // must therefore eagerly create the phis. Phis for undefined vregs will
47 // be deleted when the first throwing instruction with the vreg undefined
48 // is encountered. Unused phis will be removed by dead phi analysis.
49 for (size_t i = 0; i < vregs; ++i) {
50 // No point in creating the catch phi if it is already undefined at
51 // the first throwing instruction.
52 HInstruction* current_local_value = (*current_locals_)[i];
53 if (current_local_value != nullptr) {
54 HPhi* phi = new (arena_) HPhi(
55 arena_,
56 i,
57 0,
58 current_local_value->GetType());
59 block->AddPhi(phi);
60 (*locals)[i] = phi;
61 }
62 }
63 }
64 }
65 return locals;
66}
67
68HInstruction* HInstructionBuilder::ValueOfLocalAt(HBasicBlock* block, size_t local) {
69 ArenaVector<HInstruction*>* locals = GetLocalsFor(block);
70 return (*locals)[local];
71}
72
73void HInstructionBuilder::InitializeBlockLocals() {
74 current_locals_ = GetLocalsFor(current_block_);
75
76 if (current_block_->IsCatchBlock()) {
77 // Catch phis were already created and inputs collected from throwing sites.
78 if (kIsDebugBuild) {
79 // Make sure there was at least one throwing instruction which initialized
80 // locals (guaranteed by HGraphBuilder) and that all try blocks have been
81 // visited already (from HTryBoundary scoping and reverse post order).
82 bool catch_block_visited = false;
83 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
84 HBasicBlock* current = it.Current();
85 if (current == current_block_) {
86 catch_block_visited = true;
87 } else if (current->IsTryBlock()) {
88 const HTryBoundary& try_entry = current->GetTryCatchInformation()->GetTryEntry();
89 if (try_entry.HasExceptionHandler(*current_block_)) {
90 DCHECK(!catch_block_visited) << "Catch block visited before its try block.";
91 }
92 }
93 }
94 DCHECK_EQ(current_locals_->size(), graph_->GetNumberOfVRegs())
95 << "No instructions throwing into a live catch block.";
96 }
97 } else if (current_block_->IsLoopHeader()) {
98 // If the block is a loop header, we know we only have visited the pre header
99 // because we are visiting in reverse post order. We create phis for all initialized
100 // locals from the pre header. Their inputs will be populated at the end of
101 // the analysis.
102 for (size_t local = 0; local < current_locals_->size(); ++local) {
103 HInstruction* incoming =
104 ValueOfLocalAt(current_block_->GetLoopInformation()->GetPreHeader(), local);
105 if (incoming != nullptr) {
106 HPhi* phi = new (arena_) HPhi(
107 arena_,
108 local,
109 0,
110 incoming->GetType());
111 current_block_->AddPhi(phi);
112 (*current_locals_)[local] = phi;
113 }
114 }
115
116 // Save the loop header so that the last phase of the analysis knows which
117 // blocks need to be updated.
118 loop_headers_.push_back(current_block_);
119 } else if (current_block_->GetPredecessors().size() > 0) {
120 // All predecessors have already been visited because we are visiting in reverse post order.
121 // We merge the values of all locals, creating phis if those values differ.
122 for (size_t local = 0; local < current_locals_->size(); ++local) {
123 bool one_predecessor_has_no_value = false;
124 bool is_different = false;
125 HInstruction* value = ValueOfLocalAt(current_block_->GetPredecessors()[0], local);
126
127 for (HBasicBlock* predecessor : current_block_->GetPredecessors()) {
128 HInstruction* current = ValueOfLocalAt(predecessor, local);
129 if (current == nullptr) {
130 one_predecessor_has_no_value = true;
131 break;
132 } else if (current != value) {
133 is_different = true;
134 }
135 }
136
137 if (one_predecessor_has_no_value) {
138 // If one predecessor has no value for this local, we trust the verifier has
139 // successfully checked that there is a store dominating any read after this block.
140 continue;
141 }
142
143 if (is_different) {
144 HInstruction* first_input = ValueOfLocalAt(current_block_->GetPredecessors()[0], local);
145 HPhi* phi = new (arena_) HPhi(
146 arena_,
147 local,
148 current_block_->GetPredecessors().size(),
149 first_input->GetType());
150 for (size_t i = 0; i < current_block_->GetPredecessors().size(); i++) {
151 HInstruction* pred_value = ValueOfLocalAt(current_block_->GetPredecessors()[i], local);
152 phi->SetRawInputAt(i, pred_value);
153 }
154 current_block_->AddPhi(phi);
155 value = phi;
156 }
157 (*current_locals_)[local] = value;
158 }
159 }
160}
161
162void HInstructionBuilder::PropagateLocalsToCatchBlocks() {
163 const HTryBoundary& try_entry = current_block_->GetTryCatchInformation()->GetTryEntry();
164 for (HBasicBlock* catch_block : try_entry.GetExceptionHandlers()) {
165 ArenaVector<HInstruction*>* handler_locals = GetLocalsFor(catch_block);
166 DCHECK_EQ(handler_locals->size(), current_locals_->size());
167 for (size_t vreg = 0, e = current_locals_->size(); vreg < e; ++vreg) {
168 HInstruction* handler_value = (*handler_locals)[vreg];
169 if (handler_value == nullptr) {
170 // Vreg was undefined at a previously encountered throwing instruction
171 // and the catch phi was deleted. Do not record the local value.
172 continue;
173 }
174 DCHECK(handler_value->IsPhi());
175
176 HInstruction* local_value = (*current_locals_)[vreg];
177 if (local_value == nullptr) {
178 // This is the first instruction throwing into `catch_block` where
179 // `vreg` is undefined. Delete the catch phi.
180 catch_block->RemovePhi(handler_value->AsPhi());
181 (*handler_locals)[vreg] = nullptr;
182 } else {
183 // Vreg has been defined at all instructions throwing into `catch_block`
184 // encountered so far. Record the local value in the catch phi.
185 handler_value->AsPhi()->AddInput(local_value);
186 }
187 }
188 }
189}
190
191void HInstructionBuilder::AppendInstruction(HInstruction* instruction) {
192 current_block_->AddInstruction(instruction);
193 InitializeInstruction(instruction);
194}
195
196void HInstructionBuilder::InsertInstructionAtTop(HInstruction* instruction) {
197 if (current_block_->GetInstructions().IsEmpty()) {
198 current_block_->AddInstruction(instruction);
199 } else {
200 current_block_->InsertInstructionBefore(instruction, current_block_->GetFirstInstruction());
201 }
202 InitializeInstruction(instruction);
203}
204
205void HInstructionBuilder::InitializeInstruction(HInstruction* instruction) {
206 if (instruction->NeedsEnvironment()) {
207 HEnvironment* environment = new (arena_) HEnvironment(
208 arena_,
209 current_locals_->size(),
210 graph_->GetDexFile(),
211 graph_->GetMethodIdx(),
212 instruction->GetDexPc(),
213 graph_->GetInvokeType(),
214 instruction);
215 environment->CopyFrom(*current_locals_);
216 instruction->SetRawEnvironment(environment);
217 }
218}
219
David Brazdilc120bbe2016-04-22 16:57:00 +0100220HInstruction* HInstructionBuilder::LoadNullCheckedLocal(uint32_t register_index, uint32_t dex_pc) {
221 HInstruction* ref = LoadLocal(register_index, Primitive::kPrimNot);
222 if (!ref->CanBeNull()) {
223 return ref;
224 }
225
226 HNullCheck* null_check = new (arena_) HNullCheck(ref, dex_pc);
227 AppendInstruction(null_check);
228 return null_check;
229}
230
David Brazdildee58d62016-04-07 09:54:26 +0000231void HInstructionBuilder::SetLoopHeaderPhiInputs() {
232 for (size_t i = loop_headers_.size(); i > 0; --i) {
233 HBasicBlock* block = loop_headers_[i - 1];
234 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
235 HPhi* phi = it.Current()->AsPhi();
236 size_t vreg = phi->GetRegNumber();
237 for (HBasicBlock* predecessor : block->GetPredecessors()) {
238 HInstruction* value = ValueOfLocalAt(predecessor, vreg);
239 if (value == nullptr) {
240 // Vreg is undefined at this predecessor. Mark it dead and leave with
241 // fewer inputs than predecessors. SsaChecker will fail if not removed.
242 phi->SetDead();
243 break;
244 } else {
245 phi->AddInput(value);
246 }
247 }
248 }
249 }
250}
251
252static bool IsBlockPopulated(HBasicBlock* block) {
253 if (block->IsLoopHeader()) {
254 // Suspend checks were inserted into loop headers during building of dominator tree.
255 DCHECK(block->GetFirstInstruction()->IsSuspendCheck());
256 return block->GetFirstInstruction() != block->GetLastInstruction();
257 } else {
258 return !block->GetInstructions().IsEmpty();
259 }
260}
261
262bool HInstructionBuilder::Build() {
263 locals_for_.resize(graph_->GetBlocks().size(),
264 ArenaVector<HInstruction*>(arena_->Adapter(kArenaAllocGraphBuilder)));
265
266 // Find locations where we want to generate extra stackmaps for native debugging.
267 // This allows us to generate the info only at interesting points (for example,
268 // at start of java statement) rather than before every dex instruction.
269 const bool native_debuggable = compiler_driver_ != nullptr &&
270 compiler_driver_->GetCompilerOptions().GetNativeDebuggable();
271 ArenaBitVector* native_debug_info_locations = nullptr;
272 if (native_debuggable) {
273 const uint32_t num_instructions = code_item_.insns_size_in_code_units_;
274 native_debug_info_locations = new (arena_) ArenaBitVector (arena_, num_instructions, false);
275 FindNativeDebugInfoLocations(native_debug_info_locations);
276 }
277
278 for (HReversePostOrderIterator block_it(*graph_); !block_it.Done(); block_it.Advance()) {
279 current_block_ = block_it.Current();
280 uint32_t block_dex_pc = current_block_->GetDexPc();
281
282 InitializeBlockLocals();
283
284 if (current_block_->IsEntryBlock()) {
285 InitializeParameters();
286 AppendInstruction(new (arena_) HSuspendCheck(0u));
287 AppendInstruction(new (arena_) HGoto(0u));
288 continue;
289 } else if (current_block_->IsExitBlock()) {
290 AppendInstruction(new (arena_) HExit());
291 continue;
292 } else if (current_block_->IsLoopHeader()) {
293 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(current_block_->GetDexPc());
294 current_block_->GetLoopInformation()->SetSuspendCheck(suspend_check);
295 // This is slightly odd because the loop header might not be empty (TryBoundary).
296 // But we're still creating the environment with locals from the top of the block.
297 InsertInstructionAtTop(suspend_check);
298 }
299
300 if (block_dex_pc == kNoDexPc || current_block_ != block_builder_->GetBlockAt(block_dex_pc)) {
301 // Synthetic block that does not need to be populated.
302 DCHECK(IsBlockPopulated(current_block_));
303 continue;
304 }
305
306 DCHECK(!IsBlockPopulated(current_block_));
307
308 for (CodeItemIterator it(code_item_, block_dex_pc); !it.Done(); it.Advance()) {
309 if (current_block_ == nullptr) {
310 // The previous instruction ended this block.
311 break;
312 }
313
314 uint32_t dex_pc = it.CurrentDexPc();
315 if (dex_pc != block_dex_pc && FindBlockStartingAt(dex_pc) != nullptr) {
316 // This dex_pc starts a new basic block.
317 break;
318 }
319
320 if (current_block_->IsTryBlock() && IsThrowingDexInstruction(it.CurrentInstruction())) {
321 PropagateLocalsToCatchBlocks();
322 }
323
324 if (native_debuggable && native_debug_info_locations->IsBitSet(dex_pc)) {
325 AppendInstruction(new (arena_) HNativeDebugInfo(dex_pc));
326 }
327
328 if (!ProcessDexInstruction(it.CurrentInstruction(), dex_pc)) {
329 return false;
330 }
331 }
332
333 if (current_block_ != nullptr) {
334 // Branching instructions clear current_block, so we know the last
335 // instruction of the current block is not a branching instruction.
336 // We add an unconditional Goto to the next block.
337 DCHECK_EQ(current_block_->GetSuccessors().size(), 1u);
338 AppendInstruction(new (arena_) HGoto());
339 }
340 }
341
342 SetLoopHeaderPhiInputs();
343
344 return true;
345}
346
347void HInstructionBuilder::FindNativeDebugInfoLocations(ArenaBitVector* locations) {
348 // The callback gets called when the line number changes.
349 // In other words, it marks the start of new java statement.
350 struct Callback {
351 static bool Position(void* ctx, const DexFile::PositionInfo& entry) {
352 static_cast<ArenaBitVector*>(ctx)->SetBit(entry.address_);
353 return false;
354 }
355 };
356 dex_file_->DecodeDebugPositionInfo(&code_item_, Callback::Position, locations);
357 // Instruction-specific tweaks.
358 const Instruction* const begin = Instruction::At(code_item_.insns_);
359 const Instruction* const end = begin->RelativeAt(code_item_.insns_size_in_code_units_);
360 for (const Instruction* inst = begin; inst < end; inst = inst->Next()) {
361 switch (inst->Opcode()) {
362 case Instruction::MOVE_EXCEPTION: {
363 // Stop in native debugger after the exception has been moved.
364 // The compiler also expects the move at the start of basic block so
365 // we do not want to interfere by inserting native-debug-info before it.
366 locations->ClearBit(inst->GetDexPc(code_item_.insns_));
367 const Instruction* next = inst->Next();
368 if (next < end) {
369 locations->SetBit(next->GetDexPc(code_item_.insns_));
370 }
371 break;
372 }
373 default:
374 break;
375 }
376 }
377}
378
379HInstruction* HInstructionBuilder::LoadLocal(uint32_t reg_number, Primitive::Type type) const {
380 HInstruction* value = (*current_locals_)[reg_number];
381 DCHECK(value != nullptr);
382
383 // If the operation requests a specific type, we make sure its input is of that type.
384 if (type != value->GetType()) {
385 if (Primitive::IsFloatingPointType(type)) {
Aart Bik31883642016-06-06 15:02:44 -0700386 value = ssa_builder_->GetFloatOrDoubleEquivalent(value, type);
David Brazdildee58d62016-04-07 09:54:26 +0000387 } else if (type == Primitive::kPrimNot) {
Aart Bik31883642016-06-06 15:02:44 -0700388 value = ssa_builder_->GetReferenceTypeEquivalent(value);
David Brazdildee58d62016-04-07 09:54:26 +0000389 }
Aart Bik31883642016-06-06 15:02:44 -0700390 DCHECK(value != nullptr);
David Brazdildee58d62016-04-07 09:54:26 +0000391 }
392
393 return value;
394}
395
396void HInstructionBuilder::UpdateLocal(uint32_t reg_number, HInstruction* stored_value) {
397 Primitive::Type stored_type = stored_value->GetType();
398 DCHECK_NE(stored_type, Primitive::kPrimVoid);
399
400 // Storing into vreg `reg_number` may implicitly invalidate the surrounding
401 // registers. Consider the following cases:
402 // (1) Storing a wide value must overwrite previous values in both `reg_number`
403 // and `reg_number+1`. We store `nullptr` in `reg_number+1`.
404 // (2) If vreg `reg_number-1` holds a wide value, writing into `reg_number`
405 // must invalidate it. We store `nullptr` in `reg_number-1`.
406 // Consequently, storing a wide value into the high vreg of another wide value
407 // will invalidate both `reg_number-1` and `reg_number+1`.
408
409 if (reg_number != 0) {
410 HInstruction* local_low = (*current_locals_)[reg_number - 1];
411 if (local_low != nullptr && Primitive::Is64BitType(local_low->GetType())) {
412 // The vreg we are storing into was previously the high vreg of a pair.
413 // We need to invalidate its low vreg.
414 DCHECK((*current_locals_)[reg_number] == nullptr);
415 (*current_locals_)[reg_number - 1] = nullptr;
416 }
417 }
418
419 (*current_locals_)[reg_number] = stored_value;
420 if (Primitive::Is64BitType(stored_type)) {
421 // We are storing a pair. Invalidate the instruction in the high vreg.
422 (*current_locals_)[reg_number + 1] = nullptr;
423 }
424}
425
426void HInstructionBuilder::InitializeParameters() {
427 DCHECK(current_block_->IsEntryBlock());
428
429 // dex_compilation_unit_ is null only when unit testing.
430 if (dex_compilation_unit_ == nullptr) {
431 return;
432 }
433
434 const char* shorty = dex_compilation_unit_->GetShorty();
435 uint16_t number_of_parameters = graph_->GetNumberOfInVRegs();
436 uint16_t locals_index = graph_->GetNumberOfLocalVRegs();
437 uint16_t parameter_index = 0;
438
439 const DexFile::MethodId& referrer_method_id =
440 dex_file_->GetMethodId(dex_compilation_unit_->GetDexMethodIndex());
441 if (!dex_compilation_unit_->IsStatic()) {
442 // Add the implicit 'this' argument, not expressed in the signature.
443 HParameterValue* parameter = new (arena_) HParameterValue(*dex_file_,
444 referrer_method_id.class_idx_,
445 parameter_index++,
446 Primitive::kPrimNot,
447 true);
448 AppendInstruction(parameter);
449 UpdateLocal(locals_index++, parameter);
450 number_of_parameters--;
451 }
452
453 const DexFile::ProtoId& proto = dex_file_->GetMethodPrototype(referrer_method_id);
454 const DexFile::TypeList* arg_types = dex_file_->GetProtoParameters(proto);
455 for (int i = 0, shorty_pos = 1; i < number_of_parameters; i++) {
456 HParameterValue* parameter = new (arena_) HParameterValue(
457 *dex_file_,
458 arg_types->GetTypeItem(shorty_pos - 1).type_idx_,
459 parameter_index++,
460 Primitive::GetType(shorty[shorty_pos]),
461 false);
462 ++shorty_pos;
463 AppendInstruction(parameter);
464 // Store the parameter value in the local that the dex code will use
465 // to reference that parameter.
466 UpdateLocal(locals_index++, parameter);
467 if (Primitive::Is64BitType(parameter->GetType())) {
468 i++;
469 locals_index++;
470 parameter_index++;
471 }
472 }
473}
474
475template<typename T>
476void HInstructionBuilder::If_22t(const Instruction& instruction, uint32_t dex_pc) {
477 HInstruction* first = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
478 HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
479 T* comparison = new (arena_) T(first, second, dex_pc);
480 AppendInstruction(comparison);
481 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
482 current_block_ = nullptr;
483}
484
485template<typename T>
486void HInstructionBuilder::If_21t(const Instruction& instruction, uint32_t dex_pc) {
487 HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
488 T* comparison = new (arena_) T(value, graph_->GetIntConstant(0, dex_pc), dex_pc);
489 AppendInstruction(comparison);
490 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
491 current_block_ = nullptr;
492}
493
494template<typename T>
495void HInstructionBuilder::Unop_12x(const Instruction& instruction,
496 Primitive::Type type,
497 uint32_t dex_pc) {
498 HInstruction* first = LoadLocal(instruction.VRegB(), type);
499 AppendInstruction(new (arena_) T(type, first, dex_pc));
500 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
501}
502
503void HInstructionBuilder::Conversion_12x(const Instruction& instruction,
504 Primitive::Type input_type,
505 Primitive::Type result_type,
506 uint32_t dex_pc) {
507 HInstruction* first = LoadLocal(instruction.VRegB(), input_type);
508 AppendInstruction(new (arena_) HTypeConversion(result_type, first, dex_pc));
509 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
510}
511
512template<typename T>
513void HInstructionBuilder::Binop_23x(const Instruction& instruction,
514 Primitive::Type type,
515 uint32_t dex_pc) {
516 HInstruction* first = LoadLocal(instruction.VRegB(), type);
517 HInstruction* second = LoadLocal(instruction.VRegC(), type);
518 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
519 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
520}
521
522template<typename T>
523void HInstructionBuilder::Binop_23x_shift(const Instruction& instruction,
524 Primitive::Type type,
525 uint32_t dex_pc) {
526 HInstruction* first = LoadLocal(instruction.VRegB(), type);
527 HInstruction* second = LoadLocal(instruction.VRegC(), Primitive::kPrimInt);
528 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
529 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
530}
531
532void HInstructionBuilder::Binop_23x_cmp(const Instruction& instruction,
533 Primitive::Type type,
534 ComparisonBias bias,
535 uint32_t dex_pc) {
536 HInstruction* first = LoadLocal(instruction.VRegB(), type);
537 HInstruction* second = LoadLocal(instruction.VRegC(), type);
538 AppendInstruction(new (arena_) HCompare(type, first, second, bias, dex_pc));
539 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
540}
541
542template<typename T>
543void HInstructionBuilder::Binop_12x_shift(const Instruction& instruction,
544 Primitive::Type type,
545 uint32_t dex_pc) {
546 HInstruction* first = LoadLocal(instruction.VRegA(), type);
547 HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
548 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
549 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
550}
551
552template<typename T>
553void HInstructionBuilder::Binop_12x(const Instruction& instruction,
554 Primitive::Type type,
555 uint32_t dex_pc) {
556 HInstruction* first = LoadLocal(instruction.VRegA(), type);
557 HInstruction* second = LoadLocal(instruction.VRegB(), type);
558 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
559 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
560}
561
562template<typename T>
563void HInstructionBuilder::Binop_22s(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
564 HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
565 HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22s(), dex_pc);
566 if (reverse) {
567 std::swap(first, second);
568 }
569 AppendInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
570 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
571}
572
573template<typename T>
574void HInstructionBuilder::Binop_22b(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
575 HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
576 HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22b(), dex_pc);
577 if (reverse) {
578 std::swap(first, second);
579 }
580 AppendInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
581 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
582}
583
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700584static bool RequiresConstructorBarrier(const DexCompilationUnit* cu, CompilerDriver* driver) {
David Brazdildee58d62016-04-07 09:54:26 +0000585 Thread* self = Thread::Current();
586 return cu->IsConstructor()
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700587 && driver->RequiresConstructorBarrier(self, cu->GetDexFile(), cu->GetClassDefIndex());
David Brazdildee58d62016-04-07 09:54:26 +0000588}
589
590// Returns true if `block` has only one successor which starts at the next
591// dex_pc after `instruction` at `dex_pc`.
592static bool IsFallthroughInstruction(const Instruction& instruction,
593 uint32_t dex_pc,
594 HBasicBlock* block) {
595 uint32_t next_dex_pc = dex_pc + instruction.SizeInCodeUnits();
596 return block->GetSingleSuccessor()->GetDexPc() == next_dex_pc;
597}
598
599void HInstructionBuilder::BuildSwitch(const Instruction& instruction, uint32_t dex_pc) {
600 HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
601 DexSwitchTable table(instruction, dex_pc);
602
603 if (table.GetNumEntries() == 0) {
604 // Empty Switch. Code falls through to the next block.
605 DCHECK(IsFallthroughInstruction(instruction, dex_pc, current_block_));
606 AppendInstruction(new (arena_) HGoto(dex_pc));
607 } else if (table.ShouldBuildDecisionTree()) {
608 for (DexSwitchTableIterator it(table); !it.Done(); it.Advance()) {
609 HInstruction* case_value = graph_->GetIntConstant(it.CurrentKey(), dex_pc);
610 HEqual* comparison = new (arena_) HEqual(value, case_value, dex_pc);
611 AppendInstruction(comparison);
612 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
613
614 if (!it.IsLast()) {
615 current_block_ = FindBlockStartingAt(it.GetDexPcForCurrentIndex());
616 }
617 }
618 } else {
619 AppendInstruction(
620 new (arena_) HPackedSwitch(table.GetEntryAt(0), table.GetNumEntries(), value, dex_pc));
621 }
622
623 current_block_ = nullptr;
624}
625
626void HInstructionBuilder::BuildReturn(const Instruction& instruction,
627 Primitive::Type type,
628 uint32_t dex_pc) {
629 if (type == Primitive::kPrimVoid) {
630 if (graph_->ShouldGenerateConstructorBarrier()) {
631 // The compilation unit is null during testing.
632 if (dex_compilation_unit_ != nullptr) {
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700633 DCHECK(RequiresConstructorBarrier(dex_compilation_unit_, compiler_driver_))
David Brazdildee58d62016-04-07 09:54:26 +0000634 << "Inconsistent use of ShouldGenerateConstructorBarrier. Should not generate a barrier.";
635 }
636 AppendInstruction(new (arena_) HMemoryBarrier(kStoreStore, dex_pc));
637 }
638 AppendInstruction(new (arena_) HReturnVoid(dex_pc));
639 } else {
640 HInstruction* value = LoadLocal(instruction.VRegA(), type);
641 AppendInstruction(new (arena_) HReturn(value, dex_pc));
642 }
643 current_block_ = nullptr;
644}
645
646static InvokeType GetInvokeTypeFromOpCode(Instruction::Code opcode) {
647 switch (opcode) {
648 case Instruction::INVOKE_STATIC:
649 case Instruction::INVOKE_STATIC_RANGE:
650 return kStatic;
651 case Instruction::INVOKE_DIRECT:
652 case Instruction::INVOKE_DIRECT_RANGE:
653 return kDirect;
654 case Instruction::INVOKE_VIRTUAL:
655 case Instruction::INVOKE_VIRTUAL_QUICK:
656 case Instruction::INVOKE_VIRTUAL_RANGE:
657 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
658 return kVirtual;
659 case Instruction::INVOKE_INTERFACE:
660 case Instruction::INVOKE_INTERFACE_RANGE:
661 return kInterface;
662 case Instruction::INVOKE_SUPER_RANGE:
663 case Instruction::INVOKE_SUPER:
664 return kSuper;
665 default:
666 LOG(FATAL) << "Unexpected invoke opcode: " << opcode;
667 UNREACHABLE();
668 }
669}
670
671ArtMethod* HInstructionBuilder::ResolveMethod(uint16_t method_idx, InvokeType invoke_type) {
672 ScopedObjectAccess soa(Thread::Current());
673 StackHandleScope<3> hs(soa.Self());
674
675 ClassLinker* class_linker = dex_compilation_unit_->GetClassLinker();
676 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
677 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
678 Handle<mirror::Class> compiling_class(hs.NewHandle(GetCompilingClass()));
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100679 // We fetch the referenced class eagerly (that is, the class pointed by in the MethodId
680 // at method_idx), as `CanAccessResolvedMethod` expects it be be in the dex cache.
681 Handle<mirror::Class> methods_class(hs.NewHandle(class_linker->ResolveReferencedClassOfMethod(
682 method_idx, dex_compilation_unit_->GetDexCache(), class_loader)));
683
684 if (UNLIKELY(methods_class.Get() == nullptr)) {
685 // Clean up any exception left by type resolution.
686 soa.Self()->ClearException();
687 return nullptr;
688 }
David Brazdildee58d62016-04-07 09:54:26 +0000689
690 ArtMethod* resolved_method = class_linker->ResolveMethod<ClassLinker::kForceICCECheck>(
691 *dex_compilation_unit_->GetDexFile(),
692 method_idx,
693 dex_compilation_unit_->GetDexCache(),
694 class_loader,
695 /* referrer */ nullptr,
696 invoke_type);
697
698 if (UNLIKELY(resolved_method == nullptr)) {
699 // Clean up any exception left by type resolution.
700 soa.Self()->ClearException();
701 return nullptr;
702 }
703
704 // Check access. The class linker has a fast path for looking into the dex cache
705 // and does not check the access if it hits it.
706 if (compiling_class.Get() == nullptr) {
707 if (!resolved_method->IsPublic()) {
708 return nullptr;
709 }
710 } else if (!compiling_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
711 resolved_method,
712 dex_compilation_unit_->GetDexCache().Get(),
713 method_idx)) {
714 return nullptr;
715 }
716
717 // We have to special case the invoke-super case, as ClassLinker::ResolveMethod does not.
718 // We need to look at the referrer's super class vtable. We need to do this to know if we need to
719 // make this an invoke-unresolved to handle cross-dex invokes or abstract super methods, both of
720 // which require runtime handling.
721 if (invoke_type == kSuper) {
722 if (compiling_class.Get() == nullptr) {
723 // We could not determine the method's class we need to wait until runtime.
724 DCHECK(Runtime::Current()->IsAotCompiler());
725 return nullptr;
726 }
Aart Bikf663e342016-04-04 17:28:59 -0700727 if (!methods_class->IsAssignableFrom(compiling_class.Get())) {
728 // We cannot statically determine the target method. The runtime will throw a
729 // NoSuchMethodError on this one.
730 return nullptr;
731 }
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100732 ArtMethod* actual_method;
733 if (methods_class->IsInterface()) {
734 actual_method = methods_class->FindVirtualMethodForInterfaceSuper(
735 resolved_method, class_linker->GetImagePointerSize());
David Brazdildee58d62016-04-07 09:54:26 +0000736 } else {
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100737 uint16_t vtable_index = resolved_method->GetMethodIndex();
738 actual_method = compiling_class->GetSuperClass()->GetVTableEntry(
739 vtable_index, class_linker->GetImagePointerSize());
David Brazdildee58d62016-04-07 09:54:26 +0000740 }
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100741 if (actual_method != resolved_method &&
742 !IsSameDexFile(*actual_method->GetDexFile(), *dex_compilation_unit_->GetDexFile())) {
743 // The back-end code generator relies on this check in order to ensure that it will not
744 // attempt to read the dex_cache with a dex_method_index that is not from the correct
745 // dex_file. If we didn't do this check then the dex_method_index will not be updated in the
746 // builder, which means that the code-generator (and compiler driver during sharpening and
747 // inliner, maybe) might invoke an incorrect method.
748 // TODO: The actual method could still be referenced in the current dex file, so we
749 // could try locating it.
750 // TODO: Remove the dex_file restriction.
751 return nullptr;
752 }
753 if (!actual_method->IsInvokable()) {
754 // Fail if the actual method cannot be invoked. Otherwise, the runtime resolution stub
755 // could resolve the callee to the wrong method.
756 return nullptr;
757 }
758 resolved_method = actual_method;
David Brazdildee58d62016-04-07 09:54:26 +0000759 }
760
761 // Check for incompatible class changes. The class linker has a fast path for
762 // looking into the dex cache and does not check incompatible class changes if it hits it.
763 if (resolved_method->CheckIncompatibleClassChange(invoke_type)) {
764 return nullptr;
765 }
766
767 return resolved_method;
768}
769
770bool HInstructionBuilder::BuildInvoke(const Instruction& instruction,
771 uint32_t dex_pc,
772 uint32_t method_idx,
773 uint32_t number_of_vreg_arguments,
774 bool is_range,
775 uint32_t* args,
776 uint32_t register_index) {
777 InvokeType invoke_type = GetInvokeTypeFromOpCode(instruction.Opcode());
778 const char* descriptor = dex_file_->GetMethodShorty(method_idx);
779 Primitive::Type return_type = Primitive::GetType(descriptor[0]);
780
781 // Remove the return type from the 'proto'.
782 size_t number_of_arguments = strlen(descriptor) - 1;
783 if (invoke_type != kStatic) { // instance call
784 // One extra argument for 'this'.
785 number_of_arguments++;
786 }
787
788 MethodReference target_method(dex_file_, method_idx);
789
790 // Special handling for string init.
791 int32_t string_init_offset = 0;
792 bool is_string_init = compiler_driver_->IsStringInit(method_idx,
793 dex_file_,
794 &string_init_offset);
795 // Replace calls to String.<init> with StringFactory.
796 if (is_string_init) {
797 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
798 HInvokeStaticOrDirect::MethodLoadKind::kStringInit,
799 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
800 dchecked_integral_cast<uint64_t>(string_init_offset),
801 0U
802 };
803 HInvoke* invoke = new (arena_) HInvokeStaticOrDirect(
804 arena_,
805 number_of_arguments - 1,
806 Primitive::kPrimNot /*return_type */,
807 dex_pc,
808 method_idx,
809 target_method,
810 dispatch_info,
811 invoke_type,
812 kStatic /* optimized_invoke_type */,
813 HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit);
814 return HandleStringInit(invoke,
815 number_of_vreg_arguments,
816 args,
817 register_index,
818 is_range,
819 descriptor);
820 }
821
822 ArtMethod* resolved_method = ResolveMethod(method_idx, invoke_type);
823
824 if (UNLIKELY(resolved_method == nullptr)) {
825 MaybeRecordStat(MethodCompilationStat::kUnresolvedMethod);
826 HInvoke* invoke = new (arena_) HInvokeUnresolved(arena_,
827 number_of_arguments,
828 return_type,
829 dex_pc,
830 method_idx,
831 invoke_type);
832 return HandleInvoke(invoke,
833 number_of_vreg_arguments,
834 args,
835 register_index,
836 is_range,
837 descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -0700838 nullptr, /* clinit_check */
839 true /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000840 }
841
842 // Potential class initialization check, in the case of a static method call.
843 HClinitCheck* clinit_check = nullptr;
844 HInvoke* invoke = nullptr;
845 if (invoke_type == kDirect || invoke_type == kStatic || invoke_type == kSuper) {
846 // By default, consider that the called method implicitly requires
847 // an initialization check of its declaring method.
848 HInvokeStaticOrDirect::ClinitCheckRequirement clinit_check_requirement
849 = HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit;
850 ScopedObjectAccess soa(Thread::Current());
851 if (invoke_type == kStatic) {
852 clinit_check = ProcessClinitCheckForInvoke(
853 dex_pc, resolved_method, method_idx, &clinit_check_requirement);
854 } else if (invoke_type == kSuper) {
855 if (IsSameDexFile(*resolved_method->GetDexFile(), *dex_compilation_unit_->GetDexFile())) {
856 // Update the target method to the one resolved. Note that this may be a no-op if
857 // we resolved to the method referenced by the instruction.
858 method_idx = resolved_method->GetDexMethodIndex();
859 target_method = MethodReference(dex_file_, method_idx);
860 }
861 }
862
863 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
864 HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod,
865 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
866 0u,
867 0U
868 };
869 invoke = new (arena_) HInvokeStaticOrDirect(arena_,
870 number_of_arguments,
871 return_type,
872 dex_pc,
873 method_idx,
874 target_method,
875 dispatch_info,
876 invoke_type,
877 invoke_type,
878 clinit_check_requirement);
879 } else if (invoke_type == kVirtual) {
880 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
881 invoke = new (arena_) HInvokeVirtual(arena_,
882 number_of_arguments,
883 return_type,
884 dex_pc,
885 method_idx,
886 resolved_method->GetMethodIndex());
887 } else {
888 DCHECK_EQ(invoke_type, kInterface);
889 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
890 invoke = new (arena_) HInvokeInterface(arena_,
891 number_of_arguments,
892 return_type,
893 dex_pc,
894 method_idx,
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000895 resolved_method->GetImtIndex());
David Brazdildee58d62016-04-07 09:54:26 +0000896 }
897
898 return HandleInvoke(invoke,
899 number_of_vreg_arguments,
900 args,
901 register_index,
902 is_range,
903 descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -0700904 clinit_check,
905 false /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000906}
907
908bool HInstructionBuilder::BuildNewInstance(uint16_t type_index, uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100909 ScopedObjectAccess soa(Thread::Current());
910 StackHandleScope<1> hs(soa.Self());
911 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
912 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
913 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
914 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
915
David Brazdildee58d62016-04-07 09:54:26 +0000916 bool finalizable;
Mingyao Yang062157f2016-03-02 10:15:36 -0800917 bool needs_access_check = NeedsAccessCheck(type_index, dex_cache, &finalizable);
David Brazdildee58d62016-04-07 09:54:26 +0000918
919 // Only the non-resolved entrypoint handles the finalizable class case. If we
920 // need access checks, then we haven't resolved the method and the class may
921 // again be finalizable.
Mingyao Yang062157f2016-03-02 10:15:36 -0800922 QuickEntrypointEnum entrypoint = (finalizable || needs_access_check)
David Brazdildee58d62016-04-07 09:54:26 +0000923 ? kQuickAllocObject
924 : kQuickAllocObjectInitialized;
925
David Brazdildee58d62016-04-07 09:54:26 +0000926 if (outer_dex_cache.Get() != dex_cache.Get()) {
927 // We currently do not support inlining allocations across dex files.
928 return false;
929 }
930
931 HLoadClass* load_class = new (arena_) HLoadClass(
932 graph_->GetCurrentMethod(),
933 type_index,
934 outer_dex_file,
935 IsOutermostCompilingClass(type_index),
936 dex_pc,
Mingyao Yang062157f2016-03-02 10:15:36 -0800937 needs_access_check,
Mathieu Chartier31b12e32016-09-02 17:11:57 -0700938 /* is_in_dex_cache */ false,
939 /* is_in_boot_image */ false);
David Brazdildee58d62016-04-07 09:54:26 +0000940
941 AppendInstruction(load_class);
942 HInstruction* cls = load_class;
943 if (!IsInitialized(resolved_class)) {
944 cls = new (arena_) HClinitCheck(load_class, dex_pc);
945 AppendInstruction(cls);
946 }
947
948 AppendInstruction(new (arena_) HNewInstance(
949 cls,
950 graph_->GetCurrentMethod(),
951 dex_pc,
952 type_index,
953 *dex_compilation_unit_->GetDexFile(),
Mingyao Yang062157f2016-03-02 10:15:36 -0800954 needs_access_check,
David Brazdildee58d62016-04-07 09:54:26 +0000955 finalizable,
956 entrypoint));
957 return true;
958}
959
960static bool IsSubClass(mirror::Class* to_test, mirror::Class* super_class)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700961 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdildee58d62016-04-07 09:54:26 +0000962 return to_test != nullptr && !to_test->IsInterface() && to_test->IsSubClass(super_class);
963}
964
965bool HInstructionBuilder::IsInitialized(Handle<mirror::Class> cls) const {
966 if (cls.Get() == nullptr) {
967 return false;
968 }
969
970 // `CanAssumeClassIsLoaded` will return true if we're JITting, or will
971 // check whether the class is in an image for the AOT compilation.
972 if (cls->IsInitialized() &&
973 compiler_driver_->CanAssumeClassIsLoaded(cls.Get())) {
974 return true;
975 }
976
977 if (IsSubClass(GetOutermostCompilingClass(), cls.Get())) {
978 return true;
979 }
980
981 // TODO: We should walk over the inlined methods, but we don't pass
982 // that information to the builder.
983 if (IsSubClass(GetCompilingClass(), cls.Get())) {
984 return true;
985 }
986
987 return false;
988}
989
990HClinitCheck* HInstructionBuilder::ProcessClinitCheckForInvoke(
991 uint32_t dex_pc,
992 ArtMethod* resolved_method,
993 uint32_t method_idx,
994 HInvokeStaticOrDirect::ClinitCheckRequirement* clinit_check_requirement) {
995 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
996 Thread* self = Thread::Current();
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100997 StackHandleScope<2> hs(self);
998 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
999 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001000 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1001 Handle<mirror::Class> resolved_method_class(hs.NewHandle(resolved_method->GetDeclaringClass()));
1002
1003 // The index at which the method's class is stored in the DexCache's type array.
1004 uint32_t storage_index = DexFile::kDexNoIndex;
1005 bool is_outer_class = (resolved_method->GetDeclaringClass() == outer_class.Get());
1006 if (is_outer_class) {
1007 storage_index = outer_class->GetDexTypeIndex();
1008 } else if (outer_dex_cache.Get() == dex_cache.Get()) {
1009 // Get `storage_index` from IsClassOfStaticMethodAvailableToReferrer.
1010 compiler_driver_->IsClassOfStaticMethodAvailableToReferrer(outer_dex_cache.Get(),
1011 GetCompilingClass(),
1012 resolved_method,
1013 method_idx,
1014 &storage_index);
1015 }
1016
1017 HClinitCheck* clinit_check = nullptr;
1018
1019 if (IsInitialized(resolved_method_class)) {
1020 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kNone;
1021 } else if (storage_index != DexFile::kDexNoIndex) {
1022 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit;
1023 HLoadClass* load_class = new (arena_) HLoadClass(
1024 graph_->GetCurrentMethod(),
1025 storage_index,
1026 outer_dex_file,
1027 is_outer_class,
1028 dex_pc,
1029 /*needs_access_check*/ false,
Mathieu Chartier31b12e32016-09-02 17:11:57 -07001030 /* is_in_dex_cache */ false,
1031 /* is_in_boot_image */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001032 AppendInstruction(load_class);
1033 clinit_check = new (arena_) HClinitCheck(load_class, dex_pc);
1034 AppendInstruction(clinit_check);
1035 }
1036 return clinit_check;
1037}
1038
1039bool HInstructionBuilder::SetupInvokeArguments(HInvoke* invoke,
1040 uint32_t number_of_vreg_arguments,
1041 uint32_t* args,
1042 uint32_t register_index,
1043 bool is_range,
1044 const char* descriptor,
1045 size_t start_index,
1046 size_t* argument_index) {
1047 uint32_t descriptor_index = 1; // Skip the return type.
1048
1049 for (size_t i = start_index;
1050 // Make sure we don't go over the expected arguments or over the number of
1051 // dex registers given. If the instruction was seen as dead by the verifier,
1052 // it hasn't been properly checked.
1053 (i < number_of_vreg_arguments) && (*argument_index < invoke->GetNumberOfArguments());
1054 i++, (*argument_index)++) {
1055 Primitive::Type type = Primitive::GetType(descriptor[descriptor_index++]);
1056 bool is_wide = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble);
1057 if (!is_range
1058 && is_wide
1059 && ((i + 1 == number_of_vreg_arguments) || (args[i] + 1 != args[i + 1]))) {
1060 // Longs and doubles should be in pairs, that is, sequential registers. The verifier should
1061 // reject any class where this is violated. However, the verifier only does these checks
1062 // on non trivially dead instructions, so we just bailout the compilation.
1063 VLOG(compiler) << "Did not compile "
1064 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1065 << " because of non-sequential dex register pair in wide argument";
1066 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1067 return false;
1068 }
1069 HInstruction* arg = LoadLocal(is_range ? register_index + i : args[i], type);
1070 invoke->SetArgumentAt(*argument_index, arg);
1071 if (is_wide) {
1072 i++;
1073 }
1074 }
1075
1076 if (*argument_index != invoke->GetNumberOfArguments()) {
1077 VLOG(compiler) << "Did not compile "
1078 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1079 << " because of wrong number of arguments in invoke instruction";
1080 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1081 return false;
1082 }
1083
1084 if (invoke->IsInvokeStaticOrDirect() &&
1085 HInvokeStaticOrDirect::NeedsCurrentMethodInput(
1086 invoke->AsInvokeStaticOrDirect()->GetMethodLoadKind())) {
1087 invoke->SetArgumentAt(*argument_index, graph_->GetCurrentMethod());
1088 (*argument_index)++;
1089 }
1090
1091 return true;
1092}
1093
1094bool HInstructionBuilder::HandleInvoke(HInvoke* invoke,
1095 uint32_t number_of_vreg_arguments,
1096 uint32_t* args,
1097 uint32_t register_index,
1098 bool is_range,
1099 const char* descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -07001100 HClinitCheck* clinit_check,
1101 bool is_unresolved) {
David Brazdildee58d62016-04-07 09:54:26 +00001102 DCHECK(!invoke->IsInvokeStaticOrDirect() || !invoke->AsInvokeStaticOrDirect()->IsStringInit());
1103
1104 size_t start_index = 0;
1105 size_t argument_index = 0;
1106 if (invoke->GetOriginalInvokeType() != InvokeType::kStatic) { // Instance call.
Aart Bik296fbb42016-06-07 13:49:12 -07001107 uint32_t obj_reg = is_range ? register_index : args[0];
1108 HInstruction* arg = is_unresolved
1109 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1110 : LoadNullCheckedLocal(obj_reg, invoke->GetDexPc());
David Brazdilc120bbe2016-04-22 16:57:00 +01001111 invoke->SetArgumentAt(0, arg);
David Brazdildee58d62016-04-07 09:54:26 +00001112 start_index = 1;
1113 argument_index = 1;
1114 }
1115
1116 if (!SetupInvokeArguments(invoke,
1117 number_of_vreg_arguments,
1118 args,
1119 register_index,
1120 is_range,
1121 descriptor,
1122 start_index,
1123 &argument_index)) {
1124 return false;
1125 }
1126
1127 if (clinit_check != nullptr) {
1128 // Add the class initialization check as last input of `invoke`.
1129 DCHECK(invoke->IsInvokeStaticOrDirect());
1130 DCHECK(invoke->AsInvokeStaticOrDirect()->GetClinitCheckRequirement()
1131 == HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit);
1132 invoke->SetArgumentAt(argument_index, clinit_check);
1133 argument_index++;
1134 }
1135
1136 AppendInstruction(invoke);
1137 latest_result_ = invoke;
1138
1139 return true;
1140}
1141
1142bool HInstructionBuilder::HandleStringInit(HInvoke* invoke,
1143 uint32_t number_of_vreg_arguments,
1144 uint32_t* args,
1145 uint32_t register_index,
1146 bool is_range,
1147 const char* descriptor) {
1148 DCHECK(invoke->IsInvokeStaticOrDirect());
1149 DCHECK(invoke->AsInvokeStaticOrDirect()->IsStringInit());
1150
1151 size_t start_index = 1;
1152 size_t argument_index = 0;
1153 if (!SetupInvokeArguments(invoke,
1154 number_of_vreg_arguments,
1155 args,
1156 register_index,
1157 is_range,
1158 descriptor,
1159 start_index,
1160 &argument_index)) {
1161 return false;
1162 }
1163
1164 AppendInstruction(invoke);
1165
1166 // This is a StringFactory call, not an actual String constructor. Its result
1167 // replaces the empty String pre-allocated by NewInstance.
1168 uint32_t orig_this_reg = is_range ? register_index : args[0];
1169 HInstruction* arg_this = LoadLocal(orig_this_reg, Primitive::kPrimNot);
1170
1171 // Replacing the NewInstance might render it redundant. Keep a list of these
1172 // to be visited once it is clear whether it is has remaining uses.
1173 if (arg_this->IsNewInstance()) {
1174 ssa_builder_->AddUninitializedString(arg_this->AsNewInstance());
1175 } else {
1176 DCHECK(arg_this->IsPhi());
1177 // NewInstance is not the direct input of the StringFactory call. It might
1178 // be redundant but optimizing this case is not worth the effort.
1179 }
1180
1181 // Walk over all vregs and replace any occurrence of `arg_this` with `invoke`.
1182 for (size_t vreg = 0, e = current_locals_->size(); vreg < e; ++vreg) {
1183 if ((*current_locals_)[vreg] == arg_this) {
1184 (*current_locals_)[vreg] = invoke;
1185 }
1186 }
1187
1188 return true;
1189}
1190
1191static Primitive::Type GetFieldAccessType(const DexFile& dex_file, uint16_t field_index) {
1192 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_index);
1193 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
1194 return Primitive::GetType(type[0]);
1195}
1196
1197bool HInstructionBuilder::BuildInstanceFieldAccess(const Instruction& instruction,
1198 uint32_t dex_pc,
1199 bool is_put) {
1200 uint32_t source_or_dest_reg = instruction.VRegA_22c();
1201 uint32_t obj_reg = instruction.VRegB_22c();
1202 uint16_t field_index;
1203 if (instruction.IsQuickened()) {
1204 if (!CanDecodeQuickenedInfo()) {
1205 return false;
1206 }
1207 field_index = LookupQuickenedInfo(dex_pc);
1208 } else {
1209 field_index = instruction.VRegC_22c();
1210 }
1211
1212 ScopedObjectAccess soa(Thread::Current());
1213 ArtField* resolved_field =
1214 compiler_driver_->ComputeInstanceFieldInfo(field_index, dex_compilation_unit_, is_put, soa);
1215
1216
Aart Bik14154132016-06-02 17:53:58 -07001217 // Generate an explicit null check on the reference, unless the field access
1218 // is unresolved. In that case, we rely on the runtime to perform various
1219 // checks first, followed by a null check.
1220 HInstruction* object = (resolved_field == nullptr)
1221 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1222 : LoadNullCheckedLocal(obj_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001223
1224 Primitive::Type field_type = (resolved_field == nullptr)
1225 ? GetFieldAccessType(*dex_file_, field_index)
1226 : resolved_field->GetTypeAsPrimitiveType();
1227 if (is_put) {
1228 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1229 HInstruction* field_set = nullptr;
1230 if (resolved_field == nullptr) {
1231 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001232 field_set = new (arena_) HUnresolvedInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001233 value,
1234 field_type,
1235 field_index,
1236 dex_pc);
1237 } else {
1238 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001239 field_set = new (arena_) HInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001240 value,
1241 field_type,
1242 resolved_field->GetOffset(),
1243 resolved_field->IsVolatile(),
1244 field_index,
1245 class_def_index,
1246 *dex_file_,
1247 dex_compilation_unit_->GetDexCache(),
1248 dex_pc);
1249 }
1250 AppendInstruction(field_set);
1251 } else {
1252 HInstruction* field_get = nullptr;
1253 if (resolved_field == nullptr) {
1254 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001255 field_get = new (arena_) HUnresolvedInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001256 field_type,
1257 field_index,
1258 dex_pc);
1259 } else {
1260 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001261 field_get = new (arena_) HInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001262 field_type,
1263 resolved_field->GetOffset(),
1264 resolved_field->IsVolatile(),
1265 field_index,
1266 class_def_index,
1267 *dex_file_,
1268 dex_compilation_unit_->GetDexCache(),
1269 dex_pc);
1270 }
1271 AppendInstruction(field_get);
1272 UpdateLocal(source_or_dest_reg, field_get);
1273 }
1274
1275 return true;
1276}
1277
1278static mirror::Class* GetClassFrom(CompilerDriver* driver,
1279 const DexCompilationUnit& compilation_unit) {
1280 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001281 StackHandleScope<1> hs(soa.Self());
David Brazdildee58d62016-04-07 09:54:26 +00001282 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1283 soa.Decode<mirror::ClassLoader*>(compilation_unit.GetClassLoader())));
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001284 Handle<mirror::DexCache> dex_cache = compilation_unit.GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001285
1286 return driver->ResolveCompilingMethodsClass(soa, dex_cache, class_loader, &compilation_unit);
1287}
1288
1289mirror::Class* HInstructionBuilder::GetOutermostCompilingClass() const {
1290 return GetClassFrom(compiler_driver_, *outer_compilation_unit_);
1291}
1292
1293mirror::Class* HInstructionBuilder::GetCompilingClass() const {
1294 return GetClassFrom(compiler_driver_, *dex_compilation_unit_);
1295}
1296
1297bool HInstructionBuilder::IsOutermostCompilingClass(uint16_t type_index) const {
1298 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001299 StackHandleScope<3> hs(soa.Self());
1300 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001301 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1302 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1303 Handle<mirror::Class> cls(hs.NewHandle(compiler_driver_->ResolveClass(
1304 soa, dex_cache, class_loader, type_index, dex_compilation_unit_)));
1305 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1306
1307 // GetOutermostCompilingClass returns null when the class is unresolved
1308 // (e.g. if it derives from an unresolved class). This is bogus knowing that
1309 // we are compiling it.
1310 // When this happens we cannot establish a direct relation between the current
1311 // class and the outer class, so we return false.
1312 // (Note that this is only used for optimizing invokes and field accesses)
1313 return (cls.Get() != nullptr) && (outer_class.Get() == cls.Get());
1314}
1315
1316void HInstructionBuilder::BuildUnresolvedStaticFieldAccess(const Instruction& instruction,
1317 uint32_t dex_pc,
1318 bool is_put,
1319 Primitive::Type field_type) {
1320 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1321 uint16_t field_index = instruction.VRegB_21c();
1322
1323 if (is_put) {
1324 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1325 AppendInstruction(
1326 new (arena_) HUnresolvedStaticFieldSet(value, field_type, field_index, dex_pc));
1327 } else {
1328 AppendInstruction(new (arena_) HUnresolvedStaticFieldGet(field_type, field_index, dex_pc));
1329 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1330 }
1331}
1332
1333bool HInstructionBuilder::BuildStaticFieldAccess(const Instruction& instruction,
1334 uint32_t dex_pc,
1335 bool is_put) {
1336 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1337 uint16_t field_index = instruction.VRegB_21c();
1338
1339 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001340 StackHandleScope<3> hs(soa.Self());
1341 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001342 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1343 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1344 ArtField* resolved_field = compiler_driver_->ResolveField(
1345 soa, dex_cache, class_loader, dex_compilation_unit_, field_index, true);
1346
1347 if (resolved_field == nullptr) {
1348 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1349 Primitive::Type field_type = GetFieldAccessType(*dex_file_, field_index);
1350 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1351 return true;
1352 }
1353
1354 Primitive::Type field_type = resolved_field->GetTypeAsPrimitiveType();
1355 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001356 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001357 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1358
1359 // The index at which the field's class is stored in the DexCache's type array.
1360 uint32_t storage_index;
1361 bool is_outer_class = (outer_class.Get() == resolved_field->GetDeclaringClass());
1362 if (is_outer_class) {
1363 storage_index = outer_class->GetDexTypeIndex();
1364 } else if (outer_dex_cache.Get() != dex_cache.Get()) {
1365 // The compiler driver cannot currently understand multiple dex caches involved. Just bailout.
1366 return false;
1367 } else {
1368 // TODO: This is rather expensive. Perf it and cache the results if needed.
1369 std::pair<bool, bool> pair = compiler_driver_->IsFastStaticField(
1370 outer_dex_cache.Get(),
1371 GetCompilingClass(),
1372 resolved_field,
1373 field_index,
1374 &storage_index);
1375 bool can_easily_access = is_put ? pair.second : pair.first;
1376 if (!can_easily_access) {
1377 MaybeRecordStat(MethodCompilationStat::kUnresolvedFieldNotAFastAccess);
1378 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1379 return true;
1380 }
1381 }
1382
David Brazdildee58d62016-04-07 09:54:26 +00001383 HLoadClass* constant = new (arena_) HLoadClass(graph_->GetCurrentMethod(),
1384 storage_index,
1385 outer_dex_file,
1386 is_outer_class,
1387 dex_pc,
1388 /*needs_access_check*/ false,
Mathieu Chartier31b12e32016-09-02 17:11:57 -07001389 /* is_in_dex_cache */ false,
1390 /* is_in_boot_image */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001391 AppendInstruction(constant);
1392
1393 HInstruction* cls = constant;
1394
1395 Handle<mirror::Class> klass(hs.NewHandle(resolved_field->GetDeclaringClass()));
1396 if (!IsInitialized(klass)) {
1397 cls = new (arena_) HClinitCheck(constant, dex_pc);
1398 AppendInstruction(cls);
1399 }
1400
1401 uint16_t class_def_index = klass->GetDexClassDefIndex();
1402 if (is_put) {
1403 // We need to keep the class alive before loading the value.
1404 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1405 DCHECK_EQ(HPhi::ToPhiType(value->GetType()), HPhi::ToPhiType(field_type));
1406 AppendInstruction(new (arena_) HStaticFieldSet(cls,
1407 value,
1408 field_type,
1409 resolved_field->GetOffset(),
1410 resolved_field->IsVolatile(),
1411 field_index,
1412 class_def_index,
1413 *dex_file_,
1414 dex_cache_,
1415 dex_pc));
1416 } else {
1417 AppendInstruction(new (arena_) HStaticFieldGet(cls,
1418 field_type,
1419 resolved_field->GetOffset(),
1420 resolved_field->IsVolatile(),
1421 field_index,
1422 class_def_index,
1423 *dex_file_,
1424 dex_cache_,
1425 dex_pc));
1426 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1427 }
1428 return true;
1429}
1430
1431void HInstructionBuilder::BuildCheckedDivRem(uint16_t out_vreg,
1432 uint16_t first_vreg,
1433 int64_t second_vreg_or_constant,
1434 uint32_t dex_pc,
1435 Primitive::Type type,
1436 bool second_is_constant,
1437 bool isDiv) {
1438 DCHECK(type == Primitive::kPrimInt || type == Primitive::kPrimLong);
1439
1440 HInstruction* first = LoadLocal(first_vreg, type);
1441 HInstruction* second = nullptr;
1442 if (second_is_constant) {
1443 if (type == Primitive::kPrimInt) {
1444 second = graph_->GetIntConstant(second_vreg_or_constant, dex_pc);
1445 } else {
1446 second = graph_->GetLongConstant(second_vreg_or_constant, dex_pc);
1447 }
1448 } else {
1449 second = LoadLocal(second_vreg_or_constant, type);
1450 }
1451
1452 if (!second_is_constant
1453 || (type == Primitive::kPrimInt && second->AsIntConstant()->GetValue() == 0)
1454 || (type == Primitive::kPrimLong && second->AsLongConstant()->GetValue() == 0)) {
1455 second = new (arena_) HDivZeroCheck(second, dex_pc);
1456 AppendInstruction(second);
1457 }
1458
1459 if (isDiv) {
1460 AppendInstruction(new (arena_) HDiv(type, first, second, dex_pc));
1461 } else {
1462 AppendInstruction(new (arena_) HRem(type, first, second, dex_pc));
1463 }
1464 UpdateLocal(out_vreg, current_block_->GetLastInstruction());
1465}
1466
1467void HInstructionBuilder::BuildArrayAccess(const Instruction& instruction,
1468 uint32_t dex_pc,
1469 bool is_put,
1470 Primitive::Type anticipated_type) {
1471 uint8_t source_or_dest_reg = instruction.VRegA_23x();
1472 uint8_t array_reg = instruction.VRegB_23x();
1473 uint8_t index_reg = instruction.VRegC_23x();
1474
David Brazdilc120bbe2016-04-22 16:57:00 +01001475 HInstruction* object = LoadNullCheckedLocal(array_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001476 HInstruction* length = new (arena_) HArrayLength(object, dex_pc);
1477 AppendInstruction(length);
1478 HInstruction* index = LoadLocal(index_reg, Primitive::kPrimInt);
1479 index = new (arena_) HBoundsCheck(index, length, dex_pc);
1480 AppendInstruction(index);
1481 if (is_put) {
1482 HInstruction* value = LoadLocal(source_or_dest_reg, anticipated_type);
1483 // TODO: Insert a type check node if the type is Object.
1484 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1485 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1486 AppendInstruction(aset);
1487 } else {
1488 HArrayGet* aget = new (arena_) HArrayGet(object, index, anticipated_type, dex_pc);
1489 ssa_builder_->MaybeAddAmbiguousArrayGet(aget);
1490 AppendInstruction(aget);
1491 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1492 }
1493 graph_->SetHasBoundsChecks(true);
1494}
1495
1496void HInstructionBuilder::BuildFilledNewArray(uint32_t dex_pc,
1497 uint32_t type_index,
1498 uint32_t number_of_vreg_arguments,
1499 bool is_range,
1500 uint32_t* args,
1501 uint32_t register_index) {
1502 HInstruction* length = graph_->GetIntConstant(number_of_vreg_arguments, dex_pc);
1503 bool finalizable;
1504 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
1505 ? kQuickAllocArrayWithAccessCheck
1506 : kQuickAllocArray;
1507 HInstruction* object = new (arena_) HNewArray(length,
1508 graph_->GetCurrentMethod(),
1509 dex_pc,
1510 type_index,
1511 *dex_compilation_unit_->GetDexFile(),
1512 entrypoint);
1513 AppendInstruction(object);
1514
1515 const char* descriptor = dex_file_->StringByTypeIdx(type_index);
1516 DCHECK_EQ(descriptor[0], '[') << descriptor;
1517 char primitive = descriptor[1];
1518 DCHECK(primitive == 'I'
1519 || primitive == 'L'
1520 || primitive == '[') << descriptor;
1521 bool is_reference_array = (primitive == 'L') || (primitive == '[');
1522 Primitive::Type type = is_reference_array ? Primitive::kPrimNot : Primitive::kPrimInt;
1523
1524 for (size_t i = 0; i < number_of_vreg_arguments; ++i) {
1525 HInstruction* value = LoadLocal(is_range ? register_index + i : args[i], type);
1526 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1527 HArraySet* aset = new (arena_) HArraySet(object, index, value, type, dex_pc);
1528 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1529 AppendInstruction(aset);
1530 }
1531 latest_result_ = object;
1532}
1533
1534template <typename T>
1535void HInstructionBuilder::BuildFillArrayData(HInstruction* object,
1536 const T* data,
1537 uint32_t element_count,
1538 Primitive::Type anticipated_type,
1539 uint32_t dex_pc) {
1540 for (uint32_t i = 0; i < element_count; ++i) {
1541 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1542 HInstruction* value = graph_->GetIntConstant(data[i], dex_pc);
1543 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1544 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1545 AppendInstruction(aset);
1546 }
1547}
1548
1549void HInstructionBuilder::BuildFillArrayData(const Instruction& instruction, uint32_t dex_pc) {
David Brazdilc120bbe2016-04-22 16:57:00 +01001550 HInstruction* array = LoadNullCheckedLocal(instruction.VRegA_31t(), dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001551
1552 int32_t payload_offset = instruction.VRegB_31t() + dex_pc;
1553 const Instruction::ArrayDataPayload* payload =
1554 reinterpret_cast<const Instruction::ArrayDataPayload*>(code_item_.insns_ + payload_offset);
1555 const uint8_t* data = payload->data;
1556 uint32_t element_count = payload->element_count;
1557
Vladimir Markoc69fba22016-09-06 16:49:15 +01001558 if (element_count == 0u) {
1559 // For empty payload we emit only the null check above.
1560 return;
1561 }
1562
1563 HInstruction* length = new (arena_) HArrayLength(array, dex_pc);
1564 AppendInstruction(length);
1565
David Brazdildee58d62016-04-07 09:54:26 +00001566 // Implementation of this DEX instruction seems to be that the bounds check is
1567 // done before doing any stores.
1568 HInstruction* last_index = graph_->GetIntConstant(payload->element_count - 1, dex_pc);
1569 AppendInstruction(new (arena_) HBoundsCheck(last_index, length, dex_pc));
1570
1571 switch (payload->element_width) {
1572 case 1:
David Brazdilc120bbe2016-04-22 16:57:00 +01001573 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001574 reinterpret_cast<const int8_t*>(data),
1575 element_count,
1576 Primitive::kPrimByte,
1577 dex_pc);
1578 break;
1579 case 2:
David Brazdilc120bbe2016-04-22 16:57:00 +01001580 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001581 reinterpret_cast<const int16_t*>(data),
1582 element_count,
1583 Primitive::kPrimShort,
1584 dex_pc);
1585 break;
1586 case 4:
David Brazdilc120bbe2016-04-22 16:57:00 +01001587 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001588 reinterpret_cast<const int32_t*>(data),
1589 element_count,
1590 Primitive::kPrimInt,
1591 dex_pc);
1592 break;
1593 case 8:
David Brazdilc120bbe2016-04-22 16:57:00 +01001594 BuildFillWideArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001595 reinterpret_cast<const int64_t*>(data),
1596 element_count,
1597 dex_pc);
1598 break;
1599 default:
1600 LOG(FATAL) << "Unknown element width for " << payload->element_width;
1601 }
1602 graph_->SetHasBoundsChecks(true);
1603}
1604
1605void HInstructionBuilder::BuildFillWideArrayData(HInstruction* object,
1606 const int64_t* data,
1607 uint32_t element_count,
1608 uint32_t dex_pc) {
1609 for (uint32_t i = 0; i < element_count; ++i) {
1610 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1611 HInstruction* value = graph_->GetLongConstant(data[i], dex_pc);
1612 HArraySet* aset = new (arena_) HArraySet(object, index, value, Primitive::kPrimLong, dex_pc);
1613 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1614 AppendInstruction(aset);
1615 }
1616}
1617
1618static TypeCheckKind ComputeTypeCheckKind(Handle<mirror::Class> cls)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001619 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdildee58d62016-04-07 09:54:26 +00001620 if (cls.Get() == nullptr) {
1621 return TypeCheckKind::kUnresolvedCheck;
1622 } else if (cls->IsInterface()) {
1623 return TypeCheckKind::kInterfaceCheck;
1624 } else if (cls->IsArrayClass()) {
1625 if (cls->GetComponentType()->IsObjectClass()) {
1626 return TypeCheckKind::kArrayObjectCheck;
1627 } else if (cls->CannotBeAssignedFromOtherTypes()) {
1628 return TypeCheckKind::kExactCheck;
1629 } else {
1630 return TypeCheckKind::kArrayCheck;
1631 }
1632 } else if (cls->IsFinal()) {
1633 return TypeCheckKind::kExactCheck;
1634 } else if (cls->IsAbstract()) {
1635 return TypeCheckKind::kAbstractClassCheck;
1636 } else {
1637 return TypeCheckKind::kClassHierarchyCheck;
1638 }
1639}
1640
1641void HInstructionBuilder::BuildTypeCheck(const Instruction& instruction,
1642 uint8_t destination,
1643 uint8_t reference,
1644 uint16_t type_index,
1645 uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001646 ScopedObjectAccess soa(Thread::Current());
1647 StackHandleScope<1> hs(soa.Self());
1648 const DexFile& dex_file = *dex_compilation_unit_->GetDexFile();
1649 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1650 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
1651
David Brazdildee58d62016-04-07 09:54:26 +00001652 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
1653 dex_compilation_unit_->GetDexMethodIndex(),
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001654 dex_cache,
1655 type_index);
David Brazdildee58d62016-04-07 09:54:26 +00001656
1657 HInstruction* object = LoadLocal(reference, Primitive::kPrimNot);
1658 HLoadClass* cls = new (arena_) HLoadClass(
1659 graph_->GetCurrentMethod(),
1660 type_index,
1661 dex_file,
1662 IsOutermostCompilingClass(type_index),
1663 dex_pc,
1664 !can_access,
Mathieu Chartier31b12e32016-09-02 17:11:57 -07001665 /* is_in_dex_cache */ false,
1666 /* is_in_boot_image */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001667 AppendInstruction(cls);
1668
1669 TypeCheckKind check_kind = ComputeTypeCheckKind(resolved_class);
1670 if (instruction.Opcode() == Instruction::INSTANCE_OF) {
1671 AppendInstruction(new (arena_) HInstanceOf(object, cls, check_kind, dex_pc));
1672 UpdateLocal(destination, current_block_->GetLastInstruction());
1673 } else {
1674 DCHECK_EQ(instruction.Opcode(), Instruction::CHECK_CAST);
1675 // We emit a CheckCast followed by a BoundType. CheckCast is a statement
1676 // which may throw. If it succeeds BoundType sets the new type of `object`
1677 // for all subsequent uses.
1678 AppendInstruction(new (arena_) HCheckCast(object, cls, check_kind, dex_pc));
1679 AppendInstruction(new (arena_) HBoundType(object, dex_pc));
1680 UpdateLocal(reference, current_block_->GetLastInstruction());
1681 }
1682}
1683
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001684bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index,
1685 Handle<mirror::DexCache> dex_cache,
1686 bool* finalizable) const {
David Brazdildee58d62016-04-07 09:54:26 +00001687 return !compiler_driver_->CanAccessInstantiableTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001688 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index, finalizable);
1689}
1690
1691bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index, bool* finalizable) const {
1692 ScopedObjectAccess soa(Thread::Current());
1693 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1694 return NeedsAccessCheck(type_index, dex_cache, finalizable);
David Brazdildee58d62016-04-07 09:54:26 +00001695}
1696
1697bool HInstructionBuilder::CanDecodeQuickenedInfo() const {
1698 return interpreter_metadata_ != nullptr;
1699}
1700
1701uint16_t HInstructionBuilder::LookupQuickenedInfo(uint32_t dex_pc) {
1702 DCHECK(interpreter_metadata_ != nullptr);
1703
1704 // First check if the info has already been decoded from `interpreter_metadata_`.
1705 auto it = skipped_interpreter_metadata_.find(dex_pc);
1706 if (it != skipped_interpreter_metadata_.end()) {
1707 // Remove the entry from the map and return the parsed info.
1708 uint16_t value_in_map = it->second;
1709 skipped_interpreter_metadata_.erase(it);
1710 return value_in_map;
1711 }
1712
1713 // Otherwise start parsing `interpreter_metadata_` until the slot for `dex_pc`
1714 // is found. Store skipped values in the `skipped_interpreter_metadata_` map.
1715 while (true) {
1716 uint32_t dex_pc_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1717 uint16_t value_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1718 DCHECK_LE(dex_pc_in_map, dex_pc);
1719
1720 if (dex_pc_in_map == dex_pc) {
1721 return value_in_map;
1722 } else {
1723 skipped_interpreter_metadata_.Put(dex_pc_in_map, value_in_map);
1724 }
1725 }
1726}
1727
1728bool HInstructionBuilder::ProcessDexInstruction(const Instruction& instruction, uint32_t dex_pc) {
1729 switch (instruction.Opcode()) {
1730 case Instruction::CONST_4: {
1731 int32_t register_index = instruction.VRegA();
1732 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_11n(), dex_pc);
1733 UpdateLocal(register_index, constant);
1734 break;
1735 }
1736
1737 case Instruction::CONST_16: {
1738 int32_t register_index = instruction.VRegA();
1739 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21s(), dex_pc);
1740 UpdateLocal(register_index, constant);
1741 break;
1742 }
1743
1744 case Instruction::CONST: {
1745 int32_t register_index = instruction.VRegA();
1746 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_31i(), dex_pc);
1747 UpdateLocal(register_index, constant);
1748 break;
1749 }
1750
1751 case Instruction::CONST_HIGH16: {
1752 int32_t register_index = instruction.VRegA();
1753 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21h() << 16, dex_pc);
1754 UpdateLocal(register_index, constant);
1755 break;
1756 }
1757
1758 case Instruction::CONST_WIDE_16: {
1759 int32_t register_index = instruction.VRegA();
1760 // Get 16 bits of constant value, sign extended to 64 bits.
1761 int64_t value = instruction.VRegB_21s();
1762 value <<= 48;
1763 value >>= 48;
1764 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1765 UpdateLocal(register_index, constant);
1766 break;
1767 }
1768
1769 case Instruction::CONST_WIDE_32: {
1770 int32_t register_index = instruction.VRegA();
1771 // Get 32 bits of constant value, sign extended to 64 bits.
1772 int64_t value = instruction.VRegB_31i();
1773 value <<= 32;
1774 value >>= 32;
1775 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1776 UpdateLocal(register_index, constant);
1777 break;
1778 }
1779
1780 case Instruction::CONST_WIDE: {
1781 int32_t register_index = instruction.VRegA();
1782 HLongConstant* constant = graph_->GetLongConstant(instruction.VRegB_51l(), dex_pc);
1783 UpdateLocal(register_index, constant);
1784 break;
1785 }
1786
1787 case Instruction::CONST_WIDE_HIGH16: {
1788 int32_t register_index = instruction.VRegA();
1789 int64_t value = static_cast<int64_t>(instruction.VRegB_21h()) << 48;
1790 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1791 UpdateLocal(register_index, constant);
1792 break;
1793 }
1794
1795 // Note that the SSA building will refine the types.
1796 case Instruction::MOVE:
1797 case Instruction::MOVE_FROM16:
1798 case Instruction::MOVE_16: {
1799 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
1800 UpdateLocal(instruction.VRegA(), value);
1801 break;
1802 }
1803
1804 // Note that the SSA building will refine the types.
1805 case Instruction::MOVE_WIDE:
1806 case Instruction::MOVE_WIDE_FROM16:
1807 case Instruction::MOVE_WIDE_16: {
1808 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimLong);
1809 UpdateLocal(instruction.VRegA(), value);
1810 break;
1811 }
1812
1813 case Instruction::MOVE_OBJECT:
1814 case Instruction::MOVE_OBJECT_16:
1815 case Instruction::MOVE_OBJECT_FROM16: {
1816 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimNot);
1817 UpdateLocal(instruction.VRegA(), value);
1818 break;
1819 }
1820
1821 case Instruction::RETURN_VOID_NO_BARRIER:
1822 case Instruction::RETURN_VOID: {
1823 BuildReturn(instruction, Primitive::kPrimVoid, dex_pc);
1824 break;
1825 }
1826
1827#define IF_XX(comparison, cond) \
1828 case Instruction::IF_##cond: If_22t<comparison>(instruction, dex_pc); break; \
1829 case Instruction::IF_##cond##Z: If_21t<comparison>(instruction, dex_pc); break
1830
1831 IF_XX(HEqual, EQ);
1832 IF_XX(HNotEqual, NE);
1833 IF_XX(HLessThan, LT);
1834 IF_XX(HLessThanOrEqual, LE);
1835 IF_XX(HGreaterThan, GT);
1836 IF_XX(HGreaterThanOrEqual, GE);
1837
1838 case Instruction::GOTO:
1839 case Instruction::GOTO_16:
1840 case Instruction::GOTO_32: {
1841 AppendInstruction(new (arena_) HGoto(dex_pc));
1842 current_block_ = nullptr;
1843 break;
1844 }
1845
1846 case Instruction::RETURN: {
1847 BuildReturn(instruction, return_type_, dex_pc);
1848 break;
1849 }
1850
1851 case Instruction::RETURN_OBJECT: {
1852 BuildReturn(instruction, return_type_, dex_pc);
1853 break;
1854 }
1855
1856 case Instruction::RETURN_WIDE: {
1857 BuildReturn(instruction, return_type_, dex_pc);
1858 break;
1859 }
1860
1861 case Instruction::INVOKE_DIRECT:
1862 case Instruction::INVOKE_INTERFACE:
1863 case Instruction::INVOKE_STATIC:
1864 case Instruction::INVOKE_SUPER:
1865 case Instruction::INVOKE_VIRTUAL:
1866 case Instruction::INVOKE_VIRTUAL_QUICK: {
1867 uint16_t method_idx;
1868 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_QUICK) {
1869 if (!CanDecodeQuickenedInfo()) {
1870 return false;
1871 }
1872 method_idx = LookupQuickenedInfo(dex_pc);
1873 } else {
1874 method_idx = instruction.VRegB_35c();
1875 }
1876 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
1877 uint32_t args[5];
1878 instruction.GetVarArgs(args);
1879 if (!BuildInvoke(instruction, dex_pc, method_idx,
1880 number_of_vreg_arguments, false, args, -1)) {
1881 return false;
1882 }
1883 break;
1884 }
1885
1886 case Instruction::INVOKE_DIRECT_RANGE:
1887 case Instruction::INVOKE_INTERFACE_RANGE:
1888 case Instruction::INVOKE_STATIC_RANGE:
1889 case Instruction::INVOKE_SUPER_RANGE:
1890 case Instruction::INVOKE_VIRTUAL_RANGE:
1891 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
1892 uint16_t method_idx;
1893 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK) {
1894 if (!CanDecodeQuickenedInfo()) {
1895 return false;
1896 }
1897 method_idx = LookupQuickenedInfo(dex_pc);
1898 } else {
1899 method_idx = instruction.VRegB_3rc();
1900 }
1901 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
1902 uint32_t register_index = instruction.VRegC();
1903 if (!BuildInvoke(instruction, dex_pc, method_idx,
1904 number_of_vreg_arguments, true, nullptr, register_index)) {
1905 return false;
1906 }
1907 break;
1908 }
1909
1910 case Instruction::NEG_INT: {
1911 Unop_12x<HNeg>(instruction, Primitive::kPrimInt, dex_pc);
1912 break;
1913 }
1914
1915 case Instruction::NEG_LONG: {
1916 Unop_12x<HNeg>(instruction, Primitive::kPrimLong, dex_pc);
1917 break;
1918 }
1919
1920 case Instruction::NEG_FLOAT: {
1921 Unop_12x<HNeg>(instruction, Primitive::kPrimFloat, dex_pc);
1922 break;
1923 }
1924
1925 case Instruction::NEG_DOUBLE: {
1926 Unop_12x<HNeg>(instruction, Primitive::kPrimDouble, dex_pc);
1927 break;
1928 }
1929
1930 case Instruction::NOT_INT: {
1931 Unop_12x<HNot>(instruction, Primitive::kPrimInt, dex_pc);
1932 break;
1933 }
1934
1935 case Instruction::NOT_LONG: {
1936 Unop_12x<HNot>(instruction, Primitive::kPrimLong, dex_pc);
1937 break;
1938 }
1939
1940 case Instruction::INT_TO_LONG: {
1941 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimLong, dex_pc);
1942 break;
1943 }
1944
1945 case Instruction::INT_TO_FLOAT: {
1946 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimFloat, dex_pc);
1947 break;
1948 }
1949
1950 case Instruction::INT_TO_DOUBLE: {
1951 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimDouble, dex_pc);
1952 break;
1953 }
1954
1955 case Instruction::LONG_TO_INT: {
1956 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimInt, dex_pc);
1957 break;
1958 }
1959
1960 case Instruction::LONG_TO_FLOAT: {
1961 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimFloat, dex_pc);
1962 break;
1963 }
1964
1965 case Instruction::LONG_TO_DOUBLE: {
1966 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimDouble, dex_pc);
1967 break;
1968 }
1969
1970 case Instruction::FLOAT_TO_INT: {
1971 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimInt, dex_pc);
1972 break;
1973 }
1974
1975 case Instruction::FLOAT_TO_LONG: {
1976 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimLong, dex_pc);
1977 break;
1978 }
1979
1980 case Instruction::FLOAT_TO_DOUBLE: {
1981 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimDouble, dex_pc);
1982 break;
1983 }
1984
1985 case Instruction::DOUBLE_TO_INT: {
1986 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimInt, dex_pc);
1987 break;
1988 }
1989
1990 case Instruction::DOUBLE_TO_LONG: {
1991 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimLong, dex_pc);
1992 break;
1993 }
1994
1995 case Instruction::DOUBLE_TO_FLOAT: {
1996 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimFloat, dex_pc);
1997 break;
1998 }
1999
2000 case Instruction::INT_TO_BYTE: {
2001 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimByte, dex_pc);
2002 break;
2003 }
2004
2005 case Instruction::INT_TO_SHORT: {
2006 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimShort, dex_pc);
2007 break;
2008 }
2009
2010 case Instruction::INT_TO_CHAR: {
2011 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimChar, dex_pc);
2012 break;
2013 }
2014
2015 case Instruction::ADD_INT: {
2016 Binop_23x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2017 break;
2018 }
2019
2020 case Instruction::ADD_LONG: {
2021 Binop_23x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2022 break;
2023 }
2024
2025 case Instruction::ADD_DOUBLE: {
2026 Binop_23x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2027 break;
2028 }
2029
2030 case Instruction::ADD_FLOAT: {
2031 Binop_23x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2032 break;
2033 }
2034
2035 case Instruction::SUB_INT: {
2036 Binop_23x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2037 break;
2038 }
2039
2040 case Instruction::SUB_LONG: {
2041 Binop_23x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2042 break;
2043 }
2044
2045 case Instruction::SUB_FLOAT: {
2046 Binop_23x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2047 break;
2048 }
2049
2050 case Instruction::SUB_DOUBLE: {
2051 Binop_23x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2052 break;
2053 }
2054
2055 case Instruction::ADD_INT_2ADDR: {
2056 Binop_12x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2057 break;
2058 }
2059
2060 case Instruction::MUL_INT: {
2061 Binop_23x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2062 break;
2063 }
2064
2065 case Instruction::MUL_LONG: {
2066 Binop_23x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2067 break;
2068 }
2069
2070 case Instruction::MUL_FLOAT: {
2071 Binop_23x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2072 break;
2073 }
2074
2075 case Instruction::MUL_DOUBLE: {
2076 Binop_23x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2077 break;
2078 }
2079
2080 case Instruction::DIV_INT: {
2081 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2082 dex_pc, Primitive::kPrimInt, false, true);
2083 break;
2084 }
2085
2086 case Instruction::DIV_LONG: {
2087 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2088 dex_pc, Primitive::kPrimLong, false, true);
2089 break;
2090 }
2091
2092 case Instruction::DIV_FLOAT: {
2093 Binop_23x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2094 break;
2095 }
2096
2097 case Instruction::DIV_DOUBLE: {
2098 Binop_23x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2099 break;
2100 }
2101
2102 case Instruction::REM_INT: {
2103 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2104 dex_pc, Primitive::kPrimInt, false, false);
2105 break;
2106 }
2107
2108 case Instruction::REM_LONG: {
2109 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2110 dex_pc, Primitive::kPrimLong, false, false);
2111 break;
2112 }
2113
2114 case Instruction::REM_FLOAT: {
2115 Binop_23x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2116 break;
2117 }
2118
2119 case Instruction::REM_DOUBLE: {
2120 Binop_23x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2121 break;
2122 }
2123
2124 case Instruction::AND_INT: {
2125 Binop_23x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2126 break;
2127 }
2128
2129 case Instruction::AND_LONG: {
2130 Binop_23x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2131 break;
2132 }
2133
2134 case Instruction::SHL_INT: {
2135 Binop_23x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2136 break;
2137 }
2138
2139 case Instruction::SHL_LONG: {
2140 Binop_23x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2141 break;
2142 }
2143
2144 case Instruction::SHR_INT: {
2145 Binop_23x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2146 break;
2147 }
2148
2149 case Instruction::SHR_LONG: {
2150 Binop_23x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2151 break;
2152 }
2153
2154 case Instruction::USHR_INT: {
2155 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2156 break;
2157 }
2158
2159 case Instruction::USHR_LONG: {
2160 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2161 break;
2162 }
2163
2164 case Instruction::OR_INT: {
2165 Binop_23x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2166 break;
2167 }
2168
2169 case Instruction::OR_LONG: {
2170 Binop_23x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2171 break;
2172 }
2173
2174 case Instruction::XOR_INT: {
2175 Binop_23x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2176 break;
2177 }
2178
2179 case Instruction::XOR_LONG: {
2180 Binop_23x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2181 break;
2182 }
2183
2184 case Instruction::ADD_LONG_2ADDR: {
2185 Binop_12x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2186 break;
2187 }
2188
2189 case Instruction::ADD_DOUBLE_2ADDR: {
2190 Binop_12x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2191 break;
2192 }
2193
2194 case Instruction::ADD_FLOAT_2ADDR: {
2195 Binop_12x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2196 break;
2197 }
2198
2199 case Instruction::SUB_INT_2ADDR: {
2200 Binop_12x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2201 break;
2202 }
2203
2204 case Instruction::SUB_LONG_2ADDR: {
2205 Binop_12x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2206 break;
2207 }
2208
2209 case Instruction::SUB_FLOAT_2ADDR: {
2210 Binop_12x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2211 break;
2212 }
2213
2214 case Instruction::SUB_DOUBLE_2ADDR: {
2215 Binop_12x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2216 break;
2217 }
2218
2219 case Instruction::MUL_INT_2ADDR: {
2220 Binop_12x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2221 break;
2222 }
2223
2224 case Instruction::MUL_LONG_2ADDR: {
2225 Binop_12x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2226 break;
2227 }
2228
2229 case Instruction::MUL_FLOAT_2ADDR: {
2230 Binop_12x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2231 break;
2232 }
2233
2234 case Instruction::MUL_DOUBLE_2ADDR: {
2235 Binop_12x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2236 break;
2237 }
2238
2239 case Instruction::DIV_INT_2ADDR: {
2240 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2241 dex_pc, Primitive::kPrimInt, false, true);
2242 break;
2243 }
2244
2245 case Instruction::DIV_LONG_2ADDR: {
2246 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2247 dex_pc, Primitive::kPrimLong, false, true);
2248 break;
2249 }
2250
2251 case Instruction::REM_INT_2ADDR: {
2252 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2253 dex_pc, Primitive::kPrimInt, false, false);
2254 break;
2255 }
2256
2257 case Instruction::REM_LONG_2ADDR: {
2258 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2259 dex_pc, Primitive::kPrimLong, false, false);
2260 break;
2261 }
2262
2263 case Instruction::REM_FLOAT_2ADDR: {
2264 Binop_12x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2265 break;
2266 }
2267
2268 case Instruction::REM_DOUBLE_2ADDR: {
2269 Binop_12x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2270 break;
2271 }
2272
2273 case Instruction::SHL_INT_2ADDR: {
2274 Binop_12x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2275 break;
2276 }
2277
2278 case Instruction::SHL_LONG_2ADDR: {
2279 Binop_12x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2280 break;
2281 }
2282
2283 case Instruction::SHR_INT_2ADDR: {
2284 Binop_12x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2285 break;
2286 }
2287
2288 case Instruction::SHR_LONG_2ADDR: {
2289 Binop_12x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2290 break;
2291 }
2292
2293 case Instruction::USHR_INT_2ADDR: {
2294 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2295 break;
2296 }
2297
2298 case Instruction::USHR_LONG_2ADDR: {
2299 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2300 break;
2301 }
2302
2303 case Instruction::DIV_FLOAT_2ADDR: {
2304 Binop_12x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2305 break;
2306 }
2307
2308 case Instruction::DIV_DOUBLE_2ADDR: {
2309 Binop_12x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2310 break;
2311 }
2312
2313 case Instruction::AND_INT_2ADDR: {
2314 Binop_12x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2315 break;
2316 }
2317
2318 case Instruction::AND_LONG_2ADDR: {
2319 Binop_12x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2320 break;
2321 }
2322
2323 case Instruction::OR_INT_2ADDR: {
2324 Binop_12x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2325 break;
2326 }
2327
2328 case Instruction::OR_LONG_2ADDR: {
2329 Binop_12x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2330 break;
2331 }
2332
2333 case Instruction::XOR_INT_2ADDR: {
2334 Binop_12x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2335 break;
2336 }
2337
2338 case Instruction::XOR_LONG_2ADDR: {
2339 Binop_12x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2340 break;
2341 }
2342
2343 case Instruction::ADD_INT_LIT16: {
2344 Binop_22s<HAdd>(instruction, false, dex_pc);
2345 break;
2346 }
2347
2348 case Instruction::AND_INT_LIT16: {
2349 Binop_22s<HAnd>(instruction, false, dex_pc);
2350 break;
2351 }
2352
2353 case Instruction::OR_INT_LIT16: {
2354 Binop_22s<HOr>(instruction, false, dex_pc);
2355 break;
2356 }
2357
2358 case Instruction::XOR_INT_LIT16: {
2359 Binop_22s<HXor>(instruction, false, dex_pc);
2360 break;
2361 }
2362
2363 case Instruction::RSUB_INT: {
2364 Binop_22s<HSub>(instruction, true, dex_pc);
2365 break;
2366 }
2367
2368 case Instruction::MUL_INT_LIT16: {
2369 Binop_22s<HMul>(instruction, false, dex_pc);
2370 break;
2371 }
2372
2373 case Instruction::ADD_INT_LIT8: {
2374 Binop_22b<HAdd>(instruction, false, dex_pc);
2375 break;
2376 }
2377
2378 case Instruction::AND_INT_LIT8: {
2379 Binop_22b<HAnd>(instruction, false, dex_pc);
2380 break;
2381 }
2382
2383 case Instruction::OR_INT_LIT8: {
2384 Binop_22b<HOr>(instruction, false, dex_pc);
2385 break;
2386 }
2387
2388 case Instruction::XOR_INT_LIT8: {
2389 Binop_22b<HXor>(instruction, false, dex_pc);
2390 break;
2391 }
2392
2393 case Instruction::RSUB_INT_LIT8: {
2394 Binop_22b<HSub>(instruction, true, dex_pc);
2395 break;
2396 }
2397
2398 case Instruction::MUL_INT_LIT8: {
2399 Binop_22b<HMul>(instruction, false, dex_pc);
2400 break;
2401 }
2402
2403 case Instruction::DIV_INT_LIT16:
2404 case Instruction::DIV_INT_LIT8: {
2405 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2406 dex_pc, Primitive::kPrimInt, true, true);
2407 break;
2408 }
2409
2410 case Instruction::REM_INT_LIT16:
2411 case Instruction::REM_INT_LIT8: {
2412 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2413 dex_pc, Primitive::kPrimInt, true, false);
2414 break;
2415 }
2416
2417 case Instruction::SHL_INT_LIT8: {
2418 Binop_22b<HShl>(instruction, false, dex_pc);
2419 break;
2420 }
2421
2422 case Instruction::SHR_INT_LIT8: {
2423 Binop_22b<HShr>(instruction, false, dex_pc);
2424 break;
2425 }
2426
2427 case Instruction::USHR_INT_LIT8: {
2428 Binop_22b<HUShr>(instruction, false, dex_pc);
2429 break;
2430 }
2431
2432 case Instruction::NEW_INSTANCE: {
2433 if (!BuildNewInstance(instruction.VRegB_21c(), dex_pc)) {
2434 return false;
2435 }
2436 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
2437 break;
2438 }
2439
2440 case Instruction::NEW_ARRAY: {
2441 uint16_t type_index = instruction.VRegC_22c();
2442 HInstruction* length = LoadLocal(instruction.VRegB_22c(), Primitive::kPrimInt);
2443 bool finalizable;
2444 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
2445 ? kQuickAllocArrayWithAccessCheck
2446 : kQuickAllocArray;
2447 AppendInstruction(new (arena_) HNewArray(length,
2448 graph_->GetCurrentMethod(),
2449 dex_pc,
2450 type_index,
2451 *dex_compilation_unit_->GetDexFile(),
2452 entrypoint));
2453 UpdateLocal(instruction.VRegA_22c(), current_block_->GetLastInstruction());
2454 break;
2455 }
2456
2457 case Instruction::FILLED_NEW_ARRAY: {
2458 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
2459 uint32_t type_index = instruction.VRegB_35c();
2460 uint32_t args[5];
2461 instruction.GetVarArgs(args);
2462 BuildFilledNewArray(dex_pc, type_index, number_of_vreg_arguments, false, args, 0);
2463 break;
2464 }
2465
2466 case Instruction::FILLED_NEW_ARRAY_RANGE: {
2467 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
2468 uint32_t type_index = instruction.VRegB_3rc();
2469 uint32_t register_index = instruction.VRegC_3rc();
2470 BuildFilledNewArray(
2471 dex_pc, type_index, number_of_vreg_arguments, true, nullptr, register_index);
2472 break;
2473 }
2474
2475 case Instruction::FILL_ARRAY_DATA: {
2476 BuildFillArrayData(instruction, dex_pc);
2477 break;
2478 }
2479
2480 case Instruction::MOVE_RESULT:
2481 case Instruction::MOVE_RESULT_WIDE:
2482 case Instruction::MOVE_RESULT_OBJECT: {
2483 DCHECK(latest_result_ != nullptr);
2484 UpdateLocal(instruction.VRegA(), latest_result_);
2485 latest_result_ = nullptr;
2486 break;
2487 }
2488
2489 case Instruction::CMP_LONG: {
2490 Binop_23x_cmp(instruction, Primitive::kPrimLong, ComparisonBias::kNoBias, dex_pc);
2491 break;
2492 }
2493
2494 case Instruction::CMPG_FLOAT: {
2495 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kGtBias, dex_pc);
2496 break;
2497 }
2498
2499 case Instruction::CMPG_DOUBLE: {
2500 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kGtBias, dex_pc);
2501 break;
2502 }
2503
2504 case Instruction::CMPL_FLOAT: {
2505 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kLtBias, dex_pc);
2506 break;
2507 }
2508
2509 case Instruction::CMPL_DOUBLE: {
2510 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kLtBias, dex_pc);
2511 break;
2512 }
2513
2514 case Instruction::NOP:
2515 break;
2516
2517 case Instruction::IGET:
2518 case Instruction::IGET_QUICK:
2519 case Instruction::IGET_WIDE:
2520 case Instruction::IGET_WIDE_QUICK:
2521 case Instruction::IGET_OBJECT:
2522 case Instruction::IGET_OBJECT_QUICK:
2523 case Instruction::IGET_BOOLEAN:
2524 case Instruction::IGET_BOOLEAN_QUICK:
2525 case Instruction::IGET_BYTE:
2526 case Instruction::IGET_BYTE_QUICK:
2527 case Instruction::IGET_CHAR:
2528 case Instruction::IGET_CHAR_QUICK:
2529 case Instruction::IGET_SHORT:
2530 case Instruction::IGET_SHORT_QUICK: {
2531 if (!BuildInstanceFieldAccess(instruction, dex_pc, false)) {
2532 return false;
2533 }
2534 break;
2535 }
2536
2537 case Instruction::IPUT:
2538 case Instruction::IPUT_QUICK:
2539 case Instruction::IPUT_WIDE:
2540 case Instruction::IPUT_WIDE_QUICK:
2541 case Instruction::IPUT_OBJECT:
2542 case Instruction::IPUT_OBJECT_QUICK:
2543 case Instruction::IPUT_BOOLEAN:
2544 case Instruction::IPUT_BOOLEAN_QUICK:
2545 case Instruction::IPUT_BYTE:
2546 case Instruction::IPUT_BYTE_QUICK:
2547 case Instruction::IPUT_CHAR:
2548 case Instruction::IPUT_CHAR_QUICK:
2549 case Instruction::IPUT_SHORT:
2550 case Instruction::IPUT_SHORT_QUICK: {
2551 if (!BuildInstanceFieldAccess(instruction, dex_pc, true)) {
2552 return false;
2553 }
2554 break;
2555 }
2556
2557 case Instruction::SGET:
2558 case Instruction::SGET_WIDE:
2559 case Instruction::SGET_OBJECT:
2560 case Instruction::SGET_BOOLEAN:
2561 case Instruction::SGET_BYTE:
2562 case Instruction::SGET_CHAR:
2563 case Instruction::SGET_SHORT: {
2564 if (!BuildStaticFieldAccess(instruction, dex_pc, false)) {
2565 return false;
2566 }
2567 break;
2568 }
2569
2570 case Instruction::SPUT:
2571 case Instruction::SPUT_WIDE:
2572 case Instruction::SPUT_OBJECT:
2573 case Instruction::SPUT_BOOLEAN:
2574 case Instruction::SPUT_BYTE:
2575 case Instruction::SPUT_CHAR:
2576 case Instruction::SPUT_SHORT: {
2577 if (!BuildStaticFieldAccess(instruction, dex_pc, true)) {
2578 return false;
2579 }
2580 break;
2581 }
2582
2583#define ARRAY_XX(kind, anticipated_type) \
2584 case Instruction::AGET##kind: { \
2585 BuildArrayAccess(instruction, dex_pc, false, anticipated_type); \
2586 break; \
2587 } \
2588 case Instruction::APUT##kind: { \
2589 BuildArrayAccess(instruction, dex_pc, true, anticipated_type); \
2590 break; \
2591 }
2592
2593 ARRAY_XX(, Primitive::kPrimInt);
2594 ARRAY_XX(_WIDE, Primitive::kPrimLong);
2595 ARRAY_XX(_OBJECT, Primitive::kPrimNot);
2596 ARRAY_XX(_BOOLEAN, Primitive::kPrimBoolean);
2597 ARRAY_XX(_BYTE, Primitive::kPrimByte);
2598 ARRAY_XX(_CHAR, Primitive::kPrimChar);
2599 ARRAY_XX(_SHORT, Primitive::kPrimShort);
2600
2601 case Instruction::ARRAY_LENGTH: {
David Brazdilc120bbe2016-04-22 16:57:00 +01002602 HInstruction* object = LoadNullCheckedLocal(instruction.VRegB_12x(), dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00002603 AppendInstruction(new (arena_) HArrayLength(object, dex_pc));
2604 UpdateLocal(instruction.VRegA_12x(), current_block_->GetLastInstruction());
2605 break;
2606 }
2607
2608 case Instruction::CONST_STRING: {
2609 uint32_t string_index = instruction.VRegB_21c();
2610 AppendInstruction(
2611 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2612 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2613 break;
2614 }
2615
2616 case Instruction::CONST_STRING_JUMBO: {
2617 uint32_t string_index = instruction.VRegB_31c();
2618 AppendInstruction(
2619 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2620 UpdateLocal(instruction.VRegA_31c(), current_block_->GetLastInstruction());
2621 break;
2622 }
2623
2624 case Instruction::CONST_CLASS: {
2625 uint16_t type_index = instruction.VRegB_21c();
David Brazdildee58d62016-04-07 09:54:26 +00002626 // `CanAccessTypeWithoutChecks` will tell whether the method being
2627 // built is trying to access its own class, so that the generated
2628 // code can optimize for this case. However, the optimization does not
2629 // work for inlining, so we use `IsOutermostCompilingClass` instead.
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002630 ScopedObjectAccess soa(Thread::Current());
2631 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00002632 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002633 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index);
David Brazdildee58d62016-04-07 09:54:26 +00002634 AppendInstruction(new (arena_) HLoadClass(
2635 graph_->GetCurrentMethod(),
2636 type_index,
2637 *dex_file_,
2638 IsOutermostCompilingClass(type_index),
2639 dex_pc,
2640 !can_access,
Mathieu Chartier31b12e32016-09-02 17:11:57 -07002641 /* is_in_dex_cache */ false,
2642 /* is_in_boot_image */ false));
David Brazdildee58d62016-04-07 09:54:26 +00002643 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2644 break;
2645 }
2646
2647 case Instruction::MOVE_EXCEPTION: {
2648 AppendInstruction(new (arena_) HLoadException(dex_pc));
2649 UpdateLocal(instruction.VRegA_11x(), current_block_->GetLastInstruction());
2650 AppendInstruction(new (arena_) HClearException(dex_pc));
2651 break;
2652 }
2653
2654 case Instruction::THROW: {
2655 HInstruction* exception = LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot);
2656 AppendInstruction(new (arena_) HThrow(exception, dex_pc));
2657 // We finished building this block. Set the current block to null to avoid
2658 // adding dead instructions to it.
2659 current_block_ = nullptr;
2660 break;
2661 }
2662
2663 case Instruction::INSTANCE_OF: {
2664 uint8_t destination = instruction.VRegA_22c();
2665 uint8_t reference = instruction.VRegB_22c();
2666 uint16_t type_index = instruction.VRegC_22c();
2667 BuildTypeCheck(instruction, destination, reference, type_index, dex_pc);
2668 break;
2669 }
2670
2671 case Instruction::CHECK_CAST: {
2672 uint8_t reference = instruction.VRegA_21c();
2673 uint16_t type_index = instruction.VRegB_21c();
2674 BuildTypeCheck(instruction, -1, reference, type_index, dex_pc);
2675 break;
2676 }
2677
2678 case Instruction::MONITOR_ENTER: {
2679 AppendInstruction(new (arena_) HMonitorOperation(
2680 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2681 HMonitorOperation::OperationKind::kEnter,
2682 dex_pc));
2683 break;
2684 }
2685
2686 case Instruction::MONITOR_EXIT: {
2687 AppendInstruction(new (arena_) HMonitorOperation(
2688 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2689 HMonitorOperation::OperationKind::kExit,
2690 dex_pc));
2691 break;
2692 }
2693
2694 case Instruction::SPARSE_SWITCH:
2695 case Instruction::PACKED_SWITCH: {
2696 BuildSwitch(instruction, dex_pc);
2697 break;
2698 }
2699
2700 default:
2701 VLOG(compiler) << "Did not compile "
2702 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
2703 << " because of unhandled instruction "
2704 << instruction.Name();
2705 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnhandledInstruction);
2706 return false;
2707 }
2708 return true;
2709} // NOLINT(readability/fn_size)
2710
2711} // namespace art