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