aggressive_dead_code_elim_pass.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. // Copyright (c) 2017 The Khronos Group Inc.
  2. // Copyright (c) 2017 Valve Corporation
  3. // Copyright (c) 2017 LunarG Inc.
  4. // Copyright (c) 2018 Google LLC
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. #include "source/opt/aggressive_dead_code_elim_pass.h"
  18. #include <memory>
  19. #include <stack>
  20. #include "source/cfa.h"
  21. #include "source/latest_version_glsl_std_450_header.h"
  22. #include "source/opt/iterator.h"
  23. #include "source/opt/reflect.h"
  24. #include "source/spirv_constant.h"
  25. namespace spvtools {
  26. namespace opt {
  27. namespace {
  28. const uint32_t kTypePointerStorageClassInIdx = 0;
  29. const uint32_t kEntryPointFunctionIdInIdx = 1;
  30. const uint32_t kSelectionMergeMergeBlockIdInIdx = 0;
  31. const uint32_t kLoopMergeMergeBlockIdInIdx = 0;
  32. const uint32_t kLoopMergeContinueBlockIdInIdx = 1;
  33. const uint32_t kCopyMemoryTargetAddrInIdx = 0;
  34. const uint32_t kCopyMemorySourceAddrInIdx = 1;
  35. // Sorting functor to present annotation instructions in an easy-to-process
  36. // order. The functor orders by opcode first and falls back on unique id
  37. // ordering if both instructions have the same opcode.
  38. //
  39. // Desired priority:
  40. // SpvOpGroupDecorate
  41. // SpvOpGroupMemberDecorate
  42. // SpvOpDecorate
  43. // SpvOpMemberDecorate
  44. // SpvOpDecorateId
  45. // SpvOpDecorateStringGOOGLE
  46. // SpvOpDecorationGroup
  47. struct DecorationLess {
  48. bool operator()(const Instruction* lhs, const Instruction* rhs) const {
  49. assert(lhs && rhs);
  50. SpvOp lhsOp = lhs->opcode();
  51. SpvOp rhsOp = rhs->opcode();
  52. if (lhsOp != rhsOp) {
  53. #define PRIORITY_CASE(opcode) \
  54. if (lhsOp == opcode && rhsOp != opcode) return true; \
  55. if (rhsOp == opcode && lhsOp != opcode) return false;
  56. // OpGroupDecorate and OpGroupMember decorate are highest priority to
  57. // eliminate dead targets early and simplify subsequent checks.
  58. PRIORITY_CASE(SpvOpGroupDecorate)
  59. PRIORITY_CASE(SpvOpGroupMemberDecorate)
  60. PRIORITY_CASE(SpvOpDecorate)
  61. PRIORITY_CASE(SpvOpMemberDecorate)
  62. PRIORITY_CASE(SpvOpDecorateId)
  63. PRIORITY_CASE(SpvOpDecorateStringGOOGLE)
  64. // OpDecorationGroup is lowest priority to ensure use/def chains remain
  65. // usable for instructions that target this group.
  66. PRIORITY_CASE(SpvOpDecorationGroup)
  67. #undef PRIORITY_CASE
  68. }
  69. // Fall back to maintain total ordering (compare unique ids).
  70. return *lhs < *rhs;
  71. }
  72. };
  73. } // namespace
  74. bool AggressiveDCEPass::IsVarOfStorage(uint32_t varId, uint32_t storageClass) {
  75. if (varId == 0) return false;
  76. const Instruction* varInst = get_def_use_mgr()->GetDef(varId);
  77. const SpvOp op = varInst->opcode();
  78. if (op != SpvOpVariable) return false;
  79. const uint32_t varTypeId = varInst->type_id();
  80. const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
  81. if (varTypeInst->opcode() != SpvOpTypePointer) return false;
  82. return varTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx) ==
  83. storageClass;
  84. }
  85. bool AggressiveDCEPass::IsLocalVar(uint32_t varId) {
  86. if (IsVarOfStorage(varId, SpvStorageClassFunction)) {
  87. return true;
  88. }
  89. if (!private_like_local_) {
  90. return false;
  91. }
  92. return IsVarOfStorage(varId, SpvStorageClassPrivate) ||
  93. IsVarOfStorage(varId, SpvStorageClassWorkgroup);
  94. }
  95. void AggressiveDCEPass::AddStores(uint32_t ptrId) {
  96. get_def_use_mgr()->ForEachUser(ptrId, [this, ptrId](Instruction* user) {
  97. switch (user->opcode()) {
  98. case SpvOpAccessChain:
  99. case SpvOpInBoundsAccessChain:
  100. case SpvOpCopyObject:
  101. this->AddStores(user->result_id());
  102. break;
  103. case SpvOpLoad:
  104. break;
  105. case SpvOpCopyMemory:
  106. case SpvOpCopyMemorySized:
  107. if (user->GetSingleWordInOperand(kCopyMemoryTargetAddrInIdx) == ptrId) {
  108. AddToWorklist(user);
  109. }
  110. break;
  111. // If default, assume it stores e.g. frexp, modf, function call
  112. case SpvOpStore:
  113. default:
  114. AddToWorklist(user);
  115. break;
  116. }
  117. });
  118. }
  119. bool AggressiveDCEPass::AllExtensionsSupported() const {
  120. // If any extension not in whitelist, return false
  121. for (auto& ei : get_module()->extensions()) {
  122. const char* extName =
  123. reinterpret_cast<const char*>(&ei.GetInOperand(0).words[0]);
  124. if (extensions_whitelist_.find(extName) == extensions_whitelist_.end())
  125. return false;
  126. }
  127. return true;
  128. }
  129. bool AggressiveDCEPass::IsDead(Instruction* inst) {
  130. if (IsLive(inst)) return false;
  131. if ((inst->IsBranch() || inst->opcode() == SpvOpUnreachable) &&
  132. !IsStructuredHeader(context()->get_instr_block(inst), nullptr, nullptr,
  133. nullptr))
  134. return false;
  135. return true;
  136. }
  137. bool AggressiveDCEPass::IsTargetDead(Instruction* inst) {
  138. const uint32_t tId = inst->GetSingleWordInOperand(0);
  139. Instruction* tInst = get_def_use_mgr()->GetDef(tId);
  140. if (IsAnnotationInst(tInst->opcode())) {
  141. // This must be a decoration group. We go through annotations in a specific
  142. // order. So if this is not used by any group or group member decorates, it
  143. // is dead.
  144. assert(tInst->opcode() == SpvOpDecorationGroup);
  145. bool dead = true;
  146. get_def_use_mgr()->ForEachUser(tInst, [&dead](Instruction* user) {
  147. if (user->opcode() == SpvOpGroupDecorate ||
  148. user->opcode() == SpvOpGroupMemberDecorate)
  149. dead = false;
  150. });
  151. return dead;
  152. }
  153. return IsDead(tInst);
  154. }
  155. void AggressiveDCEPass::ProcessLoad(uint32_t varId) {
  156. // Only process locals
  157. if (!IsLocalVar(varId)) return;
  158. // Return if already processed
  159. if (live_local_vars_.find(varId) != live_local_vars_.end()) return;
  160. // Mark all stores to varId as live
  161. AddStores(varId);
  162. // Cache varId as processed
  163. live_local_vars_.insert(varId);
  164. }
  165. bool AggressiveDCEPass::IsStructuredHeader(BasicBlock* bp,
  166. Instruction** mergeInst,
  167. Instruction** branchInst,
  168. uint32_t* mergeBlockId) {
  169. if (!bp) return false;
  170. Instruction* mi = bp->GetMergeInst();
  171. if (mi == nullptr) return false;
  172. Instruction* bri = &*bp->tail();
  173. if (branchInst != nullptr) *branchInst = bri;
  174. if (mergeInst != nullptr) *mergeInst = mi;
  175. if (mergeBlockId != nullptr) *mergeBlockId = mi->GetSingleWordInOperand(0);
  176. return true;
  177. }
  178. void AggressiveDCEPass::ComputeBlock2HeaderMaps(
  179. std::list<BasicBlock*>& structuredOrder) {
  180. block2headerBranch_.clear();
  181. header2nextHeaderBranch_.clear();
  182. branch2merge_.clear();
  183. structured_order_index_.clear();
  184. std::stack<Instruction*> currentHeaderBranch;
  185. currentHeaderBranch.push(nullptr);
  186. uint32_t currentMergeBlockId = 0;
  187. uint32_t index = 0;
  188. for (auto bi = structuredOrder.begin(); bi != structuredOrder.end();
  189. ++bi, ++index) {
  190. structured_order_index_[*bi] = index;
  191. // If this block is the merge block of the current control construct,
  192. // we are leaving the current construct so we must update state
  193. if ((*bi)->id() == currentMergeBlockId) {
  194. currentHeaderBranch.pop();
  195. Instruction* chb = currentHeaderBranch.top();
  196. if (chb != nullptr)
  197. currentMergeBlockId = branch2merge_[chb]->GetSingleWordInOperand(0);
  198. }
  199. Instruction* mergeInst;
  200. Instruction* branchInst;
  201. uint32_t mergeBlockId;
  202. bool is_header =
  203. IsStructuredHeader(*bi, &mergeInst, &branchInst, &mergeBlockId);
  204. // Map header block to next enclosing header.
  205. if (is_header) header2nextHeaderBranch_[*bi] = currentHeaderBranch.top();
  206. // If this is a loop header, update state first so the block will map to
  207. // itself.
  208. if (is_header && mergeInst->opcode() == SpvOpLoopMerge) {
  209. currentHeaderBranch.push(branchInst);
  210. branch2merge_[branchInst] = mergeInst;
  211. currentMergeBlockId = mergeBlockId;
  212. }
  213. // Map the block to the current construct.
  214. block2headerBranch_[*bi] = currentHeaderBranch.top();
  215. // If this is an if header, update state so following blocks map to the if.
  216. if (is_header && mergeInst->opcode() == SpvOpSelectionMerge) {
  217. currentHeaderBranch.push(branchInst);
  218. branch2merge_[branchInst] = mergeInst;
  219. currentMergeBlockId = mergeBlockId;
  220. }
  221. }
  222. }
  223. void AggressiveDCEPass::AddBranch(uint32_t labelId, BasicBlock* bp) {
  224. std::unique_ptr<Instruction> newBranch(
  225. new Instruction(context(), SpvOpBranch, 0, 0,
  226. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {labelId}}}));
  227. context()->AnalyzeDefUse(&*newBranch);
  228. context()->set_instr_block(&*newBranch, bp);
  229. bp->AddInstruction(std::move(newBranch));
  230. }
  231. void AggressiveDCEPass::AddBreaksAndContinuesToWorklist(
  232. Instruction* mergeInst) {
  233. assert(mergeInst->opcode() == SpvOpSelectionMerge ||
  234. mergeInst->opcode() == SpvOpLoopMerge);
  235. BasicBlock* header = context()->get_instr_block(mergeInst);
  236. uint32_t headerIndex = structured_order_index_[header];
  237. const uint32_t mergeId = mergeInst->GetSingleWordInOperand(0);
  238. BasicBlock* merge = context()->get_instr_block(mergeId);
  239. uint32_t mergeIndex = structured_order_index_[merge];
  240. get_def_use_mgr()->ForEachUser(
  241. mergeId, [headerIndex, mergeIndex, this](Instruction* user) {
  242. if (!user->IsBranch()) return;
  243. BasicBlock* block = context()->get_instr_block(user);
  244. uint32_t index = structured_order_index_[block];
  245. if (headerIndex < index && index < mergeIndex) {
  246. // This is a break from the loop.
  247. AddToWorklist(user);
  248. // Add branch's merge if there is one.
  249. Instruction* userMerge = branch2merge_[user];
  250. if (userMerge != nullptr) AddToWorklist(userMerge);
  251. }
  252. });
  253. if (mergeInst->opcode() != SpvOpLoopMerge) {
  254. return;
  255. }
  256. // For loops we need to find the continues as well.
  257. const uint32_t contId =
  258. mergeInst->GetSingleWordInOperand(kLoopMergeContinueBlockIdInIdx);
  259. get_def_use_mgr()->ForEachUser(contId, [&contId, this](Instruction* user) {
  260. SpvOp op = user->opcode();
  261. if (op == SpvOpBranchConditional || op == SpvOpSwitch) {
  262. // A conditional branch or switch can only be a continue if it does not
  263. // have a merge instruction or its merge block is not the continue block.
  264. Instruction* hdrMerge = branch2merge_[user];
  265. if (hdrMerge != nullptr && hdrMerge->opcode() == SpvOpSelectionMerge) {
  266. uint32_t hdrMergeId =
  267. hdrMerge->GetSingleWordInOperand(kSelectionMergeMergeBlockIdInIdx);
  268. if (hdrMergeId == contId) return;
  269. // Need to mark merge instruction too
  270. AddToWorklist(hdrMerge);
  271. }
  272. } else if (op == SpvOpBranch) {
  273. // An unconditional branch can only be a continue if it is not
  274. // branching to its own merge block.
  275. BasicBlock* blk = context()->get_instr_block(user);
  276. Instruction* hdrBranch = block2headerBranch_[blk];
  277. if (hdrBranch == nullptr) return;
  278. Instruction* hdrMerge = branch2merge_[hdrBranch];
  279. if (hdrMerge->opcode() == SpvOpLoopMerge) return;
  280. uint32_t hdrMergeId =
  281. hdrMerge->GetSingleWordInOperand(kSelectionMergeMergeBlockIdInIdx);
  282. if (contId == hdrMergeId) return;
  283. } else {
  284. return;
  285. }
  286. AddToWorklist(user);
  287. });
  288. }
  289. bool AggressiveDCEPass::AggressiveDCE(Function* func) {
  290. // Mark function parameters as live.
  291. AddToWorklist(&func->DefInst());
  292. func->ForEachParam(
  293. [this](const Instruction* param) {
  294. AddToWorklist(const_cast<Instruction*>(param));
  295. },
  296. false);
  297. // Compute map from block to controlling conditional branch
  298. std::list<BasicBlock*> structuredOrder;
  299. cfg()->ComputeStructuredOrder(func, &*func->begin(), &structuredOrder);
  300. ComputeBlock2HeaderMaps(structuredOrder);
  301. bool modified = false;
  302. // Add instructions with external side effects to worklist. Also add branches
  303. // EXCEPT those immediately contained in an "if" selection construct or a loop
  304. // or continue construct.
  305. // TODO(greg-lunarg): Handle Frexp, Modf more optimally
  306. call_in_func_ = false;
  307. func_is_entry_point_ = false;
  308. private_stores_.clear();
  309. // Stacks to keep track of when we are inside an if- or loop-construct.
  310. // When immediately inside an if- or loop-construct, we do not initially
  311. // mark branches live. All other branches must be marked live.
  312. std::stack<bool> assume_branches_live;
  313. std::stack<uint32_t> currentMergeBlockId;
  314. // Push sentinel values on stack for when outside of any control flow.
  315. assume_branches_live.push(true);
  316. currentMergeBlockId.push(0);
  317. for (auto bi = structuredOrder.begin(); bi != structuredOrder.end(); ++bi) {
  318. // If exiting if or loop, update stacks
  319. if ((*bi)->id() == currentMergeBlockId.top()) {
  320. assume_branches_live.pop();
  321. currentMergeBlockId.pop();
  322. }
  323. for (auto ii = (*bi)->begin(); ii != (*bi)->end(); ++ii) {
  324. SpvOp op = ii->opcode();
  325. switch (op) {
  326. case SpvOpStore: {
  327. uint32_t varId;
  328. (void)GetPtr(&*ii, &varId);
  329. // Mark stores as live if their variable is not function scope
  330. // and is not private scope. Remember private stores for possible
  331. // later inclusion. We cannot call IsLocalVar at this point because
  332. // private_like_local_ has not been set yet.
  333. if (IsVarOfStorage(varId, SpvStorageClassPrivate) ||
  334. IsVarOfStorage(varId, SpvStorageClassWorkgroup))
  335. private_stores_.push_back(&*ii);
  336. else if (!IsVarOfStorage(varId, SpvStorageClassFunction))
  337. AddToWorklist(&*ii);
  338. } break;
  339. case SpvOpCopyMemory:
  340. case SpvOpCopyMemorySized: {
  341. uint32_t varId;
  342. (void)GetPtr(ii->GetSingleWordInOperand(kCopyMemoryTargetAddrInIdx),
  343. &varId);
  344. if (IsVarOfStorage(varId, SpvStorageClassPrivate) ||
  345. IsVarOfStorage(varId, SpvStorageClassWorkgroup))
  346. private_stores_.push_back(&*ii);
  347. else if (!IsVarOfStorage(varId, SpvStorageClassFunction))
  348. AddToWorklist(&*ii);
  349. } break;
  350. case SpvOpLoopMerge: {
  351. assume_branches_live.push(false);
  352. currentMergeBlockId.push(
  353. ii->GetSingleWordInOperand(kLoopMergeMergeBlockIdInIdx));
  354. } break;
  355. case SpvOpSelectionMerge: {
  356. assume_branches_live.push(false);
  357. currentMergeBlockId.push(
  358. ii->GetSingleWordInOperand(kSelectionMergeMergeBlockIdInIdx));
  359. } break;
  360. case SpvOpSwitch:
  361. case SpvOpBranch:
  362. case SpvOpBranchConditional:
  363. case SpvOpUnreachable: {
  364. if (assume_branches_live.top()) {
  365. AddToWorklist(&*ii);
  366. }
  367. } break;
  368. default: {
  369. // Function calls, atomics, function params, function returns, etc.
  370. // TODO(greg-lunarg): function calls live only if write to non-local
  371. if (!ii->IsOpcodeSafeToDelete()) {
  372. AddToWorklist(&*ii);
  373. }
  374. // Remember function calls
  375. if (op == SpvOpFunctionCall) call_in_func_ = true;
  376. } break;
  377. }
  378. }
  379. }
  380. // See if current function is an entry point
  381. for (auto& ei : get_module()->entry_points()) {
  382. if (ei.GetSingleWordInOperand(kEntryPointFunctionIdInIdx) ==
  383. func->result_id()) {
  384. func_is_entry_point_ = true;
  385. break;
  386. }
  387. }
  388. // If the current function is an entry point and has no function calls,
  389. // we can optimize private variables as locals
  390. private_like_local_ = func_is_entry_point_ && !call_in_func_;
  391. // If privates are not like local, add their stores to worklist
  392. if (!private_like_local_)
  393. for (auto& ps : private_stores_) AddToWorklist(ps);
  394. // Perform closure on live instruction set.
  395. while (!worklist_.empty()) {
  396. Instruction* liveInst = worklist_.front();
  397. // Add all operand instructions if not already live
  398. liveInst->ForEachInId([&liveInst, this](const uint32_t* iid) {
  399. Instruction* inInst = get_def_use_mgr()->GetDef(*iid);
  400. // Do not add label if an operand of a branch. This is not needed
  401. // as part of live code discovery and can create false live code,
  402. // for example, the branch to a header of a loop.
  403. if (inInst->opcode() == SpvOpLabel && liveInst->IsBranch()) return;
  404. AddToWorklist(inInst);
  405. });
  406. if (liveInst->type_id() != 0) {
  407. AddToWorklist(get_def_use_mgr()->GetDef(liveInst->type_id()));
  408. }
  409. // If in a structured if or loop construct, add the controlling
  410. // conditional branch and its merge.
  411. BasicBlock* blk = context()->get_instr_block(liveInst);
  412. Instruction* branchInst = block2headerBranch_[blk];
  413. if (branchInst != nullptr) {
  414. AddToWorklist(branchInst);
  415. Instruction* mergeInst = branch2merge_[branchInst];
  416. AddToWorklist(mergeInst);
  417. }
  418. // If the block is a header, add the next outermost controlling
  419. // conditional branch and its merge.
  420. Instruction* nextBranchInst = header2nextHeaderBranch_[blk];
  421. if (nextBranchInst != nullptr) {
  422. AddToWorklist(nextBranchInst);
  423. Instruction* mergeInst = branch2merge_[nextBranchInst];
  424. AddToWorklist(mergeInst);
  425. }
  426. // If local load, add all variable's stores if variable not already live
  427. if (liveInst->opcode() == SpvOpLoad || liveInst->IsAtomicWithLoad()) {
  428. uint32_t varId;
  429. (void)GetPtr(liveInst, &varId);
  430. if (varId != 0) {
  431. ProcessLoad(varId);
  432. }
  433. // Process memory copies like loads
  434. } else if (liveInst->opcode() == SpvOpCopyMemory ||
  435. liveInst->opcode() == SpvOpCopyMemorySized) {
  436. uint32_t varId;
  437. (void)GetPtr(liveInst->GetSingleWordInOperand(kCopyMemorySourceAddrInIdx),
  438. &varId);
  439. if (varId != 0) {
  440. ProcessLoad(varId);
  441. }
  442. // If merge, add other branches that are part of its control structure
  443. } else if (liveInst->opcode() == SpvOpLoopMerge ||
  444. liveInst->opcode() == SpvOpSelectionMerge) {
  445. AddBreaksAndContinuesToWorklist(liveInst);
  446. // If function call, treat as if it loads from all pointer arguments
  447. } else if (liveInst->opcode() == SpvOpFunctionCall) {
  448. liveInst->ForEachInId([this](const uint32_t* iid) {
  449. // Skip non-ptr args
  450. if (!IsPtr(*iid)) return;
  451. uint32_t varId;
  452. (void)GetPtr(*iid, &varId);
  453. ProcessLoad(varId);
  454. });
  455. // If function parameter, treat as if it's result id is loaded from
  456. } else if (liveInst->opcode() == SpvOpFunctionParameter) {
  457. ProcessLoad(liveInst->result_id());
  458. // We treat an OpImageTexelPointer as a load of the pointer, and
  459. // that value is manipulated to get the result.
  460. } else if (liveInst->opcode() == SpvOpImageTexelPointer) {
  461. uint32_t varId;
  462. (void)GetPtr(liveInst, &varId);
  463. if (varId != 0) {
  464. ProcessLoad(varId);
  465. }
  466. }
  467. // Add OpDecorateId instructions that apply to this instruction to the work
  468. // list. We use the decoration manager to look through the group
  469. // decorations to get to the OpDecorate* instructions themselves.
  470. auto decorations =
  471. get_decoration_mgr()->GetDecorationsFor(liveInst->result_id(), false);
  472. for (Instruction* dec : decorations) {
  473. // We only care about OpDecorateId instructions because the are the only
  474. // decorations that will reference an id that will have to be kept live
  475. // because of that use.
  476. if (dec->opcode() != SpvOpDecorateId) {
  477. continue;
  478. }
  479. if (dec->GetSingleWordInOperand(1) ==
  480. SpvDecorationHlslCounterBufferGOOGLE) {
  481. // These decorations should not force the use id to be live. It will be
  482. // removed if either the target or the in operand are dead.
  483. continue;
  484. }
  485. AddToWorklist(dec);
  486. }
  487. worklist_.pop();
  488. }
  489. // Kill dead instructions and remember dead blocks
  490. for (auto bi = structuredOrder.begin(); bi != structuredOrder.end();) {
  491. uint32_t mergeBlockId = 0;
  492. (*bi)->ForEachInst([this, &modified, &mergeBlockId](Instruction* inst) {
  493. if (!IsDead(inst)) return;
  494. if (inst->opcode() == SpvOpLabel) return;
  495. // If dead instruction is selection merge, remember merge block
  496. // for new branch at end of block
  497. if (inst->opcode() == SpvOpSelectionMerge ||
  498. inst->opcode() == SpvOpLoopMerge)
  499. mergeBlockId = inst->GetSingleWordInOperand(0);
  500. to_kill_.push_back(inst);
  501. modified = true;
  502. });
  503. // If a structured if or loop was deleted, add a branch to its merge
  504. // block, and traverse to the merge block and continue processing there.
  505. // We know the block still exists because the label is not deleted.
  506. if (mergeBlockId != 0) {
  507. AddBranch(mergeBlockId, *bi);
  508. for (++bi; (*bi)->id() != mergeBlockId; ++bi) {
  509. }
  510. auto merge_terminator = (*bi)->terminator();
  511. if (merge_terminator->opcode() == SpvOpUnreachable) {
  512. // The merge was unreachable. This is undefined behaviour so just
  513. // return (or return an undef). Then mark the new return as live.
  514. auto func_ret_type_inst = get_def_use_mgr()->GetDef(func->type_id());
  515. if (func_ret_type_inst->opcode() == SpvOpTypeVoid) {
  516. merge_terminator->SetOpcode(SpvOpReturn);
  517. } else {
  518. // Find an undef for the return value and make sure it gets kept by
  519. // the pass.
  520. auto undef_id = Type2Undef(func->type_id());
  521. auto undef = get_def_use_mgr()->GetDef(undef_id);
  522. live_insts_.Set(undef->unique_id());
  523. merge_terminator->SetOpcode(SpvOpReturnValue);
  524. merge_terminator->SetInOperands({{SPV_OPERAND_TYPE_ID, {undef_id}}});
  525. get_def_use_mgr()->AnalyzeInstUse(merge_terminator);
  526. }
  527. live_insts_.Set(merge_terminator->unique_id());
  528. }
  529. } else {
  530. ++bi;
  531. }
  532. }
  533. return modified;
  534. }
  535. void AggressiveDCEPass::InitializeModuleScopeLiveInstructions() {
  536. // Keep all execution modes.
  537. for (auto& exec : get_module()->execution_modes()) {
  538. AddToWorklist(&exec);
  539. }
  540. // Keep all entry points.
  541. for (auto& entry : get_module()->entry_points()) {
  542. if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
  543. // In SPIR-V 1.4 and later, entry points must list all global variables
  544. // used. DCE can still remove non-input/output variables and update the
  545. // interface list. Mark the entry point as live and inputs and outputs as
  546. // live, but defer decisions all other interfaces.
  547. live_insts_.Set(entry.unique_id());
  548. // The actual function is live always.
  549. AddToWorklist(
  550. get_def_use_mgr()->GetDef(entry.GetSingleWordInOperand(1u)));
  551. for (uint32_t i = 3; i < entry.NumInOperands(); ++i) {
  552. auto* var = get_def_use_mgr()->GetDef(entry.GetSingleWordInOperand(i));
  553. auto storage_class = var->GetSingleWordInOperand(0u);
  554. if (storage_class == SpvStorageClassInput ||
  555. storage_class == SpvStorageClassOutput) {
  556. AddToWorklist(var);
  557. }
  558. }
  559. } else {
  560. AddToWorklist(&entry);
  561. }
  562. }
  563. for (auto& anno : get_module()->annotations()) {
  564. if (anno.opcode() == SpvOpDecorate) {
  565. // Keep workgroup size.
  566. if (anno.GetSingleWordInOperand(1u) == SpvDecorationBuiltIn &&
  567. anno.GetSingleWordInOperand(2u) == SpvBuiltInWorkgroupSize) {
  568. AddToWorklist(&anno);
  569. }
  570. if (context()->preserve_bindings()) {
  571. // Keep all bindings.
  572. if ((anno.GetSingleWordInOperand(1u) == SpvDecorationDescriptorSet) ||
  573. (anno.GetSingleWordInOperand(1u) == SpvDecorationBinding)) {
  574. AddToWorklist(&anno);
  575. }
  576. }
  577. if (context()->preserve_spec_constants()) {
  578. // Keep all specialization constant instructions
  579. if (anno.GetSingleWordInOperand(1u) == SpvDecorationSpecId) {
  580. AddToWorklist(&anno);
  581. }
  582. }
  583. }
  584. }
  585. }
  586. Pass::Status AggressiveDCEPass::ProcessImpl() {
  587. // Current functionality assumes shader capability
  588. // TODO(greg-lunarg): Handle additional capabilities
  589. if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
  590. return Status::SuccessWithoutChange;
  591. // Current functionality assumes relaxed logical addressing (see
  592. // instruction.h)
  593. // TODO(greg-lunarg): Handle non-logical addressing
  594. if (context()->get_feature_mgr()->HasCapability(SpvCapabilityAddresses))
  595. return Status::SuccessWithoutChange;
  596. // The variable pointer extension is no longer needed to use the capability,
  597. // so we have to look for the capability.
  598. if (context()->get_feature_mgr()->HasCapability(
  599. SpvCapabilityVariablePointersStorageBuffer))
  600. return Status::SuccessWithoutChange;
  601. // If any extensions in the module are not explicitly supported,
  602. // return unmodified.
  603. if (!AllExtensionsSupported()) return Status::SuccessWithoutChange;
  604. // Eliminate Dead functions.
  605. bool modified = EliminateDeadFunctions();
  606. InitializeModuleScopeLiveInstructions();
  607. // Process all entry point functions.
  608. ProcessFunction pfn = [this](Function* fp) { return AggressiveDCE(fp); };
  609. modified |= context()->ProcessEntryPointCallTree(pfn);
  610. // If the decoration manager is kept live then the context will try to keep it
  611. // up to date. ADCE deals with group decorations by changing the operands in
  612. // |OpGroupDecorate| instruction directly without informing the decoration
  613. // manager. This can put it in an invalid state which will cause an error
  614. // when the context tries to update it. To avoid this problem invalidate
  615. // the decoration manager upfront.
  616. //
  617. // We kill it at now because it is used when processing the entry point
  618. // functions.
  619. context()->InvalidateAnalyses(IRContext::Analysis::kAnalysisDecorations);
  620. // Process module-level instructions. Now that all live instructions have
  621. // been marked, it is safe to remove dead global values.
  622. modified |= ProcessGlobalValues();
  623. // Sanity check.
  624. assert(to_kill_.size() == 0 || modified);
  625. // Kill all dead instructions.
  626. for (auto inst : to_kill_) {
  627. context()->KillInst(inst);
  628. }
  629. // Cleanup all CFG including all unreachable blocks.
  630. ProcessFunction cleanup = [this](Function* f) { return CFGCleanup(f); };
  631. modified |= context()->ProcessEntryPointCallTree(cleanup);
  632. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  633. }
  634. bool AggressiveDCEPass::EliminateDeadFunctions() {
  635. // Identify live functions first. Those that are not live
  636. // are dead. ADCE is disabled for non-shaders so we do not check for exported
  637. // functions here.
  638. std::unordered_set<const Function*> live_function_set;
  639. ProcessFunction mark_live = [&live_function_set](Function* fp) {
  640. live_function_set.insert(fp);
  641. return false;
  642. };
  643. context()->ProcessEntryPointCallTree(mark_live);
  644. bool modified = false;
  645. for (auto funcIter = get_module()->begin();
  646. funcIter != get_module()->end();) {
  647. if (live_function_set.count(&*funcIter) == 0) {
  648. modified = true;
  649. EliminateFunction(&*funcIter);
  650. funcIter = funcIter.Erase();
  651. } else {
  652. ++funcIter;
  653. }
  654. }
  655. return modified;
  656. }
  657. void AggressiveDCEPass::EliminateFunction(Function* func) {
  658. // Remove all of the instruction in the function body
  659. func->ForEachInst([this](Instruction* inst) { context()->KillInst(inst); },
  660. true);
  661. }
  662. bool AggressiveDCEPass::ProcessGlobalValues() {
  663. // Remove debug and annotation statements referencing dead instructions.
  664. // This must be done before killing the instructions, otherwise there are
  665. // dead objects in the def/use database.
  666. bool modified = false;
  667. Instruction* instruction = &*get_module()->debug2_begin();
  668. while (instruction) {
  669. if (instruction->opcode() != SpvOpName) {
  670. instruction = instruction->NextNode();
  671. continue;
  672. }
  673. if (IsTargetDead(instruction)) {
  674. instruction = context()->KillInst(instruction);
  675. modified = true;
  676. } else {
  677. instruction = instruction->NextNode();
  678. }
  679. }
  680. // This code removes all unnecessary decorations safely (see #1174). It also
  681. // does so in a more efficient manner than deleting them only as the targets
  682. // are deleted.
  683. std::vector<Instruction*> annotations;
  684. for (auto& inst : get_module()->annotations()) annotations.push_back(&inst);
  685. std::sort(annotations.begin(), annotations.end(), DecorationLess());
  686. for (auto annotation : annotations) {
  687. switch (annotation->opcode()) {
  688. case SpvOpDecorate:
  689. case SpvOpMemberDecorate:
  690. case SpvOpDecorateStringGOOGLE:
  691. case SpvOpMemberDecorateStringGOOGLE:
  692. if (IsTargetDead(annotation)) {
  693. context()->KillInst(annotation);
  694. modified = true;
  695. }
  696. break;
  697. case SpvOpDecorateId:
  698. if (IsTargetDead(annotation)) {
  699. context()->KillInst(annotation);
  700. modified = true;
  701. } else {
  702. if (annotation->GetSingleWordInOperand(1) ==
  703. SpvDecorationHlslCounterBufferGOOGLE) {
  704. // HlslCounterBuffer will reference an id other than the target.
  705. // If that id is dead, then the decoration can be removed as well.
  706. uint32_t counter_buffer_id = annotation->GetSingleWordInOperand(2);
  707. Instruction* counter_buffer_inst =
  708. get_def_use_mgr()->GetDef(counter_buffer_id);
  709. if (IsDead(counter_buffer_inst)) {
  710. context()->KillInst(annotation);
  711. modified = true;
  712. }
  713. }
  714. }
  715. break;
  716. case SpvOpGroupDecorate: {
  717. // Go through the targets of this group decorate. Remove each dead
  718. // target. If all targets are dead, remove this decoration.
  719. bool dead = true;
  720. bool removed_operand = false;
  721. for (uint32_t i = 1; i < annotation->NumOperands();) {
  722. Instruction* opInst =
  723. get_def_use_mgr()->GetDef(annotation->GetSingleWordOperand(i));
  724. if (IsDead(opInst)) {
  725. // Don't increment |i|.
  726. annotation->RemoveOperand(i);
  727. modified = true;
  728. removed_operand = true;
  729. } else {
  730. i++;
  731. dead = false;
  732. }
  733. }
  734. if (dead) {
  735. context()->KillInst(annotation);
  736. modified = true;
  737. } else if (removed_operand) {
  738. context()->UpdateDefUse(annotation);
  739. }
  740. break;
  741. }
  742. case SpvOpGroupMemberDecorate: {
  743. // Go through the targets of this group member decorate. Remove each
  744. // dead target (and member index). If all targets are dead, remove this
  745. // decoration.
  746. bool dead = true;
  747. bool removed_operand = false;
  748. for (uint32_t i = 1; i < annotation->NumOperands();) {
  749. Instruction* opInst =
  750. get_def_use_mgr()->GetDef(annotation->GetSingleWordOperand(i));
  751. if (IsDead(opInst)) {
  752. // Don't increment |i|.
  753. annotation->RemoveOperand(i + 1);
  754. annotation->RemoveOperand(i);
  755. modified = true;
  756. removed_operand = true;
  757. } else {
  758. i += 2;
  759. dead = false;
  760. }
  761. }
  762. if (dead) {
  763. context()->KillInst(annotation);
  764. modified = true;
  765. } else if (removed_operand) {
  766. context()->UpdateDefUse(annotation);
  767. }
  768. break;
  769. }
  770. case SpvOpDecorationGroup:
  771. // By the time we hit decoration groups we've checked everything that
  772. // can target them. So if they have no uses they must be dead.
  773. if (get_def_use_mgr()->NumUsers(annotation) == 0) {
  774. context()->KillInst(annotation);
  775. modified = true;
  776. }
  777. break;
  778. default:
  779. assert(false);
  780. break;
  781. }
  782. }
  783. // Since ADCE is disabled for non-shaders, we don't check for export linkage
  784. // attributes here.
  785. for (auto& val : get_module()->types_values()) {
  786. if (IsDead(&val)) {
  787. // Save forwarded pointer if pointer is live since closure does not mark
  788. // this live as it does not have a result id. This is a little too
  789. // conservative since it is not known if the structure type that needed
  790. // it is still live. TODO(greg-lunarg): Only save if needed.
  791. if (val.opcode() == SpvOpTypeForwardPointer) {
  792. uint32_t ptr_ty_id = val.GetSingleWordInOperand(0);
  793. Instruction* ptr_ty_inst = get_def_use_mgr()->GetDef(ptr_ty_id);
  794. if (!IsDead(ptr_ty_inst)) continue;
  795. }
  796. to_kill_.push_back(&val);
  797. modified = true;
  798. }
  799. }
  800. if (get_module()->version() >= SPV_SPIRV_VERSION_WORD(1, 4)) {
  801. // Remove the dead interface variables from the entry point interface list.
  802. for (auto& entry : get_module()->entry_points()) {
  803. std::vector<Operand> new_operands;
  804. for (uint32_t i = 0; i < entry.NumInOperands(); ++i) {
  805. if (i < 3) {
  806. // Execution model, function id and name are always valid.
  807. new_operands.push_back(entry.GetInOperand(i));
  808. } else {
  809. auto* var =
  810. get_def_use_mgr()->GetDef(entry.GetSingleWordInOperand(i));
  811. if (!IsDead(var)) {
  812. new_operands.push_back(entry.GetInOperand(i));
  813. }
  814. }
  815. }
  816. if (new_operands.size() != entry.NumInOperands()) {
  817. entry.SetInOperands(std::move(new_operands));
  818. get_def_use_mgr()->UpdateDefUse(&entry);
  819. }
  820. }
  821. }
  822. return modified;
  823. }
  824. AggressiveDCEPass::AggressiveDCEPass() = default;
  825. Pass::Status AggressiveDCEPass::Process() {
  826. // Initialize extensions whitelist
  827. InitExtensions();
  828. return ProcessImpl();
  829. }
  830. void AggressiveDCEPass::InitExtensions() {
  831. extensions_whitelist_.clear();
  832. extensions_whitelist_.insert({
  833. "SPV_AMD_shader_explicit_vertex_parameter",
  834. "SPV_AMD_shader_trinary_minmax",
  835. "SPV_AMD_gcn_shader",
  836. "SPV_KHR_shader_ballot",
  837. "SPV_AMD_shader_ballot",
  838. "SPV_AMD_gpu_shader_half_float",
  839. "SPV_KHR_shader_draw_parameters",
  840. "SPV_KHR_subgroup_vote",
  841. "SPV_KHR_16bit_storage",
  842. "SPV_KHR_device_group",
  843. "SPV_KHR_multiview",
  844. "SPV_NVX_multiview_per_view_attributes",
  845. "SPV_NV_viewport_array2",
  846. "SPV_NV_stereo_view_rendering",
  847. "SPV_NV_sample_mask_override_coverage",
  848. "SPV_NV_geometry_shader_passthrough",
  849. "SPV_AMD_texture_gather_bias_lod",
  850. "SPV_KHR_storage_buffer_storage_class",
  851. // SPV_KHR_variable_pointers
  852. // Currently do not support extended pointer expressions
  853. "SPV_AMD_gpu_shader_int16",
  854. "SPV_KHR_post_depth_coverage",
  855. "SPV_KHR_shader_atomic_counter_ops",
  856. "SPV_EXT_shader_stencil_export",
  857. "SPV_EXT_shader_viewport_index_layer",
  858. "SPV_AMD_shader_image_load_store_lod",
  859. "SPV_AMD_shader_fragment_mask",
  860. "SPV_EXT_fragment_fully_covered",
  861. "SPV_AMD_gpu_shader_half_float_fetch",
  862. "SPV_GOOGLE_decorate_string",
  863. "SPV_GOOGLE_hlsl_functionality1",
  864. "SPV_GOOGLE_user_type",
  865. "SPV_NV_shader_subgroup_partitioned",
  866. "SPV_EXT_descriptor_indexing",
  867. "SPV_NV_fragment_shader_barycentric",
  868. "SPV_NV_compute_shader_derivatives",
  869. "SPV_NV_shader_image_footprint",
  870. "SPV_NV_shading_rate",
  871. "SPV_NV_mesh_shader",
  872. "SPV_NV_ray_tracing",
  873. "SPV_EXT_fragment_invocation_density",
  874. "SPV_EXT_physical_storage_buffer",
  875. });
  876. }
  877. } // namespace opt
  878. } // namespace spvtools