blob: fca9933872c817e5fa6caf9eac74cc40c0b74489 [file] [log] [blame]
Roland Levillain556c3d12014-09-18 15:25:07 +01001/*
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
Roland Levillain75be2832014-10-17 17:02:00 +010017#include "constant_folding.h"
Roland Levillain556c3d12014-09-18 15:25:07 +010018
19namespace art {
20
Roland Levillain75be2832014-10-17 17:02:00 +010021void HConstantFolding::Run() {
Roland Levillain556c3d12014-09-18 15:25:07 +010022 // Process basic blocks in reverse post-order in the dominator tree,
23 // so that an instruction turned into a constant, used as input of
24 // another instruction, may possibly be used to turn that second
25 // instruction into a constant as well.
26 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
27 HBasicBlock* block = it.Current();
28 // Traverse this block's instructions in (forward) order and
29 // replace the ones that can be statically evaluated by a
30 // compile-time counterpart.
Andreas Gampe277ccbd2014-11-03 21:36:10 -080031 for (HInstructionIterator inst_it(block->GetInstructions());
32 !inst_it.Done(); inst_it.Advance()) {
33 HInstruction* inst = inst_it.Current();
Roland Levillain556c3d12014-09-18 15:25:07 +010034 if (inst->IsBinaryOperation()) {
Roland Levillain9240d6a2014-10-20 16:47:04 +010035 // Constant folding: replace `op(a, b)' with a constant at
36 // compile time if `a' and `b' are both constants.
Roland Levillain556c3d12014-09-18 15:25:07 +010037 HConstant* constant =
Roland Levillain9240d6a2014-10-20 16:47:04 +010038 inst->AsBinaryOperation()->TryStaticEvaluation();
39 if (constant != nullptr) {
40 inst->GetBlock()->ReplaceAndRemoveInstructionWith(inst, constant);
41 }
42 } else if (inst->IsUnaryOperation()) {
43 // Constant folding: replace `op(a)' with a constant at compile
44 // time if `a' is a constant.
45 HConstant* constant =
46 inst->AsUnaryOperation()->TryStaticEvaluation();
Roland Levillain556c3d12014-09-18 15:25:07 +010047 if (constant != nullptr) {
48 inst->GetBlock()->ReplaceAndRemoveInstructionWith(inst, constant);
49 }
50 }
51 }
52 }
53}
54
55} // namespace art