summaryrefslogtreecommitdiff
path: root/compiler/optimizing/builder.cc
blob: da791a7cf777096e5265177e051b3fa819f82d2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "builder.h"

#include "art_field-inl.h"
#include "base/arena_bit_vector.h"
#include "base/bit_vector-inl.h"
#include "base/logging.h"
#include "block_builder.h"
#include "code_generator.h"
#include "data_type-inl.h"
#include "driver/compiler_options.h"
#include "driver/dex_compilation_unit.h"
#include "instruction_builder.h"
#include "mirror/class_loader.h"
#include "mirror/dex_cache.h"
#include "nodes.h"
#include "optimizing_compiler_stats.h"
#include "ssa_builder.h"
#include "thread.h"

namespace art HIDDEN {

HGraphBuilder::HGraphBuilder(HGraph* graph,
                             const CodeItemDebugInfoAccessor& accessor,
                             const DexCompilationUnit* dex_compilation_unit,
                             const DexCompilationUnit* outer_compilation_unit,
                             CodeGenerator* code_generator,
                             OptimizingCompilerStats* compiler_stats)
    : graph_(graph),
      dex_file_(&graph->GetDexFile()),
      code_item_accessor_(accessor),
      dex_compilation_unit_(dex_compilation_unit),
      outer_compilation_unit_(outer_compilation_unit),
      code_generator_(code_generator),
      compilation_stats_(compiler_stats),
      return_type_(DataType::FromShorty(dex_compilation_unit_->GetShorty()[0])) {}

HGraphBuilder::HGraphBuilder(HGraph* graph,
                             const DexCompilationUnit* dex_compilation_unit,
                             const CodeItemDebugInfoAccessor& accessor,
                             DataType::Type return_type)
    : graph_(graph),
      dex_file_(&graph->GetDexFile()),
      code_item_accessor_(accessor),
      dex_compilation_unit_(dex_compilation_unit),
      outer_compilation_unit_(nullptr),
      code_generator_(nullptr),
      compilation_stats_(nullptr),
      return_type_(return_type) {}

bool HGraphBuilder::SkipCompilation(size_t number_of_branches) {
  if (code_generator_ == nullptr) {
    // Note that the codegen is null when unit testing.
    return false;
  }

  const CompilerOptions& compiler_options = code_generator_->GetCompilerOptions();
  CompilerFilter::Filter compiler_filter = compiler_options.GetCompilerFilter();
  if (compiler_filter == CompilerFilter::kEverything) {
    return false;
  }

  const uint32_t code_units = code_item_accessor_.InsnsSizeInCodeUnits();
  if (compiler_options.IsHugeMethod(code_units)) {
    VLOG(compiler) << "Skip compilation of huge method "
                   << dex_file_->PrettyMethod(dex_compilation_unit_->GetDexMethodIndex())
                   << ": " << code_units << " code units";
    MaybeRecordStat(compilation_stats_, MethodCompilationStat::kNotCompiledHugeMethod);
    return true;
  }

  // If it's large and contains no branches, it's likely to be machine generated initialization.
  if (compiler_options.IsLargeMethod(code_units) && (number_of_branches == 0)) {
    VLOG(compiler) << "Skip compilation of large method with no branch "
                   << dex_file_->PrettyMethod(dex_compilation_unit_->GetDexMethodIndex())
                   << ": " << code_units << " code units";
    MaybeRecordStat(compilation_stats_, MethodCompilationStat::kNotCompiledLargeMethodNoBranches);
    return true;
  }

  return false;
}

static bool NeedsExtraGotoBlock(HBasicBlock* block) {
  if (!block->IsSingleTryBoundary()) {
    return false;
  }

  const HTryBoundary* boundary = block->GetLastInstruction()->AsTryBoundary();
  DCHECK(boundary->GetNormalFlowSuccessor()->IsExitBlock());
  DCHECK(!boundary->IsEntry());

  const HInstruction* last_instruction = block->GetSinglePredecessor()->GetLastInstruction();
  DCHECK(last_instruction->IsReturn() ||
         last_instruction->IsReturnVoid() ||
         last_instruction->IsThrow());

  return !last_instruction->IsThrow();
}

bool HGraphBuilder::MaybeAddExtraGotoBlocks() {
  if (graph_->GetExitBlock() == nullptr) {
    return true;
  }

  bool added_block = false;
  for (size_t pred = 0, size = graph_->GetExitBlock()->GetPredecessors().size(); pred < size;
       ++pred) {
    HBasicBlock* predecessor = graph_->GetExitBlock()->GetPredecessors()[pred];
    if (NeedsExtraGotoBlock(predecessor)) {
      added_block = true;
      graph_->SplitEdge(predecessor, graph_->GetExitBlock())
          ->AddInstruction(new (graph_->GetAllocator()) HGoto(predecessor->GetDexPc()));
    }
  }

  // TODO(solanes): Avoid recomputing the full dominator tree by manually updating the relevant
  // information (loop information, dominance, try catch information).
  if (added_block) {
    if (graph_->HasIrreducibleLoops()) {
      // Recomputing loop information in graphs with irreducible loops is unsupported, as it could
      // lead to loop header changes. In this case it is safe to abort since we don't inline graphs
      // with irreducible loops anyway.
      return false;
    }
    graph_->ClearLoopInformation();
    graph_->ClearDominanceInformation();
    graph_->BuildDominatorTree();
  }
  return true;
}

GraphAnalysisResult HGraphBuilder::BuildGraph(bool build_for_inline) {
  DCHECK(code_item_accessor_.HasCodeItem());
  DCHECK(graph_->GetBlocks().empty());

  graph_->SetNumberOfVRegs(code_item_accessor_.RegistersSize());
  graph_->SetNumberOfInVRegs(code_item_accessor_.InsSize());
  graph_->SetMaximumNumberOfOutVRegs(code_item_accessor_.OutsSize());
  graph_->SetHasTryCatch(code_item_accessor_.TriesSize() != 0);

  // Use ScopedArenaAllocator for all local allocations.
  ScopedArenaAllocator local_allocator(graph_->GetArenaStack());
  HBasicBlockBuilder block_builder(graph_, dex_file_, code_item_accessor_, &local_allocator);
  SsaBuilder ssa_builder(graph_,
                         dex_compilation_unit_->GetClassLoader(),
                         dex_compilation_unit_->GetDexCache(),
                         &local_allocator);
  HInstructionBuilder instruction_builder(graph_,
                                          &block_builder,
                                          &ssa_builder,
                                          dex_file_,
                                          code_item_accessor_,
                                          return_type_,
                                          dex_compilation_unit_,
                                          outer_compilation_unit_,
                                          code_generator_,
                                          compilation_stats_,
                                          &local_allocator);

  // 1) Create basic blocks and link them together. Basic blocks are left
  //    unpopulated with the exception of synthetic blocks, e.g. HTryBoundaries.
  if (!block_builder.Build()) {
    return kAnalysisInvalidBytecode;
  }

  // 2) Decide whether to skip this method based on its code size and number
  //    of branches.
  if (SkipCompilation(block_builder.GetNumberOfBranches())) {
    return kAnalysisSkipped;
  }

  // 3) Build the dominator tree and fill in loop and try/catch metadata.
  GraphAnalysisResult result = graph_->BuildDominatorTree();
  if (result != kAnalysisSuccess) {
    return result;
  }

  // 4) Populate basic blocks with instructions.
  if (!instruction_builder.Build()) {
    return kAnalysisInvalidBytecode;
  }

  // 5) When inlining, we want to add a Goto block if we have Return/ReturnVoid->TryBoundary->Exit
  // since we will have Return/ReturnVoid->TryBoundary->`continue to normal execution` once inlined.
  if (build_for_inline) {
    if (!MaybeAddExtraGotoBlocks()) {
      return kAnalysisFailInliningIrreducibleLoop;
    }
  }

  // 6) Type the graph and eliminate dead/redundant phis.
  return ssa_builder.BuildSsa();
}

void HGraphBuilder::BuildIntrinsicGraph(ArtMethod* method) {
  DCHECK(!code_item_accessor_.HasCodeItem());
  DCHECK(graph_->GetBlocks().empty());

  // Determine the number of arguments and associated vregs.
  uint32_t method_idx = dex_compilation_unit_->GetDexMethodIndex();
  const char* shorty = dex_file_->GetMethodShorty(dex_file_->GetMethodId(method_idx));
  size_t num_args = strlen(shorty + 1);
  size_t num_wide_args = std::count(shorty + 1, shorty + 1 + num_args, 'J') +
                         std::count(shorty + 1, shorty + 1 + num_args, 'D');
  size_t num_arg_vregs = num_args + num_wide_args + (dex_compilation_unit_->IsStatic() ? 0u : 1u);

  // For simplicity, reserve 2 vregs (the maximum) for return value regardless of the return type.
  size_t return_vregs = 2u;
  graph_->SetNumberOfVRegs(return_vregs + num_arg_vregs);
  graph_->SetNumberOfInVRegs(num_arg_vregs);
  graph_->SetMaximumNumberOfOutVRegs(num_arg_vregs);
  graph_->SetHasTryCatch(false);

  // Use ScopedArenaAllocator for all local allocations.
  ScopedArenaAllocator local_allocator(graph_->GetArenaStack());
  HBasicBlockBuilder block_builder(graph_,
                                   dex_file_,
                                   CodeItemDebugInfoAccessor(),
                                   &local_allocator);
  SsaBuilder ssa_builder(graph_,
                         dex_compilation_unit_->GetClassLoader(),
                         dex_compilation_unit_->GetDexCache(),
                         &local_allocator);
  HInstructionBuilder instruction_builder(graph_,
                                          &block_builder,
                                          &ssa_builder,
                                          dex_file_,
                                          CodeItemDebugInfoAccessor(),
                                          return_type_,
                                          dex_compilation_unit_,
                                          outer_compilation_unit_,
                                          code_generator_,
                                          compilation_stats_,
                                          &local_allocator);

  // 1) Create basic blocks for the intrinsic and link them together.
  block_builder.BuildIntrinsic();

  // 2) Build the trivial dominator tree.
  GraphAnalysisResult bdt_result = graph_->BuildDominatorTree();
  DCHECK_EQ(bdt_result, kAnalysisSuccess);

  // 3) Populate basic blocks with instructions for the intrinsic.
  instruction_builder.BuildIntrinsic(method);

  // 4) Type the graph (no dead/redundant phis to eliminate).
  GraphAnalysisResult build_ssa_result = ssa_builder.BuildSsa();
  DCHECK_EQ(build_ssa_result, kAnalysisSuccess);
}

}  // namespace art