PHITransAddr.cpp 16 KB

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