DxilValueCache.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. //===---------- DxilValueCache.cpp - Dxil Constant Value Cache ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Utility to compute and cache constant values for instructions.
  11. //
  12. #include "llvm/Pass.h"
  13. #include "dxc/DXIL/DxilConstants.h"
  14. #include "llvm/IR/Module.h"
  15. #include "llvm/IR/GlobalVariable.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Instructions.h"
  18. #include "llvm/IR/Operator.h"
  19. #include "llvm/IR/CFG.h"
  20. #include "llvm/Support/Debug.h"
  21. #include "llvm/IR/Dominators.h"
  22. #include "llvm/Transforms/Scalar.h"
  23. #include "llvm/Analysis/InstructionSimplify.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/DxilValueCache.h"
  27. #include <unordered_set>
  28. #define DEBUG_TYPE "dxil-value-cache"
  29. using namespace llvm;
  30. static
  31. bool IsConstantTrue(const Value *V) {
  32. if (const ConstantInt *C = dyn_cast<ConstantInt>(V))
  33. return C->getLimitedValue() != 0;
  34. return false;
  35. }
  36. static
  37. bool IsConstantFalse(const Value *V) {
  38. if (const ConstantInt *C = dyn_cast<ConstantInt>(V))
  39. return C->getLimitedValue() == 0;
  40. return false;
  41. }
  42. static
  43. bool IsEntryBlock(const BasicBlock *BB) {
  44. return BB == &BB->getParent()->getEntryBlock();
  45. }
  46. void DxilValueCache::MarkAlwaysReachable(BasicBlock *BB) {
  47. ValueMap.Set(BB, ConstantInt::get(Type::getInt1Ty(BB->getContext()), 1));
  48. }
  49. void DxilValueCache::MarkUnreachable(BasicBlock *BB) {
  50. ValueMap.Set(BB, ConstantInt::get(Type::getInt1Ty(BB->getContext()), 0));
  51. }
  52. bool DxilValueCache::IsAlwaysReachable_(BasicBlock *BB) {
  53. if (Value *V = ValueMap.Get(BB))
  54. if (IsConstantTrue(V))
  55. return true;
  56. return false;
  57. }
  58. bool DxilValueCache::MayBranchTo(BasicBlock *A, BasicBlock *B) {
  59. BranchInst *Br = dyn_cast<BranchInst>(A->getTerminator());
  60. if (!Br) return false;
  61. if (Br->isUnconditional() && Br->getSuccessor(0) == B)
  62. return true;
  63. if (ConstantInt *C = dyn_cast<ConstantInt>(TryGetCachedValue(Br->getCondition()))) {
  64. unsigned SuccIndex = C->getLimitedValue() != 0 ? 0 : 1;
  65. return Br->getSuccessor(SuccIndex) == B;
  66. }
  67. return true;
  68. }
  69. bool DxilValueCache::IsUnreachable_(BasicBlock *BB) {
  70. if (Value *V = ValueMap.Get(BB))
  71. if (IsConstantFalse(V))
  72. return true;
  73. return false;
  74. }
  75. Value *DxilValueCache::ProcessAndSimplify_PHI(Instruction *I, DominatorTree *DT) {
  76. PHINode *PN = cast<PHINode>(I);
  77. BasicBlock *SoleIncoming = nullptr;
  78. bool Unreachable = true;
  79. Value *Simplified = nullptr;
  80. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  81. BasicBlock *PredBB = PN->getIncomingBlock(i);
  82. if (IsUnreachable_(PredBB))
  83. continue;
  84. Unreachable = false;
  85. if (MayBranchTo(PredBB, PN->getParent())) {
  86. if (SoleIncoming) {
  87. SoleIncoming = nullptr;
  88. break;
  89. }
  90. SoleIncoming = PredBB;
  91. }
  92. }
  93. if (Unreachable) {
  94. return UndefValue::get(I->getType());
  95. }
  96. if (SoleIncoming) {
  97. Value *V = TryGetCachedValue(PN->getIncomingValueForBlock(SoleIncoming));
  98. if (isa<Constant>(V))
  99. Simplified = V;
  100. else if (Instruction *I = dyn_cast<Instruction>(V)) {
  101. // If this is an instruction, we have to make sure it
  102. // dominates this PHI.
  103. // There are several conditions that qualify:
  104. // 1. There's only one predecessor
  105. // 2. If the instruction is in the entry block, then it must dominate
  106. // 3. If we are provided with a Dominator tree, and it decides that
  107. // it dominates.
  108. if (PN->getNumIncomingValues() == 1 ||
  109. IsEntryBlock(I->getParent()) ||
  110. (DT && DT->dominates(I, PN)))
  111. {
  112. Simplified = I;
  113. }
  114. }
  115. }
  116. // If we coulnd't deduce it, run the LLVM stock simplification to see
  117. // if we could do anything.
  118. if (!Simplified)
  119. Simplified = llvm::SimplifyInstruction(I, I->getModule()->getDataLayout());
  120. // One last step, to check if we have anything cached for whatever we
  121. // simplified to.
  122. if (Simplified)
  123. Simplified = TryGetCachedValue(Simplified);
  124. return Simplified;
  125. }
  126. Value *DxilValueCache::ProcessAndSimplify_Br(Instruction *I, DominatorTree *DT) {
  127. // The *only* reason we're paying special attention to the
  128. // branch inst, is to mark certain Basic Blocks as always
  129. // reachable or unreachable.
  130. BranchInst *Br = cast<BranchInst>(I);
  131. BasicBlock *BB = Br->getParent();
  132. if (Br->isConditional()) {
  133. BasicBlock *TrueSucc = Br->getSuccessor(0);
  134. BasicBlock *FalseSucc = Br->getSuccessor(1);
  135. Value *Cond = TryGetCachedValue(Br->getCondition());
  136. if (IsUnreachable_(BB)) {
  137. MarkUnreachable(FalseSucc);
  138. MarkUnreachable(TrueSucc);
  139. }
  140. else if (IsConstantTrue(Cond)) {
  141. if (IsAlwaysReachable_(BB)) {
  142. MarkAlwaysReachable(TrueSucc);
  143. }
  144. if (FalseSucc->getSinglePredecessor())
  145. MarkUnreachable(FalseSucc);
  146. }
  147. else if (IsConstantFalse(Cond)) {
  148. if (IsAlwaysReachable_(BB)) {
  149. MarkAlwaysReachable(FalseSucc);
  150. }
  151. if (TrueSucc->getSinglePredecessor())
  152. MarkUnreachable(TrueSucc);
  153. }
  154. }
  155. else {
  156. BasicBlock *Succ = Br->getSuccessor(0);
  157. if (IsAlwaysReachable_(BB))
  158. MarkAlwaysReachable(Succ);
  159. else if (Succ->getSinglePredecessor() && IsUnreachable_(BB))
  160. MarkUnreachable(Succ);
  161. }
  162. return nullptr;
  163. }
  164. Value *DxilValueCache::ProcessAndSimplify_Load(Instruction *I, DominatorTree *DT) {
  165. LoadInst *LI = cast<LoadInst>(I);
  166. Value *V = TryGetCachedValue(LI->getPointerOperand());
  167. if (Constant *ConstPtr = dyn_cast<Constant>(V)) {
  168. const DataLayout &DL = I->getModule()->getDataLayout();
  169. return llvm::ConstantFoldLoadFromConstPtr(ConstPtr, DL);
  170. }
  171. return nullptr;
  172. }
  173. Value *DxilValueCache::SimplifyAndCacheResult(Instruction *I, DominatorTree *DT) {
  174. const DataLayout &DL = I->getModule()->getDataLayout();
  175. Value *Simplified = nullptr;
  176. if (Instruction::Br == I->getOpcode()) {
  177. Simplified = ProcessAndSimplify_Br(I, DT);
  178. }
  179. else if (Instruction::PHI == I->getOpcode()) {
  180. Simplified = ProcessAndSimplify_PHI(I, DT);
  181. }
  182. else if (Instruction::Load == I->getOpcode()) {
  183. Simplified = ProcessAndSimplify_Load(I, DT);
  184. }
  185. else if (Instruction::GetElementPtr == I->getOpcode()) {
  186. SmallVector<Value *, 4> Ops;
  187. for (unsigned i = 0; i < I->getNumOperands(); i++)
  188. Ops.push_back(TryGetCachedValue(I->getOperand(i)));
  189. Simplified = llvm::SimplifyGEPInst(Ops, DL, nullptr, DT);
  190. }
  191. else if (Instruction::Call == I->getOpcode()) {
  192. Module *M = I->getModule();
  193. CallInst *CI = cast<CallInst>(I);
  194. if (CI->getCalledFunction()->getName() == hlsl::DXIL::kDxBreakFuncName) {
  195. llvm::Type *i1Ty = llvm::Type::getInt1Ty(M->getContext());
  196. Simplified = llvm::ConstantInt::get(i1Ty, 1);
  197. }
  198. }
  199. // The rest of the checks use LLVM stock simplifications
  200. else if (I->isBinaryOp()) {
  201. Simplified =
  202. llvm::SimplifyBinOp(
  203. I->getOpcode(),
  204. TryGetCachedValue(I->getOperand(0)),
  205. TryGetCachedValue(I->getOperand(1)),
  206. DL);
  207. }
  208. else if (GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(I)) {
  209. SmallVector<Value *, 4> Values;
  210. for (Value *V : Gep->operand_values()) {
  211. Values.push_back(TryGetCachedValue(V));
  212. }
  213. Simplified =
  214. llvm::SimplifyGEPInst(Values, DL, nullptr, DT, nullptr, nullptr);
  215. }
  216. else if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  217. Simplified =
  218. llvm::SimplifyCmpInst(Cmp->getPredicate(),
  219. TryGetCachedValue(I->getOperand(0)),
  220. TryGetCachedValue(I->getOperand(1)),
  221. DL);
  222. }
  223. else if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  224. Simplified =
  225. llvm::SimplifySelectInst(
  226. TryGetCachedValue(Select->getCondition()),
  227. TryGetCachedValue(Select->getTrueValue()),
  228. TryGetCachedValue(Select->getFalseValue()),
  229. DL
  230. );
  231. }
  232. else if (ExtractElementInst *IE = dyn_cast<ExtractElementInst>(I)) {
  233. Simplified =
  234. llvm::SimplifyExtractElementInst(
  235. TryGetCachedValue(IE->getVectorOperand()),
  236. TryGetCachedValue(IE->getIndexOperand()),
  237. DL, nullptr, DT);
  238. }
  239. else if (CastInst *Cast = dyn_cast<CastInst>(I)) {
  240. Simplified =
  241. llvm::SimplifyCastInst(
  242. Cast->getOpcode(),
  243. TryGetCachedValue(Cast->getOperand(0)),
  244. Cast->getType(), DL);
  245. }
  246. if (Simplified && isa<Constant>(Simplified))
  247. ValueMap.Set(I, Simplified);
  248. return Simplified;
  249. }
  250. STATISTIC(StaleValuesEncountered, "Stale Values Encountered");
  251. bool DxilValueCache::WeakValueMap::Seen(Value *V) {
  252. auto FindIt = Map.find(V);
  253. if (FindIt == Map.end())
  254. return false;
  255. auto &Entry = FindIt->second;
  256. if (Entry.IsStale())
  257. return false;
  258. return Entry.Value;
  259. }
  260. Value *DxilValueCache::WeakValueMap::Get(Value *V) {
  261. auto FindIt = Map.find(V);
  262. if (FindIt == Map.end())
  263. return nullptr;
  264. auto &Entry = FindIt->second;
  265. if (Entry.IsStale())
  266. return nullptr;
  267. Value *Result = Entry.Value;
  268. if (Result == GetSentinel(V->getContext()))
  269. return nullptr;
  270. return Result;
  271. }
  272. void DxilValueCache::WeakValueMap::SetSentinel(Value *Key) {
  273. Map[Key].Set(Key, GetSentinel(Key->getContext()));
  274. }
  275. Value *DxilValueCache::WeakValueMap::GetSentinel(LLVMContext &Ctx) {
  276. if (!Sentinel) {
  277. Sentinel.reset( PHINode::Create(Type::getInt1Ty(Ctx), 0) );
  278. }
  279. return Sentinel.get();
  280. }
  281. void DxilValueCache::WeakValueMap::ResetUnknowns() {
  282. if (!Sentinel)
  283. return;
  284. for (auto it = Map.begin(); it != Map.end(); it++) {
  285. if (it->second.Value == Sentinel.get())
  286. it->second.Value = nullptr;
  287. }
  288. }
  289. LLVM_DUMP_METHOD
  290. void DxilValueCache::WeakValueMap::dump() const {
  291. for (auto It = Map.begin(), E = Map.end(); It != E; It++) {
  292. const Value *Key = It->first;
  293. if (It->second.IsStale())
  294. continue;
  295. const Value *V = It->second.Value;
  296. bool IsSentinel = Sentinel && V == Sentinel.get();
  297. if (const BasicBlock *BB = dyn_cast<BasicBlock>(Key)) {
  298. dbgs() << "[BB]" << BB->getName() << " -> ";
  299. if (IsSentinel)
  300. dbgs() << "NO_VALUE";
  301. else {
  302. if (IsConstantTrue(V))
  303. dbgs() << "Always Reachable!";
  304. else if (IsConstantFalse(V))
  305. dbgs() << "Never Reachable!";
  306. }
  307. }
  308. else {
  309. dbgs() << Key->getName() << " -> ";
  310. if (IsSentinel)
  311. dbgs() << "NO_VALUE";
  312. else
  313. dbgs() << *V;
  314. }
  315. dbgs() << "\n";
  316. }
  317. }
  318. void DxilValueCache::WeakValueMap::Set(Value *Key, Value *V) {
  319. Map[Key].Set(Key, V);
  320. }
  321. // If there's a cached value, return it. Otherwise, return
  322. // the value itself.
  323. Value *DxilValueCache::TryGetCachedValue(Value *V) {
  324. if (Value *Simplified = ValueMap.Get(V))
  325. return Simplified;
  326. return V;
  327. }
  328. DxilValueCache::DxilValueCache() : ImmutablePass(ID) {
  329. initializeDxilValueCachePass(*PassRegistry::getPassRegistry());
  330. }
  331. const char *DxilValueCache::getPassName() const {
  332. return "Dxil Value Cache";
  333. }
  334. Value *DxilValueCache::GetValue(Value *V, DominatorTree *DT) {
  335. if (Value *NewV = ValueMap.Get(V))
  336. return NewV;
  337. return ProcessValue(V, DT);
  338. }
  339. Constant *DxilValueCache::GetConstValue(Value *V, DominatorTree *DT) {
  340. if (Value *NewV = GetValue(V))
  341. return dyn_cast<Constant>(NewV);
  342. return nullptr;
  343. }
  344. bool DxilValueCache::IsAlwaysReachable(BasicBlock *BB, DominatorTree *DT) {
  345. ProcessValue(BB, DT);
  346. return IsAlwaysReachable_(BB);
  347. }
  348. bool DxilValueCache::IsUnreachable(BasicBlock *BB, DominatorTree *DT) {
  349. ProcessValue(BB, DT);
  350. return IsUnreachable_(BB);
  351. }
  352. LLVM_DUMP_METHOD
  353. void DxilValueCache::dump() const {
  354. ValueMap.dump();
  355. }
  356. void DxilValueCache::getAnalysisUsage(AnalysisUsage &AU) const {
  357. AU.setPreservesAll();
  358. }
  359. Value *DxilValueCache::ProcessValue(Value *NewV, DominatorTree *DT) {
  360. Value *Result = nullptr;
  361. SmallVector<Value *, 16> WorkList;
  362. // Although we accept all values for convenience, we only process
  363. // Instructions.
  364. if (Instruction *I = dyn_cast<Instruction>(NewV)) {
  365. WorkList.push_back(I);
  366. }
  367. else if (BasicBlock *BB = dyn_cast<BasicBlock>(NewV)) {
  368. WorkList.push_back(BB->getTerminator());
  369. WorkList.push_back(BB);
  370. }
  371. else {
  372. return nullptr;
  373. }
  374. // Unconditionally process this one instruction, whether we've seen
  375. // it or not. The simplification might be able to do something to
  376. // simplify it even when we don't have its value cached.
  377. // This is a basic DFS setup.
  378. while (WorkList.size()) {
  379. Value *V = WorkList.back();
  380. // If we haven't seen this value, go in and push things it depends on
  381. // into the worklist.
  382. if (!ValueMap.Seen(V)) {
  383. ValueMap.SetSentinel(V);
  384. if (Instruction *I = dyn_cast<Instruction>(V)) {
  385. for (Use &U : I->operands()) {
  386. Instruction *UseI = dyn_cast<Instruction>(U.get());
  387. if (!UseI)
  388. continue;
  389. if (!ValueMap.Seen(UseI))
  390. WorkList.push_back(UseI);
  391. }
  392. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  393. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  394. BasicBlock *BB = PN->getIncomingBlock(i);
  395. TerminatorInst *Term = BB->getTerminator();
  396. if (!ValueMap.Seen(Term))
  397. WorkList.push_back(Term);
  398. if (!ValueMap.Seen(BB))
  399. WorkList.push_back(BB);
  400. }
  401. }
  402. }
  403. else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  404. if (IsEntryBlock(BB)) {
  405. MarkAlwaysReachable(BB);
  406. }
  407. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; PI++) {
  408. BasicBlock *PredBB = *PI;
  409. TerminatorInst *Term = PredBB->getTerminator();
  410. if (!ValueMap.Seen(Term))
  411. WorkList.push_back(Term);
  412. if (!ValueMap.Seen(PredBB))
  413. WorkList.push_back(PredBB);
  414. }
  415. }
  416. }
  417. // If we've seen this values, all its dependencies must have been processed
  418. // as well.
  419. else {
  420. WorkList.pop_back();
  421. if (Instruction *I = dyn_cast<Instruction>(V)) {
  422. Value *SimplifiedValue = SimplifyAndCacheResult(I, DT);
  423. // Set the result if this is the input inst.
  424. // SimplifyInst may not have cached the value
  425. // so we return it directly.
  426. if (I == NewV)
  427. Result = SimplifiedValue;
  428. }
  429. else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
  430. // Deduce the basic block's reachability based on
  431. // other analysis.
  432. if (!IsEntryBlock(BB)) {
  433. bool AllNeverReachable = true;
  434. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; PI++) {
  435. if (!IsUnreachable_(BB)) {
  436. AllNeverReachable = false;
  437. break;
  438. }
  439. }
  440. if (AllNeverReachable)
  441. MarkUnreachable(BB);
  442. }
  443. }
  444. }
  445. }
  446. return Result;
  447. }
  448. char DxilValueCache::ID;
  449. Pass *llvm::createDxilValueCachePass() {
  450. return new DxilValueCache();
  451. }
  452. INITIALIZE_PASS(DxilValueCache, DEBUG_TYPE, "Dxil Value Cache", false, false)