• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ecmascript/compiler/scheduler.h"
17 #include <cmath>
18 #include <stack>
19 #include "ecmascript/compiler/gate_accessor.h"
20 #include "ecmascript/compiler/verifier.h"
21 
22 namespace panda::ecmascript::kungfu {
CalculateDominatorTree(const Circuit * circuit,std::vector<GateRef> & bbGatesList,std::unordered_map<GateRef,size_t> & bbGatesAddrToIdx,std::vector<size_t> & immDom)23 void Scheduler::CalculateDominatorTree(const Circuit *circuit,
24                                        std::vector<GateRef>& bbGatesList,
25                                        std::unordered_map<GateRef, size_t> &bbGatesAddrToIdx,
26                                        std::vector<size_t> &immDom)
27 {
28     GateAccessor acc(const_cast<Circuit*>(circuit));
29     std::unordered_map<GateRef, size_t> dfsTimestamp;
30     std::unordered_map<GateRef, size_t> dfsFatherIdx;
31     circuit->AdvanceTime();
32     {
33         size_t timestamp = 0;
34         std::deque<GateRef> pendingList;
35         auto startGate = acc.GetStateRoot();
36         acc.SetMark(startGate, MarkCode::VISITED);
37         pendingList.push_back(startGate);
38         while (!pendingList.empty()) {
39             auto curGate = pendingList.back();
40             dfsTimestamp[curGate] = timestamp++;
41             pendingList.pop_back();
42             bbGatesList.push_back(curGate);
43             if (acc.GetOpCode(curGate) != OpCode::LOOP_BACK) {
44                 auto uses = acc.Uses(curGate);
45                 for (auto useIt = uses.begin(); useIt != uses.end(); useIt++) {
46                     if (useIt.GetIndex() < acc.GetStateCount(*useIt) &&
47                         acc.IsState(*useIt) && acc.GetMark(*useIt) == MarkCode::NO_MARK) {
48                         acc.SetMark(*useIt, MarkCode::VISITED);
49                         pendingList.push_back(*useIt);
50                         dfsFatherIdx[*useIt] = dfsTimestamp[curGate];
51                     }
52                 }
53             }
54         }
55         for (size_t idx = 0; idx < bbGatesList.size(); idx++) {
56             bbGatesAddrToIdx[bbGatesList[idx]] = idx;
57         }
58     }
59     immDom.resize(bbGatesList.size());
60     std::vector<size_t> semiDom(bbGatesList.size());
61     std::vector<std::vector<size_t> > semiDomTree(bbGatesList.size());
62     {
63         std::vector<size_t> parent(bbGatesList.size());
64         std::iota(parent.begin(), parent.end(), 0);
65         std::vector<size_t> minIdx(bbGatesList.size());
66         std::function<size_t(size_t)> unionFind = [&] (size_t idx) -> size_t {
67             size_t pIdx = parent[idx];
68             if (pIdx == idx) {
69                 return idx;
70             }
71             size_t unionFindSetRoot = unionFind(pIdx);
72             if (semiDom[minIdx[idx]] > semiDom[minIdx[pIdx]]) {
73                 minIdx[idx] = minIdx[pIdx];
74             }
75             return parent[idx] = unionFindSetRoot;
76         };
77         auto merge = [&] (size_t fatherIdx, size_t sonIdx) -> void {
78             size_t parentFatherIdx = unionFind(fatherIdx);
79             size_t parentSonIdx = unionFind(sonIdx);
80             parent[parentSonIdx] = parentFatherIdx;
81         };
82         std::iota(semiDom.begin(), semiDom.end(), 0);
83         semiDom[0] = semiDom.size();
84         for (size_t idx = bbGatesList.size() - 1; idx >= 1; idx--) {
85             std::vector<GateRef> preGates;
86             acc.GetInStates(bbGatesList[idx], preGates);
87             for (const auto &predGate : preGates) {
88                 if (bbGatesAddrToIdx.count(predGate) > 0) {
89                     size_t preGateIdx = bbGatesAddrToIdx[predGate];
90                     if (preGateIdx < idx) {
91                         semiDom[idx] = std::min(semiDom[idx], preGateIdx);
92                     } else {
93                         unionFind(preGateIdx);
94                         semiDom[idx] = std::min(semiDom[idx], semiDom[minIdx[preGateIdx]]);
95                     }
96                 }
97             }
98             for (const auto &succDomIdx : semiDomTree[idx]) {
99                 unionFind(succDomIdx);
100                 if (idx == semiDom[minIdx[succDomIdx]]) {
101                     immDom[succDomIdx] = idx;
102                 } else {
103                     immDom[succDomIdx] = minIdx[succDomIdx];
104                 }
105             }
106             minIdx[idx] = idx;
107             merge(dfsFatherIdx[bbGatesList[idx]], idx);
108             semiDomTree[semiDom[idx]].push_back(idx);
109         }
110         for (size_t idx = 1; idx < bbGatesList.size(); idx++) {
111             if (immDom[idx] != semiDom[idx]) {
112                 immDom[idx] = immDom[immDom[idx]];
113             }
114         }
115         semiDom[0] = 0;
116     }
117 }
118 
Run(const Circuit * circuit,ControlFlowGraph & result,const std::string & methodName,bool enableLog)119 void Scheduler::Run(const Circuit *circuit, ControlFlowGraph &result,
120                     [[maybe_unused]] const std::string& methodName, [[maybe_unused]] bool enableLog)
121 {
122 #ifndef NDEBUG
123     if (!Verifier::Run(circuit, methodName, enableLog)) {
124         UNREACHABLE();
125     }
126 #endif
127     GateAccessor acc(const_cast<Circuit*>(circuit));
128     std::vector<GateRef> bbGatesList;
129     std::unordered_map<GateRef, size_t> bbGatesAddrToIdx;
130     std::vector<size_t> immDom;
131     Scheduler::CalculateDominatorTree(circuit, bbGatesList, bbGatesAddrToIdx, immDom);
132     ASSERT(result.size() == 0);
133     result.resize(bbGatesList.size());
134     for (size_t idx = 0; idx < bbGatesList.size(); idx++) {
135         result[idx].push_back(bbGatesList[idx]);
136     }
137     // assuming CFG is always reducible
138     std::vector<std::vector<size_t>> sonList(result.size());
139     for (size_t idx = 1; idx < immDom.size(); idx++) {
140         sonList[immDom[idx]].push_back(idx);
141     }
142     const size_t sizeLog = std::ceil(std::log2(static_cast<double>(result.size())) + 1);
143     std::vector<size_t> timeIn(result.size());
144     std::vector<size_t> timeOut(result.size());
145     std::vector<std::vector<size_t>> jumpUp;
146     jumpUp.assign(result.size(), std::vector<size_t>(sizeLog + 1));
147     {
148         size_t timestamp = 0;
149         struct DFSState {
150             size_t cur;
151             std::vector<size_t> &succList;
152             size_t idx;
153         };
154         std::stack<DFSState> dfsStack;
155         size_t root = 0;
156         dfsStack.push({root, sonList[root], 0});
157         timeIn[root] = timestamp++;
158         jumpUp[root][0] = root;
159         for (size_t stepSize = 1; stepSize <= sizeLog; stepSize++) {
160             auto jumpUpHalf = jumpUp[root][stepSize - 1];
161             jumpUp[root][stepSize] = jumpUp[jumpUpHalf][stepSize - 1];
162         }
163         while (!dfsStack.empty()) {
164             auto &curState = dfsStack.top();
165             auto &cur = curState.cur;
166             auto &succList = curState.succList;
167             auto &idx = curState.idx;
168             if (idx == succList.size()) {
169                 timeOut[cur] = timestamp++;
170                 dfsStack.pop();
171                 continue;
172             }
173             const auto &succ = succList[idx];
174             dfsStack.push({succ, sonList[succ], 0});
175             timeIn[succ] = timestamp++;
176             jumpUp[succ][0] = cur;
177             for (size_t stepSize = 1; stepSize <= sizeLog; stepSize++) {
178                 auto jumpUpHalf = jumpUp[succ][stepSize - 1];
179                 jumpUp[succ][stepSize] = jumpUp[jumpUpHalf][stepSize - 1];
180             }
181             idx++;
182         }
183     }
184     auto isAncestor = [&](size_t nodeA, size_t nodeB) -> bool {
185         return (timeIn[nodeA] <= timeIn[nodeB]) && (timeOut[nodeA] >= timeOut[nodeB]);
186     };
187     auto lowestCommonAncestor = [&](size_t nodeA, size_t nodeB) -> size_t {
188         if (isAncestor(nodeA, nodeB)) {
189             return nodeA;
190         }
191         if (isAncestor(nodeB, nodeA)) {
192             return nodeB;
193         }
194         for (size_t stepSize = sizeLog + 1; stepSize > 0; stepSize--) {
195             if (!isAncestor(jumpUp[nodeA][stepSize - 1], nodeB)) {
196                 nodeA = jumpUp[nodeA][stepSize - 1];
197             }
198         }
199         return jumpUp[nodeA][0];
200     };
201     {
202         std::vector<GateRef> order;
203         std::unordered_map<GateRef, size_t> lowerBound;
204         Scheduler::CalculateSchedulingLowerBound(circuit, bbGatesAddrToIdx, lowestCommonAncestor, lowerBound, &order);
205         for (const auto &schedulableGate : order) {
206             result[lowerBound.at(schedulableGate)].push_back(schedulableGate);
207         }
208         std::vector<GateRef> argList;
209         acc.GetOuts(acc.GetArgRoot(), argList);
210         std::sort(argList.begin(), argList.end(), [&](const GateRef &lhs, const GateRef &rhs) -> bool {
211             return acc.TryGetValue(lhs) > acc.TryGetValue(rhs);
212         });
213         for (const auto &arg : argList) {
214             result.front().push_back(arg);
215         }
216         for (const auto &bbGate : bbGatesList) {
217             auto uses = acc.Uses(bbGate);
218             for (auto i = uses.begin(); i != uses.end(); i++) {
219                 GateRef succGate = *i;
220                 if (acc.GetMetaData(succGate)->IsFixed()) {
221                     result[bbGatesAddrToIdx.at(acc.GetIn(succGate, 0))].push_back(succGate);
222                 }
223             }
224         }
225     }
226     if (enableLog) {
227         Print(&result, circuit);
228     }
229 }
230 
CalculateSchedulingUpperBound(const Circuit * circuit,const std::unordered_map<GateRef,size_t> & bbGatesAddrToIdx,const std::function<bool (size_t,size_t)> & isAncestor,const std::vector<GateRef> & schedulableGatesList,std::unordered_map<GateRef,size_t> & upperBound)231 bool Scheduler::CalculateSchedulingUpperBound(const Circuit *circuit,
232                                               const std::unordered_map<GateRef, size_t> &bbGatesAddrToIdx,
233                                               const std::function<bool(size_t, size_t)> &isAncestor,
234                                               const std::vector<GateRef> &schedulableGatesList,
235                                               std::unordered_map<GateRef, size_t> &upperBound)
236 {
237     GateAccessor acc(const_cast<Circuit*>(circuit));
238     struct DFSState {
239         GateRef curGate = Circuit::NullGate();
240         std::vector<GateRef> predGates;
241         size_t idx = 0;
242         size_t curUpperBound = 0;
243     };
244     DFSState emptyState = {Circuit::NullGate(), std::vector<GateRef>(0), 0, 0};
245     bool getReturn = false;
246     std::optional<size_t> returnValue = 0;
247     std::stack<DFSState> dfsStack;
248     auto CheckUnschedulable = [&](GateRef gate) -> void {
249         if (upperBound.count(gate) > 0) {
250             returnValue = upperBound[gate];
251             getReturn = true;
252         } else if (acc.GetMetaData(gate)->IsProlog() || acc.GetMetaData(gate)->IsRoot()) {
253             returnValue = 0;
254             getReturn = true;
255         } else if (acc.GetMetaData(gate)->IsFixed()) {
256             returnValue = bbGatesAddrToIdx.at(acc.GetIn(gate, 0));
257             getReturn = true;
258         } else if (acc.GetMetaData(gate)->IsState()) {
259             returnValue = bbGatesAddrToIdx.at(gate);
260             getReturn = true;
261         }
262         // then gate is schedulable
263     };
264     for (const auto &schedulableGate : schedulableGatesList) {
265         if (upperBound.count(schedulableGate) != 0) {
266             continue;
267         }
268         getReturn = false;
269         CheckUnschedulable(schedulableGate);
270         if (getReturn) {
271             continue;
272         }
273         dfsStack.push(emptyState);
274         auto &rootState = dfsStack.top();
275         auto &rootPredGates = rootState.predGates;
276         rootState.curGate = schedulableGate;
277         acc.GetIns(schedulableGate, rootPredGates);
278         while (!dfsStack.empty()) {
279             auto &curState = dfsStack.top();
280             auto &curGate = curState.curGate;
281             const auto &predGates = curState.predGates;
282             auto &idx = curState.idx;
283             auto &curUpperBound = curState.curUpperBound;
284             if (idx == predGates.size()) {
285                 upperBound[curGate] = curUpperBound;
286                 returnValue = curUpperBound;
287                 dfsStack.pop();
288                 getReturn = true;
289                 continue;
290             }
291             if (getReturn) {
292                 if (!returnValue.has_value()) {
293                     break;
294                 }
295                 auto predUpperBound = returnValue.value();
296                 if (!isAncestor(curUpperBound, predUpperBound) && !isAncestor(predUpperBound, curUpperBound)) {
297                     PrintUpperBoundError(circuit, curGate, predUpperBound, curUpperBound);
298                     returnValue = std::nullopt;
299                     break;
300                 }
301                 if (isAncestor(curUpperBound, predUpperBound)) {
302                     curUpperBound = predUpperBound;
303                 }
304                 getReturn = false;
305                 idx++;
306             } else {
307                 const auto &predGate = predGates[idx];
308                 CheckUnschedulable(predGate);
309                 if (getReturn) {
310                     continue;
311                 }
312                 dfsStack.push(emptyState);
313                 auto &newState = dfsStack.top();
314                 auto &newPredGates = newState.predGates;
315                 newState.curGate = predGate;
316                 acc.GetIns(predGate, newPredGates);
317             }
318         }
319         if (!returnValue.has_value()) {
320             return false;
321         }
322     }
323     return true;
324 }
325 
PrintUpperBoundError(const Circuit * circuit,GateRef curGate,GateRef predUpperBound,GateRef curUpperBound)326 void Scheduler::PrintUpperBoundError(const Circuit *circuit, GateRef curGate,
327                                      GateRef predUpperBound, GateRef curUpperBound)
328 {
329     GateAccessor ac(const_cast<Circuit*>(circuit));
330     LOG_COMPILER(ERROR) << "[Verifier][Error] Scheduling upper bound of gate (id="
331                         << ac.GetId(curGate)
332                         << ") does not exist, current-upper-bound = "
333                         << curUpperBound << ", pred-upper-bound = "
334                         << predUpperBound << ", there is no dominator relationship between them.";
335 }
336 
CalculateSchedulingLowerBound(const Circuit * circuit,const std::unordered_map<GateRef,size_t> & bbGatesAddrToIdx,const std::function<size_t (size_t,size_t)> & lowestCommonAncestor,std::unordered_map<GateRef,size_t> & lowerBound,std::vector<GateRef> * order)337 void Scheduler::CalculateSchedulingLowerBound(const Circuit *circuit,
338                                               const std::unordered_map<GateRef, size_t> &bbGatesAddrToIdx,
339                                               const std::function<size_t(size_t, size_t)> &lowestCommonAncestor,
340                                               std::unordered_map<GateRef, size_t> &lowerBound,
341                                               std::vector<GateRef> *order)
342 {
343     GateAccessor acc(const_cast<Circuit*>(circuit));
344     std::unordered_map<GateRef, size_t> useCount;
345     std::vector<GateRef> bbAndFixedGatesList;
346     for (const auto &item : bbGatesAddrToIdx) {
347         bbAndFixedGatesList.push_back(item.first);
348         auto uses = acc.Uses(item.first);
349         for (auto i = uses.begin(); i != uses.end(); i++) {
350             GateRef succGate = *i;
351             if (acc.GetMetaData(succGate)->IsFixed()) {
352                 bbAndFixedGatesList.push_back(succGate);
353             }
354         }
355     }
356     struct DFSVisitState {
357         std::vector<GateRef> prevGates;
358         size_t idx = 0;
359     };
360     DFSVisitState emptyVisitState = {std::vector<GateRef>(0), 0};
361     std::stack<DFSVisitState> dfsVisitStack;
362     for (const auto &gate : bbAndFixedGatesList) {
363         dfsVisitStack.push(emptyVisitState);
364         auto &rootState = dfsVisitStack.top();
365         auto &rootPrevGates = rootState.prevGates;
366         acc.GetIns(gate, rootPrevGates);
367         while (!dfsVisitStack.empty()) {
368             auto &curState = dfsVisitStack.top();
369             auto &prevGates = curState.prevGates;
370             auto &idx = curState.idx;
371             if (idx == prevGates.size()) {
372                 dfsVisitStack.pop();
373                 continue;
374             }
375             const auto &prevGate = prevGates[idx];
376             if (!acc.GetMetaData(prevGate)->IsSchedulable()) {
377                 ++idx;
378                 continue;
379             }
380             useCount[prevGate]++;
381             if (useCount[prevGate] == 1) {
382                 dfsVisitStack.push(emptyVisitState);
383                 auto &newState = dfsVisitStack.top();
384                 auto &newPrevGates = newState.prevGates;
385                 acc.GetIns(prevGate, newPrevGates);
386             }
387             ++idx;
388         }
389     }
390     struct DFSFinishState {
391         GateRef curGate = Circuit::NullGate();
392         std::vector<GateRef> prevGates;
393         size_t idx = 0;
394     };
395     DFSFinishState emptyFinishState = {Circuit::NullGate(), std::vector<GateRef>(0), 0};
396     std::stack<DFSFinishState> dfsFinishStack;
397     for (const auto &gate : bbAndFixedGatesList) {
398         dfsFinishStack.push(emptyFinishState);
399         auto &rootState = dfsFinishStack.top();
400         auto &rootPrevGates = rootState.prevGates;
401         rootState.curGate = gate;
402         acc.GetIns(gate, rootPrevGates);
403         while (!dfsFinishStack.empty()) {
404             auto &curState = dfsFinishStack.top();
405             auto &curGate = curState.curGate;
406             auto &prevGates = curState.prevGates;
407             auto &idx = curState.idx;
408             if (idx == prevGates.size()) {
409                 dfsFinishStack.pop();
410                 continue;
411             }
412             const auto &prevGate = prevGates[idx];
413             if (!acc.GetMetaData(prevGate)->IsSchedulable()) {
414                 ++idx;
415                 continue;
416             }
417             useCount[prevGate]--;
418             size_t curLowerBound;
419             if (acc.GetMetaData(curGate)->IsState()) {  // cur_opcode would not be STATE_ENTRY
420                 curLowerBound = bbGatesAddrToIdx.at(curGate);
421             } else if (acc.GetMetaData(curGate)->IsFixed()) {
422                 ASSERT(idx > 0);
423                 curLowerBound = bbGatesAddrToIdx.at(acc.GetIn(acc.GetIn(curGate, 0), idx - 1));
424             } else {
425                 curLowerBound = lowerBound.at(curGate);
426             }
427             if (lowerBound.count(prevGate) == 0) {
428                 lowerBound[prevGate] = curLowerBound;
429             } else {
430                 lowerBound[prevGate] = lowestCommonAncestor(lowerBound[prevGate], curLowerBound);
431             }
432             if (useCount[prevGate] == 0) {
433                 if (order != nullptr) {
434                     order->push_back(prevGate);
435                 }
436                 dfsFinishStack.push(emptyFinishState);
437                 auto &newState = dfsFinishStack.top();
438                 auto &newPrevGates = newState.prevGates;
439                 newState.curGate = prevGate;
440                 acc.GetIns(prevGate, newPrevGates);
441             }
442             ++idx;
443         }
444     }
445 }
446 
Print(const std::vector<std::vector<GateRef>> * cfg,const Circuit * circuit)447 void Scheduler::Print(const std::vector<std::vector<GateRef>> *cfg, const Circuit *circuit)
448 {
449     GateAccessor acc(const_cast<Circuit*>(circuit));
450     std::vector<GateRef> bbGatesList;
451     std::unordered_map<GateRef, size_t> bbGatesAddrToIdx;
452     std::vector<size_t> immDom;
453     Scheduler::CalculateDominatorTree(circuit, bbGatesList, bbGatesAddrToIdx, immDom);
454     LOG_COMPILER(INFO) << "==================================== Scheduling ==================================";
455     for (size_t bbIdx = 0; bbIdx < cfg->size(); bbIdx++) {
456         auto opcode = acc.GetOpCode((*cfg)[bbIdx].front());
457         LOG_COMPILER(INFO) << "B" << bbIdx << "_" << opcode << ":"
458                            << "  immDom=" << immDom[bbIdx];
459         LOG_COMPILER(INFO) << "  pred=[";
460         bool isFirst = true;
461         GateRef head = cfg->at(bbIdx).front();
462         auto ins = acc.Ins(head);
463         for (auto i = ins.begin(); i != ins.end(); i++) {
464             GateRef predState = *i;
465             if (acc.GetMetaData(predState)->IsState() ||
466                 acc.GetOpCode(predState) == OpCode::STATE_ENTRY) {
467                 LOG_COMPILER(INFO) << (isFirst ? "" : " ") << bbGatesAddrToIdx.at(predState);
468                 isFirst = false;
469             }
470         }
471         LOG_COMPILER(INFO) << "]  succ=[";
472         isFirst = true;
473         GateRef h = cfg->at(bbIdx).front();
474         auto uses = acc.Uses(h);
475         for (auto i = uses.begin(); i != uses.end(); i++) {
476             GateRef succState = *i;
477             if (acc.GetMetaData(succState)->IsState() ||
478                 acc.GetOpCode(succState) == OpCode::STATE_ENTRY) {
479                 LOG_COMPILER(INFO) << (isFirst ? "" : " ") << bbGatesAddrToIdx.at(succState);
480                 isFirst = false;
481             }
482         }
483         LOG_COMPILER(INFO) << "]";
484         for (size_t instIdx = (*cfg)[bbIdx].size(); instIdx > 0; instIdx--) {
485             acc.Print((*cfg)[bbIdx][instIdx - 1]);
486         }
487     }
488     LOG_COMPILER(INFO) << "==================================== Scheduling ==================================";
489 }
490 }  // namespace panda::ecmascript::kungfu
491