PHITransAddr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. //===- PHITransAddr.cpp - PHI Translation for Addresses -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the PHITransAddr class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/PHITransAddr.h"
  13. #include "llvm/Analysis/InstructionSimplify.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/Config/llvm-config.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/Dominators.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace llvm;
  22. static cl::opt<bool> EnableAddPhiTranslation(
  23. "gvn-add-phi-translation", cl::init(false), cl::Hidden,
  24. cl::desc("Enable phi-translation of add instructions"));
  25. static bool CanPHITrans(Instruction *Inst) {
  26. if (isa<PHINode>(Inst) ||
  27. isa<GetElementPtrInst>(Inst))
  28. return true;
  29. if (isa<CastInst>(Inst) &&
  30. isSafeToSpeculativelyExecute(Inst))
  31. return true;
  32. if (Inst->getOpcode() == Instruction::Add &&
  33. isa<ConstantInt>(Inst->getOperand(1)))
  34. return true;
  35. return false;
  36. }
  37. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  38. LLVM_DUMP_METHOD void PHITransAddr::dump() const {
  39. if (!Addr) {
  40. dbgs() << "PHITransAddr: null\n";
  41. return;
  42. }
  43. dbgs() << "PHITransAddr: " << *Addr << "\n";
  44. for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
  45. dbgs() << " Input #" << i << " is " << *InstInputs[i] << "\n";
  46. }
  47. #endif
  48. static bool VerifySubExpr(Value *Expr,
  49. SmallVectorImpl<Instruction*> &InstInputs) {
  50. // If this is a non-instruction value, there is nothing to do.
  51. Instruction *I = dyn_cast<Instruction>(Expr);
  52. if (!I) return true;
  53. // If it's an instruction, it is either in Tmp or its operands recursively
  54. // are.
  55. SmallVectorImpl<Instruction *>::iterator Entry = find(InstInputs, I);
  56. if (Entry != InstInputs.end()) {
  57. InstInputs.erase(Entry);
  58. return true;
  59. }
  60. // If it isn't in the InstInputs list it is a subexpr incorporated into the
  61. // address. Validate that it is phi translatable.
  62. if (!CanPHITrans(I)) {
  63. errs() << "Instruction in PHITransAddr is not phi-translatable:\n";
  64. errs() << *I << '\n';
  65. llvm_unreachable("Either something is missing from InstInputs or "
  66. "CanPHITrans is wrong.");
  67. }
  68. // Validate the operands of the instruction.
  69. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  70. if (!VerifySubExpr(I->getOperand(i), InstInputs))
  71. return false;
  72. return true;
  73. }
  74. /// Verify - Check internal consistency of this data structure. If the
  75. /// structure is valid, it returns true. If invalid, it prints errors and
  76. /// returns false.
  77. bool PHITransAddr::Verify() const {
  78. if (!Addr) return true;
  79. SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
  80. if (!VerifySubExpr(Addr, Tmp))
  81. return false;
  82. if (!Tmp.empty()) {
  83. errs() << "PHITransAddr contains extra instructions:\n";
  84. for (unsigned i = 0, e = InstInputs.size(); i != e; ++i)
  85. errs() << " InstInput #" << i << " is " << *InstInputs[i] << "\n";
  86. llvm_unreachable("This is unexpected.");
  87. }
  88. // a-ok.
  89. return true;
  90. }
  91. /// IsPotentiallyPHITranslatable - If this needs PHI translation, return true
  92. /// if we have some hope of doing it. This should be used as a filter to
  93. /// avoid calling PHITranslateValue in hopeless situations.
  94. bool PHITransAddr::IsPotentiallyPHITranslatable() const {
  95. // If the input value is not an instruction, or if it is not defined in CurBB,
  96. // then we don't need to phi translate it.
  97. Instruction *Inst = dyn_cast<Instruction>(Addr);
  98. return !Inst || CanPHITrans(Inst);
  99. }
  100. static void RemoveInstInputs(Value *V,
  101. SmallVectorImpl<Instruction*> &InstInputs) {
  102. Instruction *I = dyn_cast<Instruction>(V);
  103. if (!I) return;
  104. // If the instruction is in the InstInputs list, remove it.
  105. SmallVectorImpl<Instruction *>::iterator Entry = find(InstInputs, I);
  106. if (Entry != InstInputs.end()) {
  107. InstInputs.erase(Entry);
  108. return;
  109. }
  110. assert(!isa<PHINode>(I) && "Error, removing something that isn't an input");
  111. // Otherwise, it must have instruction inputs itself. Zap them recursively.
  112. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  113. if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
  114. RemoveInstInputs(Op, InstInputs);
  115. }
  116. }
  117. Value *PHITransAddr::PHITranslateSubExpr(Value *V, BasicBlock *CurBB,
  118. BasicBlock *PredBB,
  119. const DominatorTree *DT) {
  120. // If this is a non-instruction value, it can't require PHI translation.
  121. Instruction *Inst = dyn_cast<Instruction>(V);
  122. if (!Inst) return V;
  123. // Determine whether 'Inst' is an input to our PHI translatable expression.
  124. bool isInput = is_contained(InstInputs, Inst);
  125. // Handle inputs instructions if needed.
  126. if (isInput) {
  127. if (Inst->getParent() != CurBB) {
  128. // If it is an input defined in a different block, then it remains an
  129. // input.
  130. return Inst;
  131. }
  132. // If 'Inst' is defined in this block and is an input that needs to be phi
  133. // translated, we need to incorporate the value into the expression or fail.
  134. // In either case, the instruction itself isn't an input any longer.
  135. InstInputs.erase(find(InstInputs, Inst));
  136. // If this is a PHI, go ahead and translate it.
  137. if (PHINode *PN = dyn_cast<PHINode>(Inst))
  138. return AddAsInput(PN->getIncomingValueForBlock(PredBB));
  139. // If this is a non-phi value, and it is analyzable, we can incorporate it
  140. // into the expression by making all instruction operands be inputs.
  141. if (!CanPHITrans(Inst))
  142. return nullptr;
  143. // All instruction operands are now inputs (and of course, they may also be
  144. // defined in this block, so they may need to be phi translated themselves.
  145. for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
  146. if (Instruction *Op = dyn_cast<Instruction>(Inst->getOperand(i)))
  147. InstInputs.push_back(Op);
  148. }
  149. // Ok, it must be an intermediate result (either because it started that way
  150. // or because we just incorporated it into the expression). See if its
  151. // operands need to be phi translated, and if so, reconstruct it.
  152. if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
  153. if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
  154. Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
  155. if (!PHIIn) return nullptr;
  156. if (PHIIn == Cast->getOperand(0))
  157. return Cast;
  158. // Find an available version of this cast.
  159. // Constants are trivial to find.
  160. if (Constant *C = dyn_cast<Constant>(PHIIn))
  161. return AddAsInput(ConstantExpr::getCast(Cast->getOpcode(),
  162. C, Cast->getType()));
  163. // Otherwise we have to see if a casted version of the incoming pointer
  164. // is available. If so, we can use it, otherwise we have to fail.
  165. for (User *U : PHIIn->users()) {
  166. if (CastInst *CastI = dyn_cast<CastInst>(U))
  167. if (CastI->getOpcode() == Cast->getOpcode() &&
  168. CastI->getType() == Cast->getType() &&
  169. (!DT || DT->dominates(CastI->getParent(), PredBB)))
  170. return CastI;
  171. }
  172. return nullptr;
  173. }
  174. // Handle getelementptr with at least one PHI translatable operand.
  175. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
  176. SmallVector<Value*, 8> GEPOps;
  177. bool AnyChanged = false;
  178. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
  179. Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
  180. if (!GEPOp) return nullptr;
  181. AnyChanged |= GEPOp != GEP->getOperand(i);
  182. GEPOps.push_back(GEPOp);
  183. }
  184. if (!AnyChanged)
  185. return GEP;
  186. // Simplify the GEP to handle 'gep x, 0' -> x etc.
  187. if (Value *V = simplifyGEPInst(GEP->getSourceElementType(), GEPOps[0],
  188. ArrayRef<Value *>(GEPOps).slice(1),
  189. GEP->isInBounds(), {DL, TLI, DT, AC})) {
  190. for (unsigned i = 0, e = GEPOps.size(); i != e; ++i)
  191. RemoveInstInputs(GEPOps[i], InstInputs);
  192. return AddAsInput(V);
  193. }
  194. // Scan to see if we have this GEP available.
  195. Value *APHIOp = GEPOps[0];
  196. for (User *U : APHIOp->users()) {
  197. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
  198. if (GEPI->getType() == GEP->getType() &&
  199. GEPI->getSourceElementType() == GEP->getSourceElementType() &&
  200. GEPI->getNumOperands() == GEPOps.size() &&
  201. GEPI->getParent()->getParent() == CurBB->getParent() &&
  202. (!DT || DT->dominates(GEPI->getParent(), PredBB))) {
  203. if (std::equal(GEPOps.begin(), GEPOps.end(), GEPI->op_begin()))
  204. return GEPI;
  205. }
  206. }
  207. return nullptr;
  208. }
  209. // Handle add with a constant RHS.
  210. if (Inst->getOpcode() == Instruction::Add &&
  211. isa<ConstantInt>(Inst->getOperand(1))) {
  212. // PHI translate the LHS.
  213. Constant *RHS = cast<ConstantInt>(Inst->getOperand(1));
  214. bool isNSW = cast<BinaryOperator>(Inst)->hasNoSignedWrap();
  215. bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
  216. Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
  217. if (!LHS) return nullptr;
  218. // If the PHI translated LHS is an add of a constant, fold the immediates.
  219. if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
  220. if (BOp->getOpcode() == Instruction::Add)
  221. if (ConstantInt *CI = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
  222. LHS = BOp->getOperand(0);
  223. RHS = ConstantExpr::getAdd(RHS, CI);
  224. isNSW = isNUW = false;
  225. // If the old 'LHS' was an input, add the new 'LHS' as an input.
  226. if (is_contained(InstInputs, BOp)) {
  227. RemoveInstInputs(BOp, InstInputs);
  228. AddAsInput(LHS);
  229. }
  230. }
  231. // See if the add simplifies away.
  232. if (Value *Res = simplifyAddInst(LHS, RHS, isNSW, isNUW, {DL, TLI, DT, AC})) {
  233. // If we simplified the operands, the LHS is no longer an input, but Res
  234. // is.
  235. RemoveInstInputs(LHS, InstInputs);
  236. return AddAsInput(Res);
  237. }
  238. // If we didn't modify the add, just return it.
  239. if (LHS == Inst->getOperand(0) && RHS == Inst->getOperand(1))
  240. return Inst;
  241. // Otherwise, see if we have this add available somewhere.
  242. for (User *U : LHS->users()) {
  243. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U))
  244. if (BO->getOpcode() == Instruction::Add &&
  245. BO->getOperand(0) == LHS && BO->getOperand(1) == RHS &&
  246. BO->getParent()->getParent() == CurBB->getParent() &&
  247. (!DT || DT->dominates(BO->getParent(), PredBB)))
  248. return BO;
  249. }
  250. return nullptr;
  251. }
  252. // Otherwise, we failed.
  253. return nullptr;
  254. }
  255. /// PHITranslateValue - PHI translate the current address up the CFG from
  256. /// CurBB to Pred, updating our state to reflect any needed changes. If
  257. /// 'MustDominate' is true, the translated value must dominate
  258. /// PredBB. This returns true on failure and sets Addr to null.
  259. bool PHITransAddr::PHITranslateValue(BasicBlock *CurBB, BasicBlock *PredBB,
  260. const DominatorTree *DT,
  261. bool MustDominate) {
  262. assert(DT || !MustDominate);
  263. assert(Verify() && "Invalid PHITransAddr!");
  264. if (DT && DT->isReachableFromEntry(PredBB))
  265. Addr = PHITranslateSubExpr(Addr, CurBB, PredBB, DT);
  266. else
  267. Addr = nullptr;
  268. assert(Verify() && "Invalid PHITransAddr!");
  269. if (MustDominate)
  270. // Make sure the value is live in the predecessor.
  271. if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
  272. if (!DT->dominates(Inst->getParent(), PredBB))
  273. Addr = nullptr;
  274. return Addr == nullptr;
  275. }
  276. /// PHITranslateWithInsertion - PHI translate this value into the specified
  277. /// predecessor block, inserting a computation of the value if it is
  278. /// unavailable.
  279. ///
  280. /// All newly created instructions are added to the NewInsts list. This
  281. /// returns null on failure.
  282. ///
  283. Value *PHITransAddr::
  284. PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
  285. const DominatorTree &DT,
  286. SmallVectorImpl<Instruction*> &NewInsts) {
  287. unsigned NISize = NewInsts.size();
  288. // Attempt to PHI translate with insertion.
  289. Addr = InsertPHITranslatedSubExpr(Addr, CurBB, PredBB, DT, NewInsts);
  290. // If successful, return the new value.
  291. if (Addr) return Addr;
  292. // If not, destroy any intermediate instructions inserted.
  293. while (NewInsts.size() != NISize)
  294. NewInsts.pop_back_val()->eraseFromParent();
  295. return nullptr;
  296. }
  297. /// InsertPHITranslatedPointer - Insert a computation of the PHI translated
  298. /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
  299. /// block. All newly created instructions are added to the NewInsts list.
  300. /// This returns null on failure.
  301. ///
  302. Value *PHITransAddr::
  303. InsertPHITranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
  304. BasicBlock *PredBB, const DominatorTree &DT,
  305. SmallVectorImpl<Instruction*> &NewInsts) {
  306. // See if we have a version of this value already available and dominating
  307. // PredBB. If so, there is no need to insert a new instance of it.
  308. PHITransAddr Tmp(InVal, DL, AC);
  309. if (!Tmp.PHITranslateValue(CurBB, PredBB, &DT, /*MustDominate=*/true))
  310. return Tmp.getAddr();
  311. // We don't need to PHI translate values which aren't instructions.
  312. auto *Inst = dyn_cast<Instruction>(InVal);
  313. if (!Inst)
  314. return nullptr;
  315. // Handle cast of PHI translatable value.
  316. if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
  317. if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
  318. Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
  319. CurBB, PredBB, DT, NewInsts);
  320. if (!OpVal) return nullptr;
  321. // Otherwise insert a cast at the end of PredBB.
  322. CastInst *New = CastInst::Create(Cast->getOpcode(), OpVal, InVal->getType(),
  323. InVal->getName() + ".phi.trans.insert",
  324. PredBB->getTerminator());
  325. New->setDebugLoc(Inst->getDebugLoc());
  326. NewInsts.push_back(New);
  327. return New;
  328. }
  329. // Handle getelementptr with at least one PHI operand.
  330. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
  331. SmallVector<Value*, 8> GEPOps;
  332. BasicBlock *CurBB = GEP->getParent();
  333. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
  334. Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
  335. CurBB, PredBB, DT, NewInsts);
  336. if (!OpVal) return nullptr;
  337. GEPOps.push_back(OpVal);
  338. }
  339. GetElementPtrInst *Result = GetElementPtrInst::Create(
  340. GEP->getSourceElementType(), GEPOps[0], ArrayRef(GEPOps).slice(1),
  341. InVal->getName() + ".phi.trans.insert", PredBB->getTerminator());
  342. Result->setDebugLoc(Inst->getDebugLoc());
  343. Result->setIsInBounds(GEP->isInBounds());
  344. NewInsts.push_back(Result);
  345. return Result;
  346. }
  347. // Handle add with a constant RHS.
  348. if (EnableAddPhiTranslation && Inst->getOpcode() == Instruction::Add &&
  349. isa<ConstantInt>(Inst->getOperand(1))) {
  350. // FIXME: This code works, but it is unclear that we actually want to insert
  351. // a big chain of computation in order to make a value available in a block.
  352. // This needs to be evaluated carefully to consider its cost trade offs.
  353. // PHI translate the LHS.
  354. Value *OpVal = InsertPHITranslatedSubExpr(Inst->getOperand(0),
  355. CurBB, PredBB, DT, NewInsts);
  356. if (OpVal == nullptr)
  357. return nullptr;
  358. BinaryOperator *Res = BinaryOperator::CreateAdd(OpVal, Inst->getOperand(1),
  359. InVal->getName()+".phi.trans.insert",
  360. PredBB->getTerminator());
  361. Res->setHasNoSignedWrap(cast<BinaryOperator>(Inst)->hasNoSignedWrap());
  362. Res->setHasNoUnsignedWrap(cast<BinaryOperator>(Inst)->hasNoUnsignedWrap());
  363. NewInsts.push_back(Res);
  364. return Res;
  365. }
  366. return nullptr;
  367. }