SCCPSolver.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  1. //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // \file
  10. // This file implements the Sparse Conditional Constant Propagation (SCCP)
  11. // utility.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/SCCPSolver.h"
  15. #include "llvm/Analysis/ConstantFolding.h"
  16. #include "llvm/Analysis/InstructionSimplify.h"
  17. #include "llvm/Analysis/ValueTracking.h"
  18. #include "llvm/InitializePasses.h"
  19. #include "llvm/Pass.h"
  20. #include "llvm/Support/Casting.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "llvm/Transforms/Utils/Local.h"
  25. #include <cassert>
  26. #include <utility>
  27. #include <vector>
  28. using namespace llvm;
  29. #define DEBUG_TYPE "sccp"
  30. // The maximum number of range extensions allowed for operations requiring
  31. // widening.
  32. static const unsigned MaxNumRangeExtensions = 10;
  33. /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
  34. static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
  35. return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
  36. MaxNumRangeExtensions);
  37. }
  38. namespace {
  39. // Helper to check if \p LV is either a constant or a constant
  40. // range with a single element. This should cover exactly the same cases as the
  41. // old ValueLatticeElement::isConstant() and is intended to be used in the
  42. // transition to ValueLatticeElement.
  43. bool isConstant(const ValueLatticeElement &LV) {
  44. return LV.isConstant() ||
  45. (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
  46. }
  47. // Helper to check if \p LV is either overdefined or a constant range with more
  48. // than a single element. This should cover exactly the same cases as the old
  49. // ValueLatticeElement::isOverdefined() and is intended to be used in the
  50. // transition to ValueLatticeElement.
  51. bool isOverdefined(const ValueLatticeElement &LV) {
  52. return !LV.isUnknownOrUndef() && !isConstant(LV);
  53. }
  54. } // namespace
  55. namespace llvm {
  56. /// Helper class for SCCPSolver. This implements the instruction visitor and
  57. /// holds all the state.
  58. class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
  59. const DataLayout &DL;
  60. std::function<const TargetLibraryInfo &(Function &)> GetTLI;
  61. SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
  62. DenseMap<Value *, ValueLatticeElement>
  63. ValueState; // The state each value is in.
  64. /// StructValueState - This maintains ValueState for values that have
  65. /// StructType, for example for formal arguments, calls, insertelement, etc.
  66. DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
  67. /// GlobalValue - If we are tracking any values for the contents of a global
  68. /// variable, we keep a mapping from the constant accessor to the element of
  69. /// the global, to the currently known value. If the value becomes
  70. /// overdefined, it's entry is simply removed from this map.
  71. DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
  72. /// TrackedRetVals - If we are tracking arguments into and the return
  73. /// value out of a function, it will have an entry in this map, indicating
  74. /// what the known return value for the function is.
  75. MapVector<Function *, ValueLatticeElement> TrackedRetVals;
  76. /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
  77. /// that return multiple values.
  78. MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
  79. TrackedMultipleRetVals;
  80. /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
  81. /// represented here for efficient lookup.
  82. SmallPtrSet<Function *, 16> MRVFunctionsTracked;
  83. /// A list of functions whose return cannot be modified.
  84. SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
  85. /// TrackingIncomingArguments - This is the set of functions for whose
  86. /// arguments we make optimistic assumptions about and try to prove as
  87. /// constants.
  88. SmallPtrSet<Function *, 16> TrackingIncomingArguments;
  89. /// The reason for two worklists is that overdefined is the lowest state
  90. /// on the lattice, and moving things to overdefined as fast as possible
  91. /// makes SCCP converge much faster.
  92. ///
  93. /// By having a separate worklist, we accomplish this because everything
  94. /// possibly overdefined will become overdefined at the soonest possible
  95. /// point.
  96. SmallVector<Value *, 64> OverdefinedInstWorkList;
  97. SmallVector<Value *, 64> InstWorkList;
  98. // The BasicBlock work list
  99. SmallVector<BasicBlock *, 64> BBWorkList;
  100. /// KnownFeasibleEdges - Entries in this set are edges which have already had
  101. /// PHI nodes retriggered.
  102. using Edge = std::pair<BasicBlock *, BasicBlock *>;
  103. DenseSet<Edge> KnownFeasibleEdges;
  104. DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
  105. DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
  106. LLVMContext &Ctx;
  107. private:
  108. ConstantInt *getConstantInt(const ValueLatticeElement &IV) const {
  109. return dyn_cast_or_null<ConstantInt>(getConstant(IV));
  110. }
  111. // pushToWorkList - Helper for markConstant/markOverdefined
  112. void pushToWorkList(ValueLatticeElement &IV, Value *V);
  113. // Helper to push \p V to the worklist, after updating it to \p IV. Also
  114. // prints a debug message with the updated value.
  115. void pushToWorkListMsg(ValueLatticeElement &IV, Value *V);
  116. // markConstant - Make a value be marked as "constant". If the value
  117. // is not already a constant, add it to the instruction work list so that
  118. // the users of the instruction are updated later.
  119. bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
  120. bool MayIncludeUndef = false);
  121. bool markConstant(Value *V, Constant *C) {
  122. assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
  123. return markConstant(ValueState[V], V, C);
  124. }
  125. // markOverdefined - Make a value be marked as "overdefined". If the
  126. // value is not already overdefined, add it to the overdefined instruction
  127. // work list so that the users of the instruction are updated later.
  128. bool markOverdefined(ValueLatticeElement &IV, Value *V);
  129. /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
  130. /// changes.
  131. bool mergeInValue(ValueLatticeElement &IV, Value *V,
  132. ValueLatticeElement MergeWithV,
  133. ValueLatticeElement::MergeOptions Opts = {
  134. /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
  135. bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
  136. ValueLatticeElement::MergeOptions Opts = {
  137. /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
  138. assert(!V->getType()->isStructTy() &&
  139. "non-structs should use markConstant");
  140. return mergeInValue(ValueState[V], V, MergeWithV, Opts);
  141. }
  142. /// getValueState - Return the ValueLatticeElement object that corresponds to
  143. /// the value. This function handles the case when the value hasn't been seen
  144. /// yet by properly seeding constants etc.
  145. ValueLatticeElement &getValueState(Value *V) {
  146. assert(!V->getType()->isStructTy() && "Should use getStructValueState");
  147. auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
  148. ValueLatticeElement &LV = I.first->second;
  149. if (!I.second)
  150. return LV; // Common case, already in the map.
  151. if (auto *C = dyn_cast<Constant>(V))
  152. LV.markConstant(C); // Constants are constant
  153. // All others are unknown by default.
  154. return LV;
  155. }
  156. /// getStructValueState - Return the ValueLatticeElement object that
  157. /// corresponds to the value/field pair. This function handles the case when
  158. /// the value hasn't been seen yet by properly seeding constants etc.
  159. ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
  160. assert(V->getType()->isStructTy() && "Should use getValueState");
  161. assert(i < cast<StructType>(V->getType())->getNumElements() &&
  162. "Invalid element #");
  163. auto I = StructValueState.insert(
  164. std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
  165. ValueLatticeElement &LV = I.first->second;
  166. if (!I.second)
  167. return LV; // Common case, already in the map.
  168. if (auto *C = dyn_cast<Constant>(V)) {
  169. Constant *Elt = C->getAggregateElement(i);
  170. if (!Elt)
  171. LV.markOverdefined(); // Unknown sort of constant.
  172. else if (isa<UndefValue>(Elt))
  173. ; // Undef values remain unknown.
  174. else
  175. LV.markConstant(Elt); // Constants are constant.
  176. }
  177. // All others are underdefined by default.
  178. return LV;
  179. }
  180. /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
  181. /// work list if it is not already executable.
  182. bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
  183. // getFeasibleSuccessors - Return a vector of booleans to indicate which
  184. // successors are reachable from a given terminator instruction.
  185. void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
  186. // OperandChangedState - This method is invoked on all of the users of an
  187. // instruction that was just changed state somehow. Based on this
  188. // information, we need to update the specified user of this instruction.
  189. void operandChangedState(Instruction *I) {
  190. if (BBExecutable.count(I->getParent())) // Inst is executable?
  191. visit(*I);
  192. }
  193. // Add U as additional user of V.
  194. void addAdditionalUser(Value *V, User *U) {
  195. auto Iter = AdditionalUsers.insert({V, {}});
  196. Iter.first->second.insert(U);
  197. }
  198. // Mark I's users as changed, including AdditionalUsers.
  199. void markUsersAsChanged(Value *I) {
  200. // Functions include their arguments in the use-list. Changed function
  201. // values mean that the result of the function changed. We only need to
  202. // update the call sites with the new function result and do not have to
  203. // propagate the call arguments.
  204. if (isa<Function>(I)) {
  205. for (User *U : I->users()) {
  206. if (auto *CB = dyn_cast<CallBase>(U))
  207. handleCallResult(*CB);
  208. }
  209. } else {
  210. for (User *U : I->users())
  211. if (auto *UI = dyn_cast<Instruction>(U))
  212. operandChangedState(UI);
  213. }
  214. auto Iter = AdditionalUsers.find(I);
  215. if (Iter != AdditionalUsers.end()) {
  216. // Copy additional users before notifying them of changes, because new
  217. // users may be added, potentially invalidating the iterator.
  218. SmallVector<Instruction *, 2> ToNotify;
  219. for (User *U : Iter->second)
  220. if (auto *UI = dyn_cast<Instruction>(U))
  221. ToNotify.push_back(UI);
  222. for (Instruction *UI : ToNotify)
  223. operandChangedState(UI);
  224. }
  225. }
  226. void handleCallOverdefined(CallBase &CB);
  227. void handleCallResult(CallBase &CB);
  228. void handleCallArguments(CallBase &CB);
  229. private:
  230. friend class InstVisitor<SCCPInstVisitor>;
  231. // visit implementations - Something changed in this instruction. Either an
  232. // operand made a transition, or the instruction is newly executable. Change
  233. // the value type of I to reflect these changes if appropriate.
  234. void visitPHINode(PHINode &I);
  235. // Terminators
  236. void visitReturnInst(ReturnInst &I);
  237. void visitTerminator(Instruction &TI);
  238. void visitCastInst(CastInst &I);
  239. void visitSelectInst(SelectInst &I);
  240. void visitUnaryOperator(Instruction &I);
  241. void visitBinaryOperator(Instruction &I);
  242. void visitCmpInst(CmpInst &I);
  243. void visitExtractValueInst(ExtractValueInst &EVI);
  244. void visitInsertValueInst(InsertValueInst &IVI);
  245. void visitCatchSwitchInst(CatchSwitchInst &CPI) {
  246. markOverdefined(&CPI);
  247. visitTerminator(CPI);
  248. }
  249. // Instructions that cannot be folded away.
  250. void visitStoreInst(StoreInst &I);
  251. void visitLoadInst(LoadInst &I);
  252. void visitGetElementPtrInst(GetElementPtrInst &I);
  253. void visitInvokeInst(InvokeInst &II) {
  254. visitCallBase(II);
  255. visitTerminator(II);
  256. }
  257. void visitCallBrInst(CallBrInst &CBI) {
  258. visitCallBase(CBI);
  259. visitTerminator(CBI);
  260. }
  261. void visitCallBase(CallBase &CB);
  262. void visitResumeInst(ResumeInst &I) { /*returns void*/
  263. }
  264. void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
  265. }
  266. void visitFenceInst(FenceInst &I) { /*returns void*/
  267. }
  268. void visitInstruction(Instruction &I);
  269. public:
  270. void addAnalysis(Function &F, AnalysisResultsForFn A) {
  271. AnalysisResults.insert({&F, std::move(A)});
  272. }
  273. void visitCallInst(CallInst &I) { visitCallBase(I); }
  274. bool markBlockExecutable(BasicBlock *BB);
  275. const PredicateBase *getPredicateInfoFor(Instruction *I) {
  276. auto A = AnalysisResults.find(I->getParent()->getParent());
  277. if (A == AnalysisResults.end())
  278. return nullptr;
  279. return A->second.PredInfo->getPredicateInfoFor(I);
  280. }
  281. DomTreeUpdater getDTU(Function &F) {
  282. auto A = AnalysisResults.find(&F);
  283. assert(A != AnalysisResults.end() && "Need analysis results for function.");
  284. return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
  285. }
  286. SCCPInstVisitor(const DataLayout &DL,
  287. std::function<const TargetLibraryInfo &(Function &)> GetTLI,
  288. LLVMContext &Ctx)
  289. : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
  290. void trackValueOfGlobalVariable(GlobalVariable *GV) {
  291. // We only track the contents of scalar globals.
  292. if (GV->getValueType()->isSingleValueType()) {
  293. ValueLatticeElement &IV = TrackedGlobals[GV];
  294. if (!isa<UndefValue>(GV->getInitializer()))
  295. IV.markConstant(GV->getInitializer());
  296. }
  297. }
  298. void addTrackedFunction(Function *F) {
  299. // Add an entry, F -> undef.
  300. if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
  301. MRVFunctionsTracked.insert(F);
  302. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  303. TrackedMultipleRetVals.insert(
  304. std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
  305. } else if (!F->getReturnType()->isVoidTy())
  306. TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
  307. }
  308. void addToMustPreserveReturnsInFunctions(Function *F) {
  309. MustPreserveReturnsInFunctions.insert(F);
  310. }
  311. bool mustPreserveReturn(Function *F) {
  312. return MustPreserveReturnsInFunctions.count(F);
  313. }
  314. void addArgumentTrackedFunction(Function *F) {
  315. TrackingIncomingArguments.insert(F);
  316. }
  317. bool isArgumentTrackedFunction(Function *F) {
  318. return TrackingIncomingArguments.count(F);
  319. }
  320. void solve();
  321. bool resolvedUndefsIn(Function &F);
  322. bool isBlockExecutable(BasicBlock *BB) const {
  323. return BBExecutable.count(BB);
  324. }
  325. bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
  326. std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
  327. std::vector<ValueLatticeElement> StructValues;
  328. auto *STy = dyn_cast<StructType>(V->getType());
  329. assert(STy && "getStructLatticeValueFor() can be called only on structs");
  330. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  331. auto I = StructValueState.find(std::make_pair(V, i));
  332. assert(I != StructValueState.end() && "Value not in valuemap!");
  333. StructValues.push_back(I->second);
  334. }
  335. return StructValues;
  336. }
  337. void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
  338. const ValueLatticeElement &getLatticeValueFor(Value *V) const {
  339. assert(!V->getType()->isStructTy() &&
  340. "Should use getStructLatticeValueFor");
  341. DenseMap<Value *, ValueLatticeElement>::const_iterator I =
  342. ValueState.find(V);
  343. assert(I != ValueState.end() &&
  344. "V not found in ValueState nor Paramstate map!");
  345. return I->second;
  346. }
  347. const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
  348. return TrackedRetVals;
  349. }
  350. const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
  351. return TrackedGlobals;
  352. }
  353. const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
  354. return MRVFunctionsTracked;
  355. }
  356. void markOverdefined(Value *V) {
  357. if (auto *STy = dyn_cast<StructType>(V->getType()))
  358. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  359. markOverdefined(getStructValueState(V, i), V);
  360. else
  361. markOverdefined(ValueState[V], V);
  362. }
  363. bool isStructLatticeConstant(Function *F, StructType *STy);
  364. Constant *getConstant(const ValueLatticeElement &LV) const;
  365. SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() {
  366. return TrackingIncomingArguments;
  367. }
  368. void markArgInFuncSpecialization(Function *F, Argument *A, Constant *C);
  369. void markFunctionUnreachable(Function *F) {
  370. for (auto &BB : *F)
  371. BBExecutable.erase(&BB);
  372. }
  373. };
  374. } // namespace llvm
  375. bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) {
  376. if (!BBExecutable.insert(BB).second)
  377. return false;
  378. LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
  379. BBWorkList.push_back(BB); // Add the block to the work list!
  380. return true;
  381. }
  382. void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) {
  383. if (IV.isOverdefined())
  384. return OverdefinedInstWorkList.push_back(V);
  385. InstWorkList.push_back(V);
  386. }
  387. void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
  388. LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
  389. pushToWorkList(IV, V);
  390. }
  391. bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
  392. Constant *C, bool MayIncludeUndef) {
  393. if (!IV.markConstant(C, MayIncludeUndef))
  394. return false;
  395. LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
  396. pushToWorkList(IV, V);
  397. return true;
  398. }
  399. bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
  400. if (!IV.markOverdefined())
  401. return false;
  402. LLVM_DEBUG(dbgs() << "markOverdefined: ";
  403. if (auto *F = dyn_cast<Function>(V)) dbgs()
  404. << "Function '" << F->getName() << "'\n";
  405. else dbgs() << *V << '\n');
  406. // Only instructions go on the work list
  407. pushToWorkList(IV, V);
  408. return true;
  409. }
  410. bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) {
  411. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  412. const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
  413. assert(It != TrackedMultipleRetVals.end());
  414. ValueLatticeElement LV = It->second;
  415. if (!isConstant(LV))
  416. return false;
  417. }
  418. return true;
  419. }
  420. Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV) const {
  421. if (LV.isConstant())
  422. return LV.getConstant();
  423. if (LV.isConstantRange()) {
  424. const auto &CR = LV.getConstantRange();
  425. if (CR.getSingleElement())
  426. return ConstantInt::get(Ctx, *CR.getSingleElement());
  427. }
  428. return nullptr;
  429. }
  430. void SCCPInstVisitor::markArgInFuncSpecialization(Function *F, Argument *A,
  431. Constant *C) {
  432. assert(F->arg_size() == A->getParent()->arg_size() &&
  433. "Functions should have the same number of arguments");
  434. // Mark the argument constant in the new function.
  435. markConstant(A, C);
  436. // For the remaining arguments in the new function, copy the lattice state
  437. // over from the old function.
  438. for (auto I = F->arg_begin(), J = A->getParent()->arg_begin(),
  439. E = F->arg_end();
  440. I != E; ++I, ++J)
  441. if (J != A && ValueState.count(I)) {
  442. // Note: This previously looked like this:
  443. // ValueState[J] = ValueState[I];
  444. // This is incorrect because the DenseMap class may resize the underlying
  445. // memory when inserting `J`, which will invalidate the reference to `I`.
  446. // Instead, we make sure `J` exists, then set it to `I` afterwards.
  447. auto &NewValue = ValueState[J];
  448. NewValue = ValueState[I];
  449. pushToWorkList(NewValue, J);
  450. }
  451. }
  452. void SCCPInstVisitor::visitInstruction(Instruction &I) {
  453. // All the instructions we don't do any special handling for just
  454. // go to overdefined.
  455. LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
  456. markOverdefined(&I);
  457. }
  458. bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
  459. ValueLatticeElement MergeWithV,
  460. ValueLatticeElement::MergeOptions Opts) {
  461. if (IV.mergeIn(MergeWithV, Opts)) {
  462. pushToWorkList(IV, V);
  463. LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
  464. << IV << "\n");
  465. return true;
  466. }
  467. return false;
  468. }
  469. bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
  470. if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
  471. return false; // This edge is already known to be executable!
  472. if (!markBlockExecutable(Dest)) {
  473. // If the destination is already executable, we just made an *edge*
  474. // feasible that wasn't before. Revisit the PHI nodes in the block
  475. // because they have potentially new operands.
  476. LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
  477. << " -> " << Dest->getName() << '\n');
  478. for (PHINode &PN : Dest->phis())
  479. visitPHINode(PN);
  480. }
  481. return true;
  482. }
  483. // getFeasibleSuccessors - Return a vector of booleans to indicate which
  484. // successors are reachable from a given terminator instruction.
  485. void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
  486. SmallVectorImpl<bool> &Succs) {
  487. Succs.resize(TI.getNumSuccessors());
  488. if (auto *BI = dyn_cast<BranchInst>(&TI)) {
  489. if (BI->isUnconditional()) {
  490. Succs[0] = true;
  491. return;
  492. }
  493. ValueLatticeElement BCValue = getValueState(BI->getCondition());
  494. ConstantInt *CI = getConstantInt(BCValue);
  495. if (!CI) {
  496. // Overdefined condition variables, and branches on unfoldable constant
  497. // conditions, mean the branch could go either way.
  498. if (!BCValue.isUnknownOrUndef())
  499. Succs[0] = Succs[1] = true;
  500. return;
  501. }
  502. // Constant condition variables mean the branch can only go a single way.
  503. Succs[CI->isZero()] = true;
  504. return;
  505. }
  506. // Unwinding instructions successors are always executable.
  507. if (TI.isExceptionalTerminator()) {
  508. Succs.assign(TI.getNumSuccessors(), true);
  509. return;
  510. }
  511. if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
  512. if (!SI->getNumCases()) {
  513. Succs[0] = true;
  514. return;
  515. }
  516. const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
  517. if (ConstantInt *CI = getConstantInt(SCValue)) {
  518. Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
  519. return;
  520. }
  521. // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
  522. // is ready.
  523. if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
  524. const ConstantRange &Range = SCValue.getConstantRange();
  525. for (const auto &Case : SI->cases()) {
  526. const APInt &CaseValue = Case.getCaseValue()->getValue();
  527. if (Range.contains(CaseValue))
  528. Succs[Case.getSuccessorIndex()] = true;
  529. }
  530. // TODO: Determine whether default case is reachable.
  531. Succs[SI->case_default()->getSuccessorIndex()] = true;
  532. return;
  533. }
  534. // Overdefined or unknown condition? All destinations are executable!
  535. if (!SCValue.isUnknownOrUndef())
  536. Succs.assign(TI.getNumSuccessors(), true);
  537. return;
  538. }
  539. // In case of indirect branch and its address is a blockaddress, we mark
  540. // the target as executable.
  541. if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
  542. // Casts are folded by visitCastInst.
  543. ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
  544. BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(getConstant(IBRValue));
  545. if (!Addr) { // Overdefined or unknown condition?
  546. // All destinations are executable!
  547. if (!IBRValue.isUnknownOrUndef())
  548. Succs.assign(TI.getNumSuccessors(), true);
  549. return;
  550. }
  551. BasicBlock *T = Addr->getBasicBlock();
  552. assert(Addr->getFunction() == T->getParent() &&
  553. "Block address of a different function ?");
  554. for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
  555. // This is the target.
  556. if (IBR->getDestination(i) == T) {
  557. Succs[i] = true;
  558. return;
  559. }
  560. }
  561. // If we didn't find our destination in the IBR successor list, then we
  562. // have undefined behavior. Its ok to assume no successor is executable.
  563. return;
  564. }
  565. // In case of callbr, we pessimistically assume that all successors are
  566. // feasible.
  567. if (isa<CallBrInst>(&TI)) {
  568. Succs.assign(TI.getNumSuccessors(), true);
  569. return;
  570. }
  571. LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
  572. llvm_unreachable("SCCP: Don't know how to handle this terminator!");
  573. }
  574. // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
  575. // block to the 'To' basic block is currently feasible.
  576. bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
  577. // Check if we've called markEdgeExecutable on the edge yet. (We could
  578. // be more aggressive and try to consider edges which haven't been marked
  579. // yet, but there isn't any need.)
  580. return KnownFeasibleEdges.count(Edge(From, To));
  581. }
  582. // visit Implementations - Something changed in this instruction, either an
  583. // operand made a transition, or the instruction is newly executable. Change
  584. // the value type of I to reflect these changes if appropriate. This method
  585. // makes sure to do the following actions:
  586. //
  587. // 1. If a phi node merges two constants in, and has conflicting value coming
  588. // from different branches, or if the PHI node merges in an overdefined
  589. // value, then the PHI node becomes overdefined.
  590. // 2. If a phi node merges only constants in, and they all agree on value, the
  591. // PHI node becomes a constant value equal to that.
  592. // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
  593. // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
  594. // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
  595. // 6. If a conditional branch has a value that is constant, make the selected
  596. // destination executable
  597. // 7. If a conditional branch has a value that is overdefined, make all
  598. // successors executable.
  599. void SCCPInstVisitor::visitPHINode(PHINode &PN) {
  600. // If this PN returns a struct, just mark the result overdefined.
  601. // TODO: We could do a lot better than this if code actually uses this.
  602. if (PN.getType()->isStructTy())
  603. return (void)markOverdefined(&PN);
  604. if (getValueState(&PN).isOverdefined())
  605. return; // Quick exit
  606. // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
  607. // and slow us down a lot. Just mark them overdefined.
  608. if (PN.getNumIncomingValues() > 64)
  609. return (void)markOverdefined(&PN);
  610. unsigned NumActiveIncoming = 0;
  611. // Look at all of the executable operands of the PHI node. If any of them
  612. // are overdefined, the PHI becomes overdefined as well. If they are all
  613. // constant, and they agree with each other, the PHI becomes the identical
  614. // constant. If they are constant and don't agree, the PHI is a constant
  615. // range. If there are no executable operands, the PHI remains unknown.
  616. ValueLatticeElement PhiState = getValueState(&PN);
  617. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  618. if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
  619. continue;
  620. ValueLatticeElement IV = getValueState(PN.getIncomingValue(i));
  621. PhiState.mergeIn(IV);
  622. NumActiveIncoming++;
  623. if (PhiState.isOverdefined())
  624. break;
  625. }
  626. // We allow up to 1 range extension per active incoming value and one
  627. // additional extension. Note that we manually adjust the number of range
  628. // extensions to match the number of active incoming values. This helps to
  629. // limit multiple extensions caused by the same incoming value, if other
  630. // incoming values are equal.
  631. mergeInValue(&PN, PhiState,
  632. ValueLatticeElement::MergeOptions().setMaxWidenSteps(
  633. NumActiveIncoming + 1));
  634. ValueLatticeElement &PhiStateRef = getValueState(&PN);
  635. PhiStateRef.setNumRangeExtensions(
  636. std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions()));
  637. }
  638. void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
  639. if (I.getNumOperands() == 0)
  640. return; // ret void
  641. Function *F = I.getParent()->getParent();
  642. Value *ResultOp = I.getOperand(0);
  643. // If we are tracking the return value of this function, merge it in.
  644. if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
  645. auto TFRVI = TrackedRetVals.find(F);
  646. if (TFRVI != TrackedRetVals.end()) {
  647. mergeInValue(TFRVI->second, F, getValueState(ResultOp));
  648. return;
  649. }
  650. }
  651. // Handle functions that return multiple values.
  652. if (!TrackedMultipleRetVals.empty()) {
  653. if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
  654. if (MRVFunctionsTracked.count(F))
  655. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  656. mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
  657. getStructValueState(ResultOp, i));
  658. }
  659. }
  660. void SCCPInstVisitor::visitTerminator(Instruction &TI) {
  661. SmallVector<bool, 16> SuccFeasible;
  662. getFeasibleSuccessors(TI, SuccFeasible);
  663. BasicBlock *BB = TI.getParent();
  664. // Mark all feasible successors executable.
  665. for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
  666. if (SuccFeasible[i])
  667. markEdgeExecutable(BB, TI.getSuccessor(i));
  668. }
  669. void SCCPInstVisitor::visitCastInst(CastInst &I) {
  670. // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  671. // discover a concrete value later.
  672. if (ValueState[&I].isOverdefined())
  673. return;
  674. ValueLatticeElement OpSt = getValueState(I.getOperand(0));
  675. if (OpSt.isUnknownOrUndef())
  676. return;
  677. if (Constant *OpC = getConstant(OpSt)) {
  678. // Fold the constant as we build.
  679. Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL);
  680. if (isa<UndefValue>(C))
  681. return;
  682. // Propagate constant value
  683. markConstant(&I, C);
  684. } else if (I.getDestTy()->isIntegerTy()) {
  685. auto &LV = getValueState(&I);
  686. ConstantRange OpRange =
  687. OpSt.isConstantRange()
  688. ? OpSt.getConstantRange()
  689. : ConstantRange::getFull(
  690. I.getOperand(0)->getType()->getScalarSizeInBits());
  691. Type *DestTy = I.getDestTy();
  692. // Vectors where all elements have the same known constant range are treated
  693. // as a single constant range in the lattice. When bitcasting such vectors,
  694. // there is a mis-match between the width of the lattice value (single
  695. // constant range) and the original operands (vector). Go to overdefined in
  696. // that case.
  697. if (I.getOpcode() == Instruction::BitCast &&
  698. I.getOperand(0)->getType()->isVectorTy() &&
  699. OpRange.getBitWidth() < DL.getTypeSizeInBits(DestTy))
  700. return (void)markOverdefined(&I);
  701. ConstantRange Res =
  702. OpRange.castOp(I.getOpcode(), DL.getTypeSizeInBits(DestTy));
  703. mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
  704. } else
  705. markOverdefined(&I);
  706. }
  707. void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
  708. // If this returns a struct, mark all elements over defined, we don't track
  709. // structs in structs.
  710. if (EVI.getType()->isStructTy())
  711. return (void)markOverdefined(&EVI);
  712. // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  713. // discover a concrete value later.
  714. if (ValueState[&EVI].isOverdefined())
  715. return (void)markOverdefined(&EVI);
  716. // If this is extracting from more than one level of struct, we don't know.
  717. if (EVI.getNumIndices() != 1)
  718. return (void)markOverdefined(&EVI);
  719. Value *AggVal = EVI.getAggregateOperand();
  720. if (AggVal->getType()->isStructTy()) {
  721. unsigned i = *EVI.idx_begin();
  722. ValueLatticeElement EltVal = getStructValueState(AggVal, i);
  723. mergeInValue(getValueState(&EVI), &EVI, EltVal);
  724. } else {
  725. // Otherwise, must be extracting from an array.
  726. return (void)markOverdefined(&EVI);
  727. }
  728. }
  729. void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
  730. auto *STy = dyn_cast<StructType>(IVI.getType());
  731. if (!STy)
  732. return (void)markOverdefined(&IVI);
  733. // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  734. // discover a concrete value later.
  735. if (isOverdefined(ValueState[&IVI]))
  736. return (void)markOverdefined(&IVI);
  737. // If this has more than one index, we can't handle it, drive all results to
  738. // undef.
  739. if (IVI.getNumIndices() != 1)
  740. return (void)markOverdefined(&IVI);
  741. Value *Aggr = IVI.getAggregateOperand();
  742. unsigned Idx = *IVI.idx_begin();
  743. // Compute the result based on what we're inserting.
  744. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  745. // This passes through all values that aren't the inserted element.
  746. if (i != Idx) {
  747. ValueLatticeElement EltVal = getStructValueState(Aggr, i);
  748. mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
  749. continue;
  750. }
  751. Value *Val = IVI.getInsertedValueOperand();
  752. if (Val->getType()->isStructTy())
  753. // We don't track structs in structs.
  754. markOverdefined(getStructValueState(&IVI, i), &IVI);
  755. else {
  756. ValueLatticeElement InVal = getValueState(Val);
  757. mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
  758. }
  759. }
  760. }
  761. void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
  762. // If this select returns a struct, just mark the result overdefined.
  763. // TODO: We could do a lot better than this if code actually uses this.
  764. if (I.getType()->isStructTy())
  765. return (void)markOverdefined(&I);
  766. // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  767. // discover a concrete value later.
  768. if (ValueState[&I].isOverdefined())
  769. return (void)markOverdefined(&I);
  770. ValueLatticeElement CondValue = getValueState(I.getCondition());
  771. if (CondValue.isUnknownOrUndef())
  772. return;
  773. if (ConstantInt *CondCB = getConstantInt(CondValue)) {
  774. Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
  775. mergeInValue(&I, getValueState(OpVal));
  776. return;
  777. }
  778. // Otherwise, the condition is overdefined or a constant we can't evaluate.
  779. // See if we can produce something better than overdefined based on the T/F
  780. // value.
  781. ValueLatticeElement TVal = getValueState(I.getTrueValue());
  782. ValueLatticeElement FVal = getValueState(I.getFalseValue());
  783. bool Changed = ValueState[&I].mergeIn(TVal);
  784. Changed |= ValueState[&I].mergeIn(FVal);
  785. if (Changed)
  786. pushToWorkListMsg(ValueState[&I], &I);
  787. }
  788. // Handle Unary Operators.
  789. void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
  790. ValueLatticeElement V0State = getValueState(I.getOperand(0));
  791. ValueLatticeElement &IV = ValueState[&I];
  792. // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  793. // discover a concrete value later.
  794. if (isOverdefined(IV))
  795. return (void)markOverdefined(&I);
  796. if (isConstant(V0State)) {
  797. Constant *C = ConstantExpr::get(I.getOpcode(), getConstant(V0State));
  798. // op Y -> undef.
  799. if (isa<UndefValue>(C))
  800. return;
  801. return (void)markConstant(IV, &I, C);
  802. }
  803. // If something is undef, wait for it to resolve.
  804. if (!isOverdefined(V0State))
  805. return;
  806. markOverdefined(&I);
  807. }
  808. // Handle Binary Operators.
  809. void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
  810. ValueLatticeElement V1State = getValueState(I.getOperand(0));
  811. ValueLatticeElement V2State = getValueState(I.getOperand(1));
  812. ValueLatticeElement &IV = ValueState[&I];
  813. if (IV.isOverdefined())
  814. return;
  815. // If something is undef, wait for it to resolve.
  816. if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
  817. return;
  818. if (V1State.isOverdefined() && V2State.isOverdefined())
  819. return (void)markOverdefined(&I);
  820. // If either of the operands is a constant, try to fold it to a constant.
  821. // TODO: Use information from notconstant better.
  822. if ((V1State.isConstant() || V2State.isConstant())) {
  823. Value *V1 = isConstant(V1State) ? getConstant(V1State) : I.getOperand(0);
  824. Value *V2 = isConstant(V2State) ? getConstant(V2State) : I.getOperand(1);
  825. Value *R = SimplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL));
  826. auto *C = dyn_cast_or_null<Constant>(R);
  827. if (C) {
  828. // X op Y -> undef.
  829. if (isa<UndefValue>(C))
  830. return;
  831. // Conservatively assume that the result may be based on operands that may
  832. // be undef. Note that we use mergeInValue to combine the constant with
  833. // the existing lattice value for I, as different constants might be found
  834. // after one of the operands go to overdefined, e.g. due to one operand
  835. // being a special floating value.
  836. ValueLatticeElement NewV;
  837. NewV.markConstant(C, /*MayIncludeUndef=*/true);
  838. return (void)mergeInValue(&I, NewV);
  839. }
  840. }
  841. // Only use ranges for binary operators on integers.
  842. if (!I.getType()->isIntegerTy())
  843. return markOverdefined(&I);
  844. // Try to simplify to a constant range.
  845. ConstantRange A = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
  846. ConstantRange B = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
  847. if (V1State.isConstantRange())
  848. A = V1State.getConstantRange();
  849. if (V2State.isConstantRange())
  850. B = V2State.getConstantRange();
  851. ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B);
  852. mergeInValue(&I, ValueLatticeElement::getRange(R));
  853. // TODO: Currently we do not exploit special values that produce something
  854. // better than overdefined with an overdefined operand for vector or floating
  855. // point types, like and <4 x i32> overdefined, zeroinitializer.
  856. }
  857. // Handle ICmpInst instruction.
  858. void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
  859. // Do not cache this lookup, getValueState calls later in the function might
  860. // invalidate the reference.
  861. if (isOverdefined(ValueState[&I]))
  862. return (void)markOverdefined(&I);
  863. Value *Op1 = I.getOperand(0);
  864. Value *Op2 = I.getOperand(1);
  865. // For parameters, use ParamState which includes constant range info if
  866. // available.
  867. auto V1State = getValueState(Op1);
  868. auto V2State = getValueState(Op2);
  869. Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
  870. if (C) {
  871. if (isa<UndefValue>(C))
  872. return;
  873. ValueLatticeElement CV;
  874. CV.markConstant(C);
  875. mergeInValue(&I, CV);
  876. return;
  877. }
  878. // If operands are still unknown, wait for it to resolve.
  879. if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
  880. !isConstant(ValueState[&I]))
  881. return;
  882. markOverdefined(&I);
  883. }
  884. // Handle getelementptr instructions. If all operands are constants then we
  885. // can turn this into a getelementptr ConstantExpr.
  886. void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
  887. if (isOverdefined(ValueState[&I]))
  888. return (void)markOverdefined(&I);
  889. SmallVector<Constant *, 8> Operands;
  890. Operands.reserve(I.getNumOperands());
  891. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  892. ValueLatticeElement State = getValueState(I.getOperand(i));
  893. if (State.isUnknownOrUndef())
  894. return; // Operands are not resolved yet.
  895. if (isOverdefined(State))
  896. return (void)markOverdefined(&I);
  897. if (Constant *C = getConstant(State)) {
  898. Operands.push_back(C);
  899. continue;
  900. }
  901. return (void)markOverdefined(&I);
  902. }
  903. Constant *Ptr = Operands[0];
  904. auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
  905. Constant *C =
  906. ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
  907. if (isa<UndefValue>(C))
  908. return;
  909. markConstant(&I, C);
  910. }
  911. void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
  912. // If this store is of a struct, ignore it.
  913. if (SI.getOperand(0)->getType()->isStructTy())
  914. return;
  915. if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
  916. return;
  917. GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
  918. auto I = TrackedGlobals.find(GV);
  919. if (I == TrackedGlobals.end())
  920. return;
  921. // Get the value we are storing into the global, then merge it.
  922. mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
  923. ValueLatticeElement::MergeOptions().setCheckWiden(false));
  924. if (I->second.isOverdefined())
  925. TrackedGlobals.erase(I); // No need to keep tracking this!
  926. }
  927. static ValueLatticeElement getValueFromMetadata(const Instruction *I) {
  928. if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
  929. if (I->getType()->isIntegerTy())
  930. return ValueLatticeElement::getRange(
  931. getConstantRangeFromMetadata(*Ranges));
  932. if (I->hasMetadata(LLVMContext::MD_nonnull))
  933. return ValueLatticeElement::getNot(
  934. ConstantPointerNull::get(cast<PointerType>(I->getType())));
  935. return ValueLatticeElement::getOverdefined();
  936. }
  937. // Handle load instructions. If the operand is a constant pointer to a constant
  938. // global, we can replace the load with the loaded constant value!
  939. void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
  940. // If this load is of a struct or the load is volatile, just mark the result
  941. // as overdefined.
  942. if (I.getType()->isStructTy() || I.isVolatile())
  943. return (void)markOverdefined(&I);
  944. // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
  945. // discover a concrete value later.
  946. if (ValueState[&I].isOverdefined())
  947. return (void)markOverdefined(&I);
  948. ValueLatticeElement PtrVal = getValueState(I.getOperand(0));
  949. if (PtrVal.isUnknownOrUndef())
  950. return; // The pointer is not resolved yet!
  951. ValueLatticeElement &IV = ValueState[&I];
  952. if (isConstant(PtrVal)) {
  953. Constant *Ptr = getConstant(PtrVal);
  954. // load null is undefined.
  955. if (isa<ConstantPointerNull>(Ptr)) {
  956. if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
  957. return (void)markOverdefined(IV, &I);
  958. else
  959. return;
  960. }
  961. // Transform load (constant global) into the value loaded.
  962. if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
  963. if (!TrackedGlobals.empty()) {
  964. // If we are tracking this global, merge in the known value for it.
  965. auto It = TrackedGlobals.find(GV);
  966. if (It != TrackedGlobals.end()) {
  967. mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
  968. return;
  969. }
  970. }
  971. }
  972. // Transform load from a constant into a constant if possible.
  973. if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
  974. if (isa<UndefValue>(C))
  975. return;
  976. return (void)markConstant(IV, &I, C);
  977. }
  978. }
  979. // Fall back to metadata.
  980. mergeInValue(&I, getValueFromMetadata(&I));
  981. }
  982. void SCCPInstVisitor::visitCallBase(CallBase &CB) {
  983. handleCallResult(CB);
  984. handleCallArguments(CB);
  985. }
  986. void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
  987. Function *F = CB.getCalledFunction();
  988. // Void return and not tracking callee, just bail.
  989. if (CB.getType()->isVoidTy())
  990. return;
  991. // Always mark struct return as overdefined.
  992. if (CB.getType()->isStructTy())
  993. return (void)markOverdefined(&CB);
  994. // Otherwise, if we have a single return value case, and if the function is
  995. // a declaration, maybe we can constant fold it.
  996. if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
  997. SmallVector<Constant *, 8> Operands;
  998. for (const Use &A : CB.args()) {
  999. if (A.get()->getType()->isStructTy())
  1000. return markOverdefined(&CB); // Can't handle struct args.
  1001. ValueLatticeElement State = getValueState(A);
  1002. if (State.isUnknownOrUndef())
  1003. return; // Operands are not resolved yet.
  1004. if (isOverdefined(State))
  1005. return (void)markOverdefined(&CB);
  1006. assert(isConstant(State) && "Unknown state!");
  1007. Operands.push_back(getConstant(State));
  1008. }
  1009. if (isOverdefined(getValueState(&CB)))
  1010. return (void)markOverdefined(&CB);
  1011. // If we can constant fold this, mark the result of the call as a
  1012. // constant.
  1013. if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F))) {
  1014. // call -> undef.
  1015. if (isa<UndefValue>(C))
  1016. return;
  1017. return (void)markConstant(&CB, C);
  1018. }
  1019. }
  1020. // Fall back to metadata.
  1021. mergeInValue(&CB, getValueFromMetadata(&CB));
  1022. }
  1023. void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
  1024. Function *F = CB.getCalledFunction();
  1025. // If this is a local function that doesn't have its address taken, mark its
  1026. // entry block executable and merge in the actual arguments to the call into
  1027. // the formal arguments of the function.
  1028. if (!TrackingIncomingArguments.empty() &&
  1029. TrackingIncomingArguments.count(F)) {
  1030. markBlockExecutable(&F->front());
  1031. // Propagate information from this call site into the callee.
  1032. auto CAI = CB.arg_begin();
  1033. for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
  1034. ++AI, ++CAI) {
  1035. // If this argument is byval, and if the function is not readonly, there
  1036. // will be an implicit copy formed of the input aggregate.
  1037. if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
  1038. markOverdefined(&*AI);
  1039. continue;
  1040. }
  1041. if (auto *STy = dyn_cast<StructType>(AI->getType())) {
  1042. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1043. ValueLatticeElement CallArg = getStructValueState(*CAI, i);
  1044. mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
  1045. getMaxWidenStepsOpts());
  1046. }
  1047. } else
  1048. mergeInValue(&*AI, getValueState(*CAI), getMaxWidenStepsOpts());
  1049. }
  1050. }
  1051. }
  1052. void SCCPInstVisitor::handleCallResult(CallBase &CB) {
  1053. Function *F = CB.getCalledFunction();
  1054. if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
  1055. if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
  1056. if (ValueState[&CB].isOverdefined())
  1057. return;
  1058. Value *CopyOf = CB.getOperand(0);
  1059. ValueLatticeElement CopyOfVal = getValueState(CopyOf);
  1060. const auto *PI = getPredicateInfoFor(&CB);
  1061. assert(PI && "Missing predicate info for ssa.copy");
  1062. const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
  1063. if (!Constraint) {
  1064. mergeInValue(ValueState[&CB], &CB, CopyOfVal);
  1065. return;
  1066. }
  1067. CmpInst::Predicate Pred = Constraint->Predicate;
  1068. Value *OtherOp = Constraint->OtherOp;
  1069. // Wait until OtherOp is resolved.
  1070. if (getValueState(OtherOp).isUnknown()) {
  1071. addAdditionalUser(OtherOp, &CB);
  1072. return;
  1073. }
  1074. // TODO: Actually filp MayIncludeUndef for the created range to false,
  1075. // once most places in the optimizer respect the branches on
  1076. // undef/poison are UB rule. The reason why the new range cannot be
  1077. // undef is as follows below:
  1078. // The new range is based on a branch condition. That guarantees that
  1079. // neither of the compare operands can be undef in the branch targets,
  1080. // unless we have conditions that are always true/false (e.g. icmp ule
  1081. // i32, %a, i32_max). For the latter overdefined/empty range will be
  1082. // inferred, but the branch will get folded accordingly anyways.
  1083. bool MayIncludeUndef = !isa<PredicateAssume>(PI);
  1084. ValueLatticeElement CondVal = getValueState(OtherOp);
  1085. ValueLatticeElement &IV = ValueState[&CB];
  1086. if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
  1087. auto ImposedCR =
  1088. ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
  1089. // Get the range imposed by the condition.
  1090. if (CondVal.isConstantRange())
  1091. ImposedCR = ConstantRange::makeAllowedICmpRegion(
  1092. Pred, CondVal.getConstantRange());
  1093. // Combine range info for the original value with the new range from the
  1094. // condition.
  1095. auto CopyOfCR = CopyOfVal.isConstantRange()
  1096. ? CopyOfVal.getConstantRange()
  1097. : ConstantRange::getFull(
  1098. DL.getTypeSizeInBits(CopyOf->getType()));
  1099. auto NewCR = ImposedCR.intersectWith(CopyOfCR);
  1100. // If the existing information is != x, do not use the information from
  1101. // a chained predicate, as the != x information is more likely to be
  1102. // helpful in practice.
  1103. if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
  1104. NewCR = CopyOfCR;
  1105. addAdditionalUser(OtherOp, &CB);
  1106. mergeInValue(IV, &CB,
  1107. ValueLatticeElement::getRange(NewCR, MayIncludeUndef));
  1108. return;
  1109. } else if (Pred == CmpInst::ICMP_EQ && CondVal.isConstant()) {
  1110. // For non-integer values or integer constant expressions, only
  1111. // propagate equal constants.
  1112. addAdditionalUser(OtherOp, &CB);
  1113. mergeInValue(IV, &CB, CondVal);
  1114. return;
  1115. } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant() &&
  1116. !MayIncludeUndef) {
  1117. // Propagate inequalities.
  1118. addAdditionalUser(OtherOp, &CB);
  1119. mergeInValue(IV, &CB,
  1120. ValueLatticeElement::getNot(CondVal.getConstant()));
  1121. return;
  1122. }
  1123. return (void)mergeInValue(IV, &CB, CopyOfVal);
  1124. }
  1125. if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
  1126. // Compute result range for intrinsics supported by ConstantRange.
  1127. // Do this even if we don't know a range for all operands, as we may
  1128. // still know something about the result range, e.g. of abs(x).
  1129. SmallVector<ConstantRange, 2> OpRanges;
  1130. for (Value *Op : II->args()) {
  1131. const ValueLatticeElement &State = getValueState(Op);
  1132. if (State.isConstantRange())
  1133. OpRanges.push_back(State.getConstantRange());
  1134. else
  1135. OpRanges.push_back(
  1136. ConstantRange::getFull(Op->getType()->getScalarSizeInBits()));
  1137. }
  1138. ConstantRange Result =
  1139. ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
  1140. return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
  1141. }
  1142. }
  1143. // The common case is that we aren't tracking the callee, either because we
  1144. // are not doing interprocedural analysis or the callee is indirect, or is
  1145. // external. Handle these cases first.
  1146. if (!F || F->isDeclaration())
  1147. return handleCallOverdefined(CB);
  1148. // If this is a single/zero retval case, see if we're tracking the function.
  1149. if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
  1150. if (!MRVFunctionsTracked.count(F))
  1151. return handleCallOverdefined(CB); // Not tracking this callee.
  1152. // If we are tracking this callee, propagate the result of the function
  1153. // into this call site.
  1154. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
  1155. mergeInValue(getStructValueState(&CB, i), &CB,
  1156. TrackedMultipleRetVals[std::make_pair(F, i)],
  1157. getMaxWidenStepsOpts());
  1158. } else {
  1159. auto TFRVI = TrackedRetVals.find(F);
  1160. if (TFRVI == TrackedRetVals.end())
  1161. return handleCallOverdefined(CB); // Not tracking this callee.
  1162. // If so, propagate the return value of the callee into this call result.
  1163. mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts());
  1164. }
  1165. }
  1166. void SCCPInstVisitor::solve() {
  1167. // Process the work lists until they are empty!
  1168. while (!BBWorkList.empty() || !InstWorkList.empty() ||
  1169. !OverdefinedInstWorkList.empty()) {
  1170. // Process the overdefined instruction's work list first, which drives other
  1171. // things to overdefined more quickly.
  1172. while (!OverdefinedInstWorkList.empty()) {
  1173. Value *I = OverdefinedInstWorkList.pop_back_val();
  1174. LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
  1175. // "I" got into the work list because it either made the transition from
  1176. // bottom to constant, or to overdefined.
  1177. //
  1178. // Anything on this worklist that is overdefined need not be visited
  1179. // since all of its users will have already been marked as overdefined
  1180. // Update all of the users of this instruction's value.
  1181. //
  1182. markUsersAsChanged(I);
  1183. }
  1184. // Process the instruction work list.
  1185. while (!InstWorkList.empty()) {
  1186. Value *I = InstWorkList.pop_back_val();
  1187. LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
  1188. // "I" got into the work list because it made the transition from undef to
  1189. // constant.
  1190. //
  1191. // Anything on this worklist that is overdefined need not be visited
  1192. // since all of its users will have already been marked as overdefined.
  1193. // Update all of the users of this instruction's value.
  1194. //
  1195. if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
  1196. markUsersAsChanged(I);
  1197. }
  1198. // Process the basic block work list.
  1199. while (!BBWorkList.empty()) {
  1200. BasicBlock *BB = BBWorkList.pop_back_val();
  1201. LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
  1202. // Notify all instructions in this basic block that they are newly
  1203. // executable.
  1204. visit(BB);
  1205. }
  1206. }
  1207. }
  1208. /// resolvedUndefsIn - While solving the dataflow for a function, we assume
  1209. /// that branches on undef values cannot reach any of their successors.
  1210. /// However, this is not a safe assumption. After we solve dataflow, this
  1211. /// method should be use to handle this. If this returns true, the solver
  1212. /// should be rerun.
  1213. ///
  1214. /// This method handles this by finding an unresolved branch and marking it one
  1215. /// of the edges from the block as being feasible, even though the condition
  1216. /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
  1217. /// CFG and only slightly pessimizes the analysis results (by marking one,
  1218. /// potentially infeasible, edge feasible). This cannot usefully modify the
  1219. /// constraints on the condition of the branch, as that would impact other users
  1220. /// of the value.
  1221. ///
  1222. /// This scan also checks for values that use undefs. It conservatively marks
  1223. /// them as overdefined.
  1224. bool SCCPInstVisitor::resolvedUndefsIn(Function &F) {
  1225. bool MadeChange = false;
  1226. for (BasicBlock &BB : F) {
  1227. if (!BBExecutable.count(&BB))
  1228. continue;
  1229. for (Instruction &I : BB) {
  1230. // Look for instructions which produce undef values.
  1231. if (I.getType()->isVoidTy())
  1232. continue;
  1233. if (auto *STy = dyn_cast<StructType>(I.getType())) {
  1234. // Only a few things that can be structs matter for undef.
  1235. // Tracked calls must never be marked overdefined in resolvedUndefsIn.
  1236. if (auto *CB = dyn_cast<CallBase>(&I))
  1237. if (Function *F = CB->getCalledFunction())
  1238. if (MRVFunctionsTracked.count(F))
  1239. continue;
  1240. // extractvalue and insertvalue don't need to be marked; they are
  1241. // tracked as precisely as their operands.
  1242. if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
  1243. continue;
  1244. // Send the results of everything else to overdefined. We could be
  1245. // more precise than this but it isn't worth bothering.
  1246. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1247. ValueLatticeElement &LV = getStructValueState(&I, i);
  1248. if (LV.isUnknownOrUndef()) {
  1249. markOverdefined(LV, &I);
  1250. MadeChange = true;
  1251. }
  1252. }
  1253. continue;
  1254. }
  1255. ValueLatticeElement &LV = getValueState(&I);
  1256. if (!LV.isUnknownOrUndef())
  1257. continue;
  1258. // There are two reasons a call can have an undef result
  1259. // 1. It could be tracked.
  1260. // 2. It could be constant-foldable.
  1261. // Because of the way we solve return values, tracked calls must
  1262. // never be marked overdefined in resolvedUndefsIn.
  1263. if (auto *CB = dyn_cast<CallBase>(&I))
  1264. if (Function *F = CB->getCalledFunction())
  1265. if (TrackedRetVals.count(F))
  1266. continue;
  1267. if (isa<LoadInst>(I)) {
  1268. // A load here means one of two things: a load of undef from a global,
  1269. // a load from an unknown pointer. Either way, having it return undef
  1270. // is okay.
  1271. continue;
  1272. }
  1273. markOverdefined(&I);
  1274. MadeChange = true;
  1275. }
  1276. // Check to see if we have a branch or switch on an undefined value. If so
  1277. // we force the branch to go one way or the other to make the successor
  1278. // values live. It doesn't really matter which way we force it.
  1279. Instruction *TI = BB.getTerminator();
  1280. if (auto *BI = dyn_cast<BranchInst>(TI)) {
  1281. if (!BI->isConditional())
  1282. continue;
  1283. if (!getValueState(BI->getCondition()).isUnknownOrUndef())
  1284. continue;
  1285. // If the input to SCCP is actually branch on undef, fix the undef to
  1286. // false.
  1287. if (isa<UndefValue>(BI->getCondition())) {
  1288. BI->setCondition(ConstantInt::getFalse(BI->getContext()));
  1289. markEdgeExecutable(&BB, TI->getSuccessor(1));
  1290. MadeChange = true;
  1291. continue;
  1292. }
  1293. // Otherwise, it is a branch on a symbolic value which is currently
  1294. // considered to be undef. Make sure some edge is executable, so a
  1295. // branch on "undef" always flows somewhere.
  1296. // FIXME: Distinguish between dead code and an LLVM "undef" value.
  1297. BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
  1298. if (markEdgeExecutable(&BB, DefaultSuccessor))
  1299. MadeChange = true;
  1300. continue;
  1301. }
  1302. if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
  1303. // Indirect branch with no successor ?. Its ok to assume it branches
  1304. // to no target.
  1305. if (IBR->getNumSuccessors() < 1)
  1306. continue;
  1307. if (!getValueState(IBR->getAddress()).isUnknownOrUndef())
  1308. continue;
  1309. // If the input to SCCP is actually branch on undef, fix the undef to
  1310. // the first successor of the indirect branch.
  1311. if (isa<UndefValue>(IBR->getAddress())) {
  1312. IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
  1313. markEdgeExecutable(&BB, IBR->getSuccessor(0));
  1314. MadeChange = true;
  1315. continue;
  1316. }
  1317. // Otherwise, it is a branch on a symbolic value which is currently
  1318. // considered to be undef. Make sure some edge is executable, so a
  1319. // branch on "undef" always flows somewhere.
  1320. // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
  1321. // we can assume the branch has undefined behavior instead.
  1322. BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
  1323. if (markEdgeExecutable(&BB, DefaultSuccessor))
  1324. MadeChange = true;
  1325. continue;
  1326. }
  1327. if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  1328. if (!SI->getNumCases() ||
  1329. !getValueState(SI->getCondition()).isUnknownOrUndef())
  1330. continue;
  1331. // If the input to SCCP is actually switch on undef, fix the undef to
  1332. // the first constant.
  1333. if (isa<UndefValue>(SI->getCondition())) {
  1334. SI->setCondition(SI->case_begin()->getCaseValue());
  1335. markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
  1336. MadeChange = true;
  1337. continue;
  1338. }
  1339. // Otherwise, it is a branch on a symbolic value which is currently
  1340. // considered to be undef. Make sure some edge is executable, so a
  1341. // branch on "undef" always flows somewhere.
  1342. // FIXME: Distinguish between dead code and an LLVM "undef" value.
  1343. BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
  1344. if (markEdgeExecutable(&BB, DefaultSuccessor))
  1345. MadeChange = true;
  1346. continue;
  1347. }
  1348. }
  1349. return MadeChange;
  1350. }
  1351. //===----------------------------------------------------------------------===//
  1352. //
  1353. // SCCPSolver implementations
  1354. //
  1355. SCCPSolver::SCCPSolver(
  1356. const DataLayout &DL,
  1357. std::function<const TargetLibraryInfo &(Function &)> GetTLI,
  1358. LLVMContext &Ctx)
  1359. : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
  1360. SCCPSolver::~SCCPSolver() {}
  1361. void SCCPSolver::addAnalysis(Function &F, AnalysisResultsForFn A) {
  1362. return Visitor->addAnalysis(F, std::move(A));
  1363. }
  1364. bool SCCPSolver::markBlockExecutable(BasicBlock *BB) {
  1365. return Visitor->markBlockExecutable(BB);
  1366. }
  1367. const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) {
  1368. return Visitor->getPredicateInfoFor(I);
  1369. }
  1370. DomTreeUpdater SCCPSolver::getDTU(Function &F) { return Visitor->getDTU(F); }
  1371. void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) {
  1372. Visitor->trackValueOfGlobalVariable(GV);
  1373. }
  1374. void SCCPSolver::addTrackedFunction(Function *F) {
  1375. Visitor->addTrackedFunction(F);
  1376. }
  1377. void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) {
  1378. Visitor->addToMustPreserveReturnsInFunctions(F);
  1379. }
  1380. bool SCCPSolver::mustPreserveReturn(Function *F) {
  1381. return Visitor->mustPreserveReturn(F);
  1382. }
  1383. void SCCPSolver::addArgumentTrackedFunction(Function *F) {
  1384. Visitor->addArgumentTrackedFunction(F);
  1385. }
  1386. bool SCCPSolver::isArgumentTrackedFunction(Function *F) {
  1387. return Visitor->isArgumentTrackedFunction(F);
  1388. }
  1389. void SCCPSolver::solve() { Visitor->solve(); }
  1390. bool SCCPSolver::resolvedUndefsIn(Function &F) {
  1391. return Visitor->resolvedUndefsIn(F);
  1392. }
  1393. bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const {
  1394. return Visitor->isBlockExecutable(BB);
  1395. }
  1396. bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
  1397. return Visitor->isEdgeFeasible(From, To);
  1398. }
  1399. std::vector<ValueLatticeElement>
  1400. SCCPSolver::getStructLatticeValueFor(Value *V) const {
  1401. return Visitor->getStructLatticeValueFor(V);
  1402. }
  1403. void SCCPSolver::removeLatticeValueFor(Value *V) {
  1404. return Visitor->removeLatticeValueFor(V);
  1405. }
  1406. const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const {
  1407. return Visitor->getLatticeValueFor(V);
  1408. }
  1409. const MapVector<Function *, ValueLatticeElement> &
  1410. SCCPSolver::getTrackedRetVals() {
  1411. return Visitor->getTrackedRetVals();
  1412. }
  1413. const DenseMap<GlobalVariable *, ValueLatticeElement> &
  1414. SCCPSolver::getTrackedGlobals() {
  1415. return Visitor->getTrackedGlobals();
  1416. }
  1417. const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() {
  1418. return Visitor->getMRVFunctionsTracked();
  1419. }
  1420. void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
  1421. bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) {
  1422. return Visitor->isStructLatticeConstant(F, STy);
  1423. }
  1424. Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV) const {
  1425. return Visitor->getConstant(LV);
  1426. }
  1427. SmallPtrSetImpl<Function *> &SCCPSolver::getArgumentTrackedFunctions() {
  1428. return Visitor->getArgumentTrackedFunctions();
  1429. }
  1430. void SCCPSolver::markArgInFuncSpecialization(Function *F, Argument *A,
  1431. Constant *C) {
  1432. Visitor->markArgInFuncSpecialization(F, A, C);
  1433. }
  1434. void SCCPSolver::markFunctionUnreachable(Function *F) {
  1435. Visitor->markFunctionUnreachable(F);
  1436. }
  1437. void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
  1438. void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }