loop_descriptor.cpp 33 KB

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