blob: a096338ee2f96a60387d0dcfa4b9124239e96b54 [file] [log] [blame]
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "code_generator.h"
18
Alex Light50fa9932015-08-10 15:30:07 -070019#ifdef ART_ENABLE_CODEGEN_arm
Scott Wakelingfe885462016-09-22 10:24:38 +010020#include "code_generator_arm_vixl.h"
Alex Light50fa9932015-08-10 15:30:07 -070021#endif
22
23#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames5319def2014-10-23 10:03:10 +010024#include "code_generator_arm64.h"
Alex Light50fa9932015-08-10 15:30:07 -070025#endif
26
27#ifdef ART_ENABLE_CODEGEN_x86
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000028#include "code_generator_x86.h"
Alex Light50fa9932015-08-10 15:30:07 -070029#endif
30
31#ifdef ART_ENABLE_CODEGEN_x86_64
Nicolas Geoffray9cf35522014-06-09 18:40:10 +010032#include "code_generator_x86_64.h"
Alex Light50fa9932015-08-10 15:30:07 -070033#endif
34
Vladimir Marko86c87522020-05-11 16:55:55 +010035#include "art_method-inl.h"
Andreas Gampe5678db52017-06-08 14:11:18 -070036#include "base/bit_utils.h"
37#include "base/bit_utils_iterator.h"
Vladimir Marko174b2e22017-10-12 13:34:49 +010038#include "base/casts.h"
David Sehr67bf42e2018-02-26 16:43:04 -080039#include "base/leb128.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080040#include "class_linker.h"
Vladimir Marko98873af2020-12-16 12:10:03 +000041#include "class_root-inl.h"
Yevgeny Roubane3ea8382014-08-08 16:29:38 +070042#include "compiled_method.h"
David Sehr312f3b22018-03-19 08:39:26 -070043#include "dex/bytecode_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080044#include "dex/code_item_accessors-inl.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000045#include "dex/verified_method.h"
Alexandre Rameseb7b7392015-06-19 14:47:01 +010046#include "graph_visualizer.h"
Vladimir Markoe47f60c2018-02-21 13:43:28 +000047#include "image.h"
48#include "gc/space/image_space.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070049#include "intern_table.h"
Nicolas Geoffray5bd05a52015-10-13 09:48:30 +010050#include "intrinsics.h"
Nicolas Geoffray19a19cf2014-10-22 16:07:05 +010051#include "mirror/array-inl.h"
52#include "mirror/object_array-inl.h"
53#include "mirror/object_reference.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080054#include "mirror/reference.h"
Vladimir Markodce016e2016-04-28 13:10:02 +010055#include "mirror/string.h"
Alex Light50fa9932015-08-10 15:30:07 -070056#include "parallel_move_resolver.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080057#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070058#include "ssa_liveness_analysis.h"
David Srbecky71ec1cc2018-05-18 15:57:25 +010059#include "stack_map.h"
Vladimir Marko174b2e22017-10-12 13:34:49 +010060#include "stack_map_stream.h"
Vladimir Marko552a1342017-10-31 10:56:47 +000061#include "string_builder_append.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070062#include "thread-current-inl.h"
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000063#include "utils/assembler.h"
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000064
Vladimir Marko0a516052019-10-14 13:00:44 +000065namespace art {
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000066
Alexandre Rames88c13cd2015-04-14 17:35:39 +010067// Return whether a location is consistent with a type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010068static bool CheckType(DataType::Type type, Location location) {
Alexandre Rames88c13cd2015-04-14 17:35:39 +010069 if (location.IsFpuRegister()
70 || (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresFpuRegister))) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010071 return (type == DataType::Type::kFloat32) || (type == DataType::Type::kFloat64);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010072 } else if (location.IsRegister() ||
73 (location.IsUnallocated() && (location.GetPolicy() == Location::kRequiresRegister))) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010074 return DataType::IsIntegralType(type) || (type == DataType::Type::kReference);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010075 } else if (location.IsRegisterPair()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010076 return type == DataType::Type::kInt64;
Alexandre Rames88c13cd2015-04-14 17:35:39 +010077 } else if (location.IsFpuRegisterPair()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010078 return type == DataType::Type::kFloat64;
Alexandre Rames88c13cd2015-04-14 17:35:39 +010079 } else if (location.IsStackSlot()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010080 return (DataType::IsIntegralType(type) && type != DataType::Type::kInt64)
81 || (type == DataType::Type::kFloat32)
82 || (type == DataType::Type::kReference);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010083 } else if (location.IsDoubleStackSlot()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010084 return (type == DataType::Type::kInt64) || (type == DataType::Type::kFloat64);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010085 } else if (location.IsConstant()) {
86 if (location.GetConstant()->IsIntConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010087 return DataType::IsIntegralType(type) && (type != DataType::Type::kInt64);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010088 } else if (location.GetConstant()->IsNullConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010089 return type == DataType::Type::kReference;
Alexandre Rames88c13cd2015-04-14 17:35:39 +010090 } else if (location.GetConstant()->IsLongConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010091 return type == DataType::Type::kInt64;
Alexandre Rames88c13cd2015-04-14 17:35:39 +010092 } else if (location.GetConstant()->IsFloatConstant()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010093 return type == DataType::Type::kFloat32;
Alexandre Rames88c13cd2015-04-14 17:35:39 +010094 } else {
95 return location.GetConstant()->IsDoubleConstant()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010096 && (type == DataType::Type::kFloat64);
Alexandre Rames88c13cd2015-04-14 17:35:39 +010097 }
98 } else {
99 return location.IsInvalid() || (location.GetPolicy() == Location::kAny);
100 }
101}
102
103// Check that a location summary is consistent with an instruction.
104static bool CheckTypeConsistency(HInstruction* instruction) {
105 LocationSummary* locations = instruction->GetLocations();
106 if (locations == nullptr) {
107 return true;
108 }
109
110 if (locations->Out().IsUnallocated()
111 && (locations->Out().GetPolicy() == Location::kSameAsFirstInput)) {
112 DCHECK(CheckType(instruction->GetType(), locations->InAt(0)))
113 << instruction->GetType()
114 << " " << locations->InAt(0);
115 } else {
116 DCHECK(CheckType(instruction->GetType(), locations->Out()))
117 << instruction->GetType()
118 << " " << locations->Out();
119 }
120
Vladimir Markoe9004912016-06-16 16:50:52 +0100121 HConstInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100122 for (size_t i = 0; i < inputs.size(); ++i) {
123 DCHECK(CheckType(inputs[i]->GetType(), locations->InAt(i)))
124 << inputs[i]->GetType() << " " << locations->InAt(i);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100125 }
126
127 HEnvironment* environment = instruction->GetEnvironment();
128 for (size_t i = 0; i < instruction->EnvironmentSize(); ++i) {
129 if (environment->GetInstructionAt(i) != nullptr) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100130 DataType::Type type = environment->GetInstructionAt(i)->GetType();
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100131 DCHECK(CheckType(type, environment->GetLocationAt(i)))
132 << type << " " << environment->GetLocationAt(i);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100133 } else {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100134 DCHECK(environment->GetLocationAt(i).IsInvalid())
135 << environment->GetLocationAt(i);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100136 }
137 }
138 return true;
139}
140
Vladimir Marko174b2e22017-10-12 13:34:49 +0100141class CodeGenerator::CodeGenerationData : public DeletableArenaObject<kArenaAllocCodeGenerator> {
142 public:
143 static std::unique_ptr<CodeGenerationData> Create(ArenaStack* arena_stack,
144 InstructionSet instruction_set) {
145 ScopedArenaAllocator allocator(arena_stack);
146 void* memory = allocator.Alloc<CodeGenerationData>(kArenaAllocCodeGenerator);
147 return std::unique_ptr<CodeGenerationData>(
148 ::new (memory) CodeGenerationData(std::move(allocator), instruction_set));
149 }
150
151 ScopedArenaAllocator* GetScopedAllocator() {
152 return &allocator_;
153 }
154
155 void AddSlowPath(SlowPathCode* slow_path) {
156 slow_paths_.emplace_back(std::unique_ptr<SlowPathCode>(slow_path));
157 }
158
159 ArrayRef<const std::unique_ptr<SlowPathCode>> GetSlowPaths() const {
160 return ArrayRef<const std::unique_ptr<SlowPathCode>>(slow_paths_);
161 }
162
163 StackMapStream* GetStackMapStream() { return &stack_map_stream_; }
164
165 void ReserveJitStringRoot(StringReference string_reference, Handle<mirror::String> string) {
166 jit_string_roots_.Overwrite(string_reference,
167 reinterpret_cast64<uint64_t>(string.GetReference()));
168 }
169
170 uint64_t GetJitStringRootIndex(StringReference string_reference) const {
171 return jit_string_roots_.Get(string_reference);
172 }
173
174 size_t GetNumberOfJitStringRoots() const {
175 return jit_string_roots_.size();
176 }
177
178 void ReserveJitClassRoot(TypeReference type_reference, Handle<mirror::Class> klass) {
179 jit_class_roots_.Overwrite(type_reference, reinterpret_cast64<uint64_t>(klass.GetReference()));
180 }
181
182 uint64_t GetJitClassRootIndex(TypeReference type_reference) const {
183 return jit_class_roots_.Get(type_reference);
184 }
185
186 size_t GetNumberOfJitClassRoots() const {
187 return jit_class_roots_.size();
188 }
189
190 size_t GetNumberOfJitRoots() const {
191 return GetNumberOfJitStringRoots() + GetNumberOfJitClassRoots();
192 }
193
Vladimir Markoac3ac682018-09-20 11:01:43 +0100194 void EmitJitRoots(/*out*/std::vector<Handle<mirror::Object>>* roots)
Vladimir Marko174b2e22017-10-12 13:34:49 +0100195 REQUIRES_SHARED(Locks::mutator_lock_);
196
197 private:
198 CodeGenerationData(ScopedArenaAllocator&& allocator, InstructionSet instruction_set)
199 : allocator_(std::move(allocator)),
200 stack_map_stream_(&allocator_, instruction_set),
201 slow_paths_(allocator_.Adapter(kArenaAllocCodeGenerator)),
202 jit_string_roots_(StringReferenceValueComparator(),
203 allocator_.Adapter(kArenaAllocCodeGenerator)),
204 jit_class_roots_(TypeReferenceValueComparator(),
205 allocator_.Adapter(kArenaAllocCodeGenerator)) {
206 slow_paths_.reserve(kDefaultSlowPathsCapacity);
207 }
208
209 static constexpr size_t kDefaultSlowPathsCapacity = 8;
210
211 ScopedArenaAllocator allocator_;
212 StackMapStream stack_map_stream_;
213 ScopedArenaVector<std::unique_ptr<SlowPathCode>> slow_paths_;
214
215 // Maps a StringReference (dex_file, string_index) to the index in the literal table.
216 // Entries are intially added with a pointer in the handle zone, and `EmitJitRoots`
217 // will compute all the indices.
218 ScopedArenaSafeMap<StringReference, uint64_t, StringReferenceValueComparator> jit_string_roots_;
219
220 // Maps a ClassReference (dex_file, type_index) to the index in the literal table.
221 // Entries are intially added with a pointer in the handle zone, and `EmitJitRoots`
222 // will compute all the indices.
223 ScopedArenaSafeMap<TypeReference, uint64_t, TypeReferenceValueComparator> jit_class_roots_;
224};
225
226void CodeGenerator::CodeGenerationData::EmitJitRoots(
Vladimir Markoac3ac682018-09-20 11:01:43 +0100227 /*out*/std::vector<Handle<mirror::Object>>* roots) {
228 DCHECK(roots->empty());
229 roots->reserve(GetNumberOfJitRoots());
Vladimir Marko174b2e22017-10-12 13:34:49 +0100230 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
231 size_t index = 0;
232 for (auto& entry : jit_string_roots_) {
233 // Update the `roots` with the string, and replace the address temporarily
234 // stored to the index in the table.
235 uint64_t address = entry.second;
Vladimir Markoac3ac682018-09-20 11:01:43 +0100236 roots->emplace_back(reinterpret_cast<StackReference<mirror::Object>*>(address));
237 DCHECK(roots->back() != nullptr);
238 DCHECK(roots->back()->IsString());
Vladimir Marko174b2e22017-10-12 13:34:49 +0100239 entry.second = index;
240 // Ensure the string is strongly interned. This is a requirement on how the JIT
241 // handles strings. b/32995596
Vladimir Markoac3ac682018-09-20 11:01:43 +0100242 class_linker->GetInternTable()->InternStrong(roots->back()->AsString());
Vladimir Marko174b2e22017-10-12 13:34:49 +0100243 ++index;
244 }
245 for (auto& entry : jit_class_roots_) {
246 // Update the `roots` with the class, and replace the address temporarily
247 // stored to the index in the table.
248 uint64_t address = entry.second;
Vladimir Markoac3ac682018-09-20 11:01:43 +0100249 roots->emplace_back(reinterpret_cast<StackReference<mirror::Object>*>(address));
250 DCHECK(roots->back() != nullptr);
251 DCHECK(roots->back()->IsClass());
Vladimir Marko174b2e22017-10-12 13:34:49 +0100252 entry.second = index;
253 ++index;
254 }
255}
256
257ScopedArenaAllocator* CodeGenerator::GetScopedAllocator() {
258 DCHECK(code_generation_data_ != nullptr);
259 return code_generation_data_->GetScopedAllocator();
260}
261
262StackMapStream* CodeGenerator::GetStackMapStream() {
263 DCHECK(code_generation_data_ != nullptr);
264 return code_generation_data_->GetStackMapStream();
265}
266
267void CodeGenerator::ReserveJitStringRoot(StringReference string_reference,
268 Handle<mirror::String> string) {
269 DCHECK(code_generation_data_ != nullptr);
270 code_generation_data_->ReserveJitStringRoot(string_reference, string);
271}
272
273uint64_t CodeGenerator::GetJitStringRootIndex(StringReference string_reference) {
274 DCHECK(code_generation_data_ != nullptr);
275 return code_generation_data_->GetJitStringRootIndex(string_reference);
276}
277
278void CodeGenerator::ReserveJitClassRoot(TypeReference type_reference, Handle<mirror::Class> klass) {
279 DCHECK(code_generation_data_ != nullptr);
280 code_generation_data_->ReserveJitClassRoot(type_reference, klass);
281}
282
283uint64_t CodeGenerator::GetJitClassRootIndex(TypeReference type_reference) {
284 DCHECK(code_generation_data_ != nullptr);
285 return code_generation_data_->GetJitClassRootIndex(type_reference);
286}
287
288void CodeGenerator::EmitJitRootPatches(uint8_t* code ATTRIBUTE_UNUSED,
289 const uint8_t* roots_data ATTRIBUTE_UNUSED) {
290 DCHECK(code_generation_data_ != nullptr);
291 DCHECK_EQ(code_generation_data_->GetNumberOfJitStringRoots(), 0u);
292 DCHECK_EQ(code_generation_data_->GetNumberOfJitClassRoots(), 0u);
293}
294
Vladimir Markodce016e2016-04-28 13:10:02 +0100295uint32_t CodeGenerator::GetArrayLengthOffset(HArrayLength* array_length) {
296 return array_length->IsStringLength()
297 ? mirror::String::CountOffset().Uint32Value()
298 : mirror::Array::LengthOffset().Uint32Value();
299}
300
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100301uint32_t CodeGenerator::GetArrayDataOffset(HArrayGet* array_get) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100302 DCHECK(array_get->GetType() == DataType::Type::kUint16 || !array_get->IsStringCharAt());
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100303 return array_get->IsStringCharAt()
304 ? mirror::String::ValueOffset().Uint32Value()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100305 : mirror::Array::DataOffset(DataType::Size(array_get->GetType())).Uint32Value();
Vladimir Marko87f3fcb2016-04-28 15:52:11 +0100306}
307
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000308bool CodeGenerator::GoesToNextBlock(HBasicBlock* current, HBasicBlock* next) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100309 DCHECK_EQ((*block_order_)[current_block_index_], current);
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000310 return GetNextBlockToEmit() == FirstNonEmptyBlock(next);
311}
312
313HBasicBlock* CodeGenerator::GetNextBlockToEmit() const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100314 for (size_t i = current_block_index_ + 1; i < block_order_->size(); ++i) {
315 HBasicBlock* block = (*block_order_)[i];
David Brazdilfc6a86a2015-06-26 10:33:45 +0000316 if (!block->IsSingleJump()) {
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000317 return block;
318 }
319 }
320 return nullptr;
321}
322
323HBasicBlock* CodeGenerator::FirstNonEmptyBlock(HBasicBlock* block) const {
David Brazdilfc6a86a2015-06-26 10:33:45 +0000324 while (block->IsSingleJump()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100325 block = block->GetSuccessors()[0];
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000326 }
327 return block;
328}
329
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100330class DisassemblyScope {
331 public:
332 DisassemblyScope(HInstruction* instruction, const CodeGenerator& codegen)
333 : codegen_(codegen), instruction_(instruction), start_offset_(static_cast<size_t>(-1)) {
334 if (codegen_.GetDisassemblyInformation() != nullptr) {
335 start_offset_ = codegen_.GetAssembler().CodeSize();
336 }
337 }
338
339 ~DisassemblyScope() {
340 // We avoid building this data when we know it will not be used.
341 if (codegen_.GetDisassemblyInformation() != nullptr) {
342 codegen_.GetDisassemblyInformation()->AddInstructionInterval(
343 instruction_, start_offset_, codegen_.GetAssembler().CodeSize());
344 }
345 }
346
347 private:
348 const CodeGenerator& codegen_;
349 HInstruction* instruction_;
350 size_t start_offset_;
351};
352
353
354void CodeGenerator::GenerateSlowPaths() {
Vladimir Marko174b2e22017-10-12 13:34:49 +0100355 DCHECK(code_generation_data_ != nullptr);
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100356 size_t code_start = 0;
Vladimir Marko174b2e22017-10-12 13:34:49 +0100357 for (const std::unique_ptr<SlowPathCode>& slow_path_ptr : code_generation_data_->GetSlowPaths()) {
358 SlowPathCode* slow_path = slow_path_ptr.get();
Vladimir Marko0f7dca42015-11-02 14:36:43 +0000359 current_slow_path_ = slow_path;
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100360 if (disasm_info_ != nullptr) {
361 code_start = GetAssembler()->CodeSize();
362 }
David Srbecky9cd6d372016-02-09 15:24:47 +0000363 // Record the dex pc at start of slow path (required for java line number mapping).
David Srbeckyd28f4a02016-03-14 17:14:24 +0000364 MaybeRecordNativeDebugInfo(slow_path->GetInstruction(), slow_path->GetDexPc(), slow_path);
Vladimir Marko225b6462015-09-28 12:17:40 +0100365 slow_path->EmitNativeCode(this);
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100366 if (disasm_info_ != nullptr) {
Vladimir Marko225b6462015-09-28 12:17:40 +0100367 disasm_info_->AddSlowPathInterval(slow_path, code_start, GetAssembler()->CodeSize());
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100368 }
369 }
Vladimir Marko0f7dca42015-11-02 14:36:43 +0000370 current_slow_path_ = nullptr;
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100371}
372
Vladimir Marko174b2e22017-10-12 13:34:49 +0100373void CodeGenerator::InitializeCodeGenerationData() {
374 DCHECK(code_generation_data_ == nullptr);
375 code_generation_data_ = CodeGenerationData::Create(graph_->GetArenaStack(), GetInstructionSet());
376}
377
David Brazdil58282f42016-01-14 12:45:10 +0000378void CodeGenerator::Compile(CodeAllocator* allocator) {
Vladimir Marko174b2e22017-10-12 13:34:49 +0100379 InitializeCodeGenerationData();
380
David Brazdil58282f42016-01-14 12:45:10 +0000381 // The register allocator already called `InitializeCodeGeneration`,
382 // where the frame size has been computed.
383 DCHECK(block_order_ != nullptr);
384 Initialize();
385
Nicolas Geoffray8a16d972014-09-11 10:30:02 +0100386 HGraphVisitor* instruction_visitor = GetInstructionVisitor();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000387 DCHECK_EQ(current_block_index_, 0u);
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100388
David Srbeckyf6ba5b32018-06-23 22:05:49 +0100389 GetStackMapStream()->BeginMethod(HasEmptyFrame() ? 0 : frame_size_,
390 core_spill_mask_,
391 fpu_spill_mask_,
Nicolas Geoffraya59af8a2019-11-27 17:42:32 +0000392 GetGraph()->GetNumberOfVRegs(),
393 GetGraph()->IsCompilingBaseline());
David Srbeckyf6ba5b32018-06-23 22:05:49 +0100394
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100395 size_t frame_start = GetAssembler()->CodeSize();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000396 GenerateFrameEntry();
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100397 DCHECK_EQ(GetAssembler()->cfi().GetCurrentCFAOffset(), static_cast<int>(frame_size_));
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100398 if (disasm_info_ != nullptr) {
399 disasm_info_->SetFrameEntryInterval(frame_start, GetAssembler()->CodeSize());
400 }
401
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100402 for (size_t e = block_order_->size(); current_block_index_ < e; ++current_block_index_) {
403 HBasicBlock* block = (*block_order_)[current_block_index_];
Nicolas Geoffraydc23d832015-02-16 11:15:43 +0000404 // Don't generate code for an empty block. Its predecessors will branch to its successor
405 // directly. Also, the label of that block will not be emitted, so this helps catch
406 // errors where we reference that label.
David Brazdilfc6a86a2015-06-26 10:33:45 +0000407 if (block->IsSingleJump()) continue;
Nicolas Geoffray92a73ae2014-10-16 11:12:52 +0100408 Bind(block);
David Srbeckyc7098ff2016-02-09 14:30:11 +0000409 // This ensures that we have correct native line mapping for all native instructions.
410 // It is necessary to make stepping over a statement work. Otherwise, any initial
411 // instructions (e.g. moves) would be assumed to be the start of next statement.
Andreas Gampe3db70682018-12-26 15:12:03 -0800412 MaybeRecordNativeDebugInfo(/* instruction= */ nullptr, block->GetDexPc());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100413 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
414 HInstruction* current = it.Current();
David Srbeckyd28f4a02016-03-14 17:14:24 +0000415 if (current->HasEnvironment()) {
416 // Create stackmap for HNativeDebugInfo or any instruction which calls native code.
417 // Note that we need correct mapping for the native PC of the call instruction,
418 // so the runtime's stackmap is not sufficient since it is at PC after the call.
419 MaybeRecordNativeDebugInfo(current, block->GetDexPc());
420 }
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100421 DisassemblyScope disassembly_scope(current, *this);
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100422 DCHECK(CheckTypeConsistency(current));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100423 current->Accept(instruction_visitor);
424 }
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000425 }
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000426
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100427 GenerateSlowPaths();
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000428
David Brazdil77a48ae2015-09-15 12:34:04 +0000429 // Emit catch stack maps at the end of the stack map stream as expected by the
430 // runtime exception handler.
David Brazdil58282f42016-01-14 12:45:10 +0000431 if (graph_->HasTryCatch()) {
David Brazdil77a48ae2015-09-15 12:34:04 +0000432 RecordCatchBlockInfo();
433 }
434
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000435 // Finalize instructions in assember;
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000436 Finalize(allocator);
David Srbeckyf6ba5b32018-06-23 22:05:49 +0100437
David Srbecky17b4d2b2021-03-02 18:14:31 +0000438 GetStackMapStream()->EndMethod(GetAssembler()->CodeSize());
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000439}
440
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000441void CodeGenerator::Finalize(CodeAllocator* allocator) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100442 size_t code_size = GetAssembler()->CodeSize();
443 uint8_t* buffer = allocator->Allocate(code_size);
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000444
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100445 MemoryRegion code(buffer, code_size);
446 GetAssembler()->FinalizeInstructions(code);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +0000447}
448
Vladimir Markod8dbc8d2017-09-20 13:37:47 +0100449void CodeGenerator::EmitLinkerPatches(
450 ArenaVector<linker::LinkerPatch>* linker_patches ATTRIBUTE_UNUSED) {
Vladimir Marko58155012015-08-19 12:49:41 +0000451 // No linker patches by default.
452}
453
Vladimir Markoca1e0382018-04-11 09:58:41 +0000454bool CodeGenerator::NeedsThunkCode(const linker::LinkerPatch& patch ATTRIBUTE_UNUSED) const {
455 // Code generators that create patches requiring thunk compilation should override this function.
456 return false;
457}
458
459void CodeGenerator::EmitThunkCode(const linker::LinkerPatch& patch ATTRIBUTE_UNUSED,
460 /*out*/ ArenaVector<uint8_t>* code ATTRIBUTE_UNUSED,
461 /*out*/ std::string* debug_name ATTRIBUTE_UNUSED) {
462 // Code generators that create patches requiring thunk compilation should override this function.
463 LOG(FATAL) << "Unexpected call to EmitThunkCode().";
464}
465
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000466void CodeGenerator::InitializeCodeGeneration(size_t number_of_spill_slots,
Vladimir Marko70e97462016-08-09 11:04:26 +0100467 size_t maximum_safepoint_spill_size,
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000468 size_t number_of_out_slots,
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100469 const ArenaVector<HBasicBlock*>& block_order) {
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +0000470 block_order_ = &block_order;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100471 DCHECK(!block_order.empty());
472 DCHECK(block_order[0] == GetGraph()->GetEntryBlock());
Nicolas Geoffray4dee6362015-01-23 18:23:14 +0000473 ComputeSpillMask();
Alexandre Rames68bd9b92016-07-15 17:41:13 +0100474 first_register_slot_in_slow_path_ = RoundUp(
475 (number_of_out_slots + number_of_spill_slots) * kVRegSize, GetPreferredSlotsAlignment());
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100476
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000477 if (number_of_spill_slots == 0
478 && !HasAllocatedCalleeSaveRegisters()
479 && IsLeafMethod()
480 && !RequiresCurrentMethod()) {
Vladimir Marko70e97462016-08-09 11:04:26 +0100481 DCHECK_EQ(maximum_safepoint_spill_size, 0u);
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000482 SetFrameSize(CallPushesPC() ? GetWordSize() : 0);
483 } else {
484 SetFrameSize(RoundUp(
Alexandre Rames68bd9b92016-07-15 17:41:13 +0100485 first_register_slot_in_slow_path_
Vladimir Marko70e97462016-08-09 11:04:26 +0100486 + maximum_safepoint_spill_size
Mingyao Yang063fc772016-08-02 11:02:54 -0700487 + (GetGraph()->HasShouldDeoptimizeFlag() ? kShouldDeoptimizeFlagSize : 0)
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000488 + FrameEntrySpillSize(),
489 kStackAlignment));
490 }
Nicolas Geoffrayab032bc2014-07-15 12:55:21 +0100491}
492
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100493void CodeGenerator::CreateCommonInvokeLocationSummary(
Nicolas Geoffray4e40c262015-06-03 12:02:38 +0100494 HInvoke* invoke, InvokeDexCallingConventionVisitor* visitor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100495 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetAllocator();
Serban Constantinescu54ff4822016-07-07 18:03:19 +0100496 LocationSummary* locations = new (allocator) LocationSummary(invoke,
497 LocationSummary::kCallOnMainOnly);
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100498
499 for (size_t i = 0; i < invoke->GetNumberOfArguments(); i++) {
500 HInstruction* input = invoke->InputAt(i);
501 locations->SetInAt(i, visitor->GetNextLocation(input->GetType()));
502 }
503
504 locations->SetOut(visitor->GetReturnLocation(invoke->GetType()));
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100505
506 if (invoke->IsInvokeStaticOrDirect()) {
507 HInvokeStaticOrDirect* call = invoke->AsInvokeStaticOrDirect();
Nicolas Geoffray6d69b522020-09-23 14:47:28 +0100508 MethodLoadKind method_load_kind = call->GetMethodLoadKind();
509 CodePtrLocation code_ptr_location = call->GetCodePtrLocation();
510 if (code_ptr_location == CodePtrLocation::kCallCriticalNative) {
Vladimir Marko86c87522020-05-11 16:55:55 +0100511 locations->AddTemp(Location::RequiresRegister()); // For target method.
512 }
Nicolas Geoffray6d69b522020-09-23 14:47:28 +0100513 if (code_ptr_location == CodePtrLocation::kCallCriticalNative ||
514 method_load_kind == MethodLoadKind::kRecursive) {
Vladimir Marko86c87522020-05-11 16:55:55 +0100515 // For `kCallCriticalNative` we need the current method as the hidden argument
516 // if we reach the dlsym lookup stub for @CriticalNative.
517 locations->SetInAt(call->GetCurrentMethodIndex(), visitor->GetMethodLocation());
518 } else {
519 locations->AddTemp(visitor->GetMethodLocation());
Nicolas Geoffray6d69b522020-09-23 14:47:28 +0100520 if (method_load_kind == MethodLoadKind::kRuntimeCall) {
Vladimir Marko86c87522020-05-11 16:55:55 +0100521 locations->SetInAt(call->GetCurrentMethodIndex(), Location::RequiresRegister());
522 }
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100523 }
Orion Hodsoncd260eb2018-06-06 09:04:17 +0100524 } else if (!invoke->IsInvokePolymorphic()) {
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100525 locations->AddTemp(visitor->GetMethodLocation());
526 }
Nicolas Geoffrayfd88f162015-06-03 11:23:52 +0100527}
528
Vladimir Marko86c87522020-05-11 16:55:55 +0100529void CodeGenerator::PrepareCriticalNativeArgumentMoves(
530 HInvokeStaticOrDirect* invoke,
531 /*inout*/InvokeDexCallingConventionVisitor* visitor,
532 /*out*/HParallelMove* parallel_move) {
533 LocationSummary* locations = invoke->GetLocations();
534 for (size_t i = 0, num = invoke->GetNumberOfArguments(); i != num; ++i) {
535 Location in_location = locations->InAt(i);
536 DataType::Type type = invoke->InputAt(i)->GetType();
537 DCHECK_NE(type, DataType::Type::kReference);
538 Location out_location = visitor->GetNextLocation(type);
539 if (out_location.IsStackSlot() || out_location.IsDoubleStackSlot()) {
540 // Stack arguments will need to be moved after adjusting the SP.
541 parallel_move->AddMove(in_location, out_location, type, /*instruction=*/ nullptr);
542 } else {
543 // Register arguments should have been assigned their final locations for register allocation.
544 DCHECK(out_location.Equals(in_location)) << in_location << " -> " << out_location;
545 }
546 }
547}
548
Vladimir Markodec78172020-06-19 15:31:23 +0100549void CodeGenerator::FinishCriticalNativeFrameSetup(size_t out_frame_size,
550 /*inout*/HParallelMove* parallel_move) {
551 DCHECK_NE(out_frame_size, 0u);
552 IncreaseFrame(out_frame_size);
Vladimir Marko86c87522020-05-11 16:55:55 +0100553 // Adjust the source stack offsets by `out_frame_size`, i.e. the additional
554 // frame size needed for outgoing stack arguments.
555 for (size_t i = 0, num = parallel_move->NumMoves(); i != num; ++i) {
556 MoveOperands* operands = parallel_move->MoveOperandsAt(i);
557 Location source = operands->GetSource();
558 if (operands->GetSource().IsStackSlot()) {
559 operands->SetSource(Location::StackSlot(source.GetStackIndex() + out_frame_size));
560 } else if (operands->GetSource().IsDoubleStackSlot()) {
561 operands->SetSource(Location::DoubleStackSlot(source.GetStackIndex() + out_frame_size));
562 }
563 }
Vladimir Markodec78172020-06-19 15:31:23 +0100564 // Emit the moves.
565 GetMoveResolver()->EmitNativeCode(parallel_move);
Vladimir Marko86c87522020-05-11 16:55:55 +0100566}
567
568const char* CodeGenerator::GetCriticalNativeShorty(HInvokeStaticOrDirect* invoke,
569 uint32_t* shorty_len) {
570 ScopedObjectAccess soa(Thread::Current());
571 DCHECK(invoke->GetResolvedMethod()->IsCriticalNative());
572 return invoke->GetResolvedMethod()->GetShorty(shorty_len);
573}
574
Vladimir Markoe7197bf2017-06-02 17:00:23 +0100575void CodeGenerator::GenerateInvokeStaticOrDirectRuntimeCall(
576 HInvokeStaticOrDirect* invoke, Location temp, SlowPathCode* slow_path) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100577 MethodReference method_reference(invoke->GetMethodReference());
578 MoveConstant(temp, method_reference.index);
Vladimir Markoe7197bf2017-06-02 17:00:23 +0100579
580 // The access check is unnecessary but we do not want to introduce
581 // extra entrypoints for the codegens that do not support some
582 // invoke type and fall back to the runtime call.
583
584 // Initialize to anything to silent compiler warnings.
585 QuickEntrypointEnum entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
586 switch (invoke->GetInvokeType()) {
587 case kStatic:
588 entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
589 break;
590 case kDirect:
591 entrypoint = kQuickInvokeDirectTrampolineWithAccessCheck;
592 break;
593 case kSuper:
594 entrypoint = kQuickInvokeSuperTrampolineWithAccessCheck;
595 break;
596 case kVirtual:
597 case kInterface:
Orion Hodson43f0cdb2017-10-10 14:47:32 +0100598 case kPolymorphic:
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100599 case kCustom:
Vladimir Markoe7197bf2017-06-02 17:00:23 +0100600 LOG(FATAL) << "Unexpected invoke type: " << invoke->GetInvokeType();
601 UNREACHABLE();
602 }
603
604 InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), slow_path);
605}
Calin Juravle175dc732015-08-25 15:42:32 +0100606void CodeGenerator::GenerateInvokeUnresolvedRuntimeCall(HInvokeUnresolved* invoke) {
Nicolas Geoffraye6c0f2a2020-09-07 08:30:52 +0100607 MethodReference method_reference(invoke->GetMethodReference());
608 MoveConstant(invoke->GetLocations()->GetTemp(0), method_reference.index);
Calin Juravle175dc732015-08-25 15:42:32 +0100609
610 // Initialize to anything to silent compiler warnings.
611 QuickEntrypointEnum entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
Nicolas Geoffray5e4e11e2016-09-22 13:17:41 +0100612 switch (invoke->GetInvokeType()) {
Calin Juravle175dc732015-08-25 15:42:32 +0100613 case kStatic:
614 entrypoint = kQuickInvokeStaticTrampolineWithAccessCheck;
615 break;
616 case kDirect:
617 entrypoint = kQuickInvokeDirectTrampolineWithAccessCheck;
618 break;
619 case kVirtual:
620 entrypoint = kQuickInvokeVirtualTrampolineWithAccessCheck;
621 break;
622 case kSuper:
623 entrypoint = kQuickInvokeSuperTrampolineWithAccessCheck;
624 break;
625 case kInterface:
626 entrypoint = kQuickInvokeInterfaceTrampolineWithAccessCheck;
627 break;
Orion Hodson43f0cdb2017-10-10 14:47:32 +0100628 case kPolymorphic:
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100629 case kCustom:
Orion Hodson43f0cdb2017-10-10 14:47:32 +0100630 LOG(FATAL) << "Unexpected invoke type: " << invoke->GetInvokeType();
631 UNREACHABLE();
Calin Juravle175dc732015-08-25 15:42:32 +0100632 }
633 InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), nullptr);
634}
635
Andra Danciue3e187f2020-07-30 12:19:31 +0000636void CodeGenerator::GenerateInvokePolymorphicCall(HInvokePolymorphic* invoke,
637 SlowPathCode* slow_path) {
Orion Hodsoncd260eb2018-06-06 09:04:17 +0100638 // invoke-polymorphic does not use a temporary to convey any additional information (e.g. a
639 // method index) since it requires multiple info from the instruction (registers A, B, H). Not
640 // using the reservation has no effect on the registers used in the runtime call.
Orion Hodsonac141392017-01-13 11:53:47 +0000641 QuickEntrypointEnum entrypoint = kQuickInvokePolymorphic;
Andra Danciue3e187f2020-07-30 12:19:31 +0000642 InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), slow_path);
Orion Hodsonac141392017-01-13 11:53:47 +0000643}
644
Orion Hodson4c8e12e2018-05-18 08:33:20 +0100645void CodeGenerator::GenerateInvokeCustomCall(HInvokeCustom* invoke) {
646 MoveConstant(invoke->GetLocations()->GetTemp(0), invoke->GetCallSiteIndex());
647 QuickEntrypointEnum entrypoint = kQuickInvokeCustom;
648 InvokeRuntime(entrypoint, invoke, invoke->GetDexPc(), nullptr);
649}
650
Vladimir Marko552a1342017-10-31 10:56:47 +0000651void CodeGenerator::CreateStringBuilderAppendLocations(HStringBuilderAppend* instruction,
652 Location out) {
653 ArenaAllocator* allocator = GetGraph()->GetAllocator();
654 LocationSummary* locations =
655 new (allocator) LocationSummary(instruction, LocationSummary::kCallOnMainOnly);
656 locations->SetOut(out);
657 instruction->GetLocations()->SetInAt(instruction->FormatIndex(),
658 Location::ConstantLocation(instruction->GetFormat()));
659
660 uint32_t format = static_cast<uint32_t>(instruction->GetFormat()->GetValue());
661 uint32_t f = format;
662 PointerSize pointer_size = InstructionSetPointerSize(GetInstructionSet());
663 size_t stack_offset = static_cast<size_t>(pointer_size); // Start after the ArtMethod*.
664 for (size_t i = 0, num_args = instruction->GetNumberOfArguments(); i != num_args; ++i) {
665 StringBuilderAppend::Argument arg_type =
666 static_cast<StringBuilderAppend::Argument>(f & StringBuilderAppend::kArgMask);
667 switch (arg_type) {
668 case StringBuilderAppend::Argument::kStringBuilder:
669 case StringBuilderAppend::Argument::kString:
670 case StringBuilderAppend::Argument::kCharArray:
671 static_assert(sizeof(StackReference<mirror::Object>) == sizeof(uint32_t), "Size check.");
672 FALLTHROUGH_INTENDED;
673 case StringBuilderAppend::Argument::kBoolean:
674 case StringBuilderAppend::Argument::kChar:
675 case StringBuilderAppend::Argument::kInt:
676 case StringBuilderAppend::Argument::kFloat:
677 locations->SetInAt(i, Location::StackSlot(stack_offset));
678 break;
679 case StringBuilderAppend::Argument::kLong:
680 case StringBuilderAppend::Argument::kDouble:
681 stack_offset = RoundUp(stack_offset, sizeof(uint64_t));
682 locations->SetInAt(i, Location::DoubleStackSlot(stack_offset));
683 // Skip the low word, let the common code skip the high word.
684 stack_offset += sizeof(uint32_t);
685 break;
686 default:
687 LOG(FATAL) << "Unexpected arg format: 0x" << std::hex
688 << (f & StringBuilderAppend::kArgMask) << " full format: 0x" << format;
689 UNREACHABLE();
690 }
691 f >>= StringBuilderAppend::kBitsPerArg;
692 stack_offset += sizeof(uint32_t);
693 }
694 DCHECK_EQ(f, 0u);
695
696 size_t param_size = stack_offset - static_cast<size_t>(pointer_size);
697 DCHECK_ALIGNED(param_size, kVRegSize);
698 size_t num_vregs = param_size / kVRegSize;
699 graph_->UpdateMaximumNumberOfOutVRegs(num_vregs);
700}
701
Calin Juravlee460d1d2015-09-29 04:52:17 +0100702void CodeGenerator::CreateUnresolvedFieldLocationSummary(
703 HInstruction* field_access,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100704 DataType::Type field_type,
Calin Juravlee460d1d2015-09-29 04:52:17 +0100705 const FieldAccessCallingConvention& calling_convention) {
706 bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
707 || field_access->IsUnresolvedInstanceFieldSet();
708 bool is_get = field_access->IsUnresolvedInstanceFieldGet()
709 || field_access->IsUnresolvedStaticFieldGet();
710
Vladimir Markoca6fff82017-10-03 14:49:14 +0100711 ArenaAllocator* allocator = field_access->GetBlock()->GetGraph()->GetAllocator();
Calin Juravlee460d1d2015-09-29 04:52:17 +0100712 LocationSummary* locations =
Serban Constantinescu54ff4822016-07-07 18:03:19 +0100713 new (allocator) LocationSummary(field_access, LocationSummary::kCallOnMainOnly);
Calin Juravlee460d1d2015-09-29 04:52:17 +0100714
715 locations->AddTemp(calling_convention.GetFieldIndexLocation());
716
717 if (is_instance) {
718 // Add the `this` object for instance field accesses.
719 locations->SetInAt(0, calling_convention.GetObjectLocation());
720 }
721
722 // Note that pSetXXStatic/pGetXXStatic always takes/returns an int or int64
723 // regardless of the the type. Because of that we forced to special case
724 // the access to floating point values.
725 if (is_get) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100726 if (DataType::IsFloatingPointType(field_type)) {
Calin Juravlee460d1d2015-09-29 04:52:17 +0100727 // The return value will be stored in regular registers while register
728 // allocator expects it in a floating point register.
729 // Note We don't need to request additional temps because the return
730 // register(s) are already blocked due the call and they may overlap with
731 // the input or field index.
732 // The transfer between the two will be done at codegen level.
733 locations->SetOut(calling_convention.GetFpuLocation(field_type));
734 } else {
735 locations->SetOut(calling_convention.GetReturnLocation(field_type));
736 }
737 } else {
738 size_t set_index = is_instance ? 1 : 0;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100739 if (DataType::IsFloatingPointType(field_type)) {
Calin Juravlee460d1d2015-09-29 04:52:17 +0100740 // The set value comes from a float location while the calling convention
741 // expects it in a regular register location. Allocate a temp for it and
742 // make the transfer at codegen.
743 AddLocationAsTemp(calling_convention.GetSetValueLocation(field_type, is_instance), locations);
744 locations->SetInAt(set_index, calling_convention.GetFpuLocation(field_type));
745 } else {
746 locations->SetInAt(set_index,
747 calling_convention.GetSetValueLocation(field_type, is_instance));
748 }
749 }
750}
751
752void CodeGenerator::GenerateUnresolvedFieldAccess(
753 HInstruction* field_access,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100754 DataType::Type field_type,
Calin Juravlee460d1d2015-09-29 04:52:17 +0100755 uint32_t field_index,
756 uint32_t dex_pc,
757 const FieldAccessCallingConvention& calling_convention) {
758 LocationSummary* locations = field_access->GetLocations();
759
760 MoveConstant(locations->GetTemp(0), field_index);
761
762 bool is_instance = field_access->IsUnresolvedInstanceFieldGet()
763 || field_access->IsUnresolvedInstanceFieldSet();
764 bool is_get = field_access->IsUnresolvedInstanceFieldGet()
765 || field_access->IsUnresolvedStaticFieldGet();
766
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100767 if (!is_get && DataType::IsFloatingPointType(field_type)) {
Calin Juravlee460d1d2015-09-29 04:52:17 +0100768 // Copy the float value to be set into the calling convention register.
769 // Note that using directly the temp location is problematic as we don't
770 // support temp register pairs. To avoid boilerplate conversion code, use
771 // the location from the calling convention.
772 MoveLocation(calling_convention.GetSetValueLocation(field_type, is_instance),
773 locations->InAt(is_instance ? 1 : 0),
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100774 (DataType::Is64BitType(field_type) ? DataType::Type::kInt64
775 : DataType::Type::kInt32));
Calin Juravlee460d1d2015-09-29 04:52:17 +0100776 }
777
778 QuickEntrypointEnum entrypoint = kQuickSet8Static; // Initialize to anything to avoid warnings.
779 switch (field_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100780 case DataType::Type::kBool:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100781 entrypoint = is_instance
782 ? (is_get ? kQuickGetBooleanInstance : kQuickSet8Instance)
783 : (is_get ? kQuickGetBooleanStatic : kQuickSet8Static);
784 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100785 case DataType::Type::kInt8:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100786 entrypoint = is_instance
787 ? (is_get ? kQuickGetByteInstance : kQuickSet8Instance)
788 : (is_get ? kQuickGetByteStatic : kQuickSet8Static);
789 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100790 case DataType::Type::kInt16:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100791 entrypoint = is_instance
792 ? (is_get ? kQuickGetShortInstance : kQuickSet16Instance)
793 : (is_get ? kQuickGetShortStatic : kQuickSet16Static);
794 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100795 case DataType::Type::kUint16:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100796 entrypoint = is_instance
797 ? (is_get ? kQuickGetCharInstance : kQuickSet16Instance)
798 : (is_get ? kQuickGetCharStatic : kQuickSet16Static);
799 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100800 case DataType::Type::kInt32:
801 case DataType::Type::kFloat32:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100802 entrypoint = is_instance
803 ? (is_get ? kQuickGet32Instance : kQuickSet32Instance)
804 : (is_get ? kQuickGet32Static : kQuickSet32Static);
805 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100806 case DataType::Type::kReference:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100807 entrypoint = is_instance
808 ? (is_get ? kQuickGetObjInstance : kQuickSetObjInstance)
809 : (is_get ? kQuickGetObjStatic : kQuickSetObjStatic);
810 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100811 case DataType::Type::kInt64:
812 case DataType::Type::kFloat64:
Calin Juravlee460d1d2015-09-29 04:52:17 +0100813 entrypoint = is_instance
814 ? (is_get ? kQuickGet64Instance : kQuickSet64Instance)
815 : (is_get ? kQuickGet64Static : kQuickSet64Static);
816 break;
817 default:
818 LOG(FATAL) << "Invalid type " << field_type;
819 }
820 InvokeRuntime(entrypoint, field_access, dex_pc, nullptr);
821
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100822 if (is_get && DataType::IsFloatingPointType(field_type)) {
Calin Juravlee460d1d2015-09-29 04:52:17 +0100823 MoveLocation(locations->Out(), calling_convention.GetReturnLocation(field_type), field_type);
824 }
825}
826
Vladimir Marko41559982017-01-06 14:04:23 +0000827void CodeGenerator::CreateLoadClassRuntimeCallLocationSummary(HLoadClass* cls,
828 Location runtime_type_index_location,
829 Location runtime_return_location) {
Vladimir Marko847e6ce2017-06-02 13:55:07 +0100830 DCHECK_EQ(cls->GetLoadKind(), HLoadClass::LoadKind::kRuntimeCall);
Vladimir Marko41559982017-01-06 14:04:23 +0000831 DCHECK_EQ(cls->InputCount(), 1u);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100832 LocationSummary* locations = new (cls->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
Vladimir Marko41559982017-01-06 14:04:23 +0000833 cls, LocationSummary::kCallOnMainOnly);
834 locations->SetInAt(0, Location::NoLocation());
835 locations->AddTemp(runtime_type_index_location);
836 locations->SetOut(runtime_return_location);
Calin Juravle98893e12015-10-02 21:05:03 +0100837}
838
Vladimir Marko41559982017-01-06 14:04:23 +0000839void CodeGenerator::GenerateLoadClassRuntimeCall(HLoadClass* cls) {
Vladimir Marko847e6ce2017-06-02 13:55:07 +0100840 DCHECK_EQ(cls->GetLoadKind(), HLoadClass::LoadKind::kRuntimeCall);
Vladimir Markoa9f303c2018-07-20 16:43:56 +0100841 DCHECK(!cls->MustGenerateClinitCheck());
Vladimir Marko41559982017-01-06 14:04:23 +0000842 LocationSummary* locations = cls->GetLocations();
843 MoveConstant(locations->GetTemp(0), cls->GetTypeIndex().index_);
844 if (cls->NeedsAccessCheck()) {
Vladimir Marko9d479252018-07-24 11:35:20 +0100845 CheckEntrypointTypes<kQuickResolveTypeAndVerifyAccess, void*, uint32_t>();
846 InvokeRuntime(kQuickResolveTypeAndVerifyAccess, cls, cls->GetDexPc());
Vladimir Marko41559982017-01-06 14:04:23 +0000847 } else {
Vladimir Marko9d479252018-07-24 11:35:20 +0100848 CheckEntrypointTypes<kQuickResolveType, void*, uint32_t>();
849 InvokeRuntime(kQuickResolveType, cls, cls->GetDexPc());
Vladimir Marko41559982017-01-06 14:04:23 +0000850 }
851}
Calin Juravle98893e12015-10-02 21:05:03 +0100852
Orion Hodsondbaa5c72018-05-10 08:22:46 +0100853void CodeGenerator::CreateLoadMethodHandleRuntimeCallLocationSummary(
854 HLoadMethodHandle* method_handle,
855 Location runtime_proto_index_location,
856 Location runtime_return_location) {
857 DCHECK_EQ(method_handle->InputCount(), 1u);
858 LocationSummary* locations =
859 new (method_handle->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
860 method_handle, LocationSummary::kCallOnMainOnly);
861 locations->SetInAt(0, Location::NoLocation());
862 locations->AddTemp(runtime_proto_index_location);
863 locations->SetOut(runtime_return_location);
864}
865
866void CodeGenerator::GenerateLoadMethodHandleRuntimeCall(HLoadMethodHandle* method_handle) {
867 LocationSummary* locations = method_handle->GetLocations();
868 MoveConstant(locations->GetTemp(0), method_handle->GetMethodHandleIndex());
869 CheckEntrypointTypes<kQuickResolveMethodHandle, void*, uint32_t>();
870 InvokeRuntime(kQuickResolveMethodHandle, method_handle, method_handle->GetDexPc());
871}
872
Orion Hodson18259d72018-04-12 11:18:23 +0100873void CodeGenerator::CreateLoadMethodTypeRuntimeCallLocationSummary(
874 HLoadMethodType* method_type,
875 Location runtime_proto_index_location,
876 Location runtime_return_location) {
877 DCHECK_EQ(method_type->InputCount(), 1u);
878 LocationSummary* locations =
879 new (method_type->GetBlock()->GetGraph()->GetAllocator()) LocationSummary(
880 method_type, LocationSummary::kCallOnMainOnly);
881 locations->SetInAt(0, Location::NoLocation());
882 locations->AddTemp(runtime_proto_index_location);
883 locations->SetOut(runtime_return_location);
884}
885
886void CodeGenerator::GenerateLoadMethodTypeRuntimeCall(HLoadMethodType* method_type) {
887 LocationSummary* locations = method_type->GetLocations();
Orion Hodson06d10a72018-05-14 08:53:38 +0100888 MoveConstant(locations->GetTemp(0), method_type->GetProtoIndex().index_);
Orion Hodson18259d72018-04-12 11:18:23 +0100889 CheckEntrypointTypes<kQuickResolveMethodType, void*, uint32_t>();
890 InvokeRuntime(kQuickResolveMethodType, method_type, method_type->GetDexPc());
891}
892
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000893static uint32_t GetBootImageOffsetImpl(const void* object, ImageHeader::ImageSections section) {
894 Runtime* runtime = Runtime::Current();
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000895 const std::vector<gc::space::ImageSpace*>& boot_image_spaces =
896 runtime->GetHeap()->GetBootImageSpaces();
897 // Check that the `object` is in the expected section of one of the boot image files.
898 DCHECK(std::any_of(boot_image_spaces.begin(),
899 boot_image_spaces.end(),
900 [object, section](gc::space::ImageSpace* space) {
901 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
902 uintptr_t offset = reinterpret_cast<uintptr_t>(object) - begin;
903 return space->GetImageHeader().GetImageSection(section).Contains(offset);
904 }));
905 uintptr_t begin = reinterpret_cast<uintptr_t>(boot_image_spaces.front()->Begin());
906 uintptr_t offset = reinterpret_cast<uintptr_t>(object) - begin;
907 return dchecked_integral_cast<uint32_t>(offset);
908}
909
Vladimir Markode91ca92020-10-27 13:41:40 +0000910uint32_t CodeGenerator::GetBootImageOffset(ObjPtr<mirror::Object> object) {
911 return GetBootImageOffsetImpl(object.Ptr(), ImageHeader::kSectionObjects);
912}
913
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000914// NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image classes are non-moveable.
915uint32_t CodeGenerator::GetBootImageOffset(HLoadClass* load_class) NO_THREAD_SAFETY_ANALYSIS {
916 DCHECK_EQ(load_class->GetLoadKind(), HLoadClass::LoadKind::kBootImageRelRo);
917 ObjPtr<mirror::Class> klass = load_class->GetClass().Get();
918 DCHECK(klass != nullptr);
919 return GetBootImageOffsetImpl(klass.Ptr(), ImageHeader::kSectionObjects);
920}
921
922// NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image strings are non-moveable.
923uint32_t CodeGenerator::GetBootImageOffset(HLoadString* load_string) NO_THREAD_SAFETY_ANALYSIS {
924 DCHECK_EQ(load_string->GetLoadKind(), HLoadString::LoadKind::kBootImageRelRo);
925 ObjPtr<mirror::String> string = load_string->GetString().Get();
926 DCHECK(string != nullptr);
927 return GetBootImageOffsetImpl(string.Ptr(), ImageHeader::kSectionObjects);
928}
929
Nicolas Geoffray8d34a182020-09-16 09:46:58 +0100930uint32_t CodeGenerator::GetBootImageOffset(HInvoke* invoke) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000931 ArtMethod* method = invoke->GetResolvedMethod();
932 DCHECK(method != nullptr);
933 return GetBootImageOffsetImpl(method, ImageHeader::kSectionArtMethods);
934}
935
Vladimir Marko98873af2020-12-16 12:10:03 +0000936// NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image objects are non-moveable.
937uint32_t CodeGenerator::GetBootImageOffset(ClassRoot class_root) NO_THREAD_SAFETY_ANALYSIS {
938 ObjPtr<mirror::Class> klass = GetClassRoot<kWithoutReadBarrier>(class_root);
939 return GetBootImageOffsetImpl(klass.Ptr(), ImageHeader::kSectionObjects);
940}
941
Vladimir Markode91ca92020-10-27 13:41:40 +0000942// NO_THREAD_SAFETY_ANALYSIS: Avoid taking the mutator lock, boot image classes are non-moveable.
943uint32_t CodeGenerator::GetBootImageOffsetOfIntrinsicDeclaringClass(HInvoke* invoke)
944 NO_THREAD_SAFETY_ANALYSIS {
945 DCHECK_NE(invoke->GetIntrinsic(), Intrinsics::kNone);
946 ArtMethod* method = invoke->GetResolvedMethod();
947 DCHECK(method != nullptr);
948 ObjPtr<mirror::Class> declaring_class = method->GetDeclaringClass<kWithoutReadBarrier>();
949 return GetBootImageOffsetImpl(declaring_class.Ptr(), ImageHeader::kSectionObjects);
950}
951
Mark Mendell5f874182015-03-04 15:42:45 -0500952void CodeGenerator::BlockIfInRegister(Location location, bool is_out) const {
953 // The DCHECKS below check that a register is not specified twice in
954 // the summary. The out location can overlap with an input, so we need
955 // to special case it.
956 if (location.IsRegister()) {
957 DCHECK(is_out || !blocked_core_registers_[location.reg()]);
958 blocked_core_registers_[location.reg()] = true;
959 } else if (location.IsFpuRegister()) {
960 DCHECK(is_out || !blocked_fpu_registers_[location.reg()]);
961 blocked_fpu_registers_[location.reg()] = true;
962 } else if (location.IsFpuRegisterPair()) {
963 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()]);
964 blocked_fpu_registers_[location.AsFpuRegisterPairLow<int>()] = true;
965 DCHECK(is_out || !blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()]);
966 blocked_fpu_registers_[location.AsFpuRegisterPairHigh<int>()] = true;
967 } else if (location.IsRegisterPair()) {
968 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairLow<int>()]);
969 blocked_core_registers_[location.AsRegisterPairLow<int>()] = true;
970 DCHECK(is_out || !blocked_core_registers_[location.AsRegisterPairHigh<int>()]);
971 blocked_core_registers_[location.AsRegisterPairHigh<int>()] = true;
972 }
973}
974
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000975void CodeGenerator::AllocateLocations(HInstruction* instruction) {
Vladimir Markoec32f642017-06-02 10:51:55 +0100976 for (HEnvironment* env = instruction->GetEnvironment(); env != nullptr; env = env->GetParent()) {
977 env->AllocateLocations();
978 }
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000979 instruction->Accept(GetLocationBuilder());
Alexandre Rames88c13cd2015-04-14 17:35:39 +0100980 DCHECK(CheckTypeConsistency(instruction));
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000981 LocationSummary* locations = instruction->GetLocations();
982 if (!instruction->IsSuspendCheckEntry()) {
Aart Bikd1c40452016-03-02 16:06:13 -0800983 if (locations != nullptr) {
984 if (locations->CanCall()) {
985 MarkNotLeaf();
986 } else if (locations->Intrinsified() &&
987 instruction->IsInvokeStaticOrDirect() &&
988 !instruction->AsInvokeStaticOrDirect()->HasCurrentMethodInput()) {
989 // A static method call that has been fully intrinsified, and cannot call on the slow
990 // path or refer to the current method directly, no longer needs current method.
991 return;
992 }
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000993 }
994 if (instruction->NeedsCurrentMethod()) {
995 SetRequiresCurrentMethod();
996 }
997 }
998}
999
Vladimir Markod58b8372016-04-12 18:51:43 +01001000std::unique_ptr<CodeGenerator> CodeGenerator::Create(HGraph* graph,
Vladimir Markod58b8372016-04-12 18:51:43 +01001001 const CompilerOptions& compiler_options,
1002 OptimizingCompilerStats* stats) {
Vladimir Markoe764d2e2017-10-05 14:35:55 +01001003 ArenaAllocator* allocator = graph->GetAllocator();
Vladimir Markoa0431112018-06-25 09:32:54 +01001004 switch (compiler_options.GetInstructionSet()) {
Alex Light50fa9932015-08-10 15:30:07 -07001005#ifdef ART_ENABLE_CODEGEN_arm
Vladimir Marko33bff252017-11-01 14:35:42 +00001006 case InstructionSet::kArm:
1007 case InstructionSet::kThumb2: {
Roland Levillain9983e302017-07-14 14:34:22 +01001008 return std::unique_ptr<CodeGenerator>(
Vladimir Markoa0431112018-06-25 09:32:54 +01001009 new (allocator) arm::CodeGeneratorARMVIXL(graph, compiler_options, stats));
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001010 }
Alex Light50fa9932015-08-10 15:30:07 -07001011#endif
1012#ifdef ART_ENABLE_CODEGEN_arm64
Vladimir Marko33bff252017-11-01 14:35:42 +00001013 case InstructionSet::kArm64: {
Vladimir Markod58b8372016-04-12 18:51:43 +01001014 return std::unique_ptr<CodeGenerator>(
Vladimir Markoa0431112018-06-25 09:32:54 +01001015 new (allocator) arm64::CodeGeneratorARM64(graph, compiler_options, stats));
Alexandre Rames5319def2014-10-23 10:03:10 +01001016 }
Alex Light50fa9932015-08-10 15:30:07 -07001017#endif
Alex Light50fa9932015-08-10 15:30:07 -07001018#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko33bff252017-11-01 14:35:42 +00001019 case InstructionSet::kX86: {
Vladimir Markod58b8372016-04-12 18:51:43 +01001020 return std::unique_ptr<CodeGenerator>(
Vladimir Markoa0431112018-06-25 09:32:54 +01001021 new (allocator) x86::CodeGeneratorX86(graph, compiler_options, stats));
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001022 }
Alex Light50fa9932015-08-10 15:30:07 -07001023#endif
1024#ifdef ART_ENABLE_CODEGEN_x86_64
Vladimir Marko33bff252017-11-01 14:35:42 +00001025 case InstructionSet::kX86_64: {
Vladimir Markod58b8372016-04-12 18:51:43 +01001026 return std::unique_ptr<CodeGenerator>(
Vladimir Markoa0431112018-06-25 09:32:54 +01001027 new (allocator) x86_64::CodeGeneratorX86_64(graph, compiler_options, stats));
Dmitry Petrochenko6a58cb12014-04-02 17:27:59 +07001028 }
Alex Light50fa9932015-08-10 15:30:07 -07001029#endif
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001030 default:
Nicolas Geoffray787c3072014-03-17 10:20:19 +00001031 return nullptr;
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001032 }
1033}
1034
Vladimir Marko174b2e22017-10-12 13:34:49 +01001035CodeGenerator::CodeGenerator(HGraph* graph,
1036 size_t number_of_core_registers,
1037 size_t number_of_fpu_registers,
1038 size_t number_of_register_pairs,
1039 uint32_t core_callee_save_mask,
1040 uint32_t fpu_callee_save_mask,
1041 const CompilerOptions& compiler_options,
1042 OptimizingCompilerStats* stats)
1043 : frame_size_(0),
1044 core_spill_mask_(0),
1045 fpu_spill_mask_(0),
1046 first_register_slot_in_slow_path_(0),
1047 allocated_registers_(RegisterSet::Empty()),
1048 blocked_core_registers_(graph->GetAllocator()->AllocArray<bool>(number_of_core_registers,
1049 kArenaAllocCodeGenerator)),
1050 blocked_fpu_registers_(graph->GetAllocator()->AllocArray<bool>(number_of_fpu_registers,
1051 kArenaAllocCodeGenerator)),
1052 number_of_core_registers_(number_of_core_registers),
1053 number_of_fpu_registers_(number_of_fpu_registers),
1054 number_of_register_pairs_(number_of_register_pairs),
1055 core_callee_save_mask_(core_callee_save_mask),
1056 fpu_callee_save_mask_(fpu_callee_save_mask),
1057 block_order_(nullptr),
1058 disasm_info_(nullptr),
1059 stats_(stats),
1060 graph_(graph),
1061 compiler_options_(compiler_options),
1062 current_slow_path_(nullptr),
1063 current_block_index_(0),
1064 is_leaf_(true),
1065 requires_current_method_(false),
1066 code_generation_data_() {
Nicolas Geoffray57cacb72019-12-08 22:07:08 +00001067 if (GetGraph()->IsCompilingOsr()) {
1068 // Make OSR methods have all registers spilled, this simplifies the logic of
1069 // jumping to the compiled code directly.
1070 for (size_t i = 0; i < number_of_core_registers_; ++i) {
1071 if (IsCoreCalleeSaveRegister(i)) {
1072 AddAllocatedRegister(Location::RegisterLocation(i));
1073 }
1074 }
1075 for (size_t i = 0; i < number_of_fpu_registers_; ++i) {
1076 if (IsFloatingPointCalleeSaveRegister(i)) {
1077 AddAllocatedRegister(Location::FpuRegisterLocation(i));
1078 }
1079 }
1080 }
Vladimir Marko174b2e22017-10-12 13:34:49 +01001081}
1082
1083CodeGenerator::~CodeGenerator() {}
1084
Vladimir Marko174b2e22017-10-12 13:34:49 +01001085size_t CodeGenerator::GetNumberOfJitRoots() const {
1086 DCHECK(code_generation_data_ != nullptr);
1087 return code_generation_data_->GetNumberOfJitRoots();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001088}
1089
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001090static void CheckCovers(uint32_t dex_pc,
1091 const HGraph& graph,
1092 const CodeInfo& code_info,
1093 const ArenaVector<HSuspendCheck*>& loop_headers,
1094 ArenaVector<size_t>* covered) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001095 for (size_t i = 0; i < loop_headers.size(); ++i) {
1096 if (loop_headers[i]->GetDexPc() == dex_pc) {
1097 if (graph.IsCompilingOsr()) {
David Srbecky052f8ca2018-04-26 15:42:54 +01001098 DCHECK(code_info.GetOsrStackMapForDexPc(dex_pc).IsValid());
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001099 }
1100 ++(*covered)[i];
1101 }
1102 }
1103}
1104
1105// Debug helper to ensure loop entries in compiled code are matched by
1106// dex branch instructions.
1107static void CheckLoopEntriesCanBeUsedForOsr(const HGraph& graph,
1108 const CodeInfo& code_info,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001109 const dex::CodeItem& code_item) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001110 if (graph.HasTryCatch()) {
1111 // One can write loops through try/catch, which we do not support for OSR anyway.
1112 return;
1113 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001114 ArenaVector<HSuspendCheck*> loop_headers(graph.GetAllocator()->Adapter(kArenaAllocMisc));
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001115 for (HBasicBlock* block : graph.GetReversePostOrder()) {
1116 if (block->IsLoopHeader()) {
1117 HSuspendCheck* suspend_check = block->GetLoopInformation()->GetSuspendCheck();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001118 if (!suspend_check->GetEnvironment()->IsFromInlinedInvoke()) {
1119 loop_headers.push_back(suspend_check);
1120 }
1121 }
1122 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001123 ArenaVector<size_t> covered(
1124 loop_headers.size(), 0, graph.GetAllocator()->Adapter(kArenaAllocMisc));
Mathieu Chartier698ebbc2018-01-05 11:00:42 -08001125 for (const DexInstructionPcPair& pair : CodeItemInstructionAccessor(graph.GetDexFile(),
Mathieu Chartier73f21d42018-01-02 14:26:50 -08001126 &code_item)) {
Mathieu Chartier2b2bef22017-10-26 17:10:19 -07001127 const uint32_t dex_pc = pair.DexPc();
1128 const Instruction& instruction = pair.Inst();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001129 if (instruction.IsBranch()) {
1130 uint32_t target = dex_pc + instruction.GetTargetOffset();
1131 CheckCovers(target, graph, code_info, loop_headers, &covered);
1132 } else if (instruction.IsSwitch()) {
David Brazdil86ea7ee2016-02-16 09:26:07 +00001133 DexSwitchTable table(instruction, dex_pc);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001134 uint16_t num_entries = table.GetNumEntries();
1135 size_t offset = table.GetFirstValueIndex();
1136
1137 // Use a larger loop counter type to avoid overflow issues.
1138 for (size_t i = 0; i < num_entries; ++i) {
1139 // The target of the case.
1140 uint32_t target = dex_pc + table.GetEntryAt(i + offset);
1141 CheckCovers(target, graph, code_info, loop_headers, &covered);
1142 }
1143 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001144 }
1145
1146 for (size_t i = 0; i < covered.size(); ++i) {
1147 DCHECK_NE(covered[i], 0u) << "Loop in compiled code has no dex branch equivalent";
1148 }
1149}
1150
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001151ScopedArenaVector<uint8_t> CodeGenerator::BuildStackMaps(const dex::CodeItem* code_item) {
David Srbeckye7a91942018-08-01 17:23:53 +01001152 ScopedArenaVector<uint8_t> stack_map = GetStackMapStream()->Encode();
1153 if (kIsDebugBuild && code_item != nullptr) {
1154 CheckLoopEntriesCanBeUsedForOsr(*graph_, CodeInfo(stack_map.data()), *code_item);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001155 }
David Srbeckye7a91942018-08-01 17:23:53 +01001156 return stack_map;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001157}
1158
Artem Serov2808be82018-12-20 19:15:11 +00001159// Returns whether stackmap dex register info is needed for the instruction.
1160//
1161// The following cases mandate having a dex register map:
1162// * Deoptimization
1163// when we need to obtain the values to restore actual vregisters for interpreter.
1164// * Debuggability
1165// when we want to observe the values / asynchronously deoptimize.
1166// * Monitor operations
1167// to allow dumping in a stack trace locked dex registers for non-debuggable code.
1168// * On-stack-replacement (OSR)
1169// when entering compiled for OSR code from the interpreter we need to initialize the compiled
1170// code values with the values from the vregisters.
1171// * Method local catch blocks
1172// a catch block must see the environment of the instruction from the same method that can
1173// throw to this block.
1174static bool NeedsVregInfo(HInstruction* instruction, bool osr) {
1175 HGraph* graph = instruction->GetBlock()->GetGraph();
1176 return instruction->IsDeoptimize() ||
1177 graph->IsDebuggable() ||
1178 graph->HasMonitorOperations() ||
1179 osr ||
1180 instruction->CanThrowIntoCatchBlock();
1181}
1182
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001183void CodeGenerator::RecordPcInfo(HInstruction* instruction,
1184 uint32_t dex_pc,
David Srbecky50fac062018-06-13 18:55:35 +01001185 SlowPathCode* slow_path,
1186 bool native_debug_info) {
Evgeny Astigeevich98416bf2019-09-09 14:52:12 +01001187 RecordPcInfo(instruction, dex_pc, GetAssembler()->CodePosition(), slow_path, native_debug_info);
1188}
1189
1190void CodeGenerator::RecordPcInfo(HInstruction* instruction,
1191 uint32_t dex_pc,
1192 uint32_t native_pc,
1193 SlowPathCode* slow_path,
1194 bool native_debug_info) {
Calin Juravled2ec87d2014-12-08 14:24:46 +00001195 if (instruction != nullptr) {
Roland Levillain1693a1f2016-03-15 14:57:31 +00001196 // The code generated for some type conversions
Alexey Frunze4dda3372015-06-01 18:31:49 -07001197 // may call the runtime, thus normally requiring a subsequent
1198 // call to this method. However, the method verifier does not
1199 // produce PC information for certain instructions, which are
1200 // considered "atomic" (they cannot join a GC).
Roland Levillain624279f2014-12-04 11:54:28 +00001201 // Therefore we do not currently record PC information for such
1202 // instructions. As this may change later, we added this special
1203 // case so that code generators may nevertheless call
1204 // CodeGenerator::RecordPcInfo without triggering an error in
1205 // CodeGenerator::BuildNativeGCMap ("Missing ref for dex pc 0x")
1206 // thereafter.
Roland Levillain1693a1f2016-03-15 14:57:31 +00001207 if (instruction->IsTypeConversion()) {
Calin Juravled2ec87d2014-12-08 14:24:46 +00001208 return;
1209 }
1210 if (instruction->IsRem()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001211 DataType::Type type = instruction->AsRem()->GetResultType();
1212 if ((type == DataType::Type::kFloat32) || (type == DataType::Type::kFloat64)) {
Calin Juravled2ec87d2014-12-08 14:24:46 +00001213 return;
1214 }
1215 }
Roland Levillain624279f2014-12-04 11:54:28 +00001216 }
1217
Vladimir Marko174b2e22017-10-12 13:34:49 +01001218 StackMapStream* stack_map_stream = GetStackMapStream();
Nicolas Geoffray39468442014-09-02 15:17:15 +01001219 if (instruction == nullptr) {
David Srbeckyc7098ff2016-02-09 14:30:11 +00001220 // For stack overflow checks and native-debug-info entries without dex register
1221 // mapping (i.e. start of basic block or start of slow path).
David Srbeckyf6ba5b32018-06-23 22:05:49 +01001222 stack_map_stream->BeginStackMapEntry(dex_pc, native_pc);
Vladimir Marko174b2e22017-10-12 13:34:49 +01001223 stack_map_stream->EndStackMapEntry();
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001224 return;
1225 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001226
Vladimir Markofec85cd2017-12-04 13:00:12 +00001227 LocationSummary* locations = instruction->GetLocations();
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001228 uint32_t register_mask = locations->GetRegisterMask();
Vladimir Marko70e97462016-08-09 11:04:26 +01001229 DCHECK_EQ(register_mask & ~locations->GetLiveRegisters()->GetCoreRegisters(), 0u);
1230 if (locations->OnlyCallsOnSlowPath()) {
1231 // In case of slow path, we currently set the location of caller-save registers
1232 // to register (instead of their stack location when pushed before the slow-path
1233 // call). Therefore register_mask contains both callee-save and caller-save
1234 // registers that hold objects. We must remove the spilled caller-save from the
1235 // mask, since they will be overwritten by the callee.
Andreas Gampe3db70682018-12-26 15:12:03 -08001236 uint32_t spills = GetSlowPathSpills(locations, /* core_registers= */ true);
Vladimir Marko70e97462016-08-09 11:04:26 +01001237 register_mask &= ~spills;
Vladimir Marko952dbb12016-07-28 12:01:51 +01001238 } else {
Vladimir Marko952dbb12016-07-28 12:01:51 +01001239 // The register mask must be a subset of callee-save registers.
1240 DCHECK_EQ(register_mask & core_callee_save_mask_, register_mask);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001241 }
Vladimir Markofec85cd2017-12-04 13:00:12 +00001242
1243 uint32_t outer_dex_pc = dex_pc;
1244 uint32_t outer_environment_size = 0u;
1245 uint32_t inlining_depth = 0;
1246 HEnvironment* const environment = instruction->GetEnvironment();
1247 if (environment != nullptr) {
1248 HEnvironment* outer_environment = environment;
1249 while (outer_environment->GetParent() != nullptr) {
1250 outer_environment = outer_environment->GetParent();
1251 ++inlining_depth;
1252 }
1253 outer_dex_pc = outer_environment->GetDexPc();
1254 outer_environment_size = outer_environment->Size();
1255 }
David Srbecky50fac062018-06-13 18:55:35 +01001256
1257 HLoopInformation* info = instruction->GetBlock()->GetLoopInformation();
1258 bool osr =
1259 instruction->IsSuspendCheck() &&
1260 (info != nullptr) &&
1261 graph_->IsCompilingOsr() &&
1262 (inlining_depth == 0);
1263 StackMap::Kind kind = native_debug_info
1264 ? StackMap::Kind::Debug
1265 : (osr ? StackMap::Kind::OSR : StackMap::Kind::Default);
Artem Serov2808be82018-12-20 19:15:11 +00001266 bool needs_vreg_info = NeedsVregInfo(instruction, osr);
Vladimir Marko174b2e22017-10-12 13:34:49 +01001267 stack_map_stream->BeginStackMapEntry(outer_dex_pc,
Vladimir Markobd8c7252015-06-12 10:06:32 +01001268 native_pc,
Calin Juravle4f46ac52015-04-23 18:47:21 +01001269 register_mask,
1270 locations->GetStackMask(),
Artem Serov2808be82018-12-20 19:15:11 +00001271 kind,
1272 needs_vreg_info);
1273
1274 EmitEnvironment(environment, slow_path, needs_vreg_info);
Vladimir Marko174b2e22017-10-12 13:34:49 +01001275 stack_map_stream->EndStackMapEntry();
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001276
David Srbecky50fac062018-06-13 18:55:35 +01001277 if (osr) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001278 DCHECK_EQ(info->GetSuspendCheck(), instruction);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001279 DCHECK(info->IsIrreducible());
Andreas Gampe875b4f22018-11-19 12:59:15 -08001280 DCHECK(environment != nullptr);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001281 if (kIsDebugBuild) {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001282 for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) {
1283 HInstruction* in_environment = environment->GetInstructionAt(i);
1284 if (in_environment != nullptr) {
1285 DCHECK(in_environment->IsPhi() || in_environment->IsConstant());
1286 Location location = environment->GetLocationAt(i);
1287 DCHECK(location.IsStackSlot() ||
1288 location.IsDoubleStackSlot() ||
1289 location.IsConstant() ||
1290 location.IsInvalid());
1291 if (location.IsStackSlot() || location.IsDoubleStackSlot()) {
1292 DCHECK_LT(location.GetStackIndex(), static_cast<int32_t>(GetFrameSize()));
1293 }
1294 }
1295 }
1296 }
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001297 }
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001298}
1299
David Srbeckyb7070a22016-01-08 18:13:53 +00001300bool CodeGenerator::HasStackMapAtCurrentPc() {
1301 uint32_t pc = GetAssembler()->CodeSize();
Vladimir Marko174b2e22017-10-12 13:34:49 +01001302 StackMapStream* stack_map_stream = GetStackMapStream();
1303 size_t count = stack_map_stream->GetNumberOfStackMaps();
Andreas Gampe0c95c122017-02-26 14:10:28 -08001304 if (count == 0) {
1305 return false;
1306 }
David Srbeckyd02b23f2018-05-29 23:27:22 +01001307 return stack_map_stream->GetStackMapNativePcOffset(count - 1) == pc;
David Srbeckyb7070a22016-01-08 18:13:53 +00001308}
1309
David Srbeckyd28f4a02016-03-14 17:14:24 +00001310void CodeGenerator::MaybeRecordNativeDebugInfo(HInstruction* instruction,
1311 uint32_t dex_pc,
1312 SlowPathCode* slow_path) {
David Srbeckyc7098ff2016-02-09 14:30:11 +00001313 if (GetCompilerOptions().GetNativeDebuggable() && dex_pc != kNoDexPc) {
1314 if (HasStackMapAtCurrentPc()) {
1315 // Ensure that we do not collide with the stack map of the previous instruction.
1316 GenerateNop();
1317 }
Andreas Gampe3db70682018-12-26 15:12:03 -08001318 RecordPcInfo(instruction, dex_pc, slow_path, /* native_debug_info= */ true);
David Srbeckyc7098ff2016-02-09 14:30:11 +00001319 }
1320}
1321
David Brazdil77a48ae2015-09-15 12:34:04 +00001322void CodeGenerator::RecordCatchBlockInfo() {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001323 StackMapStream* stack_map_stream = GetStackMapStream();
David Brazdil77a48ae2015-09-15 12:34:04 +00001324
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001325 for (HBasicBlock* block : *block_order_) {
David Brazdil77a48ae2015-09-15 12:34:04 +00001326 if (!block->IsCatchBlock()) {
1327 continue;
1328 }
1329
1330 uint32_t dex_pc = block->GetDexPc();
1331 uint32_t num_vregs = graph_->GetNumberOfVRegs();
David Brazdil77a48ae2015-09-15 12:34:04 +00001332 uint32_t native_pc = GetAddressOf(block);
David Brazdil77a48ae2015-09-15 12:34:04 +00001333
Vladimir Marko174b2e22017-10-12 13:34:49 +01001334 stack_map_stream->BeginStackMapEntry(dex_pc,
David Brazdil77a48ae2015-09-15 12:34:04 +00001335 native_pc,
Andreas Gampe3db70682018-12-26 15:12:03 -08001336 /* register_mask= */ 0,
1337 /* sp_mask= */ nullptr,
David Srbecky50fac062018-06-13 18:55:35 +01001338 StackMap::Kind::Catch);
David Brazdil77a48ae2015-09-15 12:34:04 +00001339
1340 HInstruction* current_phi = block->GetFirstPhi();
1341 for (size_t vreg = 0; vreg < num_vregs; ++vreg) {
David Srbecky50fac062018-06-13 18:55:35 +01001342 while (current_phi != nullptr && current_phi->AsPhi()->GetRegNumber() < vreg) {
1343 HInstruction* next_phi = current_phi->GetNext();
1344 DCHECK(next_phi == nullptr ||
1345 current_phi->AsPhi()->GetRegNumber() <= next_phi->AsPhi()->GetRegNumber())
1346 << "Phis need to be sorted by vreg number to keep this a linear-time loop.";
1347 current_phi = next_phi;
1348 }
David Brazdil77a48ae2015-09-15 12:34:04 +00001349
1350 if (current_phi == nullptr || current_phi->AsPhi()->GetRegNumber() != vreg) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001351 stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
David Brazdil77a48ae2015-09-15 12:34:04 +00001352 } else {
Vladimir Markobea75ff2017-10-11 20:39:54 +01001353 Location location = current_phi->GetLocations()->Out();
David Brazdil77a48ae2015-09-15 12:34:04 +00001354 switch (location.GetKind()) {
1355 case Location::kStackSlot: {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001356 stack_map_stream->AddDexRegisterEntry(
David Brazdil77a48ae2015-09-15 12:34:04 +00001357 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
1358 break;
1359 }
1360 case Location::kDoubleStackSlot: {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001361 stack_map_stream->AddDexRegisterEntry(
David Brazdil77a48ae2015-09-15 12:34:04 +00001362 DexRegisterLocation::Kind::kInStack, location.GetStackIndex());
Vladimir Marko174b2e22017-10-12 13:34:49 +01001363 stack_map_stream->AddDexRegisterEntry(
David Brazdil77a48ae2015-09-15 12:34:04 +00001364 DexRegisterLocation::Kind::kInStack, location.GetHighStackIndex(kVRegSize));
1365 ++vreg;
1366 DCHECK_LT(vreg, num_vregs);
1367 break;
1368 }
1369 default: {
1370 // All catch phis must be allocated to a stack slot.
1371 LOG(FATAL) << "Unexpected kind " << location.GetKind();
1372 UNREACHABLE();
1373 }
1374 }
1375 }
1376 }
1377
Vladimir Marko174b2e22017-10-12 13:34:49 +01001378 stack_map_stream->EndStackMapEntry();
David Brazdil77a48ae2015-09-15 12:34:04 +00001379 }
1380}
1381
Vladimir Marko174b2e22017-10-12 13:34:49 +01001382void CodeGenerator::AddSlowPath(SlowPathCode* slow_path) {
1383 DCHECK(code_generation_data_ != nullptr);
1384 code_generation_data_->AddSlowPath(slow_path);
1385}
1386
Artem Serov2808be82018-12-20 19:15:11 +00001387void CodeGenerator::EmitVRegInfo(HEnvironment* environment, SlowPathCode* slow_path) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001388 StackMapStream* stack_map_stream = GetStackMapStream();
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001389 // Walk over the environment, and record the location of dex registers.
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001390 for (size_t i = 0, environment_size = environment->Size(); i < environment_size; ++i) {
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001391 HInstruction* current = environment->GetInstructionAt(i);
1392 if (current == nullptr) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001393 stack_map_stream->AddDexRegisterEntry(DexRegisterLocation::Kind::kNone, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001394 continue;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001395 }
1396
David Srbeckye1402122018-06-13 18:20:45 +01001397 using Kind = DexRegisterLocation::Kind;
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001398 Location location = environment->GetLocationAt(i);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001399 switch (location.GetKind()) {
1400 case Location::kConstant: {
1401 DCHECK_EQ(current, location.GetConstant());
1402 if (current->IsLongConstant()) {
1403 int64_t value = current->AsLongConstant()->GetValue();
David Srbeckye1402122018-06-13 18:20:45 +01001404 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, Low32Bits(value));
1405 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, High32Bits(value));
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001406 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001407 DCHECK_LT(i, environment_size);
1408 } else if (current->IsDoubleConstant()) {
Roland Levillainda4d79b2015-03-24 14:36:11 +00001409 int64_t value = bit_cast<int64_t, double>(current->AsDoubleConstant()->GetValue());
David Srbeckye1402122018-06-13 18:20:45 +01001410 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, Low32Bits(value));
1411 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, High32Bits(value));
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001412 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001413 DCHECK_LT(i, environment_size);
1414 } else if (current->IsIntConstant()) {
1415 int32_t value = current->AsIntConstant()->GetValue();
David Srbeckye1402122018-06-13 18:20:45 +01001416 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, value);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001417 } else if (current->IsNullConstant()) {
David Srbeckye1402122018-06-13 18:20:45 +01001418 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001419 } else {
1420 DCHECK(current->IsFloatConstant()) << current->DebugName();
Roland Levillainda4d79b2015-03-24 14:36:11 +00001421 int32_t value = bit_cast<int32_t, float>(current->AsFloatConstant()->GetValue());
David Srbeckye1402122018-06-13 18:20:45 +01001422 stack_map_stream->AddDexRegisterEntry(Kind::kConstant, value);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001423 }
1424 break;
1425 }
1426
1427 case Location::kStackSlot: {
David Srbeckye1402122018-06-13 18:20:45 +01001428 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, location.GetStackIndex());
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001429 break;
1430 }
1431
1432 case Location::kDoubleStackSlot: {
David Srbeckye1402122018-06-13 18:20:45 +01001433 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, location.GetStackIndex());
Vladimir Marko174b2e22017-10-12 13:34:49 +01001434 stack_map_stream->AddDexRegisterEntry(
David Srbeckye1402122018-06-13 18:20:45 +01001435 Kind::kInStack, location.GetHighStackIndex(kVRegSize));
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001436 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001437 DCHECK_LT(i, environment_size);
1438 break;
1439 }
1440
1441 case Location::kRegister : {
1442 int id = location.reg();
1443 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(id)) {
1444 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(id);
David Srbeckye1402122018-06-13 18:20:45 +01001445 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 if (current->GetType() == DataType::Type::kInt64) {
David Srbeckye1402122018-06-13 18:20:45 +01001447 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset + kVRegSize);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001448 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001449 DCHECK_LT(i, environment_size);
1450 }
1451 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001452 stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, id);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001453 if (current->GetType() == DataType::Type::kInt64) {
David Srbeckye1402122018-06-13 18:20:45 +01001454 stack_map_stream->AddDexRegisterEntry(Kind::kInRegisterHigh, id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001455 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001456 DCHECK_LT(i, environment_size);
1457 }
1458 }
1459 break;
1460 }
1461
1462 case Location::kFpuRegister : {
1463 int id = location.reg();
1464 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(id)) {
1465 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(id);
David Srbeckye1402122018-06-13 18:20:45 +01001466 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001467 if (current->GetType() == DataType::Type::kFloat64) {
David Srbeckye1402122018-06-13 18:20:45 +01001468 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset + kVRegSize);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001469 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001470 DCHECK_LT(i, environment_size);
1471 }
1472 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001473 stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, id);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001474 if (current->GetType() == DataType::Type::kFloat64) {
David Srbeckye1402122018-06-13 18:20:45 +01001475 stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegisterHigh, id);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001476 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001477 DCHECK_LT(i, environment_size);
1478 }
1479 }
1480 break;
1481 }
1482
1483 case Location::kFpuRegisterPair : {
1484 int low = location.low();
1485 int high = location.high();
1486 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(low)) {
1487 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(low);
David Srbeckye1402122018-06-13 18:20:45 +01001488 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001489 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001490 stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, low);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001491 }
1492 if (slow_path != nullptr && slow_path->IsFpuRegisterSaved(high)) {
1493 uint32_t offset = slow_path->GetStackOffsetOfFpuRegister(high);
David Srbeckye1402122018-06-13 18:20:45 +01001494 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001495 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001496 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001497 stack_map_stream->AddDexRegisterEntry(Kind::kInFpuRegister, high);
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001498 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001499 }
1500 DCHECK_LT(i, environment_size);
1501 break;
1502 }
1503
1504 case Location::kRegisterPair : {
1505 int low = location.low();
1506 int high = location.high();
1507 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(low)) {
1508 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(low);
David Srbeckye1402122018-06-13 18:20:45 +01001509 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001510 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001511 stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, low);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001512 }
1513 if (slow_path != nullptr && slow_path->IsCoreRegisterSaved(high)) {
1514 uint32_t offset = slow_path->GetStackOffsetOfCoreRegister(high);
David Srbeckye1402122018-06-13 18:20:45 +01001515 stack_map_stream->AddDexRegisterEntry(Kind::kInStack, offset);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001516 } else {
David Srbeckye1402122018-06-13 18:20:45 +01001517 stack_map_stream->AddDexRegisterEntry(Kind::kInRegister, high);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001518 }
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001519 ++i;
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001520 DCHECK_LT(i, environment_size);
1521 break;
1522 }
1523
1524 case Location::kInvalid: {
David Srbeckye1402122018-06-13 18:20:45 +01001525 stack_map_stream->AddDexRegisterEntry(Kind::kNone, 0);
Nicolas Geoffrayeeefa122015-03-13 18:52:59 +00001526 break;
1527 }
1528
1529 default:
1530 LOG(FATAL) << "Unexpected kind " << location.GetKind();
1531 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001532 }
Artem Serov2808be82018-12-20 19:15:11 +00001533}
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001534
Artem Serov2808be82018-12-20 19:15:11 +00001535void CodeGenerator::EmitEnvironment(HEnvironment* environment,
1536 SlowPathCode* slow_path,
1537 bool needs_vreg_info) {
1538 if (environment == nullptr) return;
1539
1540 StackMapStream* stack_map_stream = GetStackMapStream();
1541 bool emit_inline_info = environment->GetParent() != nullptr;
1542
1543 if (emit_inline_info) {
1544 // We emit the parent environment first.
1545 EmitEnvironment(environment->GetParent(), slow_path, needs_vreg_info);
1546 stack_map_stream->BeginInlineInfoEntry(environment->GetMethod(),
1547 environment->GetDexPc(),
1548 needs_vreg_info ? environment->Size() : 0,
1549 &graph_->GetDexFile());
1550 }
1551
1552 if (needs_vreg_info) {
1553 // If a dex register map is not required we just won't emit it.
1554 EmitVRegInfo(environment, slow_path);
1555 }
1556
1557 if (emit_inline_info) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001558 stack_map_stream->EndInlineInfoEntry();
Nicolas Geoffrayb1d0f3f2015-05-14 12:41:51 +01001559 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001560}
1561
Calin Juravle77520bc2015-01-12 18:45:46 +00001562bool CodeGenerator::CanMoveNullCheckToUser(HNullCheck* null_check) {
Nicolas Geoffray61ba8d22018-08-07 09:55:57 +01001563 return null_check->IsEmittedAtUseSite();
Calin Juravle77520bc2015-01-12 18:45:46 +00001564}
1565
1566void CodeGenerator::MaybeRecordImplicitNullCheck(HInstruction* instr) {
Nicolas Geoffray61ba8d22018-08-07 09:55:57 +01001567 HNullCheck* null_check = instr->GetImplicitNullCheck();
1568 if (null_check != nullptr) {
Evgeny Astigeevich98416bf2019-09-09 14:52:12 +01001569 RecordPcInfo(null_check, null_check->GetDexPc(), GetAssembler()->CodePosition());
Calin Juravle77520bc2015-01-12 18:45:46 +00001570 }
1571}
1572
Vladimir Marko804b03f2016-09-14 16:26:36 +01001573LocationSummary* CodeGenerator::CreateThrowingSlowPathLocations(HInstruction* instruction,
1574 RegisterSet caller_saves) {
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001575 // Note: Using kNoCall allows the method to be treated as leaf (and eliminate the
1576 // HSuspendCheck from entry block). However, it will still get a valid stack frame
1577 // because the HNullCheck needs an environment.
1578 LocationSummary::CallKind call_kind = LocationSummary::kNoCall;
1579 // When throwing from a try block, we may need to retrieve dalvik registers from
1580 // physical registers and we also need to set up stack mask for GC. This is
1581 // implicitly achieved by passing kCallOnSlowPath to the LocationSummary.
Vladimir Marko804b03f2016-09-14 16:26:36 +01001582 bool can_throw_into_catch_block = instruction->CanThrowIntoCatchBlock();
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001583 if (can_throw_into_catch_block) {
1584 call_kind = LocationSummary::kCallOnSlowPath;
1585 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001586 LocationSummary* locations =
1587 new (GetGraph()->GetAllocator()) LocationSummary(instruction, call_kind);
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001588 if (can_throw_into_catch_block && compiler_options_.GetImplicitNullChecks()) {
Vladimir Marko804b03f2016-09-14 16:26:36 +01001589 locations->SetCustomSlowPathCallerSaves(caller_saves); // Default: no caller-save registers.
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001590 }
Vladimir Marko804b03f2016-09-14 16:26:36 +01001591 DCHECK(!instruction->HasUses());
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001592 return locations;
1593}
1594
Calin Juravle2ae48182016-03-16 14:05:09 +00001595void CodeGenerator::GenerateNullCheck(HNullCheck* instruction) {
Vladimir Marko3b7537b2016-09-13 11:56:01 +00001596 if (compiler_options_.GetImplicitNullChecks()) {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001597 MaybeRecordStat(stats_, MethodCompilationStat::kImplicitNullCheckGenerated);
Calin Juravle2ae48182016-03-16 14:05:09 +00001598 GenerateImplicitNullCheck(instruction);
1599 } else {
Vladimir Markocd09e1f2017-11-24 15:02:40 +00001600 MaybeRecordStat(stats_, MethodCompilationStat::kExplicitNullCheckGenerated);
Calin Juravle2ae48182016-03-16 14:05:09 +00001601 GenerateExplicitNullCheck(instruction);
1602 }
1603}
1604
Vladimir Markobea75ff2017-10-11 20:39:54 +01001605void CodeGenerator::ClearSpillSlotsFromLoopPhisInStackMap(HSuspendCheck* suspend_check,
1606 HParallelMove* spills) const {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001607 LocationSummary* locations = suspend_check->GetLocations();
1608 HBasicBlock* block = suspend_check->GetBlock();
1609 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == suspend_check);
1610 DCHECK(block->IsLoopHeader());
Vladimir Markobea75ff2017-10-11 20:39:54 +01001611 DCHECK(block->GetFirstInstruction() == spills);
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001612
Vladimir Markobea75ff2017-10-11 20:39:54 +01001613 for (size_t i = 0, num_moves = spills->NumMoves(); i != num_moves; ++i) {
1614 Location dest = spills->MoveOperandsAt(i)->GetDestination();
1615 // All parallel moves in loop headers are spills.
1616 DCHECK(dest.IsStackSlot() || dest.IsDoubleStackSlot() || dest.IsSIMDStackSlot()) << dest;
1617 // Clear the stack bit marking a reference. Do not bother to check if the spill is
1618 // actually a reference spill, clearing bits that are already zero is harmless.
1619 locations->ClearStackBit(dest.GetStackIndex() / kVRegSize);
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001620 }
1621}
1622
Nicolas Geoffray90218252015-04-15 11:56:51 +01001623void CodeGenerator::EmitParallelMoves(Location from1,
1624 Location to1,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 DataType::Type type1,
Nicolas Geoffray90218252015-04-15 11:56:51 +01001626 Location from2,
1627 Location to2,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 DataType::Type type2) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01001629 HParallelMove parallel_move(GetGraph()->GetAllocator());
Nicolas Geoffray90218252015-04-15 11:56:51 +01001630 parallel_move.AddMove(from1, to1, type1, nullptr);
1631 parallel_move.AddMove(from2, to2, type2, nullptr);
Nicolas Geoffrayf0e39372014-11-12 17:50:07 +00001632 GetMoveResolver()->EmitNativeCode(&parallel_move);
1633}
1634
Alexandre Rames91a65162016-09-19 13:54:30 +01001635void CodeGenerator::ValidateInvokeRuntime(QuickEntrypointEnum entrypoint,
1636 HInstruction* instruction,
1637 SlowPathCode* slow_path) {
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001638 // Ensure that the call kind indication given to the register allocator is
Alexandre Rames91a65162016-09-19 13:54:30 +01001639 // coherent with the runtime call generated.
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001640 if (slow_path == nullptr) {
Roland Levillain0d5a2812015-11-13 10:07:31 +00001641 DCHECK(instruction->GetLocations()->WillCall())
1642 << "instruction->DebugName()=" << instruction->DebugName();
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001643 } else {
Serban Constantinescu806f0122016-03-09 11:10:16 +00001644 DCHECK(instruction->GetLocations()->CallsOnSlowPath() || slow_path->IsFatal())
Roland Levillain0d5a2812015-11-13 10:07:31 +00001645 << "instruction->DebugName()=" << instruction->DebugName()
1646 << " slow_path->GetDescription()=" << slow_path->GetDescription();
Alexandre Rames91a65162016-09-19 13:54:30 +01001647 }
1648
1649 // Check that the GC side effect is set when required.
1650 // TODO: Reverse EntrypointCanTriggerGC
1651 if (EntrypointCanTriggerGC(entrypoint)) {
1652 if (slow_path == nullptr) {
1653 DCHECK(instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()))
1654 << "instruction->DebugName()=" << instruction->DebugName()
1655 << " instruction->GetSideEffects().ToString()="
1656 << instruction->GetSideEffects().ToString();
1657 } else {
Artem Serovd1aa7d02018-06-22 11:35:46 +01001658 // 'CanTriggerGC' side effect is used to restrict optimization of instructions which depend
1659 // on GC (e.g. IntermediateAddress) - to ensure they are not alive across GC points. However
1660 // if execution never returns to the compiled code from a GC point this restriction is
1661 // unnecessary - in particular for fatal slow paths which might trigger GC.
1662 DCHECK((slow_path->IsFatal() && !instruction->GetLocations()->WillCall()) ||
1663 instruction->GetSideEffects().Includes(SideEffects::CanTriggerGC()) ||
Alexandre Rames91a65162016-09-19 13:54:30 +01001664 // When (non-Baker) read barriers are enabled, some instructions
1665 // use a slow path to emit a read barrier, which does not trigger
1666 // GC.
1667 (kEmitCompilerReadBarrier &&
1668 !kUseBakerReadBarrier &&
1669 (instruction->IsInstanceFieldGet() ||
Alex Light3a73ffb2021-01-25 14:11:05 +00001670 instruction->IsPredicatedInstanceFieldGet() ||
Alexandre Rames91a65162016-09-19 13:54:30 +01001671 instruction->IsStaticFieldGet() ||
1672 instruction->IsArrayGet() ||
1673 instruction->IsLoadClass() ||
1674 instruction->IsLoadString() ||
1675 instruction->IsInstanceOf() ||
1676 instruction->IsCheckCast() ||
1677 (instruction->IsInvokeVirtual() && instruction->GetLocations()->Intrinsified()))))
1678 << "instruction->DebugName()=" << instruction->DebugName()
1679 << " instruction->GetSideEffects().ToString()="
1680 << instruction->GetSideEffects().ToString()
Alex Light3a73ffb2021-01-25 14:11:05 +00001681 << " slow_path->GetDescription()=" << slow_path->GetDescription() << std::endl
1682 << "Instruction and args: " << instruction->DumpWithArgs();
Alexandre Rames91a65162016-09-19 13:54:30 +01001683 }
1684 } else {
1685 // The GC side effect is not required for the instruction. But the instruction might still have
1686 // it, for example if it calls other entrypoints requiring it.
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001687 }
1688
1689 // Check the coherency of leaf information.
1690 DCHECK(instruction->IsSuspendCheck()
1691 || ((slow_path != nullptr) && slow_path->IsFatal())
1692 || instruction->GetLocations()->CanCall()
Roland Levillaindf3f8222015-08-13 12:31:44 +01001693 || !IsLeafMethod())
1694 << instruction->DebugName() << ((slow_path != nullptr) ? slow_path->GetDescription() : "");
Alexandre Rames78e3ef62015-08-12 13:43:29 +01001695}
1696
Roland Levillaindec8f632016-07-22 17:10:06 +01001697void CodeGenerator::ValidateInvokeRuntimeWithoutRecordingPcInfo(HInstruction* instruction,
1698 SlowPathCode* slow_path) {
1699 DCHECK(instruction->GetLocations()->OnlyCallsOnSlowPath())
1700 << "instruction->DebugName()=" << instruction->DebugName()
1701 << " slow_path->GetDescription()=" << slow_path->GetDescription();
1702 // Only the Baker read barrier marking slow path used by certains
1703 // instructions is expected to invoke the runtime without recording
1704 // PC-related information.
1705 DCHECK(kUseBakerReadBarrier);
1706 DCHECK(instruction->IsInstanceFieldGet() ||
Alex Light3a73ffb2021-01-25 14:11:05 +00001707 instruction->IsPredicatedInstanceFieldGet() ||
Roland Levillaindec8f632016-07-22 17:10:06 +01001708 instruction->IsStaticFieldGet() ||
1709 instruction->IsArrayGet() ||
Roland Levillain16d9f942016-08-25 17:27:56 +01001710 instruction->IsArraySet() ||
Roland Levillaindec8f632016-07-22 17:10:06 +01001711 instruction->IsLoadClass() ||
1712 instruction->IsLoadString() ||
1713 instruction->IsInstanceOf() ||
1714 instruction->IsCheckCast() ||
Andra Danciu1ca6f322020-08-12 08:58:07 +00001715 (instruction->IsInvoke() && instruction->GetLocations()->Intrinsified()))
Roland Levillaindec8f632016-07-22 17:10:06 +01001716 << "instruction->DebugName()=" << instruction->DebugName()
1717 << " slow_path->GetDescription()=" << slow_path->GetDescription();
1718}
1719
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001720void SlowPathCode::SaveLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001721 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
Roland Levillain0d5a2812015-11-13 10:07:31 +00001722
Andreas Gampe3db70682018-12-26 15:12:03 -08001723 const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
Vladimir Marko70e97462016-08-09 11:04:26 +01001724 for (uint32_t i : LowToHighBits(core_spills)) {
1725 // If the register holds an object, update the stack mask.
1726 if (locations->RegisterContainsObject(i)) {
1727 locations->SetStackBit(stack_offset / kVRegSize);
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001728 }
Vladimir Marko70e97462016-08-09 11:04:26 +01001729 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1730 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1731 saved_core_stack_offsets_[i] = stack_offset;
1732 stack_offset += codegen->SaveCoreRegister(stack_offset, i);
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001733 }
1734
Andreas Gampe3db70682018-12-26 15:12:03 -08001735 const uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
Vladimir Marko804b03f2016-09-14 16:26:36 +01001736 for (uint32_t i : LowToHighBits(fp_spills)) {
Vladimir Marko70e97462016-08-09 11:04:26 +01001737 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1738 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1739 saved_fpu_stack_offsets_[i] = stack_offset;
1740 stack_offset += codegen->SaveFloatingPointRegister(stack_offset, i);
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001741 }
1742}
1743
1744void SlowPathCode::RestoreLiveRegisters(CodeGenerator* codegen, LocationSummary* locations) {
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001745 size_t stack_offset = codegen->GetFirstRegisterSlotInSlowPath();
Roland Levillain0d5a2812015-11-13 10:07:31 +00001746
Andreas Gampe3db70682018-12-26 15:12:03 -08001747 const uint32_t core_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ true);
Vladimir Marko70e97462016-08-09 11:04:26 +01001748 for (uint32_t i : LowToHighBits(core_spills)) {
1749 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1750 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1751 stack_offset += codegen->RestoreCoreRegister(stack_offset, i);
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001752 }
1753
Andreas Gampe3db70682018-12-26 15:12:03 -08001754 const uint32_t fp_spills = codegen->GetSlowPathSpills(locations, /* core_registers= */ false);
Vladimir Marko804b03f2016-09-14 16:26:36 +01001755 for (uint32_t i : LowToHighBits(fp_spills)) {
Vladimir Marko70e97462016-08-09 11:04:26 +01001756 DCHECK_LT(stack_offset, codegen->GetFrameSize() - codegen->FrameEntrySpillSize());
1757 DCHECK_LT(i, kMaximumNumberOfExpectedRegisters);
1758 stack_offset += codegen->RestoreFloatingPointRegister(stack_offset, i);
Nicolas Geoffraya8ac9132015-03-13 16:36:36 +00001759 }
1760}
1761
Nicolas Geoffray5bd05a52015-10-13 09:48:30 +01001762void CodeGenerator::CreateSystemArrayCopyLocationSummary(HInvoke* invoke) {
1763 // Check to see if we have known failures that will cause us to have to bail out
1764 // to the runtime, and just generate the runtime call directly.
1765 HIntConstant* src_pos = invoke->InputAt(1)->AsIntConstant();
1766 HIntConstant* dest_pos = invoke->InputAt(3)->AsIntConstant();
1767
1768 // The positions must be non-negative.
1769 if ((src_pos != nullptr && src_pos->GetValue() < 0) ||
1770 (dest_pos != nullptr && dest_pos->GetValue() < 0)) {
1771 // We will have to fail anyways.
1772 return;
1773 }
1774
1775 // The length must be >= 0.
1776 HIntConstant* length = invoke->InputAt(4)->AsIntConstant();
1777 if (length != nullptr) {
1778 int32_t len = length->GetValue();
1779 if (len < 0) {
1780 // Just call as normal.
1781 return;
1782 }
1783 }
1784
1785 SystemArrayCopyOptimizations optimizations(invoke);
1786
1787 if (optimizations.GetDestinationIsSource()) {
1788 if (src_pos != nullptr && dest_pos != nullptr && src_pos->GetValue() < dest_pos->GetValue()) {
1789 // We only support backward copying if source and destination are the same.
1790 return;
1791 }
1792 }
1793
1794 if (optimizations.GetDestinationIsPrimitiveArray() || optimizations.GetSourceIsPrimitiveArray()) {
1795 // We currently don't intrinsify primitive copying.
1796 return;
1797 }
1798
Vladimir Markoca6fff82017-10-03 14:49:14 +01001799 ArenaAllocator* allocator = invoke->GetBlock()->GetGraph()->GetAllocator();
Nicolas Geoffray5bd05a52015-10-13 09:48:30 +01001800 LocationSummary* locations = new (allocator) LocationSummary(invoke,
1801 LocationSummary::kCallOnSlowPath,
1802 kIntrinsified);
1803 // arraycopy(Object src, int src_pos, Object dest, int dest_pos, int length).
1804 locations->SetInAt(0, Location::RequiresRegister());
1805 locations->SetInAt(1, Location::RegisterOrConstant(invoke->InputAt(1)));
1806 locations->SetInAt(2, Location::RequiresRegister());
1807 locations->SetInAt(3, Location::RegisterOrConstant(invoke->InputAt(3)));
1808 locations->SetInAt(4, Location::RegisterOrConstant(invoke->InputAt(4)));
1809
1810 locations->AddTemp(Location::RequiresRegister());
1811 locations->AddTemp(Location::RequiresRegister());
1812 locations->AddTemp(Location::RequiresRegister());
1813}
1814
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001815void CodeGenerator::EmitJitRoots(uint8_t* code,
Vladimir Markoac3ac682018-09-20 11:01:43 +01001816 const uint8_t* roots_data,
1817 /*out*/std::vector<Handle<mirror::Object>>* roots) {
Vladimir Marko174b2e22017-10-12 13:34:49 +01001818 code_generation_data_->EmitJitRoots(roots);
Nicolas Geoffray132d8362016-11-16 09:19:42 +00001819 EmitJitRootPatches(code, roots_data);
1820}
1821
Vladimir Markob5461632018-10-15 14:24:21 +01001822QuickEntrypointEnum CodeGenerator::GetArrayAllocationEntrypoint(HNewArray* new_array) {
1823 switch (new_array->GetComponentSizeShift()) {
1824 case 0: return kQuickAllocArrayResolved8;
1825 case 1: return kQuickAllocArrayResolved16;
1826 case 2: return kQuickAllocArrayResolved32;
1827 case 3: return kQuickAllocArrayResolved64;
Nicolas Geoffrayb048cb72017-01-23 22:50:24 +00001828 }
1829 LOG(FATAL) << "Unreachable";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001830 UNREACHABLE();
Nicolas Geoffrayb048cb72017-01-23 22:50:24 +00001831}
1832
Ulya Trafimovichc8451cb2021-06-02 17:35:16 +01001833ScaleFactor CodeGenerator::ScaleFactorForType(DataType::Type type) {
1834 switch (type) {
1835 case DataType::Type::kBool:
1836 case DataType::Type::kUint8:
1837 case DataType::Type::kInt8:
1838 return TIMES_1;
1839 case DataType::Type::kUint16:
1840 case DataType::Type::kInt16:
1841 return TIMES_2;
1842 case DataType::Type::kInt32:
1843 case DataType::Type::kUint32:
1844 case DataType::Type::kFloat32:
1845 case DataType::Type::kReference:
1846 return TIMES_4;
1847 case DataType::Type::kInt64:
1848 case DataType::Type::kUint64:
1849 case DataType::Type::kFloat64:
1850 return TIMES_8;
1851 case DataType::Type::kVoid:
1852 LOG(FATAL) << "Unreachable type " << type;
1853 UNREACHABLE();
1854 }
1855}
1856
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +00001857} // namespace art