Local.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  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 family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SetVector.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/EHPersonalities.h"
  23. #include "llvm/Analysis/InstructionSimplify.h"
  24. #include "llvm/Analysis/LazyValueInfo.h"
  25. #include "llvm/Analysis/MemoryBuiltins.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/IR/CFG.h"
  28. #include "llvm/IR/ConstantRange.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DIBuilder.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/GetElementPtrTypeIterator.h"
  36. #include "llvm/IR/GlobalAlias.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/IRBuilder.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/IntrinsicInst.h"
  41. #include "llvm/IR/Intrinsics.h"
  42. #include "llvm/IR/MDBuilder.h"
  43. #include "llvm/IR/Metadata.h"
  44. #include "llvm/IR/Operator.h"
  45. #include "llvm/IR/PatternMatch.h"
  46. #include "llvm/IR/ValueHandle.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/KnownBits.h"
  49. #include "llvm/Support/MathExtras.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. using namespace llvm;
  52. using namespace llvm::PatternMatch;
  53. #define DEBUG_TYPE "local"
  54. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  55. //===----------------------------------------------------------------------===//
  56. // Local constant propagation.
  57. //
  58. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  59. /// constant value, convert it into an unconditional branch to the constant
  60. /// destination. This is a nontrivial operation because the successors of this
  61. /// basic block must have their PHI nodes updated.
  62. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  63. /// conditions and indirectbr addresses this might make dead if
  64. /// DeleteDeadConditions is true.
  65. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  66. const TargetLibraryInfo *TLI) {
  67. TerminatorInst *T = BB->getTerminator();
  68. IRBuilder<> Builder(T);
  69. // Branch - See if we are conditional jumping on constant
  70. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  71. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  72. BasicBlock *Dest1 = BI->getSuccessor(0);
  73. BasicBlock *Dest2 = BI->getSuccessor(1);
  74. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  75. // Are we branching on constant?
  76. // YES. Change to unconditional branch...
  77. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  78. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  79. //cerr << "Function: " << T->getParent()->getParent()
  80. // << "\nRemoving branch from " << T->getParent()
  81. // << "\n\nTo: " << OldDest << endl;
  82. // Let the basic block know that we are letting go of it. Based on this,
  83. // it will adjust it's PHI nodes.
  84. OldDest->removePredecessor(BB);
  85. // Replace the conditional branch with an unconditional one.
  86. Builder.CreateBr(Destination);
  87. BI->eraseFromParent();
  88. return true;
  89. }
  90. if (Dest2 == Dest1) { // Conditional branch to same location?
  91. // This branch matches something like this:
  92. // br bool %cond, label %Dest, label %Dest
  93. // and changes it into: br label %Dest
  94. // Let the basic block know that we are letting go of one copy of it.
  95. assert(BI->getParent() && "Terminator not inserted in block!");
  96. Dest1->removePredecessor(BI->getParent());
  97. // Replace the conditional branch with an unconditional one.
  98. Builder.CreateBr(Dest1);
  99. Value *Cond = BI->getCondition();
  100. BI->eraseFromParent();
  101. if (DeleteDeadConditions)
  102. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  103. return true;
  104. }
  105. return false;
  106. }
  107. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  108. // If we are switching on a constant, we can convert the switch to an
  109. // unconditional branch.
  110. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  111. BasicBlock *DefaultDest = SI->getDefaultDest();
  112. BasicBlock *TheOnlyDest = DefaultDest;
  113. // If the default is unreachable, ignore it when searching for TheOnlyDest.
  114. if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
  115. SI->getNumCases() > 0) {
  116. TheOnlyDest = SI->case_begin()->getCaseSuccessor();
  117. }
  118. // Figure out which case it goes to.
  119. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  120. // Found case matching a constant operand?
  121. if (i->getCaseValue() == CI) {
  122. TheOnlyDest = i->getCaseSuccessor();
  123. break;
  124. }
  125. // Check to see if this branch is going to the same place as the default
  126. // dest. If so, eliminate it as an explicit compare.
  127. if (i->getCaseSuccessor() == DefaultDest) {
  128. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  129. unsigned NCases = SI->getNumCases();
  130. // Fold the case metadata into the default if there will be any branches
  131. // left, unless the metadata doesn't match the switch.
  132. if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
  133. // Collect branch weights into a vector.
  134. SmallVector<uint32_t, 8> Weights;
  135. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  136. ++MD_i) {
  137. auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  138. Weights.push_back(CI->getValue().getZExtValue());
  139. }
  140. // Merge weight of this case to the default weight.
  141. unsigned idx = i->getCaseIndex();
  142. Weights[0] += Weights[idx+1];
  143. // Remove weight for this case.
  144. std::swap(Weights[idx+1], Weights.back());
  145. Weights.pop_back();
  146. SI->setMetadata(LLVMContext::MD_prof,
  147. MDBuilder(BB->getContext()).
  148. createBranchWeights(Weights));
  149. }
  150. // Remove this entry.
  151. DefaultDest->removePredecessor(SI->getParent());
  152. i = SI->removeCase(i);
  153. e = SI->case_end();
  154. continue;
  155. }
  156. // Otherwise, check to see if the switch only branches to one destination.
  157. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  158. // destinations.
  159. if (i->getCaseSuccessor() != TheOnlyDest)
  160. TheOnlyDest = nullptr;
  161. // Increment this iterator as we haven't removed the case.
  162. ++i;
  163. }
  164. if (CI && !TheOnlyDest) {
  165. // Branching on a constant, but not any of the cases, go to the default
  166. // successor.
  167. TheOnlyDest = SI->getDefaultDest();
  168. }
  169. // If we found a single destination that we can fold the switch into, do so
  170. // now.
  171. if (TheOnlyDest) {
  172. // Insert the new branch.
  173. Builder.CreateBr(TheOnlyDest);
  174. BasicBlock *BB = SI->getParent();
  175. // Remove entries from PHI nodes which we no longer branch to...
  176. for (BasicBlock *Succ : SI->successors()) {
  177. // Found case matching a constant operand?
  178. if (Succ == TheOnlyDest)
  179. TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
  180. else
  181. Succ->removePredecessor(BB);
  182. }
  183. // Delete the old switch.
  184. Value *Cond = SI->getCondition();
  185. SI->eraseFromParent();
  186. if (DeleteDeadConditions)
  187. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  188. return true;
  189. }
  190. if (SI->getNumCases() == 1) {
  191. // Otherwise, we can fold this switch into a conditional branch
  192. // instruction if it has only one non-default destination.
  193. auto FirstCase = *SI->case_begin();
  194. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  195. FirstCase.getCaseValue(), "cond");
  196. // Insert the new branch.
  197. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  198. FirstCase.getCaseSuccessor(),
  199. SI->getDefaultDest());
  200. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  201. if (MD && MD->getNumOperands() == 3) {
  202. ConstantInt *SICase =
  203. mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  204. ConstantInt *SIDef =
  205. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  206. assert(SICase && SIDef);
  207. // The TrueWeight should be the weight for the single case of SI.
  208. NewBr->setMetadata(LLVMContext::MD_prof,
  209. MDBuilder(BB->getContext()).
  210. createBranchWeights(SICase->getValue().getZExtValue(),
  211. SIDef->getValue().getZExtValue()));
  212. }
  213. // Update make.implicit metadata to the newly-created conditional branch.
  214. MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
  215. if (MakeImplicitMD)
  216. NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
  217. // Delete the old switch.
  218. SI->eraseFromParent();
  219. return true;
  220. }
  221. return false;
  222. }
  223. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  224. // indirectbr blockaddress(@F, @BB) -> br label @BB
  225. if (BlockAddress *BA =
  226. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  227. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  228. // Insert the new branch.
  229. Builder.CreateBr(TheOnlyDest);
  230. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  231. if (IBI->getDestination(i) == TheOnlyDest)
  232. TheOnlyDest = nullptr;
  233. else
  234. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  235. }
  236. Value *Address = IBI->getAddress();
  237. IBI->eraseFromParent();
  238. if (DeleteDeadConditions)
  239. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  240. // If we didn't find our destination in the IBI successor list, then we
  241. // have undefined behavior. Replace the unconditional branch with an
  242. // 'unreachable' instruction.
  243. if (TheOnlyDest) {
  244. BB->getTerminator()->eraseFromParent();
  245. new UnreachableInst(BB->getContext(), BB);
  246. }
  247. return true;
  248. }
  249. }
  250. return false;
  251. }
  252. //===----------------------------------------------------------------------===//
  253. // Local dead code elimination.
  254. //
  255. /// isInstructionTriviallyDead - Return true if the result produced by the
  256. /// instruction is not used, and the instruction has no side effects.
  257. ///
  258. bool llvm::isInstructionTriviallyDead(Instruction *I,
  259. const TargetLibraryInfo *TLI) {
  260. if (!I->use_empty())
  261. return false;
  262. return wouldInstructionBeTriviallyDead(I, TLI);
  263. }
  264. bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
  265. const TargetLibraryInfo *TLI) {
  266. if (isa<TerminatorInst>(I))
  267. return false;
  268. // We don't want the landingpad-like instructions removed by anything this
  269. // general.
  270. if (I->isEHPad())
  271. return false;
  272. // We don't want debug info removed by anything this general, unless
  273. // debug info is empty.
  274. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  275. if (DDI->getAddress())
  276. return false;
  277. return true;
  278. }
  279. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  280. if (DVI->getValue())
  281. return false;
  282. return true;
  283. }
  284. if (!I->mayHaveSideEffects())
  285. return true;
  286. // Special case intrinsics that "may have side effects" but can be deleted
  287. // when dead.
  288. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  289. // Safe to delete llvm.stacksave if dead.
  290. if (II->getIntrinsicID() == Intrinsic::stacksave)
  291. return true;
  292. // Lifetime intrinsics are dead when their right-hand is undef.
  293. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  294. II->getIntrinsicID() == Intrinsic::lifetime_end)
  295. return isa<UndefValue>(II->getArgOperand(1));
  296. // Assumptions are dead if their condition is trivially true. Guards on
  297. // true are operationally no-ops. In the future we can consider more
  298. // sophisticated tradeoffs for guards considering potential for check
  299. // widening, but for now we keep things simple.
  300. if (II->getIntrinsicID() == Intrinsic::assume ||
  301. II->getIntrinsicID() == Intrinsic::experimental_guard) {
  302. if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  303. return !Cond->isZero();
  304. return false;
  305. }
  306. }
  307. if (isAllocLikeFn(I, TLI))
  308. return true;
  309. if (CallInst *CI = isFreeCall(I, TLI))
  310. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  311. return C->isNullValue() || isa<UndefValue>(C);
  312. if (CallSite CS = CallSite(I))
  313. if (isMathLibCallNoop(CS, TLI))
  314. return true;
  315. return false;
  316. }
  317. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  318. /// trivially dead instruction, delete it. If that makes any of its operands
  319. /// trivially dead, delete them too, recursively. Return true if any
  320. /// instructions were deleted.
  321. bool
  322. llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
  323. const TargetLibraryInfo *TLI) {
  324. Instruction *I = dyn_cast<Instruction>(V);
  325. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
  326. return false;
  327. SmallVector<Instruction*, 16> DeadInsts;
  328. DeadInsts.push_back(I);
  329. do {
  330. I = DeadInsts.pop_back_val();
  331. // Null out all of the instruction's operands to see if any operand becomes
  332. // dead as we go.
  333. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  334. Value *OpV = I->getOperand(i);
  335. I->setOperand(i, nullptr);
  336. if (!OpV->use_empty()) continue;
  337. // If the operand is an instruction that became dead as we nulled out the
  338. // operand, and if it is 'trivially' dead, delete it in a future loop
  339. // iteration.
  340. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  341. if (isInstructionTriviallyDead(OpI, TLI))
  342. DeadInsts.push_back(OpI);
  343. }
  344. I->eraseFromParent();
  345. } while (!DeadInsts.empty());
  346. return true;
  347. }
  348. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  349. /// This is similar to Instruction::hasOneUse() except this will also return
  350. /// true when there are no uses or multiple uses that all refer to the same
  351. /// value.
  352. static bool areAllUsesEqual(Instruction *I) {
  353. Value::user_iterator UI = I->user_begin();
  354. Value::user_iterator UE = I->user_end();
  355. if (UI == UE)
  356. return true;
  357. User *TheUse = *UI;
  358. for (++UI; UI != UE; ++UI) {
  359. if (*UI != TheUse)
  360. return false;
  361. }
  362. return true;
  363. }
  364. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  365. /// dead PHI node, due to being a def-use chain of single-use nodes that
  366. /// either forms a cycle or is terminated by a trivially dead instruction,
  367. /// delete it. If that makes any of its operands trivially dead, delete them
  368. /// too, recursively. Return true if a change was made.
  369. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  370. const TargetLibraryInfo *TLI) {
  371. SmallPtrSet<Instruction*, 4> Visited;
  372. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  373. I = cast<Instruction>(*I->user_begin())) {
  374. if (I->use_empty())
  375. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  376. // If we find an instruction more than once, we're on a cycle that
  377. // won't prove fruitful.
  378. if (!Visited.insert(I).second) {
  379. // Break the cycle and delete the instruction and its operands.
  380. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  381. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. static bool
  388. simplifyAndDCEInstruction(Instruction *I,
  389. SmallSetVector<Instruction *, 16> &WorkList,
  390. const DataLayout &DL,
  391. const TargetLibraryInfo *TLI) {
  392. if (isInstructionTriviallyDead(I, TLI)) {
  393. // Null out all of the instruction's operands to see if any operand becomes
  394. // dead as we go.
  395. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  396. Value *OpV = I->getOperand(i);
  397. I->setOperand(i, nullptr);
  398. if (!OpV->use_empty() || I == OpV)
  399. continue;
  400. // If the operand is an instruction that became dead as we nulled out the
  401. // operand, and if it is 'trivially' dead, delete it in a future loop
  402. // iteration.
  403. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  404. if (isInstructionTriviallyDead(OpI, TLI))
  405. WorkList.insert(OpI);
  406. }
  407. I->eraseFromParent();
  408. return true;
  409. }
  410. if (Value *SimpleV = SimplifyInstruction(I, DL)) {
  411. // Add the users to the worklist. CAREFUL: an instruction can use itself,
  412. // in the case of a phi node.
  413. for (User *U : I->users()) {
  414. if (U != I) {
  415. WorkList.insert(cast<Instruction>(U));
  416. }
  417. }
  418. // Replace the instruction with its simplified value.
  419. bool Changed = false;
  420. if (!I->use_empty()) {
  421. I->replaceAllUsesWith(SimpleV);
  422. Changed = true;
  423. }
  424. if (isInstructionTriviallyDead(I, TLI)) {
  425. I->eraseFromParent();
  426. Changed = true;
  427. }
  428. return Changed;
  429. }
  430. return false;
  431. }
  432. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  433. /// simplify any instructions in it and recursively delete dead instructions.
  434. ///
  435. /// This returns true if it changed the code, note that it can delete
  436. /// instructions in other blocks as well in this block.
  437. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
  438. const TargetLibraryInfo *TLI) {
  439. bool MadeChange = false;
  440. const DataLayout &DL = BB->getModule()->getDataLayout();
  441. #ifndef NDEBUG
  442. // In debug builds, ensure that the terminator of the block is never replaced
  443. // or deleted by these simplifications. The idea of simplification is that it
  444. // cannot introduce new instructions, and there is no way to replace the
  445. // terminator of a block without introducing a new instruction.
  446. AssertingVH<Instruction> TerminatorVH(&BB->back());
  447. #endif
  448. SmallSetVector<Instruction *, 16> WorkList;
  449. // Iterate over the original function, only adding insts to the worklist
  450. // if they actually need to be revisited. This avoids having to pre-init
  451. // the worklist with the entire function's worth of instructions.
  452. for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
  453. BI != E;) {
  454. assert(!BI->isTerminator());
  455. Instruction *I = &*BI;
  456. ++BI;
  457. // We're visiting this instruction now, so make sure it's not in the
  458. // worklist from an earlier visit.
  459. if (!WorkList.count(I))
  460. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  461. }
  462. while (!WorkList.empty()) {
  463. Instruction *I = WorkList.pop_back_val();
  464. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  465. }
  466. return MadeChange;
  467. }
  468. //===----------------------------------------------------------------------===//
  469. // Control Flow Graph Restructuring.
  470. //
  471. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  472. /// method is called when we're about to delete Pred as a predecessor of BB. If
  473. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  474. ///
  475. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  476. /// nodes that collapse into identity values. For example, if we have:
  477. /// x = phi(1, 0, 0, 0)
  478. /// y = and x, z
  479. ///
  480. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  481. /// recursively fold the and to 0.
  482. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
  483. // This only adjusts blocks with PHI nodes.
  484. if (!isa<PHINode>(BB->begin()))
  485. return;
  486. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  487. // them down. This will leave us with single entry phi nodes and other phis
  488. // that can be removed.
  489. BB->removePredecessor(Pred, true);
  490. WeakTrackingVH PhiIt = &BB->front();
  491. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  492. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  493. Value *OldPhiIt = PhiIt;
  494. if (!recursivelySimplifyInstruction(PN))
  495. continue;
  496. // If recursive simplification ended up deleting the next PHI node we would
  497. // iterate to, then our iterator is invalid, restart scanning from the top
  498. // of the block.
  499. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  500. }
  501. }
  502. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  503. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  504. /// between them, moving the instructions in the predecessor into DestBB and
  505. /// deleting the predecessor block.
  506. ///
  507. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
  508. // If BB has single-entry PHI nodes, fold them.
  509. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  510. Value *NewVal = PN->getIncomingValue(0);
  511. // Replace self referencing PHI with undef, it must be dead.
  512. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  513. PN->replaceAllUsesWith(NewVal);
  514. PN->eraseFromParent();
  515. }
  516. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  517. assert(PredBB && "Block doesn't have a single predecessor!");
  518. // Zap anything that took the address of DestBB. Not doing this will give the
  519. // address an invalid value.
  520. if (DestBB->hasAddressTaken()) {
  521. BlockAddress *BA = BlockAddress::get(DestBB);
  522. Constant *Replacement =
  523. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  524. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  525. BA->getType()));
  526. BA->destroyConstant();
  527. }
  528. // Anything that branched to PredBB now branches to DestBB.
  529. PredBB->replaceAllUsesWith(DestBB);
  530. // Splice all the instructions from PredBB to DestBB.
  531. PredBB->getTerminator()->eraseFromParent();
  532. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  533. // If the PredBB is the entry block of the function, move DestBB up to
  534. // become the entry block after we erase PredBB.
  535. if (PredBB == &DestBB->getParent()->getEntryBlock())
  536. DestBB->moveAfter(PredBB);
  537. if (DT) {
  538. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  539. DT->changeImmediateDominator(DestBB, PredBBIDom);
  540. DT->eraseNode(PredBB);
  541. }
  542. // Nuke BB.
  543. PredBB->eraseFromParent();
  544. }
  545. /// CanMergeValues - Return true if we can choose one of these values to use
  546. /// in place of the other. Note that we will always choose the non-undef
  547. /// value to keep.
  548. static bool CanMergeValues(Value *First, Value *Second) {
  549. return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
  550. }
  551. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  552. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  553. ///
  554. /// Assumption: Succ is the single successor for BB.
  555. ///
  556. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  557. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  558. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  559. << Succ->getName() << "\n");
  560. // Shortcut, if there is only a single predecessor it must be BB and merging
  561. // is always safe
  562. if (Succ->getSinglePredecessor()) return true;
  563. // Make a list of the predecessors of BB
  564. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  565. // Look at all the phi nodes in Succ, to see if they present a conflict when
  566. // merging these blocks
  567. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  568. PHINode *PN = cast<PHINode>(I);
  569. // If the incoming value from BB is again a PHINode in
  570. // BB which has the same incoming value for *PI as PN does, we can
  571. // merge the phi nodes and then the blocks can still be merged
  572. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  573. if (BBPN && BBPN->getParent() == BB) {
  574. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  575. BasicBlock *IBB = PN->getIncomingBlock(PI);
  576. if (BBPreds.count(IBB) &&
  577. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  578. PN->getIncomingValue(PI))) {
  579. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  580. << Succ->getName() << " is conflicting with "
  581. << BBPN->getName() << " with regard to common predecessor "
  582. << IBB->getName() << "\n");
  583. return false;
  584. }
  585. }
  586. } else {
  587. Value* Val = PN->getIncomingValueForBlock(BB);
  588. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  589. // See if the incoming value for the common predecessor is equal to the
  590. // one for BB, in which case this phi node will not prevent the merging
  591. // of the block.
  592. BasicBlock *IBB = PN->getIncomingBlock(PI);
  593. if (BBPreds.count(IBB) &&
  594. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  595. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  596. << Succ->getName() << " is conflicting with regard to common "
  597. << "predecessor " << IBB->getName() << "\n");
  598. return false;
  599. }
  600. }
  601. }
  602. }
  603. return true;
  604. }
  605. typedef SmallVector<BasicBlock *, 16> PredBlockVector;
  606. typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
  607. /// \brief Determines the value to use as the phi node input for a block.
  608. ///
  609. /// Select between \p OldVal any value that we know flows from \p BB
  610. /// to a particular phi on the basis of which one (if either) is not
  611. /// undef. Update IncomingValues based on the selected value.
  612. ///
  613. /// \param OldVal The value we are considering selecting.
  614. /// \param BB The block that the value flows in from.
  615. /// \param IncomingValues A map from block-to-value for other phi inputs
  616. /// that we have examined.
  617. ///
  618. /// \returns the selected value.
  619. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  620. IncomingValueMap &IncomingValues) {
  621. if (!isa<UndefValue>(OldVal)) {
  622. assert((!IncomingValues.count(BB) ||
  623. IncomingValues.find(BB)->second == OldVal) &&
  624. "Expected OldVal to match incoming value from BB!");
  625. IncomingValues.insert(std::make_pair(BB, OldVal));
  626. return OldVal;
  627. }
  628. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  629. if (It != IncomingValues.end()) return It->second;
  630. return OldVal;
  631. }
  632. /// \brief Create a map from block to value for the operands of a
  633. /// given phi.
  634. ///
  635. /// Create a map from block to value for each non-undef value flowing
  636. /// into \p PN.
  637. ///
  638. /// \param PN The phi we are collecting the map for.
  639. /// \param IncomingValues [out] The map from block to value for this phi.
  640. static void gatherIncomingValuesToPhi(PHINode *PN,
  641. IncomingValueMap &IncomingValues) {
  642. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  643. BasicBlock *BB = PN->getIncomingBlock(i);
  644. Value *V = PN->getIncomingValue(i);
  645. if (!isa<UndefValue>(V))
  646. IncomingValues.insert(std::make_pair(BB, V));
  647. }
  648. }
  649. /// \brief Replace the incoming undef values to a phi with the values
  650. /// from a block-to-value map.
  651. ///
  652. /// \param PN The phi we are replacing the undefs in.
  653. /// \param IncomingValues A map from block to value.
  654. static void replaceUndefValuesInPhi(PHINode *PN,
  655. const IncomingValueMap &IncomingValues) {
  656. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  657. Value *V = PN->getIncomingValue(i);
  658. if (!isa<UndefValue>(V)) continue;
  659. BasicBlock *BB = PN->getIncomingBlock(i);
  660. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  661. if (It == IncomingValues.end()) continue;
  662. PN->setIncomingValue(i, It->second);
  663. }
  664. }
  665. /// \brief Replace a value flowing from a block to a phi with
  666. /// potentially multiple instances of that value flowing from the
  667. /// block's predecessors to the phi.
  668. ///
  669. /// \param BB The block with the value flowing into the phi.
  670. /// \param BBPreds The predecessors of BB.
  671. /// \param PN The phi that we are updating.
  672. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  673. const PredBlockVector &BBPreds,
  674. PHINode *PN) {
  675. Value *OldVal = PN->removeIncomingValue(BB, false);
  676. assert(OldVal && "No entry in PHI for Pred BB!");
  677. IncomingValueMap IncomingValues;
  678. // We are merging two blocks - BB, and the block containing PN - and
  679. // as a result we need to redirect edges from the predecessors of BB
  680. // to go to the block containing PN, and update PN
  681. // accordingly. Since we allow merging blocks in the case where the
  682. // predecessor and successor blocks both share some predecessors,
  683. // and where some of those common predecessors might have undef
  684. // values flowing into PN, we want to rewrite those values to be
  685. // consistent with the non-undef values.
  686. gatherIncomingValuesToPhi(PN, IncomingValues);
  687. // If this incoming value is one of the PHI nodes in BB, the new entries
  688. // in the PHI node are the entries from the old PHI.
  689. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  690. PHINode *OldValPN = cast<PHINode>(OldVal);
  691. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  692. // Note that, since we are merging phi nodes and BB and Succ might
  693. // have common predecessors, we could end up with a phi node with
  694. // identical incoming branches. This will be cleaned up later (and
  695. // will trigger asserts if we try to clean it up now, without also
  696. // simplifying the corresponding conditional branch).
  697. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  698. Value *PredVal = OldValPN->getIncomingValue(i);
  699. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  700. IncomingValues);
  701. // And add a new incoming value for this predecessor for the
  702. // newly retargeted branch.
  703. PN->addIncoming(Selected, PredBB);
  704. }
  705. } else {
  706. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  707. // Update existing incoming values in PN for this
  708. // predecessor of BB.
  709. BasicBlock *PredBB = BBPreds[i];
  710. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  711. IncomingValues);
  712. // And add a new incoming value for this predecessor for the
  713. // newly retargeted branch.
  714. PN->addIncoming(Selected, PredBB);
  715. }
  716. }
  717. replaceUndefValuesInPhi(PN, IncomingValues);
  718. }
  719. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  720. /// unconditional branch, and contains no instructions other than PHI nodes,
  721. /// potential side-effect free intrinsics and the branch. If possible,
  722. /// eliminate BB by rewriting all the predecessors to branch to the successor
  723. /// block and return true. If we can't transform, return false.
  724. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  725. assert(BB != &BB->getParent()->getEntryBlock() &&
  726. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  727. // We can't eliminate infinite loops.
  728. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  729. if (BB == Succ) return false;
  730. // Check to see if merging these blocks would cause conflicts for any of the
  731. // phi nodes in BB or Succ. If not, we can safely merge.
  732. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  733. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  734. // has uses which will not disappear when the PHI nodes are merged. It is
  735. // possible to handle such cases, but difficult: it requires checking whether
  736. // BB dominates Succ, which is non-trivial to calculate in the case where
  737. // Succ has multiple predecessors. Also, it requires checking whether
  738. // constructing the necessary self-referential PHI node doesn't introduce any
  739. // conflicts; this isn't too difficult, but the previous code for doing this
  740. // was incorrect.
  741. //
  742. // Note that if this check finds a live use, BB dominates Succ, so BB is
  743. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  744. // folding the branch isn't profitable in that case anyway.
  745. if (!Succ->getSinglePredecessor()) {
  746. BasicBlock::iterator BBI = BB->begin();
  747. while (isa<PHINode>(*BBI)) {
  748. for (Use &U : BBI->uses()) {
  749. if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
  750. if (PN->getIncomingBlock(U) != BB)
  751. return false;
  752. } else {
  753. return false;
  754. }
  755. }
  756. ++BBI;
  757. }
  758. }
  759. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  760. if (isa<PHINode>(Succ->begin())) {
  761. // If there is more than one pred of succ, and there are PHI nodes in
  762. // the successor, then we need to add incoming edges for the PHI nodes
  763. //
  764. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  765. // Loop over all of the PHI nodes in the successor of BB.
  766. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  767. PHINode *PN = cast<PHINode>(I);
  768. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  769. }
  770. }
  771. if (Succ->getSinglePredecessor()) {
  772. // BB is the only predecessor of Succ, so Succ will end up with exactly
  773. // the same predecessors BB had.
  774. // Copy over any phi, debug or lifetime instruction.
  775. BB->getTerminator()->eraseFromParent();
  776. Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
  777. BB->getInstList());
  778. } else {
  779. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  780. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  781. assert(PN->use_empty() && "There shouldn't be any uses here!");
  782. PN->eraseFromParent();
  783. }
  784. }
  785. // If the unconditional branch we replaced contains llvm.loop metadata, we
  786. // add the metadata to the branch instructions in the predecessors.
  787. unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
  788. Instruction *TI = BB->getTerminator();
  789. if (TI)
  790. if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
  791. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  792. BasicBlock *Pred = *PI;
  793. Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
  794. }
  795. // Everything that jumped to BB now goes to Succ.
  796. BB->replaceAllUsesWith(Succ);
  797. if (!Succ->hasName()) Succ->takeName(BB);
  798. BB->eraseFromParent(); // Delete the old basic block.
  799. return true;
  800. }
  801. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  802. /// nodes in this block. This doesn't try to be clever about PHI nodes
  803. /// which differ only in the order of the incoming values, but instcombine
  804. /// orders them so it usually won't matter.
  805. ///
  806. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  807. // This implementation doesn't currently consider undef operands
  808. // specially. Theoretically, two phis which are identical except for
  809. // one having an undef where the other doesn't could be collapsed.
  810. struct PHIDenseMapInfo {
  811. static PHINode *getEmptyKey() {
  812. return DenseMapInfo<PHINode *>::getEmptyKey();
  813. }
  814. static PHINode *getTombstoneKey() {
  815. return DenseMapInfo<PHINode *>::getTombstoneKey();
  816. }
  817. static unsigned getHashValue(PHINode *PN) {
  818. // Compute a hash value on the operands. Instcombine will likely have
  819. // sorted them, which helps expose duplicates, but we have to check all
  820. // the operands to be safe in case instcombine hasn't run.
  821. return static_cast<unsigned>(hash_combine(
  822. hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
  823. hash_combine_range(PN->block_begin(), PN->block_end())));
  824. }
  825. static bool isEqual(PHINode *LHS, PHINode *RHS) {
  826. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  827. RHS == getEmptyKey() || RHS == getTombstoneKey())
  828. return LHS == RHS;
  829. return LHS->isIdenticalTo(RHS);
  830. }
  831. };
  832. // Set of unique PHINodes.
  833. DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
  834. // Examine each PHI.
  835. bool Changed = false;
  836. for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
  837. auto Inserted = PHISet.insert(PN);
  838. if (!Inserted.second) {
  839. // A duplicate. Replace this PHI with its duplicate.
  840. PN->replaceAllUsesWith(*Inserted.first);
  841. PN->eraseFromParent();
  842. Changed = true;
  843. // The RAUW can change PHIs that we already visited. Start over from the
  844. // beginning.
  845. PHISet.clear();
  846. I = BB->begin();
  847. }
  848. }
  849. return Changed;
  850. }
  851. /// enforceKnownAlignment - If the specified pointer points to an object that
  852. /// we control, modify the object's alignment to PrefAlign. This isn't
  853. /// often possible though. If alignment is important, a more reliable approach
  854. /// is to simply align all global variables and allocation instructions to
  855. /// their preferred alignment from the beginning.
  856. ///
  857. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  858. unsigned PrefAlign,
  859. const DataLayout &DL) {
  860. assert(PrefAlign > Align);
  861. V = V->stripPointerCasts();
  862. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  863. // TODO: ideally, computeKnownBits ought to have used
  864. // AllocaInst::getAlignment() in its computation already, making
  865. // the below max redundant. But, as it turns out,
  866. // stripPointerCasts recurses through infinite layers of bitcasts,
  867. // while computeKnownBits is not allowed to traverse more than 6
  868. // levels.
  869. Align = std::max(AI->getAlignment(), Align);
  870. if (PrefAlign <= Align)
  871. return Align;
  872. // If the preferred alignment is greater than the natural stack alignment
  873. // then don't round up. This avoids dynamic stack realignment.
  874. if (DL.exceedsNaturalStackAlignment(PrefAlign))
  875. return Align;
  876. AI->setAlignment(PrefAlign);
  877. return PrefAlign;
  878. }
  879. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  880. // TODO: as above, this shouldn't be necessary.
  881. Align = std::max(GO->getAlignment(), Align);
  882. if (PrefAlign <= Align)
  883. return Align;
  884. // If there is a large requested alignment and we can, bump up the alignment
  885. // of the global. If the memory we set aside for the global may not be the
  886. // memory used by the final program then it is impossible for us to reliably
  887. // enforce the preferred alignment.
  888. if (!GO->canIncreaseAlignment())
  889. return Align;
  890. GO->setAlignment(PrefAlign);
  891. return PrefAlign;
  892. }
  893. return Align;
  894. }
  895. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  896. const DataLayout &DL,
  897. const Instruction *CxtI,
  898. AssumptionCache *AC,
  899. const DominatorTree *DT) {
  900. assert(V->getType()->isPointerTy() &&
  901. "getOrEnforceKnownAlignment expects a pointer!");
  902. KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
  903. unsigned TrailZ = Known.countMinTrailingZeros();
  904. // Avoid trouble with ridiculously large TrailZ values, such as
  905. // those computed from a null pointer.
  906. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  907. unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
  908. // LLVM doesn't support alignments larger than this currently.
  909. Align = std::min(Align, +Value::MaximumAlignment);
  910. if (PrefAlign > Align)
  911. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  912. // We don't need to make any adjustment.
  913. return Align;
  914. }
  915. ///===---------------------------------------------------------------------===//
  916. /// Dbg Intrinsic utilities
  917. ///
  918. /// See if there is a dbg.value intrinsic for DIVar before I.
  919. static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
  920. Instruction *I) {
  921. // Since we can't guarantee that the original dbg.declare instrinsic
  922. // is removed by LowerDbgDeclare(), we need to make sure that we are
  923. // not inserting the same dbg.value intrinsic over and over.
  924. llvm::BasicBlock::InstListType::iterator PrevI(I);
  925. if (PrevI != I->getParent()->getInstList().begin()) {
  926. --PrevI;
  927. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  928. if (DVI->getValue() == I->getOperand(0) &&
  929. DVI->getVariable() == DIVar &&
  930. DVI->getExpression() == DIExpr)
  931. return true;
  932. }
  933. return false;
  934. }
  935. /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
  936. static bool PhiHasDebugValue(DILocalVariable *DIVar,
  937. DIExpression *DIExpr,
  938. PHINode *APN) {
  939. // Since we can't guarantee that the original dbg.declare instrinsic
  940. // is removed by LowerDbgDeclare(), we need to make sure that we are
  941. // not inserting the same dbg.value intrinsic over and over.
  942. SmallVector<DbgValueInst *, 1> DbgValues;
  943. findDbgValues(DbgValues, APN);
  944. for (auto *DVI : DbgValues) {
  945. assert(DVI->getValue() == APN);
  946. if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
  947. return true;
  948. }
  949. return false;
  950. }
  951. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  952. /// that has an associated llvm.dbg.decl intrinsic.
  953. void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  954. StoreInst *SI, DIBuilder &Builder) {
  955. auto *DIVar = DDI->getVariable();
  956. assert(DIVar && "Missing variable");
  957. auto *DIExpr = DDI->getExpression();
  958. Value *DV = SI->getOperand(0);
  959. // If an argument is zero extended then use argument directly. The ZExt
  960. // may be zapped by an optimization pass in future.
  961. Argument *ExtendedArg = nullptr;
  962. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  963. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  964. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  965. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  966. if (ExtendedArg) {
  967. // If this DDI was already describing only a fragment of a variable, ensure
  968. // that fragment is appropriately narrowed here.
  969. // But if a fragment wasn't used, describe the value as the original
  970. // argument (rather than the zext or sext) so that it remains described even
  971. // if the sext/zext is optimized away. This widens the variable description,
  972. // leaving it up to the consumer to know how the smaller value may be
  973. // represented in a larger register.
  974. if (auto Fragment = DIExpr->getFragmentInfo()) {
  975. unsigned FragmentOffset = Fragment->OffsetInBits;
  976. SmallVector<uint64_t, 3> Ops(DIExpr->elements_begin(),
  977. DIExpr->elements_end() - 3);
  978. Ops.push_back(dwarf::DW_OP_LLVM_fragment);
  979. Ops.push_back(FragmentOffset);
  980. const DataLayout &DL = DDI->getModule()->getDataLayout();
  981. Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType()));
  982. DIExpr = Builder.createExpression(Ops);
  983. }
  984. DV = ExtendedArg;
  985. }
  986. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  987. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DDI->getDebugLoc(),
  988. SI);
  989. }
  990. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  991. /// that has an associated llvm.dbg.decl intrinsic.
  992. void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  993. LoadInst *LI, DIBuilder &Builder) {
  994. auto *DIVar = DDI->getVariable();
  995. auto *DIExpr = DDI->getExpression();
  996. assert(DIVar && "Missing variable");
  997. if (LdStHasDebugValue(DIVar, DIExpr, LI))
  998. return;
  999. // We are now tracking the loaded value instead of the address. In the
  1000. // future if multi-location support is added to the IR, it might be
  1001. // preferable to keep tracking both the loaded value and the original
  1002. // address in case the alloca can not be elided.
  1003. Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
  1004. LI, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
  1005. DbgValue->insertAfter(LI);
  1006. }
  1007. /// Inserts a llvm.dbg.value intrinsic after a phi
  1008. /// that has an associated llvm.dbg.decl intrinsic.
  1009. void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  1010. PHINode *APN, DIBuilder &Builder) {
  1011. auto *DIVar = DDI->getVariable();
  1012. auto *DIExpr = DDI->getExpression();
  1013. assert(DIVar && "Missing variable");
  1014. if (PhiHasDebugValue(DIVar, DIExpr, APN))
  1015. return;
  1016. BasicBlock *BB = APN->getParent();
  1017. auto InsertionPt = BB->getFirstInsertionPt();
  1018. // The block may be a catchswitch block, which does not have a valid
  1019. // insertion point.
  1020. // FIXME: Insert dbg.value markers in the successors when appropriate.
  1021. if (InsertionPt != BB->end())
  1022. Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DDI->getDebugLoc(),
  1023. &*InsertionPt);
  1024. }
  1025. /// Determine whether this alloca is either a VLA or an array.
  1026. static bool isArray(AllocaInst *AI) {
  1027. return AI->isArrayAllocation() ||
  1028. AI->getType()->getElementType()->isArrayTy();
  1029. }
  1030. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  1031. /// of llvm.dbg.value intrinsics.
  1032. bool llvm::LowerDbgDeclare(Function &F) {
  1033. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1034. SmallVector<DbgDeclareInst *, 4> Dbgs;
  1035. for (auto &FI : F)
  1036. for (Instruction &BI : FI)
  1037. if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
  1038. Dbgs.push_back(DDI);
  1039. if (Dbgs.empty())
  1040. return false;
  1041. for (auto &I : Dbgs) {
  1042. DbgDeclareInst *DDI = I;
  1043. AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
  1044. // If this is an alloca for a scalar variable, insert a dbg.value
  1045. // at each load and store to the alloca and erase the dbg.declare.
  1046. // The dbg.values allow tracking a variable even if it is not
  1047. // stored on the stack, while the dbg.declare can only describe
  1048. // the stack slot (and at a lexical-scope granularity). Later
  1049. // passes will attempt to elide the stack slot.
  1050. if (AI && !isArray(AI)) {
  1051. for (auto &AIUse : AI->uses()) {
  1052. User *U = AIUse.getUser();
  1053. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1054. if (AIUse.getOperandNo() == 1)
  1055. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1056. } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1057. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1058. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1059. // This is a call by-value or some other instruction that
  1060. // takes a pointer to the variable. Insert a *value*
  1061. // intrinsic that describes the alloca.
  1062. DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(),
  1063. DDI->getExpression(), DDI->getDebugLoc(),
  1064. CI);
  1065. }
  1066. }
  1067. DDI->eraseFromParent();
  1068. }
  1069. }
  1070. return true;
  1071. }
  1072. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
  1073. /// alloca 'V', if any.
  1074. DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
  1075. if (auto *L = LocalAsMetadata::getIfExists(V))
  1076. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1077. for (User *U : MDV->users())
  1078. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  1079. return DDI;
  1080. return nullptr;
  1081. }
  1082. void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
  1083. if (auto *L = LocalAsMetadata::getIfExists(V))
  1084. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1085. for (User *U : MDV->users())
  1086. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  1087. DbgValues.push_back(DVI);
  1088. }
  1089. bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
  1090. Instruction *InsertBefore, DIBuilder &Builder,
  1091. bool Deref, int Offset) {
  1092. DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
  1093. if (!DDI)
  1094. return false;
  1095. DebugLoc Loc = DDI->getDebugLoc();
  1096. auto *DIVar = DDI->getVariable();
  1097. auto *DIExpr = DDI->getExpression();
  1098. assert(DIVar && "Missing variable");
  1099. DIExpr = DIExpression::prepend(DIExpr, Deref, Offset);
  1100. // Insert llvm.dbg.declare immediately after the original alloca, and remove
  1101. // old llvm.dbg.declare.
  1102. Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
  1103. DDI->eraseFromParent();
  1104. return true;
  1105. }
  1106. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1107. DIBuilder &Builder, bool Deref, int Offset) {
  1108. return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
  1109. Deref, Offset);
  1110. }
  1111. static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
  1112. DIBuilder &Builder, int Offset) {
  1113. DebugLoc Loc = DVI->getDebugLoc();
  1114. auto *DIVar = DVI->getVariable();
  1115. auto *DIExpr = DVI->getExpression();
  1116. assert(DIVar && "Missing variable");
  1117. // This is an alloca-based llvm.dbg.value. The first thing it should do with
  1118. // the alloca pointer is dereference it. Otherwise we don't know how to handle
  1119. // it and give up.
  1120. if (!DIExpr || DIExpr->getNumElements() < 1 ||
  1121. DIExpr->getElement(0) != dwarf::DW_OP_deref)
  1122. return;
  1123. // Insert the offset immediately after the first deref.
  1124. // We could just change the offset argument of dbg.value, but it's unsigned...
  1125. if (Offset) {
  1126. SmallVector<uint64_t, 4> Ops;
  1127. Ops.push_back(dwarf::DW_OP_deref);
  1128. DIExpression::appendOffset(Ops, Offset);
  1129. Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
  1130. DIExpr = Builder.createExpression(Ops);
  1131. }
  1132. Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
  1133. DVI->eraseFromParent();
  1134. }
  1135. void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1136. DIBuilder &Builder, int Offset) {
  1137. if (auto *L = LocalAsMetadata::getIfExists(AI))
  1138. if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
  1139. for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
  1140. Use &U = *UI++;
  1141. if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
  1142. replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
  1143. }
  1144. }
  1145. void llvm::salvageDebugInfo(Instruction &I) {
  1146. SmallVector<DbgValueInst *, 1> DbgValues;
  1147. auto &M = *I.getModule();
  1148. auto MDWrap = [&](Value *V) {
  1149. return MetadataAsValue::get(I.getContext(), ValueAsMetadata::get(V));
  1150. };
  1151. if (isa<BitCastInst>(&I)) {
  1152. findDbgValues(DbgValues, &I);
  1153. for (auto *DVI : DbgValues) {
  1154. // Bitcasts are entirely irrelevant for debug info. Rewrite the dbg.value
  1155. // to use the cast's source.
  1156. DVI->setOperand(0, MDWrap(I.getOperand(0)));
  1157. DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
  1158. }
  1159. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  1160. findDbgValues(DbgValues, &I);
  1161. for (auto *DVI : DbgValues) {
  1162. unsigned BitWidth =
  1163. M.getDataLayout().getPointerSizeInBits(GEP->getPointerAddressSpace());
  1164. APInt Offset(BitWidth, 0);
  1165. // Rewrite a constant GEP into a DIExpression. Since we are performing
  1166. // arithmetic to compute the variable's *value* in the DIExpression, we
  1167. // need to mark the expression with a DW_OP_stack_value.
  1168. if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
  1169. auto *DIExpr = DVI->getExpression();
  1170. DIBuilder DIB(M, /*AllowUnresolved*/ false);
  1171. // GEP offsets are i32 and thus always fit into an int64_t.
  1172. DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref,
  1173. Offset.getSExtValue(),
  1174. DIExpression::WithStackValue);
  1175. DVI->setOperand(0, MDWrap(I.getOperand(0)));
  1176. DVI->setOperand(2, MetadataAsValue::get(I.getContext(), DIExpr));
  1177. DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
  1178. }
  1179. }
  1180. } else if (isa<LoadInst>(&I)) {
  1181. findDbgValues(DbgValues, &I);
  1182. for (auto *DVI : DbgValues) {
  1183. // Rewrite the load into DW_OP_deref.
  1184. auto *DIExpr = DVI->getExpression();
  1185. DIBuilder DIB(M, /*AllowUnresolved*/ false);
  1186. DIExpr = DIExpression::prepend(DIExpr, DIExpression::WithDeref);
  1187. DVI->setOperand(0, MDWrap(I.getOperand(0)));
  1188. DVI->setOperand(2, MetadataAsValue::get(I.getContext(), DIExpr));
  1189. DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
  1190. }
  1191. }
  1192. }
  1193. unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
  1194. unsigned NumDeadInst = 0;
  1195. // Delete the instructions backwards, as it has a reduced likelihood of
  1196. // having to update as many def-use and use-def chains.
  1197. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  1198. while (EndInst != &BB->front()) {
  1199. // Delete the next to last instruction.
  1200. Instruction *Inst = &*--EndInst->getIterator();
  1201. if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
  1202. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  1203. if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
  1204. EndInst = Inst;
  1205. continue;
  1206. }
  1207. if (!isa<DbgInfoIntrinsic>(Inst))
  1208. ++NumDeadInst;
  1209. Inst->eraseFromParent();
  1210. }
  1211. return NumDeadInst;
  1212. }
  1213. unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
  1214. bool PreserveLCSSA) {
  1215. BasicBlock *BB = I->getParent();
  1216. // Loop over all of the successors, removing BB's entry from any PHI
  1217. // nodes.
  1218. for (BasicBlock *Successor : successors(BB))
  1219. Successor->removePredecessor(BB, PreserveLCSSA);
  1220. // Insert a call to llvm.trap right before this. This turns the undefined
  1221. // behavior into a hard fail instead of falling through into random code.
  1222. if (UseLLVMTrap) {
  1223. Function *TrapFn =
  1224. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  1225. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  1226. CallTrap->setDebugLoc(I->getDebugLoc());
  1227. }
  1228. new UnreachableInst(I->getContext(), I);
  1229. // All instructions after this are dead.
  1230. unsigned NumInstrsRemoved = 0;
  1231. BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
  1232. while (BBI != BBE) {
  1233. if (!BBI->use_empty())
  1234. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  1235. BB->getInstList().erase(BBI++);
  1236. ++NumInstrsRemoved;
  1237. }
  1238. return NumInstrsRemoved;
  1239. }
  1240. /// changeToCall - Convert the specified invoke into a normal call.
  1241. static void changeToCall(InvokeInst *II) {
  1242. SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
  1243. SmallVector<OperandBundleDef, 1> OpBundles;
  1244. II->getOperandBundlesAsDefs(OpBundles);
  1245. CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
  1246. "", II);
  1247. NewCall->takeName(II);
  1248. NewCall->setCallingConv(II->getCallingConv());
  1249. NewCall->setAttributes(II->getAttributes());
  1250. NewCall->setDebugLoc(II->getDebugLoc());
  1251. II->replaceAllUsesWith(NewCall);
  1252. // Follow the call by a branch to the normal destination.
  1253. BranchInst::Create(II->getNormalDest(), II);
  1254. // Update PHI nodes in the unwind destination
  1255. II->getUnwindDest()->removePredecessor(II->getParent());
  1256. II->eraseFromParent();
  1257. }
  1258. BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
  1259. BasicBlock *UnwindEdge) {
  1260. BasicBlock *BB = CI->getParent();
  1261. // Convert this function call into an invoke instruction. First, split the
  1262. // basic block.
  1263. BasicBlock *Split =
  1264. BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
  1265. // Delete the unconditional branch inserted by splitBasicBlock
  1266. BB->getInstList().pop_back();
  1267. // Create the new invoke instruction.
  1268. SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
  1269. SmallVector<OperandBundleDef, 1> OpBundles;
  1270. CI->getOperandBundlesAsDefs(OpBundles);
  1271. // Note: we're round tripping operand bundles through memory here, and that
  1272. // can potentially be avoided with a cleverer API design that we do not have
  1273. // as of this time.
  1274. InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
  1275. InvokeArgs, OpBundles, CI->getName(), BB);
  1276. II->setDebugLoc(CI->getDebugLoc());
  1277. II->setCallingConv(CI->getCallingConv());
  1278. II->setAttributes(CI->getAttributes());
  1279. // Make sure that anything using the call now uses the invoke! This also
  1280. // updates the CallGraph if present, because it uses a WeakTrackingVH.
  1281. CI->replaceAllUsesWith(II);
  1282. // Delete the original call
  1283. Split->getInstList().pop_front();
  1284. return Split;
  1285. }
  1286. static bool markAliveBlocks(Function &F,
  1287. SmallPtrSetImpl<BasicBlock*> &Reachable) {
  1288. SmallVector<BasicBlock*, 128> Worklist;
  1289. BasicBlock *BB = &F.front();
  1290. Worklist.push_back(BB);
  1291. Reachable.insert(BB);
  1292. bool Changed = false;
  1293. do {
  1294. BB = Worklist.pop_back_val();
  1295. // Do a quick scan of the basic block, turning any obviously unreachable
  1296. // instructions into LLVM unreachable insts. The instruction combining pass
  1297. // canonicalizes unreachable insts into stores to null or undef.
  1298. for (Instruction &I : *BB) {
  1299. // Assumptions that are known to be false are equivalent to unreachable.
  1300. // Also, if the condition is undefined, then we make the choice most
  1301. // beneficial to the optimizer, and choose that to also be unreachable.
  1302. if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
  1303. if (II->getIntrinsicID() == Intrinsic::assume) {
  1304. if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
  1305. // Don't insert a call to llvm.trap right before the unreachable.
  1306. changeToUnreachable(II, false);
  1307. Changed = true;
  1308. break;
  1309. }
  1310. }
  1311. if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
  1312. // A call to the guard intrinsic bails out of the current compilation
  1313. // unit if the predicate passed to it is false. If the predicate is a
  1314. // constant false, then we know the guard will bail out of the current
  1315. // compile unconditionally, so all code following it is dead.
  1316. //
  1317. // Note: unlike in llvm.assume, it is not "obviously profitable" for
  1318. // guards to treat `undef` as `false` since a guard on `undef` can
  1319. // still be useful for widening.
  1320. if (match(II->getArgOperand(0), m_Zero()))
  1321. if (!isa<UnreachableInst>(II->getNextNode())) {
  1322. changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
  1323. Changed = true;
  1324. break;
  1325. }
  1326. }
  1327. }
  1328. if (auto *CI = dyn_cast<CallInst>(&I)) {
  1329. Value *Callee = CI->getCalledValue();
  1330. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1331. changeToUnreachable(CI, /*UseLLVMTrap=*/false);
  1332. Changed = true;
  1333. break;
  1334. }
  1335. if (CI->doesNotReturn()) {
  1336. // If we found a call to a no-return function, insert an unreachable
  1337. // instruction after it. Make sure there isn't *already* one there
  1338. // though.
  1339. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1340. // Don't insert a call to llvm.trap right before the unreachable.
  1341. changeToUnreachable(CI->getNextNode(), false);
  1342. Changed = true;
  1343. }
  1344. break;
  1345. }
  1346. }
  1347. // Store to undef and store to null are undefined and used to signal that
  1348. // they should be changed to unreachable by passes that can't modify the
  1349. // CFG.
  1350. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1351. // Don't touch volatile stores.
  1352. if (SI->isVolatile()) continue;
  1353. Value *Ptr = SI->getOperand(1);
  1354. if (isa<UndefValue>(Ptr) ||
  1355. (isa<ConstantPointerNull>(Ptr) &&
  1356. SI->getPointerAddressSpace() == 0)) {
  1357. changeToUnreachable(SI, true);
  1358. Changed = true;
  1359. break;
  1360. }
  1361. }
  1362. }
  1363. TerminatorInst *Terminator = BB->getTerminator();
  1364. if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
  1365. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1366. Value *Callee = II->getCalledValue();
  1367. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1368. changeToUnreachable(II, true);
  1369. Changed = true;
  1370. } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
  1371. if (II->use_empty() && II->onlyReadsMemory()) {
  1372. // jump to the normal destination branch.
  1373. BranchInst::Create(II->getNormalDest(), II);
  1374. II->getUnwindDest()->removePredecessor(II->getParent());
  1375. II->eraseFromParent();
  1376. } else
  1377. changeToCall(II);
  1378. Changed = true;
  1379. }
  1380. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
  1381. // Remove catchpads which cannot be reached.
  1382. struct CatchPadDenseMapInfo {
  1383. static CatchPadInst *getEmptyKey() {
  1384. return DenseMapInfo<CatchPadInst *>::getEmptyKey();
  1385. }
  1386. static CatchPadInst *getTombstoneKey() {
  1387. return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
  1388. }
  1389. static unsigned getHashValue(CatchPadInst *CatchPad) {
  1390. return static_cast<unsigned>(hash_combine_range(
  1391. CatchPad->value_op_begin(), CatchPad->value_op_end()));
  1392. }
  1393. static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
  1394. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  1395. RHS == getEmptyKey() || RHS == getTombstoneKey())
  1396. return LHS == RHS;
  1397. return LHS->isIdenticalTo(RHS);
  1398. }
  1399. };
  1400. // Set of unique CatchPads.
  1401. SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
  1402. CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
  1403. HandlerSet;
  1404. detail::DenseSetEmpty Empty;
  1405. for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
  1406. E = CatchSwitch->handler_end();
  1407. I != E; ++I) {
  1408. BasicBlock *HandlerBB = *I;
  1409. auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
  1410. if (!HandlerSet.insert({CatchPad, Empty}).second) {
  1411. CatchSwitch->removeHandler(I);
  1412. --I;
  1413. --E;
  1414. Changed = true;
  1415. }
  1416. }
  1417. }
  1418. Changed |= ConstantFoldTerminator(BB, true);
  1419. for (BasicBlock *Successor : successors(BB))
  1420. if (Reachable.insert(Successor).second)
  1421. Worklist.push_back(Successor);
  1422. } while (!Worklist.empty());
  1423. return Changed;
  1424. }
  1425. void llvm::removeUnwindEdge(BasicBlock *BB) {
  1426. TerminatorInst *TI = BB->getTerminator();
  1427. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  1428. changeToCall(II);
  1429. return;
  1430. }
  1431. TerminatorInst *NewTI;
  1432. BasicBlock *UnwindDest;
  1433. if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  1434. NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
  1435. UnwindDest = CRI->getUnwindDest();
  1436. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
  1437. auto *NewCatchSwitch = CatchSwitchInst::Create(
  1438. CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
  1439. CatchSwitch->getName(), CatchSwitch);
  1440. for (BasicBlock *PadBB : CatchSwitch->handlers())
  1441. NewCatchSwitch->addHandler(PadBB);
  1442. NewTI = NewCatchSwitch;
  1443. UnwindDest = CatchSwitch->getUnwindDest();
  1444. } else {
  1445. llvm_unreachable("Could not find unwind successor");
  1446. }
  1447. NewTI->takeName(TI);
  1448. NewTI->setDebugLoc(TI->getDebugLoc());
  1449. UnwindDest->removePredecessor(BB);
  1450. TI->replaceAllUsesWith(NewTI);
  1451. TI->eraseFromParent();
  1452. }
  1453. /// removeUnreachableBlocks - Remove blocks that are not reachable, even
  1454. /// if they are in a dead cycle. Return true if a change was made, false
  1455. /// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
  1456. /// after modifying the CFG.
  1457. bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
  1458. SmallPtrSet<BasicBlock*, 16> Reachable;
  1459. bool Changed = markAliveBlocks(F, Reachable);
  1460. // If there are unreachable blocks in the CFG...
  1461. if (Reachable.size() == F.size())
  1462. return Changed;
  1463. assert(Reachable.size() < F.size());
  1464. NumRemoved += F.size()-Reachable.size();
  1465. // Loop over all of the basic blocks that are not reachable, dropping all of
  1466. // their internal references...
  1467. for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
  1468. if (Reachable.count(&*BB))
  1469. continue;
  1470. for (BasicBlock *Successor : successors(&*BB))
  1471. if (Reachable.count(Successor))
  1472. Successor->removePredecessor(&*BB);
  1473. if (LVI)
  1474. LVI->eraseBlock(&*BB);
  1475. BB->dropAllReferences();
  1476. }
  1477. for (Function::iterator I = ++F.begin(); I != F.end();)
  1478. if (!Reachable.count(&*I))
  1479. I = F.getBasicBlockList().erase(I);
  1480. else
  1481. ++I;
  1482. return true;
  1483. }
  1484. void llvm::combineMetadata(Instruction *K, const Instruction *J,
  1485. ArrayRef<unsigned> KnownIDs) {
  1486. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  1487. K->dropUnknownNonDebugMetadata(KnownIDs);
  1488. K->getAllMetadataOtherThanDebugLoc(Metadata);
  1489. for (const auto &MD : Metadata) {
  1490. unsigned Kind = MD.first;
  1491. MDNode *JMD = J->getMetadata(Kind);
  1492. MDNode *KMD = MD.second;
  1493. switch (Kind) {
  1494. default:
  1495. K->setMetadata(Kind, nullptr); // Remove unknown metadata
  1496. break;
  1497. case LLVMContext::MD_dbg:
  1498. llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
  1499. case LLVMContext::MD_tbaa:
  1500. K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
  1501. break;
  1502. case LLVMContext::MD_alias_scope:
  1503. K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
  1504. break;
  1505. case LLVMContext::MD_noalias:
  1506. case LLVMContext::MD_mem_parallel_loop_access:
  1507. K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
  1508. break;
  1509. case LLVMContext::MD_range:
  1510. K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
  1511. break;
  1512. case LLVMContext::MD_fpmath:
  1513. K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
  1514. break;
  1515. case LLVMContext::MD_invariant_load:
  1516. // Only set the !invariant.load if it is present in both instructions.
  1517. K->setMetadata(Kind, JMD);
  1518. break;
  1519. case LLVMContext::MD_nonnull:
  1520. // Only set the !nonnull if it is present in both instructions.
  1521. K->setMetadata(Kind, JMD);
  1522. break;
  1523. case LLVMContext::MD_invariant_group:
  1524. // Preserve !invariant.group in K.
  1525. break;
  1526. case LLVMContext::MD_align:
  1527. K->setMetadata(Kind,
  1528. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  1529. break;
  1530. case LLVMContext::MD_dereferenceable:
  1531. case LLVMContext::MD_dereferenceable_or_null:
  1532. K->setMetadata(Kind,
  1533. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  1534. break;
  1535. }
  1536. }
  1537. // Set !invariant.group from J if J has it. If both instructions have it
  1538. // then we will just pick it from J - even when they are different.
  1539. // Also make sure that K is load or store - f.e. combining bitcast with load
  1540. // could produce bitcast with invariant.group metadata, which is invalid.
  1541. // FIXME: we should try to preserve both invariant.group md if they are
  1542. // different, but right now instruction can only have one invariant.group.
  1543. if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
  1544. if (isa<LoadInst>(K) || isa<StoreInst>(K))
  1545. K->setMetadata(LLVMContext::MD_invariant_group, JMD);
  1546. }
  1547. void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) {
  1548. unsigned KnownIDs[] = {
  1549. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  1550. LLVMContext::MD_noalias, LLVMContext::MD_range,
  1551. LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
  1552. LLVMContext::MD_invariant_group, LLVMContext::MD_align,
  1553. LLVMContext::MD_dereferenceable,
  1554. LLVMContext::MD_dereferenceable_or_null};
  1555. combineMetadata(K, J, KnownIDs);
  1556. }
  1557. template <typename RootType, typename DominatesFn>
  1558. static unsigned replaceDominatedUsesWith(Value *From, Value *To,
  1559. const RootType &Root,
  1560. const DominatesFn &Dominates) {
  1561. assert(From->getType() == To->getType());
  1562. unsigned Count = 0;
  1563. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  1564. UI != UE;) {
  1565. Use &U = *UI++;
  1566. if (!Dominates(Root, U))
  1567. continue;
  1568. U.set(To);
  1569. DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
  1570. << *To << " in " << *U << "\n");
  1571. ++Count;
  1572. }
  1573. return Count;
  1574. }
  1575. unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
  1576. assert(From->getType() == To->getType());
  1577. auto *BB = From->getParent();
  1578. unsigned Count = 0;
  1579. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  1580. UI != UE;) {
  1581. Use &U = *UI++;
  1582. auto *I = cast<Instruction>(U.getUser());
  1583. if (I->getParent() == BB)
  1584. continue;
  1585. U.set(To);
  1586. ++Count;
  1587. }
  1588. return Count;
  1589. }
  1590. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  1591. DominatorTree &DT,
  1592. const BasicBlockEdge &Root) {
  1593. auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
  1594. return DT.dominates(Root, U);
  1595. };
  1596. return ::replaceDominatedUsesWith(From, To, Root, Dominates);
  1597. }
  1598. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  1599. DominatorTree &DT,
  1600. const BasicBlock *BB) {
  1601. auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
  1602. auto *I = cast<Instruction>(U.getUser())->getParent();
  1603. return DT.properlyDominates(BB, I);
  1604. };
  1605. return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
  1606. }
  1607. bool llvm::callsGCLeafFunction(ImmutableCallSite CS,
  1608. const TargetLibraryInfo &TLI) {
  1609. // Check if the function is specifically marked as a gc leaf function.
  1610. if (CS.hasFnAttr("gc-leaf-function"))
  1611. return true;
  1612. if (const Function *F = CS.getCalledFunction()) {
  1613. if (F->hasFnAttribute("gc-leaf-function"))
  1614. return true;
  1615. if (auto IID = F->getIntrinsicID())
  1616. // Most LLVM intrinsics do not take safepoints.
  1617. return IID != Intrinsic::experimental_gc_statepoint &&
  1618. IID != Intrinsic::experimental_deoptimize;
  1619. }
  1620. // Lib calls can be materialized by some passes, and won't be
  1621. // marked as 'gc-leaf-function.' All available Libcalls are
  1622. // GC-leaf.
  1623. LibFunc LF;
  1624. if (TLI.getLibFunc(CS, LF)) {
  1625. return TLI.has(LF);
  1626. }
  1627. return false;
  1628. }
  1629. void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
  1630. LoadInst &NewLI) {
  1631. auto *NewTy = NewLI.getType();
  1632. // This only directly applies if the new type is also a pointer.
  1633. if (NewTy->isPointerTy()) {
  1634. NewLI.setMetadata(LLVMContext::MD_nonnull, N);
  1635. return;
  1636. }
  1637. // The only other translation we can do is to integral loads with !range
  1638. // metadata.
  1639. if (!NewTy->isIntegerTy())
  1640. return;
  1641. MDBuilder MDB(NewLI.getContext());
  1642. const Value *Ptr = OldLI.getPointerOperand();
  1643. auto *ITy = cast<IntegerType>(NewTy);
  1644. auto *NullInt = ConstantExpr::getPtrToInt(
  1645. ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
  1646. auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
  1647. NewLI.setMetadata(LLVMContext::MD_range,
  1648. MDB.createRange(NonNullInt, NullInt));
  1649. }
  1650. void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
  1651. MDNode *N, LoadInst &NewLI) {
  1652. auto *NewTy = NewLI.getType();
  1653. // Give up unless it is converted to a pointer where there is a single very
  1654. // valuable mapping we can do reliably.
  1655. // FIXME: It would be nice to propagate this in more ways, but the type
  1656. // conversions make it hard.
  1657. if (!NewTy->isPointerTy())
  1658. return;
  1659. unsigned BitWidth = DL.getTypeSizeInBits(NewTy);
  1660. if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
  1661. MDNode *NN = MDNode::get(OldLI.getContext(), None);
  1662. NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
  1663. }
  1664. }
  1665. namespace {
  1666. /// A potential constituent of a bitreverse or bswap expression. See
  1667. /// collectBitParts for a fuller explanation.
  1668. struct BitPart {
  1669. BitPart(Value *P, unsigned BW) : Provider(P) {
  1670. Provenance.resize(BW);
  1671. }
  1672. /// The Value that this is a bitreverse/bswap of.
  1673. Value *Provider;
  1674. /// The "provenance" of each bit. Provenance[A] = B means that bit A
  1675. /// in Provider becomes bit B in the result of this expression.
  1676. SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
  1677. enum { Unset = -1 };
  1678. };
  1679. } // end anonymous namespace
  1680. /// Analyze the specified subexpression and see if it is capable of providing
  1681. /// pieces of a bswap or bitreverse. The subexpression provides a potential
  1682. /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
  1683. /// the output of the expression came from a corresponding bit in some other
  1684. /// value. This function is recursive, and the end result is a mapping of
  1685. /// bitnumber to bitnumber. It is the caller's responsibility to validate that
  1686. /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
  1687. ///
  1688. /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
  1689. /// that the expression deposits the low byte of %X into the high byte of the
  1690. /// result and that all other bits are zero. This expression is accepted and a
  1691. /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
  1692. /// [0-7].
  1693. ///
  1694. /// To avoid revisiting values, the BitPart results are memoized into the
  1695. /// provided map. To avoid unnecessary copying of BitParts, BitParts are
  1696. /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
  1697. /// store BitParts objects, not pointers. As we need the concept of a nullptr
  1698. /// BitParts (Value has been analyzed and the analysis failed), we an Optional
  1699. /// type instead to provide the same functionality.
  1700. ///
  1701. /// Because we pass around references into \c BPS, we must use a container that
  1702. /// does not invalidate internal references (std::map instead of DenseMap).
  1703. ///
  1704. static const Optional<BitPart> &
  1705. collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
  1706. std::map<Value *, Optional<BitPart>> &BPS) {
  1707. auto I = BPS.find(V);
  1708. if (I != BPS.end())
  1709. return I->second;
  1710. auto &Result = BPS[V] = None;
  1711. auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
  1712. if (Instruction *I = dyn_cast<Instruction>(V)) {
  1713. // If this is an or instruction, it may be an inner node of the bswap.
  1714. if (I->getOpcode() == Instruction::Or) {
  1715. auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
  1716. MatchBitReversals, BPS);
  1717. auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
  1718. MatchBitReversals, BPS);
  1719. if (!A || !B)
  1720. return Result;
  1721. // Try and merge the two together.
  1722. if (!A->Provider || A->Provider != B->Provider)
  1723. return Result;
  1724. Result = BitPart(A->Provider, BitWidth);
  1725. for (unsigned i = 0; i < A->Provenance.size(); ++i) {
  1726. if (A->Provenance[i] != BitPart::Unset &&
  1727. B->Provenance[i] != BitPart::Unset &&
  1728. A->Provenance[i] != B->Provenance[i])
  1729. return Result = None;
  1730. if (A->Provenance[i] == BitPart::Unset)
  1731. Result->Provenance[i] = B->Provenance[i];
  1732. else
  1733. Result->Provenance[i] = A->Provenance[i];
  1734. }
  1735. return Result;
  1736. }
  1737. // If this is a logical shift by a constant, recurse then shift the result.
  1738. if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
  1739. unsigned BitShift =
  1740. cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
  1741. // Ensure the shift amount is defined.
  1742. if (BitShift > BitWidth)
  1743. return Result;
  1744. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1745. MatchBitReversals, BPS);
  1746. if (!Res)
  1747. return Result;
  1748. Result = Res;
  1749. // Perform the "shift" on BitProvenance.
  1750. auto &P = Result->Provenance;
  1751. if (I->getOpcode() == Instruction::Shl) {
  1752. P.erase(std::prev(P.end(), BitShift), P.end());
  1753. P.insert(P.begin(), BitShift, BitPart::Unset);
  1754. } else {
  1755. P.erase(P.begin(), std::next(P.begin(), BitShift));
  1756. P.insert(P.end(), BitShift, BitPart::Unset);
  1757. }
  1758. return Result;
  1759. }
  1760. // If this is a logical 'and' with a mask that clears bits, recurse then
  1761. // unset the appropriate bits.
  1762. if (I->getOpcode() == Instruction::And &&
  1763. isa<ConstantInt>(I->getOperand(1))) {
  1764. APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
  1765. const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
  1766. // Check that the mask allows a multiple of 8 bits for a bswap, for an
  1767. // early exit.
  1768. unsigned NumMaskedBits = AndMask.countPopulation();
  1769. if (!MatchBitReversals && NumMaskedBits % 8 != 0)
  1770. return Result;
  1771. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1772. MatchBitReversals, BPS);
  1773. if (!Res)
  1774. return Result;
  1775. Result = Res;
  1776. for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
  1777. // If the AndMask is zero for this bit, clear the bit.
  1778. if ((AndMask & Bit) == 0)
  1779. Result->Provenance[i] = BitPart::Unset;
  1780. return Result;
  1781. }
  1782. // If this is a zext instruction zero extend the result.
  1783. if (I->getOpcode() == Instruction::ZExt) {
  1784. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  1785. MatchBitReversals, BPS);
  1786. if (!Res)
  1787. return Result;
  1788. Result = BitPart(Res->Provider, BitWidth);
  1789. auto NarrowBitWidth =
  1790. cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
  1791. for (unsigned i = 0; i < NarrowBitWidth; ++i)
  1792. Result->Provenance[i] = Res->Provenance[i];
  1793. for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
  1794. Result->Provenance[i] = BitPart::Unset;
  1795. return Result;
  1796. }
  1797. }
  1798. // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
  1799. // the input value to the bswap/bitreverse.
  1800. Result = BitPart(V, BitWidth);
  1801. for (unsigned i = 0; i < BitWidth; ++i)
  1802. Result->Provenance[i] = i;
  1803. return Result;
  1804. }
  1805. static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
  1806. unsigned BitWidth) {
  1807. if (From % 8 != To % 8)
  1808. return false;
  1809. // Convert from bit indices to byte indices and check for a byte reversal.
  1810. From >>= 3;
  1811. To >>= 3;
  1812. BitWidth >>= 3;
  1813. return From == BitWidth - To - 1;
  1814. }
  1815. static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
  1816. unsigned BitWidth) {
  1817. return From == BitWidth - To - 1;
  1818. }
  1819. /// Given an OR instruction, check to see if this is a bitreverse
  1820. /// idiom. If so, insert the new intrinsic and return true.
  1821. bool llvm::recognizeBSwapOrBitReverseIdiom(
  1822. Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
  1823. SmallVectorImpl<Instruction *> &InsertedInsts) {
  1824. if (Operator::getOpcode(I) != Instruction::Or)
  1825. return false;
  1826. if (!MatchBSwaps && !MatchBitReversals)
  1827. return false;
  1828. IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
  1829. if (!ITy || ITy->getBitWidth() > 128)
  1830. return false; // Can't do vectors or integers > 128 bits.
  1831. unsigned BW = ITy->getBitWidth();
  1832. unsigned DemandedBW = BW;
  1833. IntegerType *DemandedTy = ITy;
  1834. if (I->hasOneUse()) {
  1835. if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
  1836. DemandedTy = cast<IntegerType>(Trunc->getType());
  1837. DemandedBW = DemandedTy->getBitWidth();
  1838. }
  1839. }
  1840. // Try to find all the pieces corresponding to the bswap.
  1841. std::map<Value *, Optional<BitPart>> BPS;
  1842. auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
  1843. if (!Res)
  1844. return false;
  1845. auto &BitProvenance = Res->Provenance;
  1846. // Now, is the bit permutation correct for a bswap or a bitreverse? We can
  1847. // only byteswap values with an even number of bytes.
  1848. bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
  1849. for (unsigned i = 0; i < DemandedBW; ++i) {
  1850. OKForBSwap &=
  1851. bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
  1852. OKForBitReverse &=
  1853. bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
  1854. }
  1855. Intrinsic::ID Intrin;
  1856. if (OKForBSwap && MatchBSwaps)
  1857. Intrin = Intrinsic::bswap;
  1858. else if (OKForBitReverse && MatchBitReversals)
  1859. Intrin = Intrinsic::bitreverse;
  1860. else
  1861. return false;
  1862. if (ITy != DemandedTy) {
  1863. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
  1864. Value *Provider = Res->Provider;
  1865. IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
  1866. // We may need to truncate the provider.
  1867. if (DemandedTy != ProviderTy) {
  1868. auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
  1869. "trunc", I);
  1870. InsertedInsts.push_back(Trunc);
  1871. Provider = Trunc;
  1872. }
  1873. auto *CI = CallInst::Create(F, Provider, "rev", I);
  1874. InsertedInsts.push_back(CI);
  1875. auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
  1876. InsertedInsts.push_back(ExtInst);
  1877. return true;
  1878. }
  1879. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
  1880. InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
  1881. return true;
  1882. }
  1883. // CodeGen has special handling for some string functions that may replace
  1884. // them with target-specific intrinsics. Since that'd skip our interceptors
  1885. // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
  1886. // we mark affected calls as NoBuiltin, which will disable optimization
  1887. // in CodeGen.
  1888. void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
  1889. CallInst *CI, const TargetLibraryInfo *TLI) {
  1890. Function *F = CI->getCalledFunction();
  1891. LibFunc Func;
  1892. if (F && !F->hasLocalLinkage() && F->hasName() &&
  1893. TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
  1894. !F->doesNotAccessMemory())
  1895. CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
  1896. }
  1897. bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
  1898. // We can't have a PHI with a metadata type.
  1899. if (I->getOperand(OpIdx)->getType()->isMetadataTy())
  1900. return false;
  1901. // Early exit.
  1902. if (!isa<Constant>(I->getOperand(OpIdx)))
  1903. return true;
  1904. switch (I->getOpcode()) {
  1905. default:
  1906. return true;
  1907. case Instruction::Call:
  1908. case Instruction::Invoke:
  1909. // Can't handle inline asm. Skip it.
  1910. if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
  1911. return false;
  1912. // Many arithmetic intrinsics have no issue taking a
  1913. // variable, however it's hard to distingish these from
  1914. // specials such as @llvm.frameaddress that require a constant.
  1915. if (isa<IntrinsicInst>(I))
  1916. return false;
  1917. // Constant bundle operands may need to retain their constant-ness for
  1918. // correctness.
  1919. if (ImmutableCallSite(I).isBundleOperand(OpIdx))
  1920. return false;
  1921. return true;
  1922. case Instruction::ShuffleVector:
  1923. // Shufflevector masks are constant.
  1924. return OpIdx != 2;
  1925. case Instruction::Switch:
  1926. case Instruction::ExtractValue:
  1927. // All operands apart from the first are constant.
  1928. return OpIdx == 0;
  1929. case Instruction::InsertValue:
  1930. // All operands apart from the first and the second are constant.
  1931. return OpIdx < 2;
  1932. case Instruction::Alloca:
  1933. // Static allocas (constant size in the entry block) are handled by
  1934. // prologue/epilogue insertion so they're free anyway. We definitely don't
  1935. // want to make them non-constant.
  1936. return !dyn_cast<AllocaInst>(I)->isStaticAlloca();
  1937. case Instruction::GetElementPtr:
  1938. if (OpIdx == 0)
  1939. return true;
  1940. gep_type_iterator It = gep_type_begin(I);
  1941. for (auto E = std::next(It, OpIdx); It != E; ++It)
  1942. if (It.isStruct())
  1943. return false;
  1944. return true;
  1945. }
  1946. }