loop_descriptor.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. // Copyright (c) 2017 Google Inc.
  2. //
  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. #include "source/opt/loop_descriptor.h"
  15. #include <algorithm>
  16. #include <iostream>
  17. #include <limits>
  18. #include <stack>
  19. #include <type_traits>
  20. #include <utility>
  21. #include <vector>
  22. #include "source/opt/cfg.h"
  23. #include "source/opt/constants.h"
  24. #include "source/opt/dominator_tree.h"
  25. #include "source/opt/ir_builder.h"
  26. #include "source/opt/ir_context.h"
  27. #include "source/opt/iterator.h"
  28. #include "source/opt/tree_iterator.h"
  29. #include "source/util/make_unique.h"
  30. namespace spvtools {
  31. namespace opt {
  32. // Takes in a phi instruction |induction| and the loop |header| and returns the
  33. // step operation of the loop.
  34. Instruction* Loop::GetInductionStepOperation(
  35. const Instruction* induction) const {
  36. // Induction must be a phi instruction.
  37. assert(induction->opcode() == SpvOpPhi);
  38. Instruction* step = nullptr;
  39. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  40. // Traverse the incoming operands of the phi instruction.
  41. for (uint32_t operand_id = 1; operand_id < induction->NumInOperands();
  42. operand_id += 2) {
  43. // Incoming edge.
  44. BasicBlock* incoming_block =
  45. context_->cfg()->block(induction->GetSingleWordInOperand(operand_id));
  46. // Check if the block is dominated by header, and thus coming from within
  47. // the loop.
  48. if (IsInsideLoop(incoming_block)) {
  49. step = def_use_manager->GetDef(
  50. induction->GetSingleWordInOperand(operand_id - 1));
  51. break;
  52. }
  53. }
  54. if (!step || !IsSupportedStepOp(step->opcode())) {
  55. return nullptr;
  56. }
  57. // The induction variable which binds the loop must only be modified once.
  58. uint32_t lhs = step->GetSingleWordInOperand(0);
  59. uint32_t rhs = step->GetSingleWordInOperand(1);
  60. // One of the left hand side or right hand side of the step instruction must
  61. // be the induction phi and the other must be an OpConstant.
  62. if (lhs != induction->result_id() && rhs != induction->result_id()) {
  63. return nullptr;
  64. }
  65. if (def_use_manager->GetDef(lhs)->opcode() != SpvOp::SpvOpConstant &&
  66. def_use_manager->GetDef(rhs)->opcode() != SpvOp::SpvOpConstant) {
  67. return nullptr;
  68. }
  69. return step;
  70. }
  71. // Returns true if the |step| operation is an induction variable step operation
  72. // which is currently handled.
  73. bool Loop::IsSupportedStepOp(SpvOp step) const {
  74. switch (step) {
  75. case SpvOp::SpvOpISub:
  76. case SpvOp::SpvOpIAdd:
  77. return true;
  78. default:
  79. return false;
  80. }
  81. }
  82. bool Loop::IsSupportedCondition(SpvOp condition) const {
  83. switch (condition) {
  84. // <
  85. case SpvOp::SpvOpULessThan:
  86. case SpvOp::SpvOpSLessThan:
  87. // >
  88. case SpvOp::SpvOpUGreaterThan:
  89. case SpvOp::SpvOpSGreaterThan:
  90. // >=
  91. case SpvOp::SpvOpSGreaterThanEqual:
  92. case SpvOp::SpvOpUGreaterThanEqual:
  93. // <=
  94. case SpvOp::SpvOpSLessThanEqual:
  95. case SpvOp::SpvOpULessThanEqual:
  96. return true;
  97. default:
  98. return false;
  99. }
  100. }
  101. int64_t Loop::GetResidualConditionValue(SpvOp condition, int64_t initial_value,
  102. int64_t step_value,
  103. size_t number_of_iterations,
  104. size_t factor) {
  105. int64_t remainder =
  106. initial_value + (number_of_iterations % factor) * step_value;
  107. // We subtract or add one as the above formula calculates the remainder if the
  108. // loop where just less than or greater than. Adding or subtracting one should
  109. // give a functionally equivalent value.
  110. switch (condition) {
  111. case SpvOp::SpvOpSGreaterThanEqual:
  112. case SpvOp::SpvOpUGreaterThanEqual: {
  113. remainder -= 1;
  114. break;
  115. }
  116. case SpvOp::SpvOpSLessThanEqual:
  117. case SpvOp::SpvOpULessThanEqual: {
  118. remainder += 1;
  119. break;
  120. }
  121. default:
  122. break;
  123. }
  124. return remainder;
  125. }
  126. Instruction* Loop::GetConditionInst() const {
  127. BasicBlock* condition_block = FindConditionBlock();
  128. if (!condition_block) {
  129. return nullptr;
  130. }
  131. Instruction* branch_conditional = &*condition_block->tail();
  132. if (!branch_conditional ||
  133. branch_conditional->opcode() != SpvOpBranchConditional) {
  134. return nullptr;
  135. }
  136. Instruction* condition_inst = context_->get_def_use_mgr()->GetDef(
  137. branch_conditional->GetSingleWordInOperand(0));
  138. if (IsSupportedCondition(condition_inst->opcode())) {
  139. return condition_inst;
  140. }
  141. return nullptr;
  142. }
  143. // Extract the initial value from the |induction| OpPhi instruction and store it
  144. // in |value|. If the function couldn't find the initial value of |induction|
  145. // return false.
  146. bool Loop::GetInductionInitValue(const Instruction* induction,
  147. int64_t* value) const {
  148. Instruction* constant_instruction = nullptr;
  149. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  150. for (uint32_t operand_id = 0; operand_id < induction->NumInOperands();
  151. operand_id += 2) {
  152. BasicBlock* bb = context_->cfg()->block(
  153. induction->GetSingleWordInOperand(operand_id + 1));
  154. if (!IsInsideLoop(bb)) {
  155. constant_instruction = def_use_manager->GetDef(
  156. induction->GetSingleWordInOperand(operand_id));
  157. }
  158. }
  159. if (!constant_instruction) return false;
  160. const analysis::Constant* constant =
  161. context_->get_constant_mgr()->FindDeclaredConstant(
  162. constant_instruction->result_id());
  163. if (!constant) return false;
  164. if (value) {
  165. const analysis::Integer* type =
  166. constant->AsIntConstant()->type()->AsInteger();
  167. if (type->IsSigned()) {
  168. *value = constant->AsIntConstant()->GetS32BitValue();
  169. } else {
  170. *value = constant->AsIntConstant()->GetU32BitValue();
  171. }
  172. }
  173. return true;
  174. }
  175. Loop::Loop(IRContext* context, DominatorAnalysis* dom_analysis,
  176. BasicBlock* header, BasicBlock* continue_target,
  177. BasicBlock* merge_target)
  178. : context_(context),
  179. loop_header_(header),
  180. loop_continue_(continue_target),
  181. loop_merge_(merge_target),
  182. loop_preheader_(nullptr),
  183. parent_(nullptr),
  184. loop_is_marked_for_removal_(false) {
  185. assert(context);
  186. assert(dom_analysis);
  187. loop_preheader_ = FindLoopPreheader(dom_analysis);
  188. loop_latch_ = FindLatchBlock();
  189. }
  190. BasicBlock* Loop::FindLoopPreheader(DominatorAnalysis* dom_analysis) {
  191. CFG* cfg = context_->cfg();
  192. DominatorTree& dom_tree = dom_analysis->GetDomTree();
  193. DominatorTreeNode* header_node = dom_tree.GetTreeNode(loop_header_);
  194. // The loop predecessor.
  195. BasicBlock* loop_pred = nullptr;
  196. auto header_pred = cfg->preds(loop_header_->id());
  197. for (uint32_t p_id : header_pred) {
  198. DominatorTreeNode* node = dom_tree.GetTreeNode(p_id);
  199. if (node && !dom_tree.Dominates(header_node, node)) {
  200. // The predecessor is not part of the loop, so potential loop preheader.
  201. if (loop_pred && node->bb_ != loop_pred) {
  202. // If we saw 2 distinct predecessors that are outside the loop, we don't
  203. // have a loop preheader.
  204. return nullptr;
  205. }
  206. loop_pred = node->bb_;
  207. }
  208. }
  209. // Safe guard against invalid code, SPIR-V spec forbids loop with the entry
  210. // node as header.
  211. assert(loop_pred && "The header node is the entry block ?");
  212. // So we have a unique basic block that can enter this loop.
  213. // If this loop is the unique successor of this block, then it is a loop
  214. // preheader.
  215. bool is_preheader = true;
  216. uint32_t loop_header_id = loop_header_->id();
  217. const auto* const_loop_pred = loop_pred;
  218. const_loop_pred->ForEachSuccessorLabel(
  219. [&is_preheader, loop_header_id](const uint32_t id) {
  220. if (id != loop_header_id) is_preheader = false;
  221. });
  222. if (is_preheader) return loop_pred;
  223. return nullptr;
  224. }
  225. bool Loop::IsInsideLoop(Instruction* inst) const {
  226. const BasicBlock* parent_block = context_->get_instr_block(inst);
  227. if (!parent_block) return false;
  228. return IsInsideLoop(parent_block);
  229. }
  230. bool Loop::IsBasicBlockInLoopSlow(const BasicBlock* bb) {
  231. assert(bb->GetParent() && "The basic block does not belong to a function");
  232. DominatorAnalysis* dom_analysis =
  233. context_->GetDominatorAnalysis(bb->GetParent());
  234. if (dom_analysis->IsReachable(bb) &&
  235. !dom_analysis->Dominates(GetHeaderBlock(), bb))
  236. return false;
  237. return true;
  238. }
  239. BasicBlock* Loop::GetOrCreatePreHeaderBlock() {
  240. if (loop_preheader_) return loop_preheader_;
  241. CFG* cfg = context_->cfg();
  242. loop_header_ = cfg->SplitLoopHeader(loop_header_);
  243. return loop_preheader_;
  244. }
  245. void Loop::SetContinueBlock(BasicBlock* continue_block) {
  246. assert(IsInsideLoop(continue_block));
  247. loop_continue_ = continue_block;
  248. }
  249. void Loop::SetLatchBlock(BasicBlock* latch) {
  250. #ifndef NDEBUG
  251. assert(latch->GetParent() && "The basic block does not belong to a function");
  252. const auto* const_latch = latch;
  253. const_latch->ForEachSuccessorLabel([this](uint32_t id) {
  254. assert((!IsInsideLoop(id) || id == GetHeaderBlock()->id()) &&
  255. "A predecessor of the continue block does not belong to the loop");
  256. });
  257. #endif // NDEBUG
  258. assert(IsInsideLoop(latch) && "The continue block is not in the loop");
  259. SetLatchBlockImpl(latch);
  260. }
  261. void Loop::SetMergeBlock(BasicBlock* merge) {
  262. #ifndef NDEBUG
  263. assert(merge->GetParent() && "The basic block does not belong to a function");
  264. #endif // NDEBUG
  265. assert(!IsInsideLoop(merge) && "The merge block is in the loop");
  266. SetMergeBlockImpl(merge);
  267. if (GetHeaderBlock()->GetLoopMergeInst()) {
  268. UpdateLoopMergeInst();
  269. }
  270. }
  271. void Loop::SetPreHeaderBlock(BasicBlock* preheader) {
  272. if (preheader) {
  273. assert(!IsInsideLoop(preheader) && "The preheader block is in the loop");
  274. assert(preheader->tail()->opcode() == SpvOpBranch &&
  275. "The preheader block does not unconditionally branch to the header "
  276. "block");
  277. assert(preheader->tail()->GetSingleWordOperand(0) ==
  278. GetHeaderBlock()->id() &&
  279. "The preheader block does not unconditionally branch to the header "
  280. "block");
  281. }
  282. loop_preheader_ = preheader;
  283. }
  284. BasicBlock* Loop::FindLatchBlock() {
  285. CFG* cfg = context_->cfg();
  286. DominatorAnalysis* dominator_analysis =
  287. context_->GetDominatorAnalysis(loop_header_->GetParent());
  288. // Look at the predecessors of the loop header to find a predecessor block
  289. // which is dominated by the loop continue target. There should only be one
  290. // block which meets this criteria and this is the latch block, as per the
  291. // SPIR-V spec.
  292. for (uint32_t block_id : cfg->preds(loop_header_->id())) {
  293. if (dominator_analysis->Dominates(loop_continue_->id(), block_id)) {
  294. return cfg->block(block_id);
  295. }
  296. }
  297. assert(
  298. false &&
  299. "Every loop should have a latch block dominated by the continue target");
  300. return nullptr;
  301. }
  302. void Loop::GetExitBlocks(std::unordered_set<uint32_t>* exit_blocks) const {
  303. CFG* cfg = context_->cfg();
  304. exit_blocks->clear();
  305. for (uint32_t bb_id : GetBlocks()) {
  306. const BasicBlock* bb = cfg->block(bb_id);
  307. bb->ForEachSuccessorLabel([exit_blocks, this](uint32_t succ) {
  308. if (!IsInsideLoop(succ)) {
  309. exit_blocks->insert(succ);
  310. }
  311. });
  312. }
  313. }
  314. void Loop::GetMergingBlocks(
  315. std::unordered_set<uint32_t>* merging_blocks) const {
  316. assert(GetMergeBlock() && "This loop is not structured");
  317. CFG* cfg = context_->cfg();
  318. merging_blocks->clear();
  319. std::stack<const BasicBlock*> to_visit;
  320. to_visit.push(GetMergeBlock());
  321. while (!to_visit.empty()) {
  322. const BasicBlock* bb = to_visit.top();
  323. to_visit.pop();
  324. merging_blocks->insert(bb->id());
  325. for (uint32_t pred_id : cfg->preds(bb->id())) {
  326. if (!IsInsideLoop(pred_id) && !merging_blocks->count(pred_id)) {
  327. to_visit.push(cfg->block(pred_id));
  328. }
  329. }
  330. }
  331. }
  332. namespace {
  333. static inline bool IsBasicBlockSafeToClone(IRContext* context, BasicBlock* bb) {
  334. for (Instruction& inst : *bb) {
  335. if (!inst.IsBranch() && !context->IsCombinatorInstruction(&inst))
  336. return false;
  337. }
  338. return true;
  339. }
  340. } // namespace
  341. bool Loop::IsSafeToClone() const {
  342. CFG& cfg = *context_->cfg();
  343. for (uint32_t bb_id : GetBlocks()) {
  344. BasicBlock* bb = cfg.block(bb_id);
  345. assert(bb);
  346. if (!IsBasicBlockSafeToClone(context_, bb)) return false;
  347. }
  348. // Look at the merge construct.
  349. if (GetHeaderBlock()->GetLoopMergeInst()) {
  350. std::unordered_set<uint32_t> blocks;
  351. GetMergingBlocks(&blocks);
  352. blocks.erase(GetMergeBlock()->id());
  353. for (uint32_t bb_id : blocks) {
  354. BasicBlock* bb = cfg.block(bb_id);
  355. assert(bb);
  356. if (!IsBasicBlockSafeToClone(context_, bb)) return false;
  357. }
  358. }
  359. return true;
  360. }
  361. bool Loop::IsLCSSA() const {
  362. CFG* cfg = context_->cfg();
  363. analysis::DefUseManager* def_use_mgr = context_->get_def_use_mgr();
  364. std::unordered_set<uint32_t> exit_blocks;
  365. GetExitBlocks(&exit_blocks);
  366. // Declare ir_context so we can capture context_ in the below lambda
  367. IRContext* ir_context = context_;
  368. for (uint32_t bb_id : GetBlocks()) {
  369. for (Instruction& insn : *cfg->block(bb_id)) {
  370. // All uses must be either:
  371. // - In the loop;
  372. // - In an exit block and in a phi instruction.
  373. if (!def_use_mgr->WhileEachUser(
  374. &insn,
  375. [&exit_blocks, ir_context, this](Instruction* use) -> bool {
  376. BasicBlock* parent = ir_context->get_instr_block(use);
  377. assert(parent && "Invalid analysis");
  378. if (IsInsideLoop(parent)) return true;
  379. if (use->opcode() != SpvOpPhi) return false;
  380. return exit_blocks.count(parent->id());
  381. }))
  382. return false;
  383. }
  384. }
  385. return true;
  386. }
  387. bool Loop::ShouldHoistInstruction(IRContext* context, Instruction* inst) {
  388. return AreAllOperandsOutsideLoop(context, inst) &&
  389. inst->IsOpcodeCodeMotionSafe();
  390. }
  391. bool Loop::AreAllOperandsOutsideLoop(IRContext* context, Instruction* inst) {
  392. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  393. bool all_outside_loop = true;
  394. const std::function<void(uint32_t*)> operand_outside_loop =
  395. [this, &def_use_mgr, &all_outside_loop](uint32_t* id) {
  396. if (this->IsInsideLoop(def_use_mgr->GetDef(*id))) {
  397. all_outside_loop = false;
  398. return;
  399. }
  400. };
  401. inst->ForEachInId(operand_outside_loop);
  402. return all_outside_loop;
  403. }
  404. void Loop::ComputeLoopStructuredOrder(
  405. std::vector<BasicBlock*>* ordered_loop_blocks, bool include_pre_header,
  406. bool include_merge) const {
  407. CFG& cfg = *context_->cfg();
  408. // Reserve the memory: all blocks in the loop + extra if needed.
  409. ordered_loop_blocks->reserve(GetBlocks().size() + include_pre_header +
  410. include_merge);
  411. if (include_pre_header && GetPreHeaderBlock())
  412. ordered_loop_blocks->push_back(loop_preheader_);
  413. cfg.ForEachBlockInReversePostOrder(
  414. loop_header_, [ordered_loop_blocks, this](BasicBlock* bb) {
  415. if (IsInsideLoop(bb)) ordered_loop_blocks->push_back(bb);
  416. });
  417. if (include_merge && GetMergeBlock())
  418. ordered_loop_blocks->push_back(loop_merge_);
  419. }
  420. LoopDescriptor::LoopDescriptor(IRContext* context, const Function* f)
  421. : loops_(), dummy_top_loop_(nullptr) {
  422. PopulateList(context, f);
  423. }
  424. LoopDescriptor::~LoopDescriptor() { ClearLoops(); }
  425. void LoopDescriptor::PopulateList(IRContext* context, const Function* f) {
  426. DominatorAnalysis* dom_analysis = context->GetDominatorAnalysis(f);
  427. ClearLoops();
  428. // Post-order traversal of the dominator tree to find all the OpLoopMerge
  429. // instructions.
  430. DominatorTree& dom_tree = dom_analysis->GetDomTree();
  431. for (DominatorTreeNode& node :
  432. make_range(dom_tree.post_begin(), dom_tree.post_end())) {
  433. Instruction* merge_inst = node.bb_->GetLoopMergeInst();
  434. if (merge_inst) {
  435. bool all_backedge_unreachable = true;
  436. for (uint32_t pid : context->cfg()->preds(node.bb_->id())) {
  437. if (dom_analysis->IsReachable(pid) &&
  438. dom_analysis->Dominates(node.bb_->id(), pid)) {
  439. all_backedge_unreachable = false;
  440. break;
  441. }
  442. }
  443. if (all_backedge_unreachable)
  444. continue; // ignore this one, we actually never branch back.
  445. // The id of the merge basic block of this loop.
  446. uint32_t merge_bb_id = merge_inst->GetSingleWordOperand(0);
  447. // The id of the continue basic block of this loop.
  448. uint32_t continue_bb_id = merge_inst->GetSingleWordOperand(1);
  449. // The merge target of this loop.
  450. BasicBlock* merge_bb = context->cfg()->block(merge_bb_id);
  451. // The continue target of this loop.
  452. BasicBlock* continue_bb = context->cfg()->block(continue_bb_id);
  453. // The basic block containing the merge instruction.
  454. BasicBlock* header_bb = context->get_instr_block(merge_inst);
  455. // Add the loop to the list of all the loops in the function.
  456. Loop* current_loop =
  457. new Loop(context, dom_analysis, header_bb, continue_bb, merge_bb);
  458. loops_.push_back(current_loop);
  459. // We have a bottom-up construction, so if this loop has nested-loops,
  460. // they are by construction at the tail of the loop list.
  461. for (auto itr = loops_.rbegin() + 1; itr != loops_.rend(); ++itr) {
  462. Loop* previous_loop = *itr;
  463. // If the loop already has a parent, then it has been processed.
  464. if (previous_loop->HasParent()) continue;
  465. // If the current loop does not dominates the previous loop then it is
  466. // not nested loop.
  467. if (!dom_analysis->Dominates(header_bb,
  468. previous_loop->GetHeaderBlock()))
  469. continue;
  470. // If the current loop merge dominates the previous loop then it is
  471. // not nested loop.
  472. if (dom_analysis->Dominates(merge_bb, previous_loop->GetHeaderBlock()))
  473. continue;
  474. current_loop->AddNestedLoop(previous_loop);
  475. }
  476. DominatorTreeNode* dom_merge_node = dom_tree.GetTreeNode(merge_bb);
  477. for (DominatorTreeNode& loop_node :
  478. make_range(node.df_begin(), node.df_end())) {
  479. // Check if we are in the loop.
  480. if (dom_tree.Dominates(dom_merge_node, &loop_node)) continue;
  481. current_loop->AddBasicBlock(loop_node.bb_);
  482. basic_block_to_loop_.insert(
  483. std::make_pair(loop_node.bb_->id(), current_loop));
  484. }
  485. }
  486. }
  487. for (Loop* loop : loops_) {
  488. if (!loop->HasParent()) dummy_top_loop_.nested_loops_.push_back(loop);
  489. }
  490. }
  491. std::vector<Loop*> LoopDescriptor::GetLoopsInBinaryLayoutOrder() {
  492. std::vector<uint32_t> ids{};
  493. for (size_t i = 0; i < NumLoops(); ++i) {
  494. ids.push_back(GetLoopByIndex(i).GetHeaderBlock()->id());
  495. }
  496. std::vector<Loop*> loops{};
  497. if (!ids.empty()) {
  498. auto function = GetLoopByIndex(0).GetHeaderBlock()->GetParent();
  499. for (const auto& block : *function) {
  500. auto block_id = block.id();
  501. auto element = std::find(std::begin(ids), std::end(ids), block_id);
  502. if (element != std::end(ids)) {
  503. loops.push_back(&GetLoopByIndex(element - std::begin(ids)));
  504. }
  505. }
  506. }
  507. return loops;
  508. }
  509. BasicBlock* Loop::FindConditionBlock() const {
  510. if (!loop_merge_) {
  511. return nullptr;
  512. }
  513. BasicBlock* condition_block = nullptr;
  514. uint32_t in_loop_pred = 0;
  515. for (uint32_t p : context_->cfg()->preds(loop_merge_->id())) {
  516. if (IsInsideLoop(p)) {
  517. if (in_loop_pred) {
  518. // 2 in-loop predecessors.
  519. return nullptr;
  520. }
  521. in_loop_pred = p;
  522. }
  523. }
  524. if (!in_loop_pred) {
  525. // Merge block is unreachable.
  526. return nullptr;
  527. }
  528. BasicBlock* bb = context_->cfg()->block(in_loop_pred);
  529. if (!bb) return nullptr;
  530. const Instruction& branch = *bb->ctail();
  531. // Make sure the branch is a conditional branch.
  532. if (branch.opcode() != SpvOpBranchConditional) return nullptr;
  533. // Make sure one of the two possible branches is to the merge block.
  534. if (branch.GetSingleWordInOperand(1) == loop_merge_->id() ||
  535. branch.GetSingleWordInOperand(2) == loop_merge_->id()) {
  536. condition_block = bb;
  537. }
  538. return condition_block;
  539. }
  540. bool Loop::FindNumberOfIterations(const Instruction* induction,
  541. const Instruction* branch_inst,
  542. size_t* iterations_out,
  543. int64_t* step_value_out,
  544. int64_t* init_value_out) const {
  545. // From the branch instruction find the branch condition.
  546. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  547. // Condition instruction from the OpConditionalBranch.
  548. Instruction* condition =
  549. def_use_manager->GetDef(branch_inst->GetSingleWordOperand(0));
  550. assert(IsSupportedCondition(condition->opcode()));
  551. // Get the constant manager from the ir context.
  552. analysis::ConstantManager* const_manager = context_->get_constant_mgr();
  553. // Find the constant value used by the condition variable. Exit out if it
  554. // isn't a constant int.
  555. const analysis::Constant* upper_bound =
  556. const_manager->FindDeclaredConstant(condition->GetSingleWordOperand(3));
  557. if (!upper_bound) return false;
  558. // Must be integer because of the opcode on the condition.
  559. int64_t condition_value = 0;
  560. const analysis::Integer* type =
  561. upper_bound->AsIntConstant()->type()->AsInteger();
  562. if (type->width() > 32) {
  563. return false;
  564. }
  565. if (type->IsSigned()) {
  566. condition_value = upper_bound->AsIntConstant()->GetS32BitValue();
  567. } else {
  568. condition_value = upper_bound->AsIntConstant()->GetU32BitValue();
  569. }
  570. // Find the instruction which is stepping through the loop.
  571. Instruction* step_inst = GetInductionStepOperation(induction);
  572. if (!step_inst) return false;
  573. // Find the constant value used by the condition variable.
  574. const analysis::Constant* step_constant =
  575. const_manager->FindDeclaredConstant(step_inst->GetSingleWordOperand(3));
  576. if (!step_constant) return false;
  577. // Must be integer because of the opcode on the condition.
  578. int64_t step_value = 0;
  579. const analysis::Integer* step_type =
  580. step_constant->AsIntConstant()->type()->AsInteger();
  581. if (step_type->IsSigned()) {
  582. step_value = step_constant->AsIntConstant()->GetS32BitValue();
  583. } else {
  584. step_value = step_constant->AsIntConstant()->GetU32BitValue();
  585. }
  586. // If this is a subtraction step we should negate the step value.
  587. if (step_inst->opcode() == SpvOp::SpvOpISub) {
  588. step_value = -step_value;
  589. }
  590. // Find the inital value of the loop and make sure it is a constant integer.
  591. int64_t init_value = 0;
  592. if (!GetInductionInitValue(induction, &init_value)) return false;
  593. // If iterations is non null then store the value in that.
  594. int64_t num_itrs = GetIterations(condition->opcode(), condition_value,
  595. init_value, step_value);
  596. // If the loop body will not be reached return false.
  597. if (num_itrs <= 0) {
  598. return false;
  599. }
  600. if (iterations_out) {
  601. assert(static_cast<size_t>(num_itrs) <= std::numeric_limits<size_t>::max());
  602. *iterations_out = static_cast<size_t>(num_itrs);
  603. }
  604. if (step_value_out) {
  605. *step_value_out = step_value;
  606. }
  607. if (init_value_out) {
  608. *init_value_out = init_value;
  609. }
  610. return true;
  611. }
  612. // We retrieve the number of iterations using the following formula, diff /
  613. // |step_value| where diff is calculated differently according to the
  614. // |condition| and uses the |condition_value| and |init_value|. If diff /
  615. // |step_value| is NOT cleanly divisable then we add one to the sum.
  616. int64_t Loop::GetIterations(SpvOp condition, int64_t condition_value,
  617. int64_t init_value, int64_t step_value) const {
  618. int64_t diff = 0;
  619. switch (condition) {
  620. case SpvOp::SpvOpSLessThan:
  621. case SpvOp::SpvOpULessThan: {
  622. // If the condition is not met to begin with the loop will never iterate.
  623. if (!(init_value < condition_value)) return 0;
  624. diff = condition_value - init_value;
  625. // If the operation is a less then operation then the diff and step must
  626. // have the same sign otherwise the induction will never cross the
  627. // condition (either never true or always true).
  628. if ((diff < 0 && step_value > 0) || (diff > 0 && step_value < 0)) {
  629. return 0;
  630. }
  631. break;
  632. }
  633. case SpvOp::SpvOpSGreaterThan:
  634. case SpvOp::SpvOpUGreaterThan: {
  635. // If the condition is not met to begin with the loop will never iterate.
  636. if (!(init_value > condition_value)) return 0;
  637. diff = init_value - condition_value;
  638. // If the operation is a greater than operation then the diff and step
  639. // must have opposite signs. Otherwise the condition will always be true
  640. // or will never be true.
  641. if ((diff < 0 && step_value < 0) || (diff > 0 && step_value > 0)) {
  642. return 0;
  643. }
  644. break;
  645. }
  646. case SpvOp::SpvOpSGreaterThanEqual:
  647. case SpvOp::SpvOpUGreaterThanEqual: {
  648. // If the condition is not met to begin with the loop will never iterate.
  649. if (!(init_value >= condition_value)) return 0;
  650. // We subract one to make it the same as SpvOpGreaterThan as it is
  651. // functionally equivalent.
  652. diff = init_value - (condition_value - 1);
  653. // If the operation is a greater than operation then the diff and step
  654. // must have opposite signs. Otherwise the condition will always be true
  655. // or will never be true.
  656. if ((diff > 0 && step_value > 0) || (diff < 0 && step_value < 0)) {
  657. return 0;
  658. }
  659. break;
  660. }
  661. case SpvOp::SpvOpSLessThanEqual:
  662. case SpvOp::SpvOpULessThanEqual: {
  663. // If the condition is not met to begin with the loop will never iterate.
  664. if (!(init_value <= condition_value)) return 0;
  665. // We add one to make it the same as SpvOpLessThan as it is functionally
  666. // equivalent.
  667. diff = (condition_value + 1) - init_value;
  668. // If the operation is a less than operation then the diff and step must
  669. // have the same sign otherwise the induction will never cross the
  670. // condition (either never true or always true).
  671. if ((diff < 0 && step_value > 0) || (diff > 0 && step_value < 0)) {
  672. return 0;
  673. }
  674. break;
  675. }
  676. default:
  677. assert(false &&
  678. "Could not retrieve number of iterations from the loop condition. "
  679. "Condition is not supported.");
  680. }
  681. // Take the abs of - step values.
  682. step_value = llabs(step_value);
  683. diff = llabs(diff);
  684. int64_t result = diff / step_value;
  685. if (diff % step_value != 0) {
  686. result += 1;
  687. }
  688. return result;
  689. }
  690. // Returns the list of induction variables within the loop.
  691. void Loop::GetInductionVariables(
  692. std::vector<Instruction*>& induction_variables) const {
  693. for (Instruction& inst : *loop_header_) {
  694. if (inst.opcode() == SpvOp::SpvOpPhi) {
  695. induction_variables.push_back(&inst);
  696. }
  697. }
  698. }
  699. Instruction* Loop::FindConditionVariable(
  700. const BasicBlock* condition_block) const {
  701. // Find the branch instruction.
  702. const Instruction& branch_inst = *condition_block->ctail();
  703. Instruction* induction = nullptr;
  704. // Verify that the branch instruction is a conditional branch.
  705. if (branch_inst.opcode() == SpvOp::SpvOpBranchConditional) {
  706. // From the branch instruction find the branch condition.
  707. analysis::DefUseManager* def_use_manager = context_->get_def_use_mgr();
  708. // Find the instruction representing the condition used in the conditional
  709. // branch.
  710. Instruction* condition =
  711. def_use_manager->GetDef(branch_inst.GetSingleWordOperand(0));
  712. // Ensure that the condition is a less than operation.
  713. if (condition && IsSupportedCondition(condition->opcode())) {
  714. // The left hand side operand of the operation.
  715. Instruction* variable_inst =
  716. def_use_manager->GetDef(condition->GetSingleWordOperand(2));
  717. // Make sure the variable instruction used is a phi.
  718. if (!variable_inst || variable_inst->opcode() != SpvOpPhi) return nullptr;
  719. // Make sure the phi instruction only has two incoming blocks. Each
  720. // incoming block will be represented by two in operands in the phi
  721. // instruction, the value and the block which that value came from. We
  722. // assume the cannocalised phi will have two incoming values, one from the
  723. // preheader and one from the continue block.
  724. size_t max_supported_operands = 4;
  725. if (variable_inst->NumInOperands() == max_supported_operands) {
  726. // The operand index of the first incoming block label.
  727. uint32_t operand_label_1 = 1;
  728. // The operand index of the second incoming block label.
  729. uint32_t operand_label_2 = 3;
  730. // Make sure one of them is the preheader.
  731. if (!IsInsideLoop(
  732. variable_inst->GetSingleWordInOperand(operand_label_1)) &&
  733. !IsInsideLoop(
  734. variable_inst->GetSingleWordInOperand(operand_label_2))) {
  735. return nullptr;
  736. }
  737. // And make sure that the other is the latch block.
  738. if (variable_inst->GetSingleWordInOperand(operand_label_1) !=
  739. loop_latch_->id() &&
  740. variable_inst->GetSingleWordInOperand(operand_label_2) !=
  741. loop_latch_->id()) {
  742. return nullptr;
  743. }
  744. } else {
  745. return nullptr;
  746. }
  747. if (!FindNumberOfIterations(variable_inst, &branch_inst, nullptr))
  748. return nullptr;
  749. induction = variable_inst;
  750. }
  751. }
  752. return induction;
  753. }
  754. bool LoopDescriptor::CreatePreHeaderBlocksIfMissing() {
  755. auto modified = false;
  756. for (auto& loop : *this) {
  757. if (!loop.GetPreHeaderBlock()) {
  758. modified = true;
  759. // TODO(1841): Handle failure to create pre-header.
  760. loop.GetOrCreatePreHeaderBlock();
  761. }
  762. }
  763. return modified;
  764. }
  765. // Add and remove loops which have been marked for addition and removal to
  766. // maintain the state of the loop descriptor class.
  767. void LoopDescriptor::PostModificationCleanup() {
  768. LoopContainerType loops_to_remove_;
  769. for (Loop* loop : loops_) {
  770. if (loop->IsMarkedForRemoval()) {
  771. loops_to_remove_.push_back(loop);
  772. if (loop->HasParent()) {
  773. loop->GetParent()->RemoveChildLoop(loop);
  774. }
  775. }
  776. }
  777. for (Loop* loop : loops_to_remove_) {
  778. loops_.erase(std::find(loops_.begin(), loops_.end(), loop));
  779. delete loop;
  780. }
  781. for (auto& pair : loops_to_add_) {
  782. Loop* parent = pair.first;
  783. std::unique_ptr<Loop> loop = std::move(pair.second);
  784. if (parent) {
  785. loop->SetParent(nullptr);
  786. parent->AddNestedLoop(loop.get());
  787. for (uint32_t block_id : loop->GetBlocks()) {
  788. parent->AddBasicBlock(block_id);
  789. }
  790. }
  791. loops_.emplace_back(loop.release());
  792. }
  793. loops_to_add_.clear();
  794. }
  795. void LoopDescriptor::ClearLoops() {
  796. for (Loop* loop : loops_) {
  797. delete loop;
  798. }
  799. loops_.clear();
  800. }
  801. // Adds a new loop nest to the descriptor set.
  802. Loop* LoopDescriptor::AddLoopNest(std::unique_ptr<Loop> new_loop) {
  803. Loop* loop = new_loop.release();
  804. if (!loop->HasParent()) dummy_top_loop_.nested_loops_.push_back(loop);
  805. // Iterate from inner to outer most loop, adding basic block to loop mapping
  806. // as we go.
  807. for (Loop& current_loop :
  808. make_range(iterator::begin(loop), iterator::end(nullptr))) {
  809. loops_.push_back(&current_loop);
  810. for (uint32_t bb_id : current_loop.GetBlocks())
  811. basic_block_to_loop_.insert(std::make_pair(bb_id, &current_loop));
  812. }
  813. return loop;
  814. }
  815. void LoopDescriptor::RemoveLoop(Loop* loop) {
  816. Loop* parent = loop->GetParent() ? loop->GetParent() : &dummy_top_loop_;
  817. parent->nested_loops_.erase(std::find(parent->nested_loops_.begin(),
  818. parent->nested_loops_.end(), loop));
  819. std::for_each(
  820. loop->nested_loops_.begin(), loop->nested_loops_.end(),
  821. [loop](Loop* sub_loop) { sub_loop->SetParent(loop->GetParent()); });
  822. parent->nested_loops_.insert(parent->nested_loops_.end(),
  823. loop->nested_loops_.begin(),
  824. loop->nested_loops_.end());
  825. for (uint32_t bb_id : loop->GetBlocks()) {
  826. Loop* l = FindLoopForBasicBlock(bb_id);
  827. if (l == loop) {
  828. SetBasicBlockToLoop(bb_id, l->GetParent());
  829. } else {
  830. ForgetBasicBlock(bb_id);
  831. }
  832. }
  833. LoopContainerType::iterator it =
  834. std::find(loops_.begin(), loops_.end(), loop);
  835. assert(it != loops_.end());
  836. delete loop;
  837. loops_.erase(it);
  838. }
  839. } // namespace opt
  840. } // namespace spvtools