1 /*
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 #ifndef ART_COMPILER_OPTIMIZING_OPTIMIZING_UNIT_TEST_H_
18 #define ART_COMPILER_OPTIMIZING_OPTIMIZING_UNIT_TEST_H_
19 
20 #include <memory>
21 #include <vector>
22 
23 #include "base/malloc_arena_pool.h"
24 #include "base/scoped_arena_allocator.h"
25 #include "builder.h"
26 #include "common_compiler_test.h"
27 #include "dex/code_item_accessors-inl.h"
28 #include "dex/dex_file.h"
29 #include "dex/dex_instruction.h"
30 #include "dex/standard_dex_file.h"
31 #include "driver/dex_compilation_unit.h"
32 #include "graph_checker.h"
33 #include "handle_scope-inl.h"
34 #include "mirror/class_loader.h"
35 #include "mirror/dex_cache.h"
36 #include "nodes.h"
37 #include "scoped_thread_state_change.h"
38 #include "ssa_builder.h"
39 #include "ssa_liveness_analysis.h"
40 
41 #include "gtest/gtest.h"
42 
43 namespace art {
44 
45 #define NUM_INSTRUCTIONS(...)  \
46   (sizeof((uint16_t[]) {__VA_ARGS__}) /sizeof(uint16_t))
47 
48 #define N_REGISTERS_CODE_ITEM(NUM_REGS, ...)                            \
49     { NUM_REGS, 0, 0, 0, 0, 0, NUM_INSTRUCTIONS(__VA_ARGS__), 0, __VA_ARGS__ }
50 
51 #define ZERO_REGISTER_CODE_ITEM(...)   N_REGISTERS_CODE_ITEM(0, __VA_ARGS__)
52 #define ONE_REGISTER_CODE_ITEM(...)    N_REGISTERS_CODE_ITEM(1, __VA_ARGS__)
53 #define TWO_REGISTERS_CODE_ITEM(...)   N_REGISTERS_CODE_ITEM(2, __VA_ARGS__)
54 #define THREE_REGISTERS_CODE_ITEM(...) N_REGISTERS_CODE_ITEM(3, __VA_ARGS__)
55 #define FOUR_REGISTERS_CODE_ITEM(...)  N_REGISTERS_CODE_ITEM(4, __VA_ARGS__)
56 #define FIVE_REGISTERS_CODE_ITEM(...)  N_REGISTERS_CODE_ITEM(5, __VA_ARGS__)
57 #define SIX_REGISTERS_CODE_ITEM(...)   N_REGISTERS_CODE_ITEM(6, __VA_ARGS__)
58 
59 inline LiveInterval* BuildInterval(const size_t ranges[][2],
60                                    size_t number_of_ranges,
61                                    ScopedArenaAllocator* allocator,
62                                    int reg = -1,
63                                    HInstruction* defined_by = nullptr) {
64   LiveInterval* interval =
65       LiveInterval::MakeInterval(allocator, DataType::Type::kInt32, defined_by);
66   if (defined_by != nullptr) {
67     defined_by->SetLiveInterval(interval);
68   }
69   for (size_t i = number_of_ranges; i > 0; --i) {
70     interval->AddRange(ranges[i - 1][0], ranges[i - 1][1]);
71   }
72   interval->SetRegister(reg);
73   return interval;
74 }
75 
RemoveSuspendChecks(HGraph * graph)76 inline void RemoveSuspendChecks(HGraph* graph) {
77   for (HBasicBlock* block : graph->GetBlocks()) {
78     if (block != nullptr) {
79       if (block->GetLoopInformation() != nullptr) {
80         block->GetLoopInformation()->SetSuspendCheck(nullptr);
81       }
82       for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
83         HInstruction* current = it.Current();
84         if (current->IsSuspendCheck()) {
85           current->GetBlock()->RemoveInstruction(current);
86         }
87       }
88     }
89   }
90 }
91 
92 class ArenaPoolAndAllocator {
93  public:
ArenaPoolAndAllocator()94   ArenaPoolAndAllocator()
95       : pool_(), allocator_(&pool_), arena_stack_(&pool_), scoped_allocator_(&arena_stack_) { }
96 
GetAllocator()97   ArenaAllocator* GetAllocator() { return &allocator_; }
GetArenaStack()98   ArenaStack* GetArenaStack() { return &arena_stack_; }
GetScopedAllocator()99   ScopedArenaAllocator* GetScopedAllocator() { return &scoped_allocator_; }
100 
101  private:
102   MallocArenaPool pool_;
103   ArenaAllocator allocator_;
104   ArenaStack arena_stack_;
105   ScopedArenaAllocator scoped_allocator_;
106 };
107 
108 // Have a separate helper so the OptimizingCFITest can inherit it without causing
109 // multiple inheritance errors from having two gtest as a parent twice.
110 class OptimizingUnitTestHelper {
111  public:
OptimizingUnitTestHelper()112   OptimizingUnitTestHelper()
113       : pool_and_allocator_(new ArenaPoolAndAllocator()),
114         graph_(nullptr),
115         entry_block_(nullptr),
116         return_block_(nullptr),
117         exit_block_(nullptr) { }
118 
GetAllocator()119   ArenaAllocator* GetAllocator() { return pool_and_allocator_->GetAllocator(); }
GetArenaStack()120   ArenaStack* GetArenaStack() { return pool_and_allocator_->GetArenaStack(); }
GetScopedAllocator()121   ScopedArenaAllocator* GetScopedAllocator() { return pool_and_allocator_->GetScopedAllocator(); }
122 
ResetPoolAndAllocator()123   void ResetPoolAndAllocator() {
124     pool_and_allocator_.reset(new ArenaPoolAndAllocator());
125   }
126 
127   HGraph* CreateGraph(VariableSizedHandleScope* handles = nullptr) {
128     ArenaAllocator* const allocator = pool_and_allocator_->GetAllocator();
129 
130     // Reserve a big array of 0s so the dex file constructor can offsets from the header.
131     static constexpr size_t kDexDataSize = 4 * KB;
132     const uint8_t* dex_data = reinterpret_cast<uint8_t*>(allocator->Alloc(kDexDataSize));
133 
134     // Create the dex file based on the fake data. Call the constructor so that we can use virtual
135     // functions. Don't use the arena for the StandardDexFile otherwise the dex location leaks.
136     dex_files_.emplace_back(new StandardDexFile(
137         dex_data,
138         sizeof(StandardDexFile::Header),
139         "no_location",
140         /*location_checksum*/ 0,
141         /*oat_dex_file*/ nullptr,
142         /*container*/ nullptr));
143 
144     graph_ = new (allocator) HGraph(
145         allocator,
146         pool_and_allocator_->GetArenaStack(),
147         handles,
148         *dex_files_.back(),
149         /*method_idx*/-1,
150         kRuntimeISA);
151     return graph_;
152   }
153 
154   // Create a control-flow graph from Dex instructions.
155   HGraph* CreateCFG(const std::vector<uint16_t>& data,
156                     DataType::Type return_type = DataType::Type::kInt32,
157                     VariableSizedHandleScope* handles = nullptr) {
158     HGraph* graph = CreateGraph(handles);
159 
160     // The code item data might not aligned to 4 bytes, copy it to ensure that.
161     const size_t code_item_size = data.size() * sizeof(data.front());
162     void* aligned_data = GetAllocator()->Alloc(code_item_size);
163     memcpy(aligned_data, &data[0], code_item_size);
164     CHECK_ALIGNED(aligned_data, StandardDexFile::CodeItem::kAlignment);
165     const dex::CodeItem* code_item = reinterpret_cast<const dex::CodeItem*>(aligned_data);
166 
167     {
168       const DexCompilationUnit* dex_compilation_unit =
169           new (graph->GetAllocator()) DexCompilationUnit(
170               /* class_loader= */ Handle<mirror::ClassLoader>(),  // Invalid handle.
171               /* class_linker= */ nullptr,
172               graph->GetDexFile(),
173               code_item,
174               /* class_def_index= */ DexFile::kDexNoIndex16,
175               /* method_idx= */ dex::kDexNoIndex,
176               /* access_flags= */ 0u,
177               /* verified_method= */ nullptr,
178               /* dex_cache= */ Handle<mirror::DexCache>());  // Invalid handle.
179       CodeItemDebugInfoAccessor accessor(graph->GetDexFile(), code_item, /*dex_method_idx*/ 0u);
180       HGraphBuilder builder(graph, dex_compilation_unit, accessor, return_type);
181       bool graph_built = (builder.BuildGraph() == kAnalysisSuccess);
182       return graph_built ? graph : nullptr;
183     }
184   }
185 
InitGraph()186   void InitGraph() {
187     CreateGraph();
188     entry_block_ = AddNewBlock();
189     return_block_ = AddNewBlock();
190     exit_block_ = AddNewBlock();
191 
192     graph_->SetEntryBlock(entry_block_);
193     graph_->SetExitBlock(exit_block_);
194 
195     entry_block_->AddSuccessor(return_block_);
196     return_block_->AddSuccessor(exit_block_);
197 
198     return_block_->AddInstruction(new (GetAllocator()) HReturnVoid());
199     exit_block_->AddInstruction(new (GetAllocator()) HExit());
200   }
201 
AddParameter(HInstruction * parameter)202   void AddParameter(HInstruction* parameter) {
203     entry_block_->AddInstruction(parameter);
204     parameters_.push_back(parameter);
205   }
206 
AddNewBlock()207   HBasicBlock* AddNewBlock() {
208     HBasicBlock* block = new (GetAllocator()) HBasicBlock(graph_);
209     graph_->AddBlock(block);
210     return block;
211   }
212 
213   // Run GraphChecker with all checks.
214   //
215   // Return: the status whether the run is successful.
CheckGraph(HGraph * graph)216   bool CheckGraph(HGraph* graph) {
217     return CheckGraph(graph, /*check_ref_type_info=*/true);
218   }
219 
CheckGraph()220   bool CheckGraph() {
221     return CheckGraph(graph_);
222   }
223 
224   // Run GraphChecker with all checks except reference type information checks.
225   //
226   // Return: the status whether the run is successful.
CheckGraphSkipRefTypeInfoChecks(HGraph * graph)227   bool CheckGraphSkipRefTypeInfoChecks(HGraph* graph) {
228     return CheckGraph(graph, /*check_ref_type_info=*/false);
229   }
230 
CheckGraphSkipRefTypeInfoChecks()231   bool CheckGraphSkipRefTypeInfoChecks() {
232     return CheckGraphSkipRefTypeInfoChecks(graph_);
233   }
234 
ManuallyBuildEnvFor(HInstruction * instruction,ArenaVector<HInstruction * > * current_locals)235   HEnvironment* ManuallyBuildEnvFor(HInstruction* instruction,
236                                     ArenaVector<HInstruction*>* current_locals) {
237     HEnvironment* environment = new (GetAllocator()) HEnvironment(
238         (GetAllocator()),
239         current_locals->size(),
240         graph_->GetArtMethod(),
241         instruction->GetDexPc(),
242         instruction);
243 
244     environment->CopyFrom(ArrayRef<HInstruction* const>(*current_locals));
245     instruction->SetRawEnvironment(environment);
246     return environment;
247   }
248 
249  protected:
CheckGraph(HGraph * graph,bool check_ref_type_info)250   bool CheckGraph(HGraph* graph, bool check_ref_type_info) {
251     GraphChecker checker(graph);
252     checker.SetRefTypeInfoCheckEnabled(check_ref_type_info);
253     checker.Run();
254     checker.Dump(std::cerr);
255     return checker.IsValid();
256   }
257 
258   std::vector<std::unique_ptr<const StandardDexFile>> dex_files_;
259   std::unique_ptr<ArenaPoolAndAllocator> pool_and_allocator_;
260 
261   HGraph* graph_;
262   HBasicBlock* entry_block_;
263   HBasicBlock* return_block_;
264   HBasicBlock* exit_block_;
265 
266   std::vector<HInstruction*> parameters_;
267 };
268 
269 class OptimizingUnitTest : public CommonArtTest, public OptimizingUnitTestHelper {};
270 
271 // Naive string diff data type.
272 typedef std::list<std::pair<std::string, std::string>> diff_t;
273 
274 // An alias for the empty string used to make it clear that a line is
275 // removed in a diff.
276 static const std::string removed = "";  // NOLINT [runtime/string] [4]
277 
278 // Naive patch command: apply a diff to a string.
Patch(const std::string & original,const diff_t & diff)279 inline std::string Patch(const std::string& original, const diff_t& diff) {
280   std::string result = original;
281   for (const auto& p : diff) {
282     std::string::size_type pos = result.find(p.first);
283     DCHECK_NE(pos, std::string::npos)
284         << "Could not find: \"" << p.first << "\" in \"" << result << "\"";
285     result.replace(pos, p.first.size(), p.second);
286   }
287   return result;
288 }
289 
290 // Returns if the instruction is removed from the graph.
IsRemoved(HInstruction * instruction)291 inline bool IsRemoved(HInstruction* instruction) {
292   return instruction->GetBlock() == nullptr;
293 }
294 
295 }  // namespace art
296 
297 #endif  // ART_COMPILER_OPTIMIZING_OPTIMIZING_UNIT_TEST_H_
298