SCCP.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
  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 sparse conditional constant propagation and merging:
  11. //
  12. // Specifically, this:
  13. // * Assumes values are constant unless proven otherwise
  14. // * Assumes BasicBlocks are dead unless proven otherwise
  15. // * Proves values to be constant, and replaces them with constants
  16. // * Proves conditional branches to be unconditional
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/Transforms/Scalar.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/ADT/PointerIntPair.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/Analysis/ConstantFolding.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/IR/CallSite.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/DerivedTypes.h"
  32. #include "llvm/IR/InstVisitor.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/IPO.h"
  39. #include "llvm/Transforms/Utils/Local.h"
  40. #include <algorithm>
  41. using namespace llvm;
  42. #define DEBUG_TYPE "sccp"
  43. STATISTIC(NumInstRemoved, "Number of instructions removed");
  44. STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
  45. STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
  46. STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
  47. STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
  48. namespace {
  49. /// LatticeVal class - This class represents the different lattice values that
  50. /// an LLVM value may occupy. It is a simple class with value semantics.
  51. ///
  52. class LatticeVal {
  53. enum LatticeValueTy {
  54. /// undefined - This LLVM Value has no known value yet.
  55. undefined,
  56. /// constant - This LLVM Value has a specific constant value.
  57. constant,
  58. /// forcedconstant - This LLVM Value was thought to be undef until
  59. /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
  60. /// with another (different) constant, it goes to overdefined, instead of
  61. /// asserting.
  62. forcedconstant,
  63. /// overdefined - This instruction is not known to be constant, and we know
  64. /// it has a value.
  65. overdefined
  66. };
  67. /// Val: This stores the current lattice value along with the Constant* for
  68. /// the constant if this is a 'constant' or 'forcedconstant' value.
  69. PointerIntPair<Constant *, 2, LatticeValueTy> Val;
  70. LatticeValueTy getLatticeValue() const {
  71. return Val.getInt();
  72. }
  73. public:
  74. LatticeVal() : Val(nullptr, undefined) {}
  75. bool isUndefined() const { return getLatticeValue() == undefined; }
  76. bool isConstant() const {
  77. return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
  78. }
  79. bool isOverdefined() const { return getLatticeValue() == overdefined; }
  80. Constant *getConstant() const {
  81. assert(isConstant() && "Cannot get the constant of a non-constant!");
  82. return Val.getPointer();
  83. }
  84. /// markOverdefined - Return true if this is a change in status.
  85. bool markOverdefined() {
  86. if (isOverdefined())
  87. return false;
  88. Val.setInt(overdefined);
  89. return true;
  90. }
  91. /// markConstant - Return true if this is a change in status.
  92. bool markConstant(Constant *V) {
  93. if (getLatticeValue() == constant) { // Constant but not forcedconstant.
  94. assert(getConstant() == V && "Marking constant with different value");
  95. return false;
  96. }
  97. if (isUndefined()) {
  98. Val.setInt(constant);
  99. assert(V && "Marking constant with NULL");
  100. Val.setPointer(V);
  101. } else {
  102. assert(getLatticeValue() == forcedconstant &&
  103. "Cannot move from overdefined to constant!");
  104. // Stay at forcedconstant if the constant is the same.
  105. if (V == getConstant()) return false;
  106. // Otherwise, we go to overdefined. Assumptions made based on the
  107. // forced value are possibly wrong. Assuming this is another constant
  108. // could expose a contradiction.
  109. Val.setInt(overdefined);
  110. }
  111. return true;
  112. }
  113. /// getConstantInt - If this is a constant with a ConstantInt value, return it
  114. /// otherwise return null.
  115. ConstantInt *getConstantInt() const {
  116. if (isConstant())
  117. return dyn_cast<ConstantInt>(getConstant());
  118. return nullptr;
  119. }
  120. void markForcedConstant(Constant *V) {
  121. assert(isUndefined() && "Can't force a defined value!");
  122. Val.setInt(forcedconstant);
  123. Val.setPointer(V);
  124. }
  125. };
  126. } // end anonymous namespace.
  127. namespace {
  128. //===----------------------------------------------------------------------===//
  129. //
  130. /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
  131. /// Constant Propagation.
  132. ///
  133. class SCCPSolver : public InstVisitor<SCCPSolver> {
  134. const DataLayout &DL;
  135. const TargetLibraryInfo *TLI;
  136. SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
  137. DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
  138. /// StructValueState - This maintains ValueState for values that have
  139. /// StructType, for example for formal arguments, calls, insertelement, etc.
  140. ///
  141. DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
  142. /// GlobalValue - If we are tracking any values for the contents of a global
  143. /// variable, we keep a mapping from the constant accessor to the element of
  144. /// the global, to the currently known value. If the value becomes
  145. /// overdefined, it's entry is simply removed from this map.
  146. DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
  147. /// TrackedRetVals - If we are tracking arguments into and the return
  148. /// value out of a function, it will have an entry in this map, indicating
  149. /// what the known return value for the function is.
  150. DenseMap<Function*, LatticeVal> TrackedRetVals;
  151. /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
  152. /// that return multiple values.
  153. DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
  154. /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
  155. /// represented here for efficient lookup.
  156. SmallPtrSet<Function*, 16> MRVFunctionsTracked;
  157. /// TrackingIncomingArguments - This is the set of functions for whose
  158. /// arguments we make optimistic assumptions about and try to prove as
  159. /// constants.
  160. SmallPtrSet<Function*, 16> TrackingIncomingArguments;
  161. /// The reason for two worklists is that overdefined is the lowest state
  162. /// on the lattice, and moving things to overdefined as fast as possible
  163. /// makes SCCP converge much faster.
  164. ///
  165. /// By having a separate worklist, we accomplish this because everything
  166. /// possibly overdefined will become overdefined at the soonest possible
  167. /// point.
  168. SmallVector<Value*, 64> OverdefinedInstWorkList;
  169. SmallVector<Value*, 64> InstWorkList;
  170. SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
  171. /// KnownFeasibleEdges - Entries in this set are edges which have already had
  172. /// PHI nodes retriggered.
  173. typedef std::pair<BasicBlock*, BasicBlock*> Edge;
  174. DenseSet<Edge> KnownFeasibleEdges;
  175. public:
  176. SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
  177. : DL(DL), TLI(tli) {}
  178. /// MarkBlockExecutable - This method can be used by clients to mark all of
  179. /// the blocks that are known to be intrinsically live in the processed unit.
  180. ///
  181. /// This returns true if the block was not considered live before.
  182. bool MarkBlockExecutable(BasicBlock *BB) {
  183. if (!BBExecutable.insert(BB).second)
  184. return false;
  185. DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
  186. BBWorkList.push_back(BB); // Add the block to the work list!
  187. return true;
  188. }
  189. /// TrackValueOfGlobalVariable - Clients can use this method to
  190. /// inform the SCCPSolver that it should track loads and stores to the
  191. /// specified global variable if it can. This is only legal to call if
  192. /// performing Interprocedural SCCP.
  193. void TrackValueOfGlobalVariable(GlobalVariable *GV) {
  194. // We only track the contents of scalar globals.
  195. if (GV->getType()->getElementType()->isSingleValueType()) {
  196. LatticeVal &IV = TrackedGlobals[GV];
  197. if (!isa<UndefValue>(GV->getInitializer()))
  198. IV.markConstant(GV->getInitializer());
  199. }
  200. }
  201. /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
  202. /// and out of the specified function (which cannot have its address taken),
  203. /// this method must be called.
  204. void AddTrackedFunction(Function *F) {
  205. // Add an entry, F -> undef.
  206. if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
  207. MRVFunctionsTracked.insert(F);
  208. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  209. TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
  210. LatticeVal()));
  211. } else
  212. TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
  213. }
  214. void AddArgumentTrackedFunction(Function *F) {
  215. TrackingIncomingArguments.insert(F);
  216. }
  217. /// Solve - Solve for constants and executable blocks.
  218. ///
  219. void Solve();
  220. /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
  221. /// that branches on undef values cannot reach any of their successors.
  222. /// However, this is not a safe assumption. After we solve dataflow, this
  223. /// method should be use to handle this. If this returns true, the solver
  224. /// should be rerun.
  225. bool ResolvedUndefsIn(Function &F);
  226. bool isBlockExecutable(BasicBlock *BB) const {
  227. return BBExecutable.count(BB);
  228. }
  229. LatticeVal getLatticeValueFor(Value *V) const {
  230. DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
  231. assert(I != ValueState.end() && "V is not in valuemap!");
  232. return I->second;
  233. }
  234. /// getTrackedRetVals - Get the inferred return value map.
  235. ///
  236. const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
  237. return TrackedRetVals;
  238. }
  239. /// getTrackedGlobals - Get and return the set of inferred initializers for
  240. /// global variables.
  241. const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
  242. return TrackedGlobals;
  243. }
  244. void markOverdefined(Value *V) {
  245. assert(!V->getType()->isStructTy() && "Should use other method");
  246. markOverdefined(ValueState[V], V);
  247. }
  248. /// markAnythingOverdefined - Mark the specified value overdefined. This
  249. /// works with both scalars and structs.
  250. void markAnythingOverdefined(Value *V) {
  251. if (StructType *STy = dyn_cast<StructType>(V->getType()))
  252. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  253. markOverdefined(getStructValueState(V, i), V);
  254. else
  255. markOverdefined(V);
  256. }
  257. private:
  258. // markConstant - Make a value be marked as "constant". If the value
  259. // is not already a constant, add it to the instruction work list so that
  260. // the users of the instruction are updated later.
  261. //
  262. void markConstant(LatticeVal &IV, Value *V, Constant *C) {
  263. if (!IV.markConstant(C)) return;
  264. DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
  265. if (IV.isOverdefined())
  266. OverdefinedInstWorkList.push_back(V);
  267. else
  268. InstWorkList.push_back(V);
  269. }
  270. void markConstant(Value *V, Constant *C) {
  271. assert(!V->getType()->isStructTy() && "Should use other method");
  272. markConstant(ValueState[V], V, C);
  273. }
  274. void markForcedConstant(Value *V, Constant *C) {
  275. assert(!V->getType()->isStructTy() && "Should use other method");
  276. LatticeVal &IV = ValueState[V];
  277. IV.markForcedConstant(C);
  278. DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
  279. if (IV.isOverdefined())
  280. OverdefinedInstWorkList.push_back(V);
  281. else
  282. InstWorkList.push_back(V);
  283. }
  284. // markOverdefined - Make a value be marked as "overdefined". If the
  285. // value is not already overdefined, add it to the overdefined instruction
  286. // work list so that the users of the instruction are updated later.
  287. void markOverdefined(LatticeVal &IV, Value *V) {
  288. if (!IV.markOverdefined()) return;
  289. DEBUG(dbgs() << "markOverdefined: ";
  290. if (Function *F = dyn_cast<Function>(V))
  291. dbgs() << "Function '" << F->getName() << "'\n";
  292. else
  293. dbgs() << *V << '\n');
  294. // Only instructions go on the work list
  295. OverdefinedInstWorkList.push_back(V);
  296. }
  297. void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
  298. if (IV.isOverdefined() || MergeWithV.isUndefined())
  299. return; // Noop.
  300. if (MergeWithV.isOverdefined())
  301. markOverdefined(IV, V);
  302. else if (IV.isUndefined())
  303. markConstant(IV, V, MergeWithV.getConstant());
  304. else if (IV.getConstant() != MergeWithV.getConstant())
  305. markOverdefined(IV, V);
  306. }
  307. void mergeInValue(Value *V, LatticeVal MergeWithV) {
  308. assert(!V->getType()->isStructTy() && "Should use other method");
  309. mergeInValue(ValueState[V], V, MergeWithV);
  310. }
  311. /// getValueState - Return the LatticeVal object that corresponds to the
  312. /// value. This function handles the case when the value hasn't been seen yet
  313. /// by properly seeding constants etc.
  314. LatticeVal &getValueState(Value *V) {
  315. assert(!V->getType()->isStructTy() && "Should use getStructValueState");
  316. std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
  317. ValueState.insert(std::make_pair(V, LatticeVal()));
  318. LatticeVal &LV = I.first->second;
  319. if (!I.second)
  320. return LV; // Common case, already in the map.
  321. if (Constant *C = dyn_cast<Constant>(V)) {
  322. // Undef values remain undefined.
  323. if (!isa<UndefValue>(V))
  324. LV.markConstant(C); // Constants are constant
  325. }
  326. // All others are underdefined by default.
  327. return LV;
  328. }
  329. /// getStructValueState - Return the LatticeVal object that corresponds to the
  330. /// value/field pair. This function handles the case when the value hasn't
  331. /// been seen yet by properly seeding constants etc.
  332. LatticeVal &getStructValueState(Value *V, unsigned i) {
  333. assert(V->getType()->isStructTy() && "Should use getValueState");
  334. assert(i < cast<StructType>(V->getType())->getNumElements() &&
  335. "Invalid element #");
  336. std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
  337. bool> I = StructValueState.insert(
  338. std::make_pair(std::make_pair(V, i), LatticeVal()));
  339. LatticeVal &LV = I.first->second;
  340. if (!I.second)
  341. return LV; // Common case, already in the map.
  342. if (Constant *C = dyn_cast<Constant>(V)) {
  343. Constant *Elt = C->getAggregateElement(i);
  344. if (!Elt)
  345. LV.markOverdefined(); // Unknown sort of constant.
  346. else if (isa<UndefValue>(Elt))
  347. ; // Undef values remain undefined.
  348. else
  349. LV.markConstant(Elt); // Constants are constant.
  350. }
  351. // All others are underdefined by default.
  352. return LV;
  353. }
  354. /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
  355. /// work list if it is not already executable.
  356. void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
  357. if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
  358. return; // This edge is already known to be executable!
  359. if (!MarkBlockExecutable(Dest)) {
  360. // If the destination is already executable, we just made an *edge*
  361. // feasible that wasn't before. Revisit the PHI nodes in the block
  362. // because they have potentially new operands.
  363. DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
  364. << " -> " << Dest->getName() << '\n');
  365. PHINode *PN;
  366. for (BasicBlock::iterator I = Dest->begin();
  367. (PN = dyn_cast<PHINode>(I)); ++I)
  368. visitPHINode(*PN);
  369. }
  370. }
  371. // getFeasibleSuccessors - Return a vector of booleans to indicate which
  372. // successors are reachable from a given terminator instruction.
  373. //
  374. void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
  375. // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
  376. // block to the 'To' basic block is currently feasible.
  377. //
  378. bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
  379. // OperandChangedState - This method is invoked on all of the users of an
  380. // instruction that was just changed state somehow. Based on this
  381. // information, we need to update the specified user of this instruction.
  382. //
  383. void OperandChangedState(Instruction *I) {
  384. if (BBExecutable.count(I->getParent())) // Inst is executable?
  385. visit(*I);
  386. }
  387. private:
  388. friend class InstVisitor<SCCPSolver>;
  389. // visit implementations - Something changed in this instruction. Either an
  390. // operand made a transition, or the instruction is newly executable. Change
  391. // the value type of I to reflect these changes if appropriate.
  392. void visitPHINode(PHINode &I);
  393. // Terminators
  394. void visitReturnInst(ReturnInst &I);
  395. void visitTerminatorInst(TerminatorInst &TI);
  396. void visitCastInst(CastInst &I);
  397. void visitSelectInst(SelectInst &I);
  398. void visitBinaryOperator(Instruction &I);
  399. void visitCmpInst(CmpInst &I);
  400. void visitExtractElementInst(ExtractElementInst &I);
  401. void visitInsertElementInst(InsertElementInst &I);
  402. void visitShuffleVectorInst(ShuffleVectorInst &I);
  403. void visitExtractValueInst(ExtractValueInst &EVI);
  404. void visitInsertValueInst(InsertValueInst &IVI);
  405. void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
  406. // Instructions that cannot be folded away.
  407. void visitStoreInst (StoreInst &I);
  408. void visitLoadInst (LoadInst &I);
  409. void visitGetElementPtrInst(GetElementPtrInst &I);
  410. void visitCallInst (CallInst &I) {
  411. visitCallSite(&I);
  412. }
  413. void visitInvokeInst (InvokeInst &II) {
  414. visitCallSite(&II);
  415. visitTerminatorInst(II);
  416. }
  417. void visitCallSite (CallSite CS);
  418. void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
  419. void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
  420. void visitFenceInst (FenceInst &I) { /*returns void*/ }
  421. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
  422. markAnythingOverdefined(&I);
  423. }
  424. void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
  425. void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
  426. void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
  427. void visitInstruction(Instruction &I) {
  428. // If a new instruction is added to LLVM that we don't handle.
  429. dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
  430. markAnythingOverdefined(&I); // Just in case
  431. }
  432. };
  433. } // end anonymous namespace
  434. // getFeasibleSuccessors - Return a vector of booleans to indicate which
  435. // successors are reachable from a given terminator instruction.
  436. //
  437. void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
  438. SmallVectorImpl<bool> &Succs) {
  439. Succs.resize(TI.getNumSuccessors());
  440. if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
  441. if (BI->isUnconditional()) {
  442. Succs[0] = true;
  443. return;
  444. }
  445. LatticeVal BCValue = getValueState(BI->getCondition());
  446. ConstantInt *CI = BCValue.getConstantInt();
  447. if (!CI) {
  448. // Overdefined condition variables, and branches on unfoldable constant
  449. // conditions, mean the branch could go either way.
  450. if (!BCValue.isUndefined())
  451. Succs[0] = Succs[1] = true;
  452. return;
  453. }
  454. // Constant condition variables mean the branch can only go a single way.
  455. Succs[CI->isZero()] = true;
  456. return;
  457. }
  458. if (isa<InvokeInst>(TI)) {
  459. // Invoke instructions successors are always executable.
  460. Succs[0] = Succs[1] = true;
  461. return;
  462. }
  463. if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
  464. if (!SI->getNumCases()) {
  465. Succs[0] = true;
  466. return;
  467. }
  468. LatticeVal SCValue = getValueState(SI->getCondition());
  469. ConstantInt *CI = SCValue.getConstantInt();
  470. if (!CI) { // Overdefined or undefined condition?
  471. // All destinations are executable!
  472. if (!SCValue.isUndefined())
  473. Succs.assign(TI.getNumSuccessors(), true);
  474. return;
  475. }
  476. Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
  477. return;
  478. }
  479. // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
  480. if (isa<IndirectBrInst>(&TI)) {
  481. // Just mark all destinations executable!
  482. Succs.assign(TI.getNumSuccessors(), true);
  483. return;
  484. }
  485. #ifndef NDEBUG
  486. dbgs() << "Unknown terminator instruction: " << TI << '\n';
  487. #endif
  488. llvm_unreachable("SCCP: Don't know how to handle this terminator!");
  489. }
  490. // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
  491. // block to the 'To' basic block is currently feasible.
  492. //
  493. bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
  494. assert(BBExecutable.count(To) && "Dest should always be alive!");
  495. // Make sure the source basic block is executable!!
  496. if (!BBExecutable.count(From)) return false;
  497. // Check to make sure this edge itself is actually feasible now.
  498. TerminatorInst *TI = From->getTerminator();
  499. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  500. if (BI->isUnconditional())
  501. return true;
  502. LatticeVal BCValue = getValueState(BI->getCondition());
  503. // Overdefined condition variables mean the branch could go either way,
  504. // undef conditions mean that neither edge is feasible yet.
  505. ConstantInt *CI = BCValue.getConstantInt();
  506. if (!CI)
  507. return !BCValue.isUndefined();
  508. // Constant condition variables mean the branch can only go a single way.
  509. return BI->getSuccessor(CI->isZero()) == To;
  510. }
  511. // Invoke instructions successors are always executable.
  512. if (isa<InvokeInst>(TI))
  513. return true;
  514. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  515. if (SI->getNumCases() < 1)
  516. return true;
  517. LatticeVal SCValue = getValueState(SI->getCondition());
  518. ConstantInt *CI = SCValue.getConstantInt();
  519. if (!CI)
  520. return !SCValue.isUndefined();
  521. return SI->findCaseValue(CI).getCaseSuccessor() == To;
  522. }
  523. // Just mark all destinations executable!
  524. // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
  525. if (isa<IndirectBrInst>(TI))
  526. return true;
  527. #ifndef NDEBUG
  528. dbgs() << "Unknown terminator instruction: " << *TI << '\n';
  529. #endif
  530. llvm_unreachable(nullptr);
  531. }
  532. // visit Implementations - Something changed in this instruction, either an
  533. // operand made a transition, or the instruction is newly executable. Change
  534. // the value type of I to reflect these changes if appropriate. This method
  535. // makes sure to do the following actions:
  536. //
  537. // 1. If a phi node merges two constants in, and has conflicting value coming
  538. // from different branches, or if the PHI node merges in an overdefined
  539. // value, then the PHI node becomes overdefined.
  540. // 2. If a phi node merges only constants in, and they all agree on value, the
  541. // PHI node becomes a constant value equal to that.
  542. // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
  543. // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
  544. // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
  545. // 6. If a conditional branch has a value that is constant, make the selected
  546. // destination executable
  547. // 7. If a conditional branch has a value that is overdefined, make all
  548. // successors executable.
  549. //
  550. void SCCPSolver::visitPHINode(PHINode &PN) {
  551. // If this PN returns a struct, just mark the result overdefined.
  552. // TODO: We could do a lot better than this if code actually uses this.
  553. if (PN.getType()->isStructTy())
  554. return markAnythingOverdefined(&PN);
  555. if (getValueState(&PN).isOverdefined())
  556. return; // Quick exit
  557. // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
  558. // and slow us down a lot. Just mark them overdefined.
  559. if (PN.getNumIncomingValues() > 64)
  560. return markOverdefined(&PN);
  561. // Look at all of the executable operands of the PHI node. If any of them
  562. // are overdefined, the PHI becomes overdefined as well. If they are all
  563. // constant, and they agree with each other, the PHI becomes the identical
  564. // constant. If they are constant and don't agree, the PHI is overdefined.
  565. // If there are no executable operands, the PHI remains undefined.
  566. //
  567. Constant *OperandVal = nullptr;
  568. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  569. LatticeVal IV = getValueState(PN.getIncomingValue(i));
  570. if (IV.isUndefined()) continue; // Doesn't influence PHI node.
  571. if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
  572. continue;
  573. if (IV.isOverdefined()) // PHI node becomes overdefined!
  574. return markOverdefined(&PN);
  575. if (!OperandVal) { // Grab the first value.
  576. OperandVal = IV.getConstant();
  577. continue;
  578. }
  579. // There is already a reachable operand. If we conflict with it,
  580. // then the PHI node becomes overdefined. If we agree with it, we
  581. // can continue on.
  582. // Check to see if there are two different constants merging, if so, the PHI
  583. // node is overdefined.
  584. if (IV.getConstant() != OperandVal)
  585. return markOverdefined(&PN);
  586. }
  587. // If we exited the loop, this means that the PHI node only has constant
  588. // arguments that agree with each other(and OperandVal is the constant) or
  589. // OperandVal is null because there are no defined incoming arguments. If
  590. // this is the case, the PHI remains undefined.
  591. //
  592. if (OperandVal)
  593. markConstant(&PN, OperandVal); // Acquire operand value
  594. }
  595. void SCCPSolver::visitReturnInst(ReturnInst &I) {
  596. if (I.getNumOperands() == 0) return; // ret void
  597. Function *F = I.getParent()->getParent();
  598. Value *ResultOp = I.getOperand(0);
  599. // If we are tracking the return value of this function, merge it in.
  600. if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
  601. DenseMap<Function*, LatticeVal>::iterator TFRVI =
  602. TrackedRetVals.find(F);
  603. if (TFRVI != TrackedRetVals.end()) {
  604. mergeInValue(TFRVI->second, F, getValueState(ResultOp));
  605. return;
  606. }
  607. }
  608. // Handle functions that return multiple values.
  609. if (!TrackedMultipleRetVals.empty()) {
  610. if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
  611. if (MRVFunctionsTracked.count(F))
  612. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  613. mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
  614. getStructValueState(ResultOp, i));
  615. }
  616. }
  617. void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
  618. SmallVector<bool, 16> SuccFeasible;
  619. getFeasibleSuccessors(TI, SuccFeasible);
  620. BasicBlock *BB = TI.getParent();
  621. // Mark all feasible successors executable.
  622. for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
  623. if (SuccFeasible[i])
  624. markEdgeExecutable(BB, TI.getSuccessor(i));
  625. }
  626. void SCCPSolver::visitCastInst(CastInst &I) {
  627. LatticeVal OpSt = getValueState(I.getOperand(0));
  628. if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
  629. markOverdefined(&I);
  630. else if (OpSt.isConstant()) // Propagate constant value
  631. markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
  632. OpSt.getConstant(), I.getType()));
  633. }
  634. void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
  635. // If this returns a struct, mark all elements over defined, we don't track
  636. // structs in structs.
  637. if (EVI.getType()->isStructTy())
  638. return markAnythingOverdefined(&EVI);
  639. // If this is extracting from more than one level of struct, we don't know.
  640. if (EVI.getNumIndices() != 1)
  641. return markOverdefined(&EVI);
  642. Value *AggVal = EVI.getAggregateOperand();
  643. if (AggVal->getType()->isStructTy()) {
  644. unsigned i = *EVI.idx_begin();
  645. LatticeVal EltVal = getStructValueState(AggVal, i);
  646. mergeInValue(getValueState(&EVI), &EVI, EltVal);
  647. } else {
  648. // Otherwise, must be extracting from an array.
  649. return markOverdefined(&EVI);
  650. }
  651. }
  652. void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
  653. StructType *STy = dyn_cast<StructType>(IVI.getType());
  654. if (!STy)
  655. return markOverdefined(&IVI);
  656. // If this has more than one index, we can't handle it, drive all results to
  657. // undef.
  658. if (IVI.getNumIndices() != 1)
  659. return markAnythingOverdefined(&IVI);
  660. Value *Aggr = IVI.getAggregateOperand();
  661. unsigned Idx = *IVI.idx_begin();
  662. // Compute the result based on what we're inserting.
  663. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  664. // This passes through all values that aren't the inserted element.
  665. if (i != Idx) {
  666. LatticeVal EltVal = getStructValueState(Aggr, i);
  667. mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
  668. continue;
  669. }
  670. Value *Val = IVI.getInsertedValueOperand();
  671. if (Val->getType()->isStructTy())
  672. // We don't track structs in structs.
  673. markOverdefined(getStructValueState(&IVI, i), &IVI);
  674. else {
  675. LatticeVal InVal = getValueState(Val);
  676. mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
  677. }
  678. }
  679. }
  680. void SCCPSolver::visitSelectInst(SelectInst &I) {
  681. // If this select returns a struct, just mark the result overdefined.
  682. // TODO: We could do a lot better than this if code actually uses this.
  683. if (I.getType()->isStructTy())
  684. return markAnythingOverdefined(&I);
  685. LatticeVal CondValue = getValueState(I.getCondition());
  686. if (CondValue.isUndefined())
  687. return;
  688. if (ConstantInt *CondCB = CondValue.getConstantInt()) {
  689. Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
  690. mergeInValue(&I, getValueState(OpVal));
  691. return;
  692. }
  693. // Otherwise, the condition is overdefined or a constant we can't evaluate.
  694. // See if we can produce something better than overdefined based on the T/F
  695. // value.
  696. LatticeVal TVal = getValueState(I.getTrueValue());
  697. LatticeVal FVal = getValueState(I.getFalseValue());
  698. // select ?, C, C -> C.
  699. if (TVal.isConstant() && FVal.isConstant() &&
  700. TVal.getConstant() == FVal.getConstant())
  701. return markConstant(&I, FVal.getConstant());
  702. if (TVal.isUndefined()) // select ?, undef, X -> X.
  703. return mergeInValue(&I, FVal);
  704. if (FVal.isUndefined()) // select ?, X, undef -> X.
  705. return mergeInValue(&I, TVal);
  706. markOverdefined(&I);
  707. }
  708. // Handle Binary Operators.
  709. void SCCPSolver::visitBinaryOperator(Instruction &I) {
  710. LatticeVal V1State = getValueState(I.getOperand(0));
  711. LatticeVal V2State = getValueState(I.getOperand(1));
  712. LatticeVal &IV = ValueState[&I];
  713. if (IV.isOverdefined()) return;
  714. if (V1State.isConstant() && V2State.isConstant())
  715. return markConstant(IV, &I,
  716. ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
  717. V2State.getConstant()));
  718. // If something is undef, wait for it to resolve.
  719. if (!V1State.isOverdefined() && !V2State.isOverdefined())
  720. return;
  721. // Otherwise, one of our operands is overdefined. Try to produce something
  722. // better than overdefined with some tricks.
  723. // If this is an AND or OR with 0 or -1, it doesn't matter that the other
  724. // operand is overdefined.
  725. if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
  726. LatticeVal *NonOverdefVal = nullptr;
  727. if (!V1State.isOverdefined())
  728. NonOverdefVal = &V1State;
  729. else if (!V2State.isOverdefined())
  730. NonOverdefVal = &V2State;
  731. if (NonOverdefVal) {
  732. if (NonOverdefVal->isUndefined()) {
  733. // Could annihilate value.
  734. if (I.getOpcode() == Instruction::And)
  735. markConstant(IV, &I, Constant::getNullValue(I.getType()));
  736. else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
  737. markConstant(IV, &I, Constant::getAllOnesValue(PT));
  738. else
  739. markConstant(IV, &I,
  740. Constant::getAllOnesValue(I.getType()));
  741. return;
  742. }
  743. if (I.getOpcode() == Instruction::And) {
  744. // X and 0 = 0
  745. if (NonOverdefVal->getConstant()->isNullValue())
  746. return markConstant(IV, &I, NonOverdefVal->getConstant());
  747. } else {
  748. if (ConstantInt *CI = NonOverdefVal->getConstantInt())
  749. if (CI->isAllOnesValue()) // X or -1 = -1
  750. return markConstant(IV, &I, NonOverdefVal->getConstant());
  751. }
  752. }
  753. }
  754. markOverdefined(&I);
  755. }
  756. // Handle ICmpInst instruction.
  757. void SCCPSolver::visitCmpInst(CmpInst &I) {
  758. LatticeVal V1State = getValueState(I.getOperand(0));
  759. LatticeVal V2State = getValueState(I.getOperand(1));
  760. LatticeVal &IV = ValueState[&I];
  761. if (IV.isOverdefined()) return;
  762. if (V1State.isConstant() && V2State.isConstant())
  763. return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
  764. V1State.getConstant(),
  765. V2State.getConstant()));
  766. // If operands are still undefined, wait for it to resolve.
  767. if (!V1State.isOverdefined() && !V2State.isOverdefined())
  768. return;
  769. markOverdefined(&I);
  770. }
  771. void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
  772. // TODO : SCCP does not handle vectors properly.
  773. return markOverdefined(&I);
  774. #if 0
  775. LatticeVal &ValState = getValueState(I.getOperand(0));
  776. LatticeVal &IdxState = getValueState(I.getOperand(1));
  777. if (ValState.isOverdefined() || IdxState.isOverdefined())
  778. markOverdefined(&I);
  779. else if(ValState.isConstant() && IdxState.isConstant())
  780. markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
  781. IdxState.getConstant()));
  782. #endif
  783. }
  784. void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
  785. // TODO : SCCP does not handle vectors properly.
  786. return markOverdefined(&I);
  787. #if 0
  788. LatticeVal &ValState = getValueState(I.getOperand(0));
  789. LatticeVal &EltState = getValueState(I.getOperand(1));
  790. LatticeVal &IdxState = getValueState(I.getOperand(2));
  791. if (ValState.isOverdefined() || EltState.isOverdefined() ||
  792. IdxState.isOverdefined())
  793. markOverdefined(&I);
  794. else if(ValState.isConstant() && EltState.isConstant() &&
  795. IdxState.isConstant())
  796. markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
  797. EltState.getConstant(),
  798. IdxState.getConstant()));
  799. else if (ValState.isUndefined() && EltState.isConstant() &&
  800. IdxState.isConstant())
  801. markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
  802. EltState.getConstant(),
  803. IdxState.getConstant()));
  804. #endif
  805. }
  806. void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
  807. // TODO : SCCP does not handle vectors properly.
  808. return markOverdefined(&I);
  809. #if 0
  810. LatticeVal &V1State = getValueState(I.getOperand(0));
  811. LatticeVal &V2State = getValueState(I.getOperand(1));
  812. LatticeVal &MaskState = getValueState(I.getOperand(2));
  813. if (MaskState.isUndefined() ||
  814. (V1State.isUndefined() && V2State.isUndefined()))
  815. return; // Undefined output if mask or both inputs undefined.
  816. if (V1State.isOverdefined() || V2State.isOverdefined() ||
  817. MaskState.isOverdefined()) {
  818. markOverdefined(&I);
  819. } else {
  820. // A mix of constant/undef inputs.
  821. Constant *V1 = V1State.isConstant() ?
  822. V1State.getConstant() : UndefValue::get(I.getType());
  823. Constant *V2 = V2State.isConstant() ?
  824. V2State.getConstant() : UndefValue::get(I.getType());
  825. Constant *Mask = MaskState.isConstant() ?
  826. MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
  827. markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
  828. }
  829. #endif
  830. }
  831. // Handle getelementptr instructions. If all operands are constants then we
  832. // can turn this into a getelementptr ConstantExpr.
  833. //
  834. void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
  835. if (ValueState[&I].isOverdefined()) return;
  836. SmallVector<Constant*, 8> Operands;
  837. Operands.reserve(I.getNumOperands());
  838. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  839. LatticeVal State = getValueState(I.getOperand(i));
  840. if (State.isUndefined())
  841. return; // Operands are not resolved yet.
  842. if (State.isOverdefined())
  843. return markOverdefined(&I);
  844. assert(State.isConstant() && "Unknown state!");
  845. Operands.push_back(State.getConstant());
  846. }
  847. Constant *Ptr = Operands[0];
  848. auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
  849. markConstant(&I, ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr,
  850. Indices));
  851. }
  852. void SCCPSolver::visitStoreInst(StoreInst &SI) {
  853. // If this store is of a struct, ignore it.
  854. if (SI.getOperand(0)->getType()->isStructTy())
  855. return;
  856. if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
  857. return;
  858. GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
  859. DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
  860. if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
  861. // Get the value we are storing into the global, then merge it.
  862. mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
  863. if (I->second.isOverdefined())
  864. TrackedGlobals.erase(I); // No need to keep tracking this!
  865. }
  866. // Handle load instructions. If the operand is a constant pointer to a constant
  867. // global, we can replace the load with the loaded constant value!
  868. void SCCPSolver::visitLoadInst(LoadInst &I) {
  869. // If this load is of a struct, just mark the result overdefined.
  870. if (I.getType()->isStructTy())
  871. return markAnythingOverdefined(&I);
  872. LatticeVal PtrVal = getValueState(I.getOperand(0));
  873. if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
  874. LatticeVal &IV = ValueState[&I];
  875. if (IV.isOverdefined()) return;
  876. if (!PtrVal.isConstant() || I.isVolatile())
  877. return markOverdefined(IV, &I);
  878. Constant *Ptr = PtrVal.getConstant();
  879. // load null -> null
  880. if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
  881. return markConstant(IV, &I, UndefValue::get(I.getType()));
  882. // Transform load (constant global) into the value loaded.
  883. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
  884. if (!TrackedGlobals.empty()) {
  885. // If we are tracking this global, merge in the known value for it.
  886. DenseMap<GlobalVariable*, LatticeVal>::iterator It =
  887. TrackedGlobals.find(GV);
  888. if (It != TrackedGlobals.end()) {
  889. mergeInValue(IV, &I, It->second);
  890. return;
  891. }
  892. }
  893. }
  894. // Transform load from a constant into a constant if possible.
  895. if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
  896. return markConstant(IV, &I, C);
  897. // Otherwise we cannot say for certain what value this load will produce.
  898. // Bail out.
  899. markOverdefined(IV, &I);
  900. }
  901. void SCCPSolver::visitCallSite(CallSite CS) {
  902. Function *F = CS.getCalledFunction();
  903. Instruction *I = CS.getInstruction();
  904. // The common case is that we aren't tracking the callee, either because we
  905. // are not doing interprocedural analysis or the callee is indirect, or is
  906. // external. Handle these cases first.
  907. if (!F || F->isDeclaration()) {
  908. CallOverdefined:
  909. // Void return and not tracking callee, just bail.
  910. if (I->getType()->isVoidTy()) return;
  911. // Otherwise, if we have a single return value case, and if the function is
  912. // a declaration, maybe we can constant fold it.
  913. if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
  914. canConstantFoldCallTo(F)) {
  915. SmallVector<Constant*, 8> Operands;
  916. for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
  917. AI != E; ++AI) {
  918. LatticeVal State = getValueState(*AI);
  919. if (State.isUndefined())
  920. return; // Operands are not resolved yet.
  921. if (State.isOverdefined())
  922. return markOverdefined(I);
  923. assert(State.isConstant() && "Unknown state!");
  924. Operands.push_back(State.getConstant());
  925. }
  926. if (getValueState(I).isOverdefined())
  927. return;
  928. // If we can constant fold this, mark the result of the call as a
  929. // constant.
  930. if (Constant *C = ConstantFoldCall(F, Operands, TLI))
  931. return markConstant(I, C);
  932. }
  933. // Otherwise, we don't know anything about this call, mark it overdefined.
  934. return markAnythingOverdefined(I);
  935. }
  936. // If this is a local function that doesn't have its address taken, mark its
  937. // entry block executable and merge in the actual arguments to the call into
  938. // the formal arguments of the function.
  939. if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
  940. MarkBlockExecutable(F->begin());
  941. // Propagate information from this call site into the callee.
  942. CallSite::arg_iterator CAI = CS.arg_begin();
  943. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
  944. AI != E; ++AI, ++CAI) {
  945. // If this argument is byval, and if the function is not readonly, there
  946. // will be an implicit copy formed of the input aggregate.
  947. if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
  948. markOverdefined(AI);
  949. continue;
  950. }
  951. if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
  952. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  953. LatticeVal CallArg = getStructValueState(*CAI, i);
  954. mergeInValue(getStructValueState(AI, i), AI, CallArg);
  955. }
  956. } else {
  957. mergeInValue(AI, getValueState(*CAI));
  958. }
  959. }
  960. }
  961. // If this is a single/zero retval case, see if we're tracking the function.
  962. if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
  963. if (!MRVFunctionsTracked.count(F))
  964. goto CallOverdefined; // Not tracking this callee.
  965. // If we are tracking this callee, propagate the result of the function
  966. // into this call site.
  967. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  968. mergeInValue(getStructValueState(I, i), I,
  969. TrackedMultipleRetVals[std::make_pair(F, i)]);
  970. } else {
  971. DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
  972. if (TFRVI == TrackedRetVals.end())
  973. goto CallOverdefined; // Not tracking this callee.
  974. // If so, propagate the return value of the callee into this call result.
  975. mergeInValue(I, TFRVI->second);
  976. }
  977. }
  978. void SCCPSolver::Solve() {
  979. // Process the work lists until they are empty!
  980. while (!BBWorkList.empty() || !InstWorkList.empty() ||
  981. !OverdefinedInstWorkList.empty()) {
  982. // Process the overdefined instruction's work list first, which drives other
  983. // things to overdefined more quickly.
  984. while (!OverdefinedInstWorkList.empty()) {
  985. Value *I = OverdefinedInstWorkList.pop_back_val();
  986. DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
  987. // "I" got into the work list because it either made the transition from
  988. // bottom to constant, or to overdefined.
  989. //
  990. // Anything on this worklist that is overdefined need not be visited
  991. // since all of its users will have already been marked as overdefined
  992. // Update all of the users of this instruction's value.
  993. //
  994. for (User *U : I->users())
  995. if (Instruction *UI = dyn_cast<Instruction>(U))
  996. OperandChangedState(UI);
  997. }
  998. // Process the instruction work list.
  999. while (!InstWorkList.empty()) {
  1000. Value *I = InstWorkList.pop_back_val();
  1001. DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
  1002. // "I" got into the work list because it made the transition from undef to
  1003. // constant.
  1004. //
  1005. // Anything on this worklist that is overdefined need not be visited
  1006. // since all of its users will have already been marked as overdefined.
  1007. // Update all of the users of this instruction's value.
  1008. //
  1009. if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
  1010. for (User *U : I->users())
  1011. if (Instruction *UI = dyn_cast<Instruction>(U))
  1012. OperandChangedState(UI);
  1013. }
  1014. // Process the basic block work list.
  1015. while (!BBWorkList.empty()) {
  1016. BasicBlock *BB = BBWorkList.back();
  1017. BBWorkList.pop_back();
  1018. DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
  1019. // Notify all instructions in this basic block that they are newly
  1020. // executable.
  1021. visit(BB);
  1022. }
  1023. }
  1024. }
  1025. /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
  1026. /// that branches on undef values cannot reach any of their successors.
  1027. /// However, this is not a safe assumption. After we solve dataflow, this
  1028. /// method should be use to handle this. If this returns true, the solver
  1029. /// should be rerun.
  1030. ///
  1031. /// This method handles this by finding an unresolved branch and marking it one
  1032. /// of the edges from the block as being feasible, even though the condition
  1033. /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
  1034. /// CFG and only slightly pessimizes the analysis results (by marking one,
  1035. /// potentially infeasible, edge feasible). This cannot usefully modify the
  1036. /// constraints on the condition of the branch, as that would impact other users
  1037. /// of the value.
  1038. ///
  1039. /// This scan also checks for values that use undefs, whose results are actually
  1040. /// defined. For example, 'zext i8 undef to i32' should produce all zeros
  1041. /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
  1042. /// even if X isn't defined.
  1043. bool SCCPSolver::ResolvedUndefsIn(Function &F) {
  1044. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  1045. if (!BBExecutable.count(BB))
  1046. continue;
  1047. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  1048. // Look for instructions which produce undef values.
  1049. if (I->getType()->isVoidTy()) continue;
  1050. if (StructType *STy = dyn_cast<StructType>(I->getType())) {
  1051. // Only a few things that can be structs matter for undef.
  1052. // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
  1053. if (CallSite CS = CallSite(I))
  1054. if (Function *F = CS.getCalledFunction())
  1055. if (MRVFunctionsTracked.count(F))
  1056. continue;
  1057. // extractvalue and insertvalue don't need to be marked; they are
  1058. // tracked as precisely as their operands.
  1059. if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
  1060. continue;
  1061. // Send the results of everything else to overdefined. We could be
  1062. // more precise than this but it isn't worth bothering.
  1063. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1064. LatticeVal &LV = getStructValueState(I, i);
  1065. if (LV.isUndefined())
  1066. markOverdefined(LV, I);
  1067. }
  1068. continue;
  1069. }
  1070. LatticeVal &LV = getValueState(I);
  1071. if (!LV.isUndefined()) continue;
  1072. // extractvalue is safe; check here because the argument is a struct.
  1073. if (isa<ExtractValueInst>(I))
  1074. continue;
  1075. // Compute the operand LatticeVals, for convenience below.
  1076. // Anything taking a struct is conservatively assumed to require
  1077. // overdefined markings.
  1078. if (I->getOperand(0)->getType()->isStructTy()) {
  1079. markOverdefined(I);
  1080. return true;
  1081. }
  1082. LatticeVal Op0LV = getValueState(I->getOperand(0));
  1083. LatticeVal Op1LV;
  1084. if (I->getNumOperands() == 2) {
  1085. if (I->getOperand(1)->getType()->isStructTy()) {
  1086. markOverdefined(I);
  1087. return true;
  1088. }
  1089. Op1LV = getValueState(I->getOperand(1));
  1090. }
  1091. // If this is an instructions whose result is defined even if the input is
  1092. // not fully defined, propagate the information.
  1093. Type *ITy = I->getType();
  1094. switch (I->getOpcode()) {
  1095. case Instruction::Add:
  1096. case Instruction::Sub:
  1097. case Instruction::Trunc:
  1098. case Instruction::FPTrunc:
  1099. case Instruction::BitCast:
  1100. break; // Any undef -> undef
  1101. case Instruction::FSub:
  1102. case Instruction::FAdd:
  1103. case Instruction::FMul:
  1104. case Instruction::FDiv:
  1105. case Instruction::FRem:
  1106. // Floating-point binary operation: be conservative.
  1107. if (Op0LV.isUndefined() && Op1LV.isUndefined())
  1108. markForcedConstant(I, Constant::getNullValue(ITy));
  1109. else
  1110. markOverdefined(I);
  1111. return true;
  1112. case Instruction::ZExt:
  1113. case Instruction::SExt:
  1114. case Instruction::FPToUI:
  1115. case Instruction::FPToSI:
  1116. case Instruction::FPExt:
  1117. case Instruction::PtrToInt:
  1118. case Instruction::IntToPtr:
  1119. case Instruction::SIToFP:
  1120. case Instruction::UIToFP:
  1121. // undef -> 0; some outputs are impossible
  1122. markForcedConstant(I, Constant::getNullValue(ITy));
  1123. return true;
  1124. case Instruction::Mul:
  1125. case Instruction::And:
  1126. // Both operands undef -> undef
  1127. if (Op0LV.isUndefined() && Op1LV.isUndefined())
  1128. break;
  1129. // undef * X -> 0. X could be zero.
  1130. // undef & X -> 0. X could be zero.
  1131. markForcedConstant(I, Constant::getNullValue(ITy));
  1132. return true;
  1133. case Instruction::Or:
  1134. // Both operands undef -> undef
  1135. if (Op0LV.isUndefined() && Op1LV.isUndefined())
  1136. break;
  1137. // undef | X -> -1. X could be -1.
  1138. markForcedConstant(I, Constant::getAllOnesValue(ITy));
  1139. return true;
  1140. case Instruction::Xor:
  1141. // undef ^ undef -> 0; strictly speaking, this is not strictly
  1142. // necessary, but we try to be nice to people who expect this
  1143. // behavior in simple cases
  1144. if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
  1145. markForcedConstant(I, Constant::getNullValue(ITy));
  1146. return true;
  1147. }
  1148. // undef ^ X -> undef
  1149. break;
  1150. case Instruction::SDiv:
  1151. case Instruction::UDiv:
  1152. case Instruction::SRem:
  1153. case Instruction::URem:
  1154. // X / undef -> undef. No change.
  1155. // X % undef -> undef. No change.
  1156. if (Op1LV.isUndefined()) break;
  1157. // undef / X -> 0. X could be maxint.
  1158. // undef % X -> 0. X could be 1.
  1159. markForcedConstant(I, Constant::getNullValue(ITy));
  1160. return true;
  1161. case Instruction::AShr:
  1162. // X >>a undef -> undef.
  1163. if (Op1LV.isUndefined()) break;
  1164. // undef >>a X -> all ones
  1165. markForcedConstant(I, Constant::getAllOnesValue(ITy));
  1166. return true;
  1167. case Instruction::LShr:
  1168. case Instruction::Shl:
  1169. // X << undef -> undef.
  1170. // X >> undef -> undef.
  1171. if (Op1LV.isUndefined()) break;
  1172. // undef << X -> 0
  1173. // undef >> X -> 0
  1174. markForcedConstant(I, Constant::getNullValue(ITy));
  1175. return true;
  1176. case Instruction::Select:
  1177. Op1LV = getValueState(I->getOperand(1));
  1178. // undef ? X : Y -> X or Y. There could be commonality between X/Y.
  1179. if (Op0LV.isUndefined()) {
  1180. if (!Op1LV.isConstant()) // Pick the constant one if there is any.
  1181. Op1LV = getValueState(I->getOperand(2));
  1182. } else if (Op1LV.isUndefined()) {
  1183. // c ? undef : undef -> undef. No change.
  1184. Op1LV = getValueState(I->getOperand(2));
  1185. if (Op1LV.isUndefined())
  1186. break;
  1187. // Otherwise, c ? undef : x -> x.
  1188. } else {
  1189. // Leave Op1LV as Operand(1)'s LatticeValue.
  1190. }
  1191. if (Op1LV.isConstant())
  1192. markForcedConstant(I, Op1LV.getConstant());
  1193. else
  1194. markOverdefined(I);
  1195. return true;
  1196. case Instruction::Load:
  1197. // A load here means one of two things: a load of undef from a global,
  1198. // a load from an unknown pointer. Either way, having it return undef
  1199. // is okay.
  1200. break;
  1201. case Instruction::ICmp:
  1202. // X == undef -> undef. Other comparisons get more complicated.
  1203. if (cast<ICmpInst>(I)->isEquality())
  1204. break;
  1205. markOverdefined(I);
  1206. return true;
  1207. case Instruction::Call:
  1208. case Instruction::Invoke: {
  1209. // There are two reasons a call can have an undef result
  1210. // 1. It could be tracked.
  1211. // 2. It could be constant-foldable.
  1212. // Because of the way we solve return values, tracked calls must
  1213. // never be marked overdefined in ResolvedUndefsIn.
  1214. if (Function *F = CallSite(I).getCalledFunction())
  1215. if (TrackedRetVals.count(F))
  1216. break;
  1217. // If the call is constant-foldable, we mark it overdefined because
  1218. // we do not know what return values are valid.
  1219. markOverdefined(I);
  1220. return true;
  1221. }
  1222. default:
  1223. // If we don't know what should happen here, conservatively mark it
  1224. // overdefined.
  1225. markOverdefined(I);
  1226. return true;
  1227. }
  1228. }
  1229. // Check to see if we have a branch or switch on an undefined value. If so
  1230. // we force the branch to go one way or the other to make the successor
  1231. // values live. It doesn't really matter which way we force it.
  1232. TerminatorInst *TI = BB->getTerminator();
  1233. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  1234. if (!BI->isConditional()) continue;
  1235. if (!getValueState(BI->getCondition()).isUndefined())
  1236. continue;
  1237. // If the input to SCCP is actually branch on undef, fix the undef to
  1238. // false.
  1239. if (isa<UndefValue>(BI->getCondition())) {
  1240. BI->setCondition(ConstantInt::getFalse(BI->getContext()));
  1241. markEdgeExecutable(BB, TI->getSuccessor(1));
  1242. return true;
  1243. }
  1244. // Otherwise, it is a branch on a symbolic value which is currently
  1245. // considered to be undef. Handle this by forcing the input value to the
  1246. // branch to false.
  1247. markForcedConstant(BI->getCondition(),
  1248. ConstantInt::getFalse(TI->getContext()));
  1249. return true;
  1250. }
  1251. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  1252. if (!SI->getNumCases())
  1253. continue;
  1254. if (!getValueState(SI->getCondition()).isUndefined())
  1255. continue;
  1256. // If the input to SCCP is actually switch on undef, fix the undef to
  1257. // the first constant.
  1258. if (isa<UndefValue>(SI->getCondition())) {
  1259. SI->setCondition(SI->case_begin().getCaseValue());
  1260. markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
  1261. return true;
  1262. }
  1263. markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
  1264. return true;
  1265. }
  1266. }
  1267. return false;
  1268. }
  1269. namespace {
  1270. //===--------------------------------------------------------------------===//
  1271. //
  1272. /// SCCP Class - This class uses the SCCPSolver to implement a per-function
  1273. /// Sparse Conditional Constant Propagator.
  1274. ///
  1275. struct SCCP : public FunctionPass {
  1276. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1277. AU.addRequired<TargetLibraryInfoWrapperPass>();
  1278. }
  1279. static char ID; // Pass identification, replacement for typeid
  1280. SCCP() : FunctionPass(ID) {
  1281. initializeSCCPPass(*PassRegistry::getPassRegistry());
  1282. }
  1283. // runOnFunction - Run the Sparse Conditional Constant Propagation
  1284. // algorithm, and return true if the function was modified.
  1285. //
  1286. bool runOnFunction(Function &F) override;
  1287. };
  1288. } // end anonymous namespace
  1289. char SCCP::ID = 0;
  1290. INITIALIZE_PASS(SCCP, "sccp",
  1291. "Sparse Conditional Constant Propagation", false, false)
  1292. // createSCCPPass - This is the public interface to this file.
  1293. FunctionPass *llvm::createSCCPPass() {
  1294. return new SCCP();
  1295. }
  1296. static void DeleteInstructionInBlock(BasicBlock *BB) {
  1297. DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
  1298. ++NumDeadBlocks;
  1299. // Check to see if there are non-terminating instructions to delete.
  1300. if (isa<TerminatorInst>(BB->begin()))
  1301. return;
  1302. // Delete the instructions backwards, as it has a reduced likelihood of having
  1303. // to update as many def-use and use-def chains.
  1304. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  1305. while (EndInst != BB->begin()) {
  1306. // Delete the next to last instruction.
  1307. BasicBlock::iterator I = EndInst;
  1308. Instruction *Inst = --I;
  1309. if (!Inst->use_empty())
  1310. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  1311. if (isa<LandingPadInst>(Inst)) {
  1312. EndInst = Inst;
  1313. continue;
  1314. }
  1315. BB->getInstList().erase(Inst);
  1316. ++NumInstRemoved;
  1317. }
  1318. }
  1319. // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
  1320. // and return true if the function was modified.
  1321. //
  1322. bool SCCP::runOnFunction(Function &F) {
  1323. if (skipOptnoneFunction(F))
  1324. return false;
  1325. DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
  1326. const DataLayout &DL = F.getParent()->getDataLayout();
  1327. const TargetLibraryInfo *TLI =
  1328. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  1329. SCCPSolver Solver(DL, TLI);
  1330. // Mark the first block of the function as being executable.
  1331. Solver.MarkBlockExecutable(F.begin());
  1332. // Mark all arguments to the function as being overdefined.
  1333. for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
  1334. Solver.markAnythingOverdefined(AI);
  1335. // Solve for constants.
  1336. bool ResolvedUndefs = true;
  1337. while (ResolvedUndefs) {
  1338. Solver.Solve();
  1339. DEBUG(dbgs() << "RESOLVING UNDEFs\n");
  1340. ResolvedUndefs = Solver.ResolvedUndefsIn(F);
  1341. }
  1342. bool MadeChanges = false;
  1343. // If we decided that there are basic blocks that are dead in this function,
  1344. // delete their contents now. Note that we cannot actually delete the blocks,
  1345. // as we cannot modify the CFG of the function.
  1346. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  1347. if (!Solver.isBlockExecutable(BB)) {
  1348. DeleteInstructionInBlock(BB);
  1349. MadeChanges = true;
  1350. continue;
  1351. }
  1352. // Iterate over all of the instructions in a function, replacing them with
  1353. // constants if we have found them to be of constant values.
  1354. //
  1355. for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
  1356. Instruction *Inst = BI++;
  1357. if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
  1358. continue;
  1359. // TODO: Reconstruct structs from their elements.
  1360. if (Inst->getType()->isStructTy())
  1361. continue;
  1362. LatticeVal IV = Solver.getLatticeValueFor(Inst);
  1363. if (IV.isOverdefined())
  1364. continue;
  1365. Constant *Const = IV.isConstant()
  1366. ? IV.getConstant() : UndefValue::get(Inst->getType());
  1367. DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
  1368. // Replaces all of the uses of a variable with uses of the constant.
  1369. Inst->replaceAllUsesWith(Const);
  1370. // Delete the instruction.
  1371. Inst->eraseFromParent();
  1372. // Hey, we just changed something!
  1373. MadeChanges = true;
  1374. ++NumInstRemoved;
  1375. }
  1376. }
  1377. return MadeChanges;
  1378. }
  1379. namespace {
  1380. //===--------------------------------------------------------------------===//
  1381. //
  1382. /// IPSCCP Class - This class implements interprocedural Sparse Conditional
  1383. /// Constant Propagation.
  1384. ///
  1385. struct IPSCCP : public ModulePass {
  1386. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1387. AU.addRequired<TargetLibraryInfoWrapperPass>();
  1388. }
  1389. static char ID;
  1390. IPSCCP() : ModulePass(ID) {
  1391. initializeIPSCCPPass(*PassRegistry::getPassRegistry());
  1392. }
  1393. bool runOnModule(Module &M) override;
  1394. };
  1395. } // end anonymous namespace
  1396. char IPSCCP::ID = 0;
  1397. INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
  1398. "Interprocedural Sparse Conditional Constant Propagation",
  1399. false, false)
  1400. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  1401. INITIALIZE_PASS_END(IPSCCP, "ipsccp",
  1402. "Interprocedural Sparse Conditional Constant Propagation",
  1403. false, false)
  1404. // createIPSCCPPass - This is the public interface to this file.
  1405. ModulePass *llvm::createIPSCCPPass() {
  1406. return new IPSCCP();
  1407. }
  1408. static bool AddressIsTaken(const GlobalValue *GV) {
  1409. // Delete any dead constantexpr klingons.
  1410. GV->removeDeadConstantUsers();
  1411. for (const Use &U : GV->uses()) {
  1412. const User *UR = U.getUser();
  1413. if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
  1414. if (SI->getOperand(0) == GV || SI->isVolatile())
  1415. return true; // Storing addr of GV.
  1416. } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
  1417. // Make sure we are calling the function, not passing the address.
  1418. ImmutableCallSite CS(cast<Instruction>(UR));
  1419. if (!CS.isCallee(&U))
  1420. return true;
  1421. } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
  1422. if (LI->isVolatile())
  1423. return true;
  1424. } else if (isa<BlockAddress>(UR)) {
  1425. // blockaddress doesn't take the address of the function, it takes addr
  1426. // of label.
  1427. } else {
  1428. return true;
  1429. }
  1430. }
  1431. return false;
  1432. }
  1433. bool IPSCCP::runOnModule(Module &M) {
  1434. const DataLayout &DL = M.getDataLayout();
  1435. const TargetLibraryInfo *TLI =
  1436. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  1437. SCCPSolver Solver(DL, TLI);
  1438. // AddressTakenFunctions - This set keeps track of the address-taken functions
  1439. // that are in the input. As IPSCCP runs through and simplifies code,
  1440. // functions that were address taken can end up losing their
  1441. // address-taken-ness. Because of this, we keep track of their addresses from
  1442. // the first pass so we can use them for the later simplification pass.
  1443. SmallPtrSet<Function*, 32> AddressTakenFunctions;
  1444. // Loop over all functions, marking arguments to those with their addresses
  1445. // taken or that are external as overdefined.
  1446. //
  1447. for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
  1448. if (F->isDeclaration())
  1449. continue;
  1450. // If this is a strong or ODR definition of this function, then we can
  1451. // propagate information about its result into callsites of it.
  1452. if (!F->mayBeOverridden())
  1453. Solver.AddTrackedFunction(F);
  1454. // If this function only has direct calls that we can see, we can track its
  1455. // arguments and return value aggressively, and can assume it is not called
  1456. // unless we see evidence to the contrary.
  1457. if (F->hasLocalLinkage()) {
  1458. if (AddressIsTaken(F))
  1459. AddressTakenFunctions.insert(F);
  1460. else {
  1461. Solver.AddArgumentTrackedFunction(F);
  1462. continue;
  1463. }
  1464. }
  1465. // Assume the function is called.
  1466. Solver.MarkBlockExecutable(F->begin());
  1467. // Assume nothing about the incoming arguments.
  1468. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
  1469. AI != E; ++AI)
  1470. Solver.markAnythingOverdefined(AI);
  1471. }
  1472. // Loop over global variables. We inform the solver about any internal global
  1473. // variables that do not have their 'addresses taken'. If they don't have
  1474. // their addresses taken, we can propagate constants through them.
  1475. for (Module::global_iterator G = M.global_begin(), E = M.global_end();
  1476. G != E; ++G)
  1477. if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
  1478. Solver.TrackValueOfGlobalVariable(G);
  1479. // Solve for constants.
  1480. bool ResolvedUndefs = true;
  1481. while (ResolvedUndefs) {
  1482. Solver.Solve();
  1483. DEBUG(dbgs() << "RESOLVING UNDEFS\n");
  1484. ResolvedUndefs = false;
  1485. for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
  1486. ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
  1487. }
  1488. bool MadeChanges = false;
  1489. // Iterate over all of the instructions in the module, replacing them with
  1490. // constants if we have found them to be of constant values.
  1491. //
  1492. SmallVector<BasicBlock*, 512> BlocksToErase;
  1493. for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
  1494. if (Solver.isBlockExecutable(F->begin())) {
  1495. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
  1496. AI != E; ++AI) {
  1497. if (AI->use_empty() || AI->getType()->isStructTy()) continue;
  1498. // TODO: Could use getStructLatticeValueFor to find out if the entire
  1499. // result is a constant and replace it entirely if so.
  1500. LatticeVal IV = Solver.getLatticeValueFor(AI);
  1501. if (IV.isOverdefined()) continue;
  1502. Constant *CST = IV.isConstant() ?
  1503. IV.getConstant() : UndefValue::get(AI->getType());
  1504. DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
  1505. // Replaces all of the uses of a variable with uses of the
  1506. // constant.
  1507. AI->replaceAllUsesWith(CST);
  1508. ++IPNumArgsElimed;
  1509. }
  1510. }
  1511. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
  1512. if (!Solver.isBlockExecutable(BB)) {
  1513. DeleteInstructionInBlock(BB);
  1514. MadeChanges = true;
  1515. TerminatorInst *TI = BB->getTerminator();
  1516. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
  1517. BasicBlock *Succ = TI->getSuccessor(i);
  1518. if (!Succ->empty() && isa<PHINode>(Succ->begin()))
  1519. TI->getSuccessor(i)->removePredecessor(BB);
  1520. }
  1521. if (!TI->use_empty())
  1522. TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
  1523. TI->eraseFromParent();
  1524. new UnreachableInst(M.getContext(), BB);
  1525. if (&*BB != &F->front())
  1526. BlocksToErase.push_back(BB);
  1527. continue;
  1528. }
  1529. for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
  1530. Instruction *Inst = BI++;
  1531. if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
  1532. continue;
  1533. // TODO: Could use getStructLatticeValueFor to find out if the entire
  1534. // result is a constant and replace it entirely if so.
  1535. LatticeVal IV = Solver.getLatticeValueFor(Inst);
  1536. if (IV.isOverdefined())
  1537. continue;
  1538. Constant *Const = IV.isConstant()
  1539. ? IV.getConstant() : UndefValue::get(Inst->getType());
  1540. DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
  1541. // Replaces all of the uses of a variable with uses of the
  1542. // constant.
  1543. Inst->replaceAllUsesWith(Const);
  1544. // Delete the instruction.
  1545. if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
  1546. Inst->eraseFromParent();
  1547. // Hey, we just changed something!
  1548. MadeChanges = true;
  1549. ++IPNumInstRemoved;
  1550. }
  1551. }
  1552. // Now that all instructions in the function are constant folded, erase dead
  1553. // blocks, because we can now use ConstantFoldTerminator to get rid of
  1554. // in-edges.
  1555. for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
  1556. // If there are any PHI nodes in this successor, drop entries for BB now.
  1557. BasicBlock *DeadBB = BlocksToErase[i];
  1558. for (Value::user_iterator UI = DeadBB->user_begin(),
  1559. UE = DeadBB->user_end();
  1560. UI != UE;) {
  1561. // Grab the user and then increment the iterator early, as the user
  1562. // will be deleted. Step past all adjacent uses from the same user.
  1563. Instruction *I = dyn_cast<Instruction>(*UI);
  1564. do { ++UI; } while (UI != UE && *UI == I);
  1565. // Ignore blockaddress users; BasicBlock's dtor will handle them.
  1566. if (!I) continue;
  1567. bool Folded = ConstantFoldTerminator(I->getParent());
  1568. if (!Folded) {
  1569. // The constant folder may not have been able to fold the terminator
  1570. // if this is a branch or switch on undef. Fold it manually as a
  1571. // branch to the first successor.
  1572. #ifndef NDEBUG
  1573. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1574. assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
  1575. "Branch should be foldable!");
  1576. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
  1577. assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
  1578. } else {
  1579. llvm_unreachable("Didn't fold away reference to block!");
  1580. }
  1581. #endif
  1582. // Make this an uncond branch to the first successor.
  1583. TerminatorInst *TI = I->getParent()->getTerminator();
  1584. BranchInst::Create(TI->getSuccessor(0), TI);
  1585. // Remove entries in successor phi nodes to remove edges.
  1586. for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
  1587. TI->getSuccessor(i)->removePredecessor(TI->getParent());
  1588. // Remove the old terminator.
  1589. TI->eraseFromParent();
  1590. }
  1591. }
  1592. // Finally, delete the basic block.
  1593. F->getBasicBlockList().erase(DeadBB);
  1594. }
  1595. BlocksToErase.clear();
  1596. }
  1597. // If we inferred constant or undef return values for a function, we replaced
  1598. // all call uses with the inferred value. This means we don't need to bother
  1599. // actually returning anything from the function. Replace all return
  1600. // instructions with return undef.
  1601. //
  1602. // Do this in two stages: first identify the functions we should process, then
  1603. // actually zap their returns. This is important because we can only do this
  1604. // if the address of the function isn't taken. In cases where a return is the
  1605. // last use of a function, the order of processing functions would affect
  1606. // whether other functions are optimizable.
  1607. SmallVector<ReturnInst*, 8> ReturnsToZap;
  1608. // TODO: Process multiple value ret instructions also.
  1609. const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
  1610. for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
  1611. E = RV.end(); I != E; ++I) {
  1612. Function *F = I->first;
  1613. if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
  1614. continue;
  1615. // We can only do this if we know that nothing else can call the function.
  1616. if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
  1617. continue;
  1618. for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
  1619. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
  1620. if (!isa<UndefValue>(RI->getOperand(0)))
  1621. ReturnsToZap.push_back(RI);
  1622. }
  1623. // Zap all returns which we've identified as zap to change.
  1624. for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
  1625. Function *F = ReturnsToZap[i]->getParent()->getParent();
  1626. ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
  1627. }
  1628. // If we inferred constant or undef values for globals variables, we can
  1629. // delete the global and any stores that remain to it.
  1630. const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
  1631. for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
  1632. E = TG.end(); I != E; ++I) {
  1633. GlobalVariable *GV = I->first;
  1634. assert(!I->second.isOverdefined() &&
  1635. "Overdefined values should have been taken out of the map!");
  1636. DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
  1637. while (!GV->use_empty()) {
  1638. StoreInst *SI = cast<StoreInst>(GV->user_back());
  1639. SI->eraseFromParent();
  1640. }
  1641. M.getGlobalList().erase(GV);
  1642. ++IPNumGlobalConst;
  1643. }
  1644. return MadeChanges;
  1645. }