Local.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929
  1. //===- Local.cpp - Functions to perform local transformations -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This family of functions perform various local transformations to the
  10. // program.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/Local.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseMapInfo.h"
  17. #include "llvm/ADT/DenseSet.h"
  18. #include "llvm/ADT/Hashing.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/ADT/TinyPtrVector.h"
  27. #include "llvm/Analysis/ConstantFolding.h"
  28. #include "llvm/Analysis/DomTreeUpdater.h"
  29. #include "llvm/Analysis/EHPersonalities.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/LazyValueInfo.h"
  32. #include "llvm/Analysis/MemoryBuiltins.h"
  33. #include "llvm/Analysis/MemorySSAUpdater.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/BinaryFormat/Dwarf.h"
  38. #include "llvm/IR/Argument.h"
  39. #include "llvm/IR/Attributes.h"
  40. #include "llvm/IR/BasicBlock.h"
  41. #include "llvm/IR/CFG.h"
  42. #include "llvm/IR/CallSite.h"
  43. #include "llvm/IR/Constant.h"
  44. #include "llvm/IR/ConstantRange.h"
  45. #include "llvm/IR/Constants.h"
  46. #include "llvm/IR/DIBuilder.h"
  47. #include "llvm/IR/DataLayout.h"
  48. #include "llvm/IR/DebugInfoMetadata.h"
  49. #include "llvm/IR/DebugLoc.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/Dominators.h"
  52. #include "llvm/IR/Function.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/GlobalObject.h"
  55. #include "llvm/IR/IRBuilder.h"
  56. #include "llvm/IR/InstrTypes.h"
  57. #include "llvm/IR/Instruction.h"
  58. #include "llvm/IR/Instructions.h"
  59. #include "llvm/IR/IntrinsicInst.h"
  60. #include "llvm/IR/Intrinsics.h"
  61. #include "llvm/IR/LLVMContext.h"
  62. #include "llvm/IR/MDBuilder.h"
  63. #include "llvm/IR/Metadata.h"
  64. #include "llvm/IR/Module.h"
  65. #include "llvm/IR/Operator.h"
  66. #include "llvm/IR/PatternMatch.h"
  67. #include "llvm/IR/Type.h"
  68. #include "llvm/IR/Use.h"
  69. #include "llvm/IR/User.h"
  70. #include "llvm/IR/Value.h"
  71. #include "llvm/IR/ValueHandle.h"
  72. #include "llvm/Support/Casting.h"
  73. #include "llvm/Support/Debug.h"
  74. #include "llvm/Support/ErrorHandling.h"
  75. #include "llvm/Support/KnownBits.h"
  76. #include "llvm/Support/raw_ostream.h"
  77. #include "llvm/Transforms/Utils/ValueMapper.h"
  78. #include <algorithm>
  79. #include <cassert>
  80. #include <climits>
  81. #include <cstdint>
  82. #include <iterator>
  83. #include <map>
  84. #include <utility>
  85. using namespace llvm;
  86. using namespace llvm::PatternMatch;
  87. #define DEBUG_TYPE "local"
  88. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  89. //===----------------------------------------------------------------------===//
  90. // Local constant propagation.
  91. //
  92. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  93. /// constant value, convert it into an unconditional branch to the constant
  94. /// destination. This is a nontrivial operation because the successors of this
  95. /// basic block must have their PHI nodes updated.
  96. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  97. /// conditions and indirectbr addresses this might make dead if
  98. /// DeleteDeadConditions is true.
  99. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  100. const TargetLibraryInfo *TLI,
  101. DomTreeUpdater *DTU) {
  102. Instruction *T = BB->getTerminator();
  103. IRBuilder<> Builder(T);
  104. // Branch - See if we are conditional jumping on constant
  105. if (auto *BI = dyn_cast<BranchInst>(T)) {
  106. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  107. BasicBlock *Dest1 = BI->getSuccessor(0);
  108. BasicBlock *Dest2 = BI->getSuccessor(1);
  109. if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  110. // Are we branching on constant?
  111. // YES. Change to unconditional branch...
  112. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  113. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  114. // Let the basic block know that we are letting go of it. Based on this,
  115. // it will adjust it's PHI nodes.
  116. OldDest->removePredecessor(BB);
  117. // Replace the conditional branch with an unconditional one.
  118. Builder.CreateBr(Destination);
  119. BI->eraseFromParent();
  120. if (DTU)
  121. DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, OldDest}});
  122. return true;
  123. }
  124. if (Dest2 == Dest1) { // Conditional branch to same location?
  125. // This branch matches something like this:
  126. // br bool %cond, label %Dest, label %Dest
  127. // and changes it into: br label %Dest
  128. // Let the basic block know that we are letting go of one copy of it.
  129. assert(BI->getParent() && "Terminator not inserted in block!");
  130. Dest1->removePredecessor(BI->getParent());
  131. // Replace the conditional branch with an unconditional one.
  132. Builder.CreateBr(Dest1);
  133. Value *Cond = BI->getCondition();
  134. BI->eraseFromParent();
  135. if (DeleteDeadConditions)
  136. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  137. return true;
  138. }
  139. return false;
  140. }
  141. if (auto *SI = dyn_cast<SwitchInst>(T)) {
  142. // If we are switching on a constant, we can convert the switch to an
  143. // unconditional branch.
  144. auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
  145. BasicBlock *DefaultDest = SI->getDefaultDest();
  146. BasicBlock *TheOnlyDest = DefaultDest;
  147. // If the default is unreachable, ignore it when searching for TheOnlyDest.
  148. if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
  149. SI->getNumCases() > 0) {
  150. TheOnlyDest = SI->case_begin()->getCaseSuccessor();
  151. }
  152. // Figure out which case it goes to.
  153. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  154. // Found case matching a constant operand?
  155. if (i->getCaseValue() == CI) {
  156. TheOnlyDest = i->getCaseSuccessor();
  157. break;
  158. }
  159. // Check to see if this branch is going to the same place as the default
  160. // dest. If so, eliminate it as an explicit compare.
  161. if (i->getCaseSuccessor() == DefaultDest) {
  162. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  163. unsigned NCases = SI->getNumCases();
  164. // Fold the case metadata into the default if there will be any branches
  165. // left, unless the metadata doesn't match the switch.
  166. if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
  167. // Collect branch weights into a vector.
  168. SmallVector<uint32_t, 8> Weights;
  169. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  170. ++MD_i) {
  171. auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  172. Weights.push_back(CI->getValue().getZExtValue());
  173. }
  174. // Merge weight of this case to the default weight.
  175. unsigned idx = i->getCaseIndex();
  176. Weights[0] += Weights[idx+1];
  177. // Remove weight for this case.
  178. std::swap(Weights[idx+1], Weights.back());
  179. Weights.pop_back();
  180. SI->setMetadata(LLVMContext::MD_prof,
  181. MDBuilder(BB->getContext()).
  182. createBranchWeights(Weights));
  183. }
  184. // Remove this entry.
  185. BasicBlock *ParentBB = SI->getParent();
  186. DefaultDest->removePredecessor(ParentBB);
  187. i = SI->removeCase(i);
  188. e = SI->case_end();
  189. if (DTU)
  190. DTU->applyUpdatesPermissive(
  191. {{DominatorTree::Delete, ParentBB, DefaultDest}});
  192. continue;
  193. }
  194. // Otherwise, check to see if the switch only branches to one destination.
  195. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  196. // destinations.
  197. if (i->getCaseSuccessor() != TheOnlyDest)
  198. TheOnlyDest = nullptr;
  199. // Increment this iterator as we haven't removed the case.
  200. ++i;
  201. }
  202. if (CI && !TheOnlyDest) {
  203. // Branching on a constant, but not any of the cases, go to the default
  204. // successor.
  205. TheOnlyDest = SI->getDefaultDest();
  206. }
  207. // If we found a single destination that we can fold the switch into, do so
  208. // now.
  209. if (TheOnlyDest) {
  210. // Insert the new branch.
  211. Builder.CreateBr(TheOnlyDest);
  212. BasicBlock *BB = SI->getParent();
  213. std::vector <DominatorTree::UpdateType> Updates;
  214. if (DTU)
  215. Updates.reserve(SI->getNumSuccessors() - 1);
  216. // Remove entries from PHI nodes which we no longer branch to...
  217. for (BasicBlock *Succ : successors(SI)) {
  218. // Found case matching a constant operand?
  219. if (Succ == TheOnlyDest) {
  220. TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
  221. } else {
  222. Succ->removePredecessor(BB);
  223. if (DTU)
  224. Updates.push_back({DominatorTree::Delete, BB, Succ});
  225. }
  226. }
  227. // Delete the old switch.
  228. Value *Cond = SI->getCondition();
  229. SI->eraseFromParent();
  230. if (DeleteDeadConditions)
  231. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  232. if (DTU)
  233. DTU->applyUpdatesPermissive(Updates);
  234. return true;
  235. }
  236. if (SI->getNumCases() == 1) {
  237. // Otherwise, we can fold this switch into a conditional branch
  238. // instruction if it has only one non-default destination.
  239. auto FirstCase = *SI->case_begin();
  240. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  241. FirstCase.getCaseValue(), "cond");
  242. // Insert the new branch.
  243. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  244. FirstCase.getCaseSuccessor(),
  245. SI->getDefaultDest());
  246. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  247. if (MD && MD->getNumOperands() == 3) {
  248. ConstantInt *SICase =
  249. mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  250. ConstantInt *SIDef =
  251. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  252. assert(SICase && SIDef);
  253. // The TrueWeight should be the weight for the single case of SI.
  254. NewBr->setMetadata(LLVMContext::MD_prof,
  255. MDBuilder(BB->getContext()).
  256. createBranchWeights(SICase->getValue().getZExtValue(),
  257. SIDef->getValue().getZExtValue()));
  258. }
  259. // Update make.implicit metadata to the newly-created conditional branch.
  260. MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
  261. if (MakeImplicitMD)
  262. NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
  263. // Delete the old switch.
  264. SI->eraseFromParent();
  265. return true;
  266. }
  267. return false;
  268. }
  269. if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
  270. // indirectbr blockaddress(@F, @BB) -> br label @BB
  271. if (auto *BA =
  272. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  273. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  274. std::vector <DominatorTree::UpdateType> Updates;
  275. if (DTU)
  276. Updates.reserve(IBI->getNumDestinations() - 1);
  277. // Insert the new branch.
  278. Builder.CreateBr(TheOnlyDest);
  279. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  280. if (IBI->getDestination(i) == TheOnlyDest) {
  281. TheOnlyDest = nullptr;
  282. } else {
  283. BasicBlock *ParentBB = IBI->getParent();
  284. BasicBlock *DestBB = IBI->getDestination(i);
  285. DestBB->removePredecessor(ParentBB);
  286. if (DTU)
  287. Updates.push_back({DominatorTree::Delete, ParentBB, DestBB});
  288. }
  289. }
  290. Value *Address = IBI->getAddress();
  291. IBI->eraseFromParent();
  292. if (DeleteDeadConditions)
  293. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  294. // If we didn't find our destination in the IBI successor list, then we
  295. // have undefined behavior. Replace the unconditional branch with an
  296. // 'unreachable' instruction.
  297. if (TheOnlyDest) {
  298. BB->getTerminator()->eraseFromParent();
  299. new UnreachableInst(BB->getContext(), BB);
  300. }
  301. if (DTU)
  302. DTU->applyUpdatesPermissive(Updates);
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. //===----------------------------------------------------------------------===//
  309. // Local dead code elimination.
  310. //
  311. /// isInstructionTriviallyDead - Return true if the result produced by the
  312. /// instruction is not used, and the instruction has no side effects.
  313. ///
  314. bool llvm::isInstructionTriviallyDead(Instruction *I,
  315. const TargetLibraryInfo *TLI) {
  316. if (!I->use_empty())
  317. return false;
  318. return wouldInstructionBeTriviallyDead(I, TLI);
  319. }
  320. bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
  321. const TargetLibraryInfo *TLI) {
  322. if (I->isTerminator())
  323. return false;
  324. // We don't want the landingpad-like instructions removed by anything this
  325. // general.
  326. if (I->isEHPad())
  327. return false;
  328. // We don't want debug info removed by anything this general, unless
  329. // debug info is empty.
  330. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  331. if (DDI->getAddress())
  332. return false;
  333. return true;
  334. }
  335. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  336. if (DVI->getValue())
  337. return false;
  338. return true;
  339. }
  340. if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
  341. if (DLI->getLabel())
  342. return false;
  343. return true;
  344. }
  345. if (!I->mayHaveSideEffects())
  346. return true;
  347. // Special case intrinsics that "may have side effects" but can be deleted
  348. // when dead.
  349. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  350. // Safe to delete llvm.stacksave and launder.invariant.group if dead.
  351. if (II->getIntrinsicID() == Intrinsic::stacksave ||
  352. II->getIntrinsicID() == Intrinsic::launder_invariant_group)
  353. return true;
  354. // Lifetime intrinsics are dead when their right-hand is undef.
  355. if (II->isLifetimeStartOrEnd())
  356. return isa<UndefValue>(II->getArgOperand(1));
  357. // Assumptions are dead if their condition is trivially true. Guards on
  358. // true are operationally no-ops. In the future we can consider more
  359. // sophisticated tradeoffs for guards considering potential for check
  360. // widening, but for now we keep things simple.
  361. if (II->getIntrinsicID() == Intrinsic::assume ||
  362. II->getIntrinsicID() == Intrinsic::experimental_guard) {
  363. if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  364. return !Cond->isZero();
  365. return false;
  366. }
  367. }
  368. if (isAllocLikeFn(I, TLI))
  369. return true;
  370. if (CallInst *CI = isFreeCall(I, TLI))
  371. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  372. return C->isNullValue() || isa<UndefValue>(C);
  373. if (auto *Call = dyn_cast<CallBase>(I))
  374. if (isMathLibCallNoop(Call, TLI))
  375. return true;
  376. return false;
  377. }
  378. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  379. /// trivially dead instruction, delete it. If that makes any of its operands
  380. /// trivially dead, delete them too, recursively. Return true if any
  381. /// instructions were deleted.
  382. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
  383. Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU) {
  384. Instruction *I = dyn_cast<Instruction>(V);
  385. if (!I || !isInstructionTriviallyDead(I, TLI))
  386. return false;
  387. SmallVector<Instruction*, 16> DeadInsts;
  388. DeadInsts.push_back(I);
  389. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU);
  390. return true;
  391. }
  392. void llvm::RecursivelyDeleteTriviallyDeadInstructions(
  393. SmallVectorImpl<Instruction *> &DeadInsts, const TargetLibraryInfo *TLI,
  394. MemorySSAUpdater *MSSAU) {
  395. // Process the dead instruction list until empty.
  396. while (!DeadInsts.empty()) {
  397. Instruction &I = *DeadInsts.pop_back_val();
  398. assert(I.use_empty() && "Instructions with uses are not dead.");
  399. assert(isInstructionTriviallyDead(&I, TLI) &&
  400. "Live instruction found in dead worklist!");
  401. // Don't lose the debug info while deleting the instructions.
  402. salvageDebugInfo(I);
  403. // Null out all of the instruction's operands to see if any operand becomes
  404. // dead as we go.
  405. for (Use &OpU : I.operands()) {
  406. Value *OpV = OpU.get();
  407. OpU.set(nullptr);
  408. if (!OpV->use_empty())
  409. continue;
  410. // If the operand is an instruction that became dead as we nulled out the
  411. // operand, and if it is 'trivially' dead, delete it in a future loop
  412. // iteration.
  413. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  414. if (isInstructionTriviallyDead(OpI, TLI))
  415. DeadInsts.push_back(OpI);
  416. }
  417. if (MSSAU)
  418. MSSAU->removeMemoryAccess(&I);
  419. I.eraseFromParent();
  420. }
  421. }
  422. bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
  423. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  424. findDbgUsers(DbgUsers, I);
  425. for (auto *DII : DbgUsers) {
  426. Value *Undef = UndefValue::get(I->getType());
  427. DII->setOperand(0, MetadataAsValue::get(DII->getContext(),
  428. ValueAsMetadata::get(Undef)));
  429. }
  430. return !DbgUsers.empty();
  431. }
  432. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  433. /// This is similar to Instruction::hasOneUse() except this will also return
  434. /// true when there are no uses or multiple uses that all refer to the same
  435. /// value.
  436. static bool areAllUsesEqual(Instruction *I) {
  437. Value::user_iterator UI = I->user_begin();
  438. Value::user_iterator UE = I->user_end();
  439. if (UI == UE)
  440. return true;
  441. User *TheUse = *UI;
  442. for (++UI; UI != UE; ++UI) {
  443. if (*UI != TheUse)
  444. return false;
  445. }
  446. return true;
  447. }
  448. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  449. /// dead PHI node, due to being a def-use chain of single-use nodes that
  450. /// either forms a cycle or is terminated by a trivially dead instruction,
  451. /// delete it. If that makes any of its operands trivially dead, delete them
  452. /// too, recursively. Return true if a change was made.
  453. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  454. const TargetLibraryInfo *TLI) {
  455. SmallPtrSet<Instruction*, 4> Visited;
  456. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  457. I = cast<Instruction>(*I->user_begin())) {
  458. if (I->use_empty())
  459. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  460. // If we find an instruction more than once, we're on a cycle that
  461. // won't prove fruitful.
  462. if (!Visited.insert(I).second) {
  463. // Break the cycle and delete the instruction and its operands.
  464. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  465. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  466. return true;
  467. }
  468. }
  469. return false;
  470. }
  471. static bool
  472. simplifyAndDCEInstruction(Instruction *I,
  473. SmallSetVector<Instruction *, 16> &WorkList,
  474. const DataLayout &DL,
  475. const TargetLibraryInfo *TLI) {
  476. if (isInstructionTriviallyDead(I, TLI)) {
  477. salvageDebugInfo(*I);
  478. // Null out all of the instruction's operands to see if any operand becomes
  479. // dead as we go.
  480. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  481. Value *OpV = I->getOperand(i);
  482. I->setOperand(i, nullptr);
  483. if (!OpV->use_empty() || I == OpV)
  484. continue;
  485. // If the operand is an instruction that became dead as we nulled out the
  486. // operand, and if it is 'trivially' dead, delete it in a future loop
  487. // iteration.
  488. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  489. if (isInstructionTriviallyDead(OpI, TLI))
  490. WorkList.insert(OpI);
  491. }
  492. I->eraseFromParent();
  493. return true;
  494. }
  495. if (Value *SimpleV = SimplifyInstruction(I, DL)) {
  496. // Add the users to the worklist. CAREFUL: an instruction can use itself,
  497. // in the case of a phi node.
  498. for (User *U : I->users()) {
  499. if (U != I) {
  500. WorkList.insert(cast<Instruction>(U));
  501. }
  502. }
  503. // Replace the instruction with its simplified value.
  504. bool Changed = false;
  505. if (!I->use_empty()) {
  506. I->replaceAllUsesWith(SimpleV);
  507. Changed = true;
  508. }
  509. if (isInstructionTriviallyDead(I, TLI)) {
  510. I->eraseFromParent();
  511. Changed = true;
  512. }
  513. return Changed;
  514. }
  515. return false;
  516. }
  517. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  518. /// simplify any instructions in it and recursively delete dead instructions.
  519. ///
  520. /// This returns true if it changed the code, note that it can delete
  521. /// instructions in other blocks as well in this block.
  522. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
  523. const TargetLibraryInfo *TLI) {
  524. bool MadeChange = false;
  525. const DataLayout &DL = BB->getModule()->getDataLayout();
  526. #ifndef NDEBUG
  527. // In debug builds, ensure that the terminator of the block is never replaced
  528. // or deleted by these simplifications. The idea of simplification is that it
  529. // cannot introduce new instructions, and there is no way to replace the
  530. // terminator of a block without introducing a new instruction.
  531. AssertingVH<Instruction> TerminatorVH(&BB->back());
  532. #endif
  533. SmallSetVector<Instruction *, 16> WorkList;
  534. // Iterate over the original function, only adding insts to the worklist
  535. // if they actually need to be revisited. This avoids having to pre-init
  536. // the worklist with the entire function's worth of instructions.
  537. for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
  538. BI != E;) {
  539. assert(!BI->isTerminator());
  540. Instruction *I = &*BI;
  541. ++BI;
  542. // We're visiting this instruction now, so make sure it's not in the
  543. // worklist from an earlier visit.
  544. if (!WorkList.count(I))
  545. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  546. }
  547. while (!WorkList.empty()) {
  548. Instruction *I = WorkList.pop_back_val();
  549. MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
  550. }
  551. return MadeChange;
  552. }
  553. //===----------------------------------------------------------------------===//
  554. // Control Flow Graph Restructuring.
  555. //
  556. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  557. /// method is called when we're about to delete Pred as a predecessor of BB. If
  558. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  559. ///
  560. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  561. /// nodes that collapse into identity values. For example, if we have:
  562. /// x = phi(1, 0, 0, 0)
  563. /// y = and x, z
  564. ///
  565. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  566. /// recursively fold the and to 0.
  567. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  568. DomTreeUpdater *DTU) {
  569. // This only adjusts blocks with PHI nodes.
  570. if (!isa<PHINode>(BB->begin()))
  571. return;
  572. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  573. // them down. This will leave us with single entry phi nodes and other phis
  574. // that can be removed.
  575. BB->removePredecessor(Pred, true);
  576. WeakTrackingVH PhiIt = &BB->front();
  577. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  578. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  579. Value *OldPhiIt = PhiIt;
  580. if (!recursivelySimplifyInstruction(PN))
  581. continue;
  582. // If recursive simplification ended up deleting the next PHI node we would
  583. // iterate to, then our iterator is invalid, restart scanning from the top
  584. // of the block.
  585. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  586. }
  587. if (DTU)
  588. DTU->applyUpdatesPermissive({{DominatorTree::Delete, Pred, BB}});
  589. }
  590. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  591. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  592. /// between them, moving the instructions in the predecessor into DestBB and
  593. /// deleting the predecessor block.
  594. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
  595. DomTreeUpdater *DTU) {
  596. // If BB has single-entry PHI nodes, fold them.
  597. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  598. Value *NewVal = PN->getIncomingValue(0);
  599. // Replace self referencing PHI with undef, it must be dead.
  600. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  601. PN->replaceAllUsesWith(NewVal);
  602. PN->eraseFromParent();
  603. }
  604. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  605. assert(PredBB && "Block doesn't have a single predecessor!");
  606. bool ReplaceEntryBB = false;
  607. if (PredBB == &DestBB->getParent()->getEntryBlock())
  608. ReplaceEntryBB = true;
  609. // DTU updates: Collect all the edges that enter
  610. // PredBB. These dominator edges will be redirected to DestBB.
  611. SmallVector<DominatorTree::UpdateType, 32> Updates;
  612. if (DTU) {
  613. Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
  614. for (auto I = pred_begin(PredBB), E = pred_end(PredBB); I != E; ++I) {
  615. Updates.push_back({DominatorTree::Delete, *I, PredBB});
  616. // This predecessor of PredBB may already have DestBB as a successor.
  617. if (llvm::find(successors(*I), DestBB) == succ_end(*I))
  618. Updates.push_back({DominatorTree::Insert, *I, DestBB});
  619. }
  620. }
  621. // Zap anything that took the address of DestBB. Not doing this will give the
  622. // address an invalid value.
  623. if (DestBB->hasAddressTaken()) {
  624. BlockAddress *BA = BlockAddress::get(DestBB);
  625. Constant *Replacement =
  626. ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
  627. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  628. BA->getType()));
  629. BA->destroyConstant();
  630. }
  631. // Anything that branched to PredBB now branches to DestBB.
  632. PredBB->replaceAllUsesWith(DestBB);
  633. // Splice all the instructions from PredBB to DestBB.
  634. PredBB->getTerminator()->eraseFromParent();
  635. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  636. new UnreachableInst(PredBB->getContext(), PredBB);
  637. // If the PredBB is the entry block of the function, move DestBB up to
  638. // become the entry block after we erase PredBB.
  639. if (ReplaceEntryBB)
  640. DestBB->moveAfter(PredBB);
  641. if (DTU) {
  642. assert(PredBB->getInstList().size() == 1 &&
  643. isa<UnreachableInst>(PredBB->getTerminator()) &&
  644. "The successor list of PredBB isn't empty before "
  645. "applying corresponding DTU updates.");
  646. DTU->applyUpdatesPermissive(Updates);
  647. DTU->deleteBB(PredBB);
  648. // Recalculation of DomTree is needed when updating a forward DomTree and
  649. // the Entry BB is replaced.
  650. if (ReplaceEntryBB && DTU->hasDomTree()) {
  651. // The entry block was removed and there is no external interface for
  652. // the dominator tree to be notified of this change. In this corner-case
  653. // we recalculate the entire tree.
  654. DTU->recalculate(*(DestBB->getParent()));
  655. }
  656. }
  657. else {
  658. PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
  659. }
  660. }
  661. /// CanMergeValues - Return true if we can choose one of these values to use
  662. /// in place of the other. Note that we will always choose the non-undef
  663. /// value to keep.
  664. static bool CanMergeValues(Value *First, Value *Second) {
  665. return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
  666. }
  667. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  668. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  669. ///
  670. /// Assumption: Succ is the single successor for BB.
  671. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  672. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  673. LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  674. << Succ->getName() << "\n");
  675. // Shortcut, if there is only a single predecessor it must be BB and merging
  676. // is always safe
  677. if (Succ->getSinglePredecessor()) return true;
  678. // Make a list of the predecessors of BB
  679. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  680. // Look at all the phi nodes in Succ, to see if they present a conflict when
  681. // merging these blocks
  682. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  683. PHINode *PN = cast<PHINode>(I);
  684. // If the incoming value from BB is again a PHINode in
  685. // BB which has the same incoming value for *PI as PN does, we can
  686. // merge the phi nodes and then the blocks can still be merged
  687. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  688. if (BBPN && BBPN->getParent() == BB) {
  689. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  690. BasicBlock *IBB = PN->getIncomingBlock(PI);
  691. if (BBPreds.count(IBB) &&
  692. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  693. PN->getIncomingValue(PI))) {
  694. LLVM_DEBUG(dbgs()
  695. << "Can't fold, phi node " << PN->getName() << " in "
  696. << Succ->getName() << " is conflicting with "
  697. << BBPN->getName() << " with regard to common predecessor "
  698. << IBB->getName() << "\n");
  699. return false;
  700. }
  701. }
  702. } else {
  703. Value* Val = PN->getIncomingValueForBlock(BB);
  704. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  705. // See if the incoming value for the common predecessor is equal to the
  706. // one for BB, in which case this phi node will not prevent the merging
  707. // of the block.
  708. BasicBlock *IBB = PN->getIncomingBlock(PI);
  709. if (BBPreds.count(IBB) &&
  710. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  711. LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
  712. << " in " << Succ->getName()
  713. << " is conflicting with regard to common "
  714. << "predecessor " << IBB->getName() << "\n");
  715. return false;
  716. }
  717. }
  718. }
  719. }
  720. return true;
  721. }
  722. using PredBlockVector = SmallVector<BasicBlock *, 16>;
  723. using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
  724. /// Determines the value to use as the phi node input for a block.
  725. ///
  726. /// Select between \p OldVal any value that we know flows from \p BB
  727. /// to a particular phi on the basis of which one (if either) is not
  728. /// undef. Update IncomingValues based on the selected value.
  729. ///
  730. /// \param OldVal The value we are considering selecting.
  731. /// \param BB The block that the value flows in from.
  732. /// \param IncomingValues A map from block-to-value for other phi inputs
  733. /// that we have examined.
  734. ///
  735. /// \returns the selected value.
  736. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  737. IncomingValueMap &IncomingValues) {
  738. if (!isa<UndefValue>(OldVal)) {
  739. assert((!IncomingValues.count(BB) ||
  740. IncomingValues.find(BB)->second == OldVal) &&
  741. "Expected OldVal to match incoming value from BB!");
  742. IncomingValues.insert(std::make_pair(BB, OldVal));
  743. return OldVal;
  744. }
  745. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  746. if (It != IncomingValues.end()) return It->second;
  747. return OldVal;
  748. }
  749. /// Create a map from block to value for the operands of a
  750. /// given phi.
  751. ///
  752. /// Create a map from block to value for each non-undef value flowing
  753. /// into \p PN.
  754. ///
  755. /// \param PN The phi we are collecting the map for.
  756. /// \param IncomingValues [out] The map from block to value for this phi.
  757. static void gatherIncomingValuesToPhi(PHINode *PN,
  758. IncomingValueMap &IncomingValues) {
  759. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  760. BasicBlock *BB = PN->getIncomingBlock(i);
  761. Value *V = PN->getIncomingValue(i);
  762. if (!isa<UndefValue>(V))
  763. IncomingValues.insert(std::make_pair(BB, V));
  764. }
  765. }
  766. /// Replace the incoming undef values to a phi with the values
  767. /// from a block-to-value map.
  768. ///
  769. /// \param PN The phi we are replacing the undefs in.
  770. /// \param IncomingValues A map from block to value.
  771. static void replaceUndefValuesInPhi(PHINode *PN,
  772. const IncomingValueMap &IncomingValues) {
  773. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  774. Value *V = PN->getIncomingValue(i);
  775. if (!isa<UndefValue>(V)) continue;
  776. BasicBlock *BB = PN->getIncomingBlock(i);
  777. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  778. if (It == IncomingValues.end()) continue;
  779. PN->setIncomingValue(i, It->second);
  780. }
  781. }
  782. /// Replace a value flowing from a block to a phi with
  783. /// potentially multiple instances of that value flowing from the
  784. /// block's predecessors to the phi.
  785. ///
  786. /// \param BB The block with the value flowing into the phi.
  787. /// \param BBPreds The predecessors of BB.
  788. /// \param PN The phi that we are updating.
  789. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  790. const PredBlockVector &BBPreds,
  791. PHINode *PN) {
  792. Value *OldVal = PN->removeIncomingValue(BB, false);
  793. assert(OldVal && "No entry in PHI for Pred BB!");
  794. IncomingValueMap IncomingValues;
  795. // We are merging two blocks - BB, and the block containing PN - and
  796. // as a result we need to redirect edges from the predecessors of BB
  797. // to go to the block containing PN, and update PN
  798. // accordingly. Since we allow merging blocks in the case where the
  799. // predecessor and successor blocks both share some predecessors,
  800. // and where some of those common predecessors might have undef
  801. // values flowing into PN, we want to rewrite those values to be
  802. // consistent with the non-undef values.
  803. gatherIncomingValuesToPhi(PN, IncomingValues);
  804. // If this incoming value is one of the PHI nodes in BB, the new entries
  805. // in the PHI node are the entries from the old PHI.
  806. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  807. PHINode *OldValPN = cast<PHINode>(OldVal);
  808. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  809. // Note that, since we are merging phi nodes and BB and Succ might
  810. // have common predecessors, we could end up with a phi node with
  811. // identical incoming branches. This will be cleaned up later (and
  812. // will trigger asserts if we try to clean it up now, without also
  813. // simplifying the corresponding conditional branch).
  814. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  815. Value *PredVal = OldValPN->getIncomingValue(i);
  816. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  817. IncomingValues);
  818. // And add a new incoming value for this predecessor for the
  819. // newly retargeted branch.
  820. PN->addIncoming(Selected, PredBB);
  821. }
  822. } else {
  823. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  824. // Update existing incoming values in PN for this
  825. // predecessor of BB.
  826. BasicBlock *PredBB = BBPreds[i];
  827. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  828. IncomingValues);
  829. // And add a new incoming value for this predecessor for the
  830. // newly retargeted branch.
  831. PN->addIncoming(Selected, PredBB);
  832. }
  833. }
  834. replaceUndefValuesInPhi(PN, IncomingValues);
  835. }
  836. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  837. /// unconditional branch, and contains no instructions other than PHI nodes,
  838. /// potential side-effect free intrinsics and the branch. If possible,
  839. /// eliminate BB by rewriting all the predecessors to branch to the successor
  840. /// block and return true. If we can't transform, return false.
  841. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
  842. DomTreeUpdater *DTU) {
  843. assert(BB != &BB->getParent()->getEntryBlock() &&
  844. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  845. // We can't eliminate infinite loops.
  846. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  847. if (BB == Succ) return false;
  848. // Check to see if merging these blocks would cause conflicts for any of the
  849. // phi nodes in BB or Succ. If not, we can safely merge.
  850. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  851. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  852. // has uses which will not disappear when the PHI nodes are merged. It is
  853. // possible to handle such cases, but difficult: it requires checking whether
  854. // BB dominates Succ, which is non-trivial to calculate in the case where
  855. // Succ has multiple predecessors. Also, it requires checking whether
  856. // constructing the necessary self-referential PHI node doesn't introduce any
  857. // conflicts; this isn't too difficult, but the previous code for doing this
  858. // was incorrect.
  859. //
  860. // Note that if this check finds a live use, BB dominates Succ, so BB is
  861. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  862. // folding the branch isn't profitable in that case anyway.
  863. if (!Succ->getSinglePredecessor()) {
  864. BasicBlock::iterator BBI = BB->begin();
  865. while (isa<PHINode>(*BBI)) {
  866. for (Use &U : BBI->uses()) {
  867. if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
  868. if (PN->getIncomingBlock(U) != BB)
  869. return false;
  870. } else {
  871. return false;
  872. }
  873. }
  874. ++BBI;
  875. }
  876. }
  877. // We cannot fold the block if it's a branch to an already present callbr
  878. // successor because that creates duplicate successors.
  879. for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  880. if (auto *CBI = dyn_cast<CallBrInst>((*I)->getTerminator())) {
  881. if (Succ == CBI->getDefaultDest())
  882. return false;
  883. for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
  884. if (Succ == CBI->getIndirectDest(i))
  885. return false;
  886. }
  887. }
  888. LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  889. SmallVector<DominatorTree::UpdateType, 32> Updates;
  890. if (DTU) {
  891. Updates.push_back({DominatorTree::Delete, BB, Succ});
  892. // All predecessors of BB will be moved to Succ.
  893. for (auto I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
  894. Updates.push_back({DominatorTree::Delete, *I, BB});
  895. // This predecessor of BB may already have Succ as a successor.
  896. if (llvm::find(successors(*I), Succ) == succ_end(*I))
  897. Updates.push_back({DominatorTree::Insert, *I, Succ});
  898. }
  899. }
  900. if (isa<PHINode>(Succ->begin())) {
  901. // If there is more than one pred of succ, and there are PHI nodes in
  902. // the successor, then we need to add incoming edges for the PHI nodes
  903. //
  904. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  905. // Loop over all of the PHI nodes in the successor of BB.
  906. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  907. PHINode *PN = cast<PHINode>(I);
  908. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  909. }
  910. }
  911. if (Succ->getSinglePredecessor()) {
  912. // BB is the only predecessor of Succ, so Succ will end up with exactly
  913. // the same predecessors BB had.
  914. // Copy over any phi, debug or lifetime instruction.
  915. BB->getTerminator()->eraseFromParent();
  916. Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
  917. BB->getInstList());
  918. } else {
  919. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  920. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  921. assert(PN->use_empty() && "There shouldn't be any uses here!");
  922. PN->eraseFromParent();
  923. }
  924. }
  925. // If the unconditional branch we replaced contains llvm.loop metadata, we
  926. // add the metadata to the branch instructions in the predecessors.
  927. unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
  928. Instruction *TI = BB->getTerminator();
  929. if (TI)
  930. if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
  931. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  932. BasicBlock *Pred = *PI;
  933. Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
  934. }
  935. // Everything that jumped to BB now goes to Succ.
  936. BB->replaceAllUsesWith(Succ);
  937. if (!Succ->hasName()) Succ->takeName(BB);
  938. // Clear the successor list of BB to match updates applying to DTU later.
  939. if (BB->getTerminator())
  940. BB->getInstList().pop_back();
  941. new UnreachableInst(BB->getContext(), BB);
  942. assert(succ_empty(BB) && "The successor list of BB isn't empty before "
  943. "applying corresponding DTU updates.");
  944. if (DTU) {
  945. DTU->applyUpdatesPermissive(Updates);
  946. DTU->deleteBB(BB);
  947. } else {
  948. BB->eraseFromParent(); // Delete the old basic block.
  949. }
  950. return true;
  951. }
  952. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  953. /// nodes in this block. This doesn't try to be clever about PHI nodes
  954. /// which differ only in the order of the incoming values, but instcombine
  955. /// orders them so it usually won't matter.
  956. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  957. // This implementation doesn't currently consider undef operands
  958. // specially. Theoretically, two phis which are identical except for
  959. // one having an undef where the other doesn't could be collapsed.
  960. struct PHIDenseMapInfo {
  961. static PHINode *getEmptyKey() {
  962. return DenseMapInfo<PHINode *>::getEmptyKey();
  963. }
  964. static PHINode *getTombstoneKey() {
  965. return DenseMapInfo<PHINode *>::getTombstoneKey();
  966. }
  967. static unsigned getHashValue(PHINode *PN) {
  968. // Compute a hash value on the operands. Instcombine will likely have
  969. // sorted them, which helps expose duplicates, but we have to check all
  970. // the operands to be safe in case instcombine hasn't run.
  971. return static_cast<unsigned>(hash_combine(
  972. hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
  973. hash_combine_range(PN->block_begin(), PN->block_end())));
  974. }
  975. static bool isEqual(PHINode *LHS, PHINode *RHS) {
  976. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  977. RHS == getEmptyKey() || RHS == getTombstoneKey())
  978. return LHS == RHS;
  979. return LHS->isIdenticalTo(RHS);
  980. }
  981. };
  982. // Set of unique PHINodes.
  983. DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
  984. // Examine each PHI.
  985. bool Changed = false;
  986. for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
  987. auto Inserted = PHISet.insert(PN);
  988. if (!Inserted.second) {
  989. // A duplicate. Replace this PHI with its duplicate.
  990. PN->replaceAllUsesWith(*Inserted.first);
  991. PN->eraseFromParent();
  992. Changed = true;
  993. // The RAUW can change PHIs that we already visited. Start over from the
  994. // beginning.
  995. PHISet.clear();
  996. I = BB->begin();
  997. }
  998. }
  999. return Changed;
  1000. }
  1001. /// enforceKnownAlignment - If the specified pointer points to an object that
  1002. /// we control, modify the object's alignment to PrefAlign. This isn't
  1003. /// often possible though. If alignment is important, a more reliable approach
  1004. /// is to simply align all global variables and allocation instructions to
  1005. /// their preferred alignment from the beginning.
  1006. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  1007. unsigned PrefAlign,
  1008. const DataLayout &DL) {
  1009. assert(PrefAlign > Align);
  1010. V = V->stripPointerCasts();
  1011. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1012. // TODO: ideally, computeKnownBits ought to have used
  1013. // AllocaInst::getAlignment() in its computation already, making
  1014. // the below max redundant. But, as it turns out,
  1015. // stripPointerCasts recurses through infinite layers of bitcasts,
  1016. // while computeKnownBits is not allowed to traverse more than 6
  1017. // levels.
  1018. Align = std::max(AI->getAlignment(), Align);
  1019. if (PrefAlign <= Align)
  1020. return Align;
  1021. // If the preferred alignment is greater than the natural stack alignment
  1022. // then don't round up. This avoids dynamic stack realignment.
  1023. if (DL.exceedsNaturalStackAlignment(PrefAlign))
  1024. return Align;
  1025. AI->setAlignment(PrefAlign);
  1026. return PrefAlign;
  1027. }
  1028. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1029. // TODO: as above, this shouldn't be necessary.
  1030. Align = std::max(GO->getAlignment(), Align);
  1031. if (PrefAlign <= Align)
  1032. return Align;
  1033. // If there is a large requested alignment and we can, bump up the alignment
  1034. // of the global. If the memory we set aside for the global may not be the
  1035. // memory used by the final program then it is impossible for us to reliably
  1036. // enforce the preferred alignment.
  1037. if (!GO->canIncreaseAlignment())
  1038. return Align;
  1039. GO->setAlignment(PrefAlign);
  1040. return PrefAlign;
  1041. }
  1042. return Align;
  1043. }
  1044. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  1045. const DataLayout &DL,
  1046. const Instruction *CxtI,
  1047. AssumptionCache *AC,
  1048. const DominatorTree *DT) {
  1049. assert(V->getType()->isPointerTy() &&
  1050. "getOrEnforceKnownAlignment expects a pointer!");
  1051. KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
  1052. unsigned TrailZ = Known.countMinTrailingZeros();
  1053. // Avoid trouble with ridiculously large TrailZ values, such as
  1054. // those computed from a null pointer.
  1055. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  1056. unsigned Align = 1u << std::min(Known.getBitWidth() - 1, TrailZ);
  1057. // LLVM doesn't support alignments larger than this currently.
  1058. Align = std::min(Align, +Value::MaximumAlignment);
  1059. if (PrefAlign > Align)
  1060. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  1061. // We don't need to make any adjustment.
  1062. return Align;
  1063. }
  1064. ///===---------------------------------------------------------------------===//
  1065. /// Dbg Intrinsic utilities
  1066. ///
  1067. /// See if there is a dbg.value intrinsic for DIVar before I.
  1068. static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
  1069. Instruction *I) {
  1070. // Since we can't guarantee that the original dbg.declare instrinsic
  1071. // is removed by LowerDbgDeclare(), we need to make sure that we are
  1072. // not inserting the same dbg.value intrinsic over and over.
  1073. BasicBlock::InstListType::iterator PrevI(I);
  1074. if (PrevI != I->getParent()->getInstList().begin()) {
  1075. --PrevI;
  1076. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  1077. if (DVI->getValue() == I->getOperand(0) &&
  1078. DVI->getVariable() == DIVar &&
  1079. DVI->getExpression() == DIExpr)
  1080. return true;
  1081. }
  1082. return false;
  1083. }
  1084. /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
  1085. static bool PhiHasDebugValue(DILocalVariable *DIVar,
  1086. DIExpression *DIExpr,
  1087. PHINode *APN) {
  1088. // Since we can't guarantee that the original dbg.declare instrinsic
  1089. // is removed by LowerDbgDeclare(), we need to make sure that we are
  1090. // not inserting the same dbg.value intrinsic over and over.
  1091. SmallVector<DbgValueInst *, 1> DbgValues;
  1092. findDbgValues(DbgValues, APN);
  1093. for (auto *DVI : DbgValues) {
  1094. assert(DVI->getValue() == APN);
  1095. if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. /// Check if the alloc size of \p ValTy is large enough to cover the variable
  1101. /// (or fragment of the variable) described by \p DII.
  1102. ///
  1103. /// This is primarily intended as a helper for the different
  1104. /// ConvertDebugDeclareToDebugValue functions. The dbg.declare/dbg.addr that is
  1105. /// converted describes an alloca'd variable, so we need to use the
  1106. /// alloc size of the value when doing the comparison. E.g. an i1 value will be
  1107. /// identified as covering an n-bit fragment, if the store size of i1 is at
  1108. /// least n bits.
  1109. static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
  1110. const DataLayout &DL = DII->getModule()->getDataLayout();
  1111. uint64_t ValueSize = DL.getTypeAllocSizeInBits(ValTy);
  1112. if (auto FragmentSize = DII->getFragmentSizeInBits())
  1113. return ValueSize >= *FragmentSize;
  1114. // We can't always calculate the size of the DI variable (e.g. if it is a
  1115. // VLA). Try to use the size of the alloca that the dbg intrinsic describes
  1116. // intead.
  1117. if (DII->isAddressOfVariable())
  1118. if (auto *AI = dyn_cast_or_null<AllocaInst>(DII->getVariableLocation()))
  1119. if (auto FragmentSize = AI->getAllocationSizeInBits(DL))
  1120. return ValueSize >= *FragmentSize;
  1121. // Could not determine size of variable. Conservatively return false.
  1122. return false;
  1123. }
  1124. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  1125. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1126. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1127. StoreInst *SI, DIBuilder &Builder) {
  1128. assert(DII->isAddressOfVariable());
  1129. auto *DIVar = DII->getVariable();
  1130. assert(DIVar && "Missing variable");
  1131. auto *DIExpr = DII->getExpression();
  1132. Value *DV = SI->getValueOperand();
  1133. if (!valueCoversEntireFragment(DV->getType(), DII)) {
  1134. // FIXME: If storing to a part of the variable described by the dbg.declare,
  1135. // then we want to insert a dbg.value for the corresponding fragment.
  1136. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1137. << *DII << '\n');
  1138. // For now, when there is a store to parts of the variable (but we do not
  1139. // know which part) we insert an dbg.value instrinsic to indicate that we
  1140. // know nothing about the variable's content.
  1141. DV = UndefValue::get(DV->getType());
  1142. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  1143. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
  1144. SI);
  1145. return;
  1146. }
  1147. if (!LdStHasDebugValue(DIVar, DIExpr, SI))
  1148. Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, DII->getDebugLoc(),
  1149. SI);
  1150. }
  1151. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  1152. /// that has an associated llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1153. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1154. LoadInst *LI, DIBuilder &Builder) {
  1155. auto *DIVar = DII->getVariable();
  1156. auto *DIExpr = DII->getExpression();
  1157. assert(DIVar && "Missing variable");
  1158. if (LdStHasDebugValue(DIVar, DIExpr, LI))
  1159. return;
  1160. if (!valueCoversEntireFragment(LI->getType(), DII)) {
  1161. // FIXME: If only referring to a part of the variable described by the
  1162. // dbg.declare, then we want to insert a dbg.value for the corresponding
  1163. // fragment.
  1164. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1165. << *DII << '\n');
  1166. return;
  1167. }
  1168. // We are now tracking the loaded value instead of the address. In the
  1169. // future if multi-location support is added to the IR, it might be
  1170. // preferable to keep tracking both the loaded value and the original
  1171. // address in case the alloca can not be elided.
  1172. Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
  1173. LI, DIVar, DIExpr, DII->getDebugLoc(), (Instruction *)nullptr);
  1174. DbgValue->insertAfter(LI);
  1175. }
  1176. /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
  1177. /// llvm.dbg.declare or llvm.dbg.addr intrinsic.
  1178. void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
  1179. PHINode *APN, DIBuilder &Builder) {
  1180. auto *DIVar = DII->getVariable();
  1181. auto *DIExpr = DII->getExpression();
  1182. assert(DIVar && "Missing variable");
  1183. if (PhiHasDebugValue(DIVar, DIExpr, APN))
  1184. return;
  1185. if (!valueCoversEntireFragment(APN->getType(), DII)) {
  1186. // FIXME: If only referring to a part of the variable described by the
  1187. // dbg.declare, then we want to insert a dbg.value for the corresponding
  1188. // fragment.
  1189. LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
  1190. << *DII << '\n');
  1191. return;
  1192. }
  1193. BasicBlock *BB = APN->getParent();
  1194. auto InsertionPt = BB->getFirstInsertionPt();
  1195. // The block may be a catchswitch block, which does not have a valid
  1196. // insertion point.
  1197. // FIXME: Insert dbg.value markers in the successors when appropriate.
  1198. if (InsertionPt != BB->end())
  1199. Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, DII->getDebugLoc(),
  1200. &*InsertionPt);
  1201. }
  1202. /// Determine whether this alloca is either a VLA or an array.
  1203. static bool isArray(AllocaInst *AI) {
  1204. return AI->isArrayAllocation() ||
  1205. AI->getType()->getElementType()->isArrayTy();
  1206. }
  1207. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  1208. /// of llvm.dbg.value intrinsics.
  1209. bool llvm::LowerDbgDeclare(Function &F) {
  1210. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1211. SmallVector<DbgDeclareInst *, 4> Dbgs;
  1212. for (auto &FI : F)
  1213. for (Instruction &BI : FI)
  1214. if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
  1215. Dbgs.push_back(DDI);
  1216. if (Dbgs.empty())
  1217. return false;
  1218. for (auto &I : Dbgs) {
  1219. DbgDeclareInst *DDI = I;
  1220. AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
  1221. // If this is an alloca for a scalar variable, insert a dbg.value
  1222. // at each load and store to the alloca and erase the dbg.declare.
  1223. // The dbg.values allow tracking a variable even if it is not
  1224. // stored on the stack, while the dbg.declare can only describe
  1225. // the stack slot (and at a lexical-scope granularity). Later
  1226. // passes will attempt to elide the stack slot.
  1227. if (!AI || isArray(AI))
  1228. continue;
  1229. // A volatile load/store means that the alloca can't be elided anyway.
  1230. if (llvm::any_of(AI->users(), [](User *U) -> bool {
  1231. if (LoadInst *LI = dyn_cast<LoadInst>(U))
  1232. return LI->isVolatile();
  1233. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  1234. return SI->isVolatile();
  1235. return false;
  1236. }))
  1237. continue;
  1238. for (auto &AIUse : AI->uses()) {
  1239. User *U = AIUse.getUser();
  1240. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1241. if (AIUse.getOperandNo() == 1)
  1242. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1243. } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1244. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1245. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1246. // This is a call by-value or some other instruction that takes a
  1247. // pointer to the variable. Insert a *value* intrinsic that describes
  1248. // the variable by dereferencing the alloca.
  1249. auto *DerefExpr =
  1250. DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
  1251. DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
  1252. DDI->getDebugLoc(), CI);
  1253. }
  1254. }
  1255. DDI->eraseFromParent();
  1256. }
  1257. return true;
  1258. }
  1259. /// Propagate dbg.value intrinsics through the newly inserted PHIs.
  1260. void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
  1261. SmallVectorImpl<PHINode *> &InsertedPHIs) {
  1262. assert(BB && "No BasicBlock to clone dbg.value(s) from.");
  1263. if (InsertedPHIs.size() == 0)
  1264. return;
  1265. // Map existing PHI nodes to their dbg.values.
  1266. ValueToValueMapTy DbgValueMap;
  1267. for (auto &I : *BB) {
  1268. if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
  1269. if (auto *Loc = dyn_cast_or_null<PHINode>(DbgII->getVariableLocation()))
  1270. DbgValueMap.insert({Loc, DbgII});
  1271. }
  1272. }
  1273. if (DbgValueMap.size() == 0)
  1274. return;
  1275. // Then iterate through the new PHIs and look to see if they use one of the
  1276. // previously mapped PHIs. If so, insert a new dbg.value intrinsic that will
  1277. // propagate the info through the new PHI.
  1278. LLVMContext &C = BB->getContext();
  1279. for (auto PHI : InsertedPHIs) {
  1280. BasicBlock *Parent = PHI->getParent();
  1281. // Avoid inserting an intrinsic into an EH block.
  1282. if (Parent->getFirstNonPHI()->isEHPad())
  1283. continue;
  1284. auto PhiMAV = MetadataAsValue::get(C, ValueAsMetadata::get(PHI));
  1285. for (auto VI : PHI->operand_values()) {
  1286. auto V = DbgValueMap.find(VI);
  1287. if (V != DbgValueMap.end()) {
  1288. auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
  1289. Instruction *NewDbgII = DbgII->clone();
  1290. NewDbgII->setOperand(0, PhiMAV);
  1291. auto InsertionPt = Parent->getFirstInsertionPt();
  1292. assert(InsertionPt != Parent->end() && "Ill-formed basic block");
  1293. NewDbgII->insertBefore(&*InsertionPt);
  1294. }
  1295. }
  1296. }
  1297. }
  1298. /// Finds all intrinsics declaring local variables as living in the memory that
  1299. /// 'V' points to. This may include a mix of dbg.declare and
  1300. /// dbg.addr intrinsics.
  1301. TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
  1302. // This function is hot. Check whether the value has any metadata to avoid a
  1303. // DenseMap lookup.
  1304. if (!V->isUsedByMetadata())
  1305. return {};
  1306. auto *L = LocalAsMetadata::getIfExists(V);
  1307. if (!L)
  1308. return {};
  1309. auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
  1310. if (!MDV)
  1311. return {};
  1312. TinyPtrVector<DbgVariableIntrinsic *> Declares;
  1313. for (User *U : MDV->users()) {
  1314. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
  1315. if (DII->isAddressOfVariable())
  1316. Declares.push_back(DII);
  1317. }
  1318. return Declares;
  1319. }
  1320. void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
  1321. // This function is hot. Check whether the value has any metadata to avoid a
  1322. // DenseMap lookup.
  1323. if (!V->isUsedByMetadata())
  1324. return;
  1325. if (auto *L = LocalAsMetadata::getIfExists(V))
  1326. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1327. for (User *U : MDV->users())
  1328. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  1329. DbgValues.push_back(DVI);
  1330. }
  1331. void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
  1332. Value *V) {
  1333. // This function is hot. Check whether the value has any metadata to avoid a
  1334. // DenseMap lookup.
  1335. if (!V->isUsedByMetadata())
  1336. return;
  1337. if (auto *L = LocalAsMetadata::getIfExists(V))
  1338. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  1339. for (User *U : MDV->users())
  1340. if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
  1341. DbgUsers.push_back(DII);
  1342. }
  1343. bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
  1344. Instruction *InsertBefore, DIBuilder &Builder,
  1345. bool DerefBefore, int Offset, bool DerefAfter) {
  1346. auto DbgAddrs = FindDbgAddrUses(Address);
  1347. for (DbgVariableIntrinsic *DII : DbgAddrs) {
  1348. DebugLoc Loc = DII->getDebugLoc();
  1349. auto *DIVar = DII->getVariable();
  1350. auto *DIExpr = DII->getExpression();
  1351. assert(DIVar && "Missing variable");
  1352. DIExpr = DIExpression::prepend(DIExpr, DerefBefore, Offset, DerefAfter);
  1353. // Insert llvm.dbg.declare immediately before InsertBefore, and remove old
  1354. // llvm.dbg.declare.
  1355. Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
  1356. if (DII == InsertBefore)
  1357. InsertBefore = InsertBefore->getNextNode();
  1358. DII->eraseFromParent();
  1359. }
  1360. return !DbgAddrs.empty();
  1361. }
  1362. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1363. DIBuilder &Builder, bool DerefBefore,
  1364. int Offset, bool DerefAfter) {
  1365. return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
  1366. DerefBefore, Offset, DerefAfter);
  1367. }
  1368. static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
  1369. DIBuilder &Builder, int Offset) {
  1370. DebugLoc Loc = DVI->getDebugLoc();
  1371. auto *DIVar = DVI->getVariable();
  1372. auto *DIExpr = DVI->getExpression();
  1373. assert(DIVar && "Missing variable");
  1374. // This is an alloca-based llvm.dbg.value. The first thing it should do with
  1375. // the alloca pointer is dereference it. Otherwise we don't know how to handle
  1376. // it and give up.
  1377. if (!DIExpr || DIExpr->getNumElements() < 1 ||
  1378. DIExpr->getElement(0) != dwarf::DW_OP_deref)
  1379. return;
  1380. // Insert the offset immediately after the first deref.
  1381. // We could just change the offset argument of dbg.value, but it's unsigned...
  1382. if (Offset) {
  1383. SmallVector<uint64_t, 4> Ops;
  1384. Ops.push_back(dwarf::DW_OP_deref);
  1385. DIExpression::appendOffset(Ops, Offset);
  1386. Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
  1387. DIExpr = Builder.createExpression(Ops);
  1388. }
  1389. Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
  1390. DVI->eraseFromParent();
  1391. }
  1392. void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  1393. DIBuilder &Builder, int Offset) {
  1394. if (auto *L = LocalAsMetadata::getIfExists(AI))
  1395. if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
  1396. for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
  1397. Use &U = *UI++;
  1398. if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
  1399. replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
  1400. }
  1401. }
  1402. /// Wrap \p V in a ValueAsMetadata instance.
  1403. static MetadataAsValue *wrapValueInMetadata(LLVMContext &C, Value *V) {
  1404. return MetadataAsValue::get(C, ValueAsMetadata::get(V));
  1405. }
  1406. bool llvm::salvageDebugInfo(Instruction &I) {
  1407. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  1408. findDbgUsers(DbgUsers, &I);
  1409. if (DbgUsers.empty())
  1410. return false;
  1411. return salvageDebugInfoForDbgValues(I, DbgUsers);
  1412. }
  1413. bool llvm::salvageDebugInfoForDbgValues(
  1414. Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
  1415. auto &Ctx = I.getContext();
  1416. auto wrapMD = [&](Value *V) { return wrapValueInMetadata(Ctx, V); };
  1417. for (auto *DII : DbgUsers) {
  1418. // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
  1419. // are implicitly pointing out the value as a DWARF memory location
  1420. // description.
  1421. bool StackValue = isa<DbgValueInst>(DII);
  1422. DIExpression *DIExpr =
  1423. salvageDebugInfoImpl(I, DII->getExpression(), StackValue);
  1424. // salvageDebugInfoImpl should fail on examining the first element of
  1425. // DbgUsers, or none of them.
  1426. if (!DIExpr)
  1427. return false;
  1428. DII->setOperand(0, wrapMD(I.getOperand(0)));
  1429. DII->setOperand(2, MetadataAsValue::get(Ctx, DIExpr));
  1430. LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
  1431. }
  1432. return true;
  1433. }
  1434. DIExpression *llvm::salvageDebugInfoImpl(Instruction &I,
  1435. DIExpression *SrcDIExpr,
  1436. bool WithStackValue) {
  1437. auto &M = *I.getModule();
  1438. auto &DL = M.getDataLayout();
  1439. // Apply a vector of opcodes to the source DIExpression.
  1440. auto doSalvage = [&](SmallVectorImpl<uint64_t> &Ops) -> DIExpression * {
  1441. DIExpression *DIExpr = SrcDIExpr;
  1442. if (!Ops.empty()) {
  1443. DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
  1444. }
  1445. return DIExpr;
  1446. };
  1447. // Apply the given offset to the source DIExpression.
  1448. auto applyOffset = [&](uint64_t Offset) -> DIExpression * {
  1449. SmallVector<uint64_t, 8> Ops;
  1450. DIExpression::appendOffset(Ops, Offset);
  1451. return doSalvage(Ops);
  1452. };
  1453. // initializer-list helper for applying operators to the source DIExpression.
  1454. auto applyOps =
  1455. [&](std::initializer_list<uint64_t> Opcodes) -> DIExpression * {
  1456. SmallVector<uint64_t, 8> Ops(Opcodes);
  1457. return doSalvage(Ops);
  1458. };
  1459. if (auto *CI = dyn_cast<CastInst>(&I)) {
  1460. // No-op casts and zexts are irrelevant for debug info.
  1461. if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
  1462. return SrcDIExpr;
  1463. return nullptr;
  1464. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  1465. unsigned BitWidth =
  1466. M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
  1467. // Rewrite a constant GEP into a DIExpression.
  1468. APInt Offset(BitWidth, 0);
  1469. if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
  1470. return applyOffset(Offset.getSExtValue());
  1471. } else {
  1472. return nullptr;
  1473. }
  1474. } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
  1475. // Rewrite binary operations with constant integer operands.
  1476. auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
  1477. if (!ConstInt || ConstInt->getBitWidth() > 64)
  1478. return nullptr;
  1479. uint64_t Val = ConstInt->getSExtValue();
  1480. switch (BI->getOpcode()) {
  1481. case Instruction::Add:
  1482. return applyOffset(Val);
  1483. case Instruction::Sub:
  1484. return applyOffset(-int64_t(Val));
  1485. case Instruction::Mul:
  1486. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
  1487. case Instruction::SDiv:
  1488. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
  1489. case Instruction::SRem:
  1490. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
  1491. case Instruction::Or:
  1492. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
  1493. case Instruction::And:
  1494. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
  1495. case Instruction::Xor:
  1496. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
  1497. case Instruction::Shl:
  1498. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
  1499. case Instruction::LShr:
  1500. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
  1501. case Instruction::AShr:
  1502. return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
  1503. default:
  1504. // TODO: Salvage constants from each kind of binop we know about.
  1505. return nullptr;
  1506. }
  1507. // *Not* to do: we should not attempt to salvage load instructions,
  1508. // because the validity and lifetime of a dbg.value containing
  1509. // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
  1510. }
  1511. return nullptr;
  1512. }
  1513. /// A replacement for a dbg.value expression.
  1514. using DbgValReplacement = Optional<DIExpression *>;
  1515. /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
  1516. /// possibly moving/deleting users to prevent use-before-def. Returns true if
  1517. /// changes are made.
  1518. static bool rewriteDebugUsers(
  1519. Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
  1520. function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
  1521. // Find debug users of From.
  1522. SmallVector<DbgVariableIntrinsic *, 1> Users;
  1523. findDbgUsers(Users, &From);
  1524. if (Users.empty())
  1525. return false;
  1526. // Prevent use-before-def of To.
  1527. bool Changed = false;
  1528. SmallPtrSet<DbgVariableIntrinsic *, 1> DeleteOrSalvage;
  1529. if (isa<Instruction>(&To)) {
  1530. bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
  1531. for (auto *DII : Users) {
  1532. // It's common to see a debug user between From and DomPoint. Move it
  1533. // after DomPoint to preserve the variable update without any reordering.
  1534. if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
  1535. LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
  1536. DII->moveAfter(&DomPoint);
  1537. Changed = true;
  1538. // Users which otherwise aren't dominated by the replacement value must
  1539. // be salvaged or deleted.
  1540. } else if (!DT.dominates(&DomPoint, DII)) {
  1541. DeleteOrSalvage.insert(DII);
  1542. }
  1543. }
  1544. }
  1545. // Update debug users without use-before-def risk.
  1546. for (auto *DII : Users) {
  1547. if (DeleteOrSalvage.count(DII))
  1548. continue;
  1549. LLVMContext &Ctx = DII->getContext();
  1550. DbgValReplacement DVR = RewriteExpr(*DII);
  1551. if (!DVR)
  1552. continue;
  1553. DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
  1554. DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
  1555. LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
  1556. Changed = true;
  1557. }
  1558. if (!DeleteOrSalvage.empty()) {
  1559. // Try to salvage the remaining debug users.
  1560. Changed |= salvageDebugInfo(From);
  1561. // Delete the debug users which weren't salvaged.
  1562. for (auto *DII : DeleteOrSalvage) {
  1563. if (DII->getVariableLocation() == &From) {
  1564. LLVM_DEBUG(dbgs() << "Erased UseBeforeDef: " << *DII << '\n');
  1565. DII->eraseFromParent();
  1566. Changed = true;
  1567. }
  1568. }
  1569. }
  1570. return Changed;
  1571. }
  1572. /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
  1573. /// losslessly preserve the bits and semantics of the value. This predicate is
  1574. /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
  1575. ///
  1576. /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
  1577. /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
  1578. /// and also does not allow lossless pointer <-> integer conversions.
  1579. static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
  1580. Type *ToTy) {
  1581. // Trivially compatible types.
  1582. if (FromTy == ToTy)
  1583. return true;
  1584. // Handle compatible pointer <-> integer conversions.
  1585. if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
  1586. bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
  1587. bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
  1588. !DL.isNonIntegralPointerType(ToTy);
  1589. return SameSize && LosslessConversion;
  1590. }
  1591. // TODO: This is not exhaustive.
  1592. return false;
  1593. }
  1594. bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
  1595. Instruction &DomPoint, DominatorTree &DT) {
  1596. // Exit early if From has no debug users.
  1597. if (!From.isUsedByMetadata())
  1598. return false;
  1599. assert(&From != &To && "Can't replace something with itself");
  1600. Type *FromTy = From.getType();
  1601. Type *ToTy = To.getType();
  1602. auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
  1603. return DII.getExpression();
  1604. };
  1605. // Handle no-op conversions.
  1606. Module &M = *From.getModule();
  1607. const DataLayout &DL = M.getDataLayout();
  1608. if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
  1609. return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
  1610. // Handle integer-to-integer widening and narrowing.
  1611. // FIXME: Use DW_OP_convert when it's available everywhere.
  1612. if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
  1613. uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
  1614. uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
  1615. assert(FromBits != ToBits && "Unexpected no-op conversion");
  1616. // When the width of the result grows, assume that a debugger will only
  1617. // access the low `FromBits` bits when inspecting the source variable.
  1618. if (FromBits < ToBits)
  1619. return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
  1620. // The width of the result has shrunk. Use sign/zero extension to describe
  1621. // the source variable's high bits.
  1622. auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
  1623. DILocalVariable *Var = DII.getVariable();
  1624. // Without knowing signedness, sign/zero extension isn't possible.
  1625. auto Signedness = Var->getSignedness();
  1626. if (!Signedness)
  1627. return None;
  1628. bool Signed = *Signedness == DIBasicType::Signedness::Signed;
  1629. dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
  1630. SmallVector<uint64_t, 8> Ops({dwarf::DW_OP_LLVM_convert, ToBits, TK,
  1631. dwarf::DW_OP_LLVM_convert, FromBits, TK});
  1632. return DIExpression::appendToStack(DII.getExpression(), Ops);
  1633. };
  1634. return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
  1635. }
  1636. // TODO: Floating-point conversions, vectors.
  1637. return false;
  1638. }
  1639. unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
  1640. unsigned NumDeadInst = 0;
  1641. // Delete the instructions backwards, as it has a reduced likelihood of
  1642. // having to update as many def-use and use-def chains.
  1643. Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
  1644. while (EndInst != &BB->front()) {
  1645. // Delete the next to last instruction.
  1646. Instruction *Inst = &*--EndInst->getIterator();
  1647. if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
  1648. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  1649. if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
  1650. EndInst = Inst;
  1651. continue;
  1652. }
  1653. if (!isa<DbgInfoIntrinsic>(Inst))
  1654. ++NumDeadInst;
  1655. Inst->eraseFromParent();
  1656. }
  1657. return NumDeadInst;
  1658. }
  1659. unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
  1660. bool PreserveLCSSA, DomTreeUpdater *DTU,
  1661. MemorySSAUpdater *MSSAU) {
  1662. BasicBlock *BB = I->getParent();
  1663. std::vector <DominatorTree::UpdateType> Updates;
  1664. if (MSSAU)
  1665. MSSAU->changeToUnreachable(I);
  1666. // Loop over all of the successors, removing BB's entry from any PHI
  1667. // nodes.
  1668. if (DTU)
  1669. Updates.reserve(BB->getTerminator()->getNumSuccessors());
  1670. for (BasicBlock *Successor : successors(BB)) {
  1671. Successor->removePredecessor(BB, PreserveLCSSA);
  1672. if (DTU)
  1673. Updates.push_back({DominatorTree::Delete, BB, Successor});
  1674. }
  1675. // Insert a call to llvm.trap right before this. This turns the undefined
  1676. // behavior into a hard fail instead of falling through into random code.
  1677. if (UseLLVMTrap) {
  1678. Function *TrapFn =
  1679. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  1680. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  1681. CallTrap->setDebugLoc(I->getDebugLoc());
  1682. }
  1683. auto *UI = new UnreachableInst(I->getContext(), I);
  1684. UI->setDebugLoc(I->getDebugLoc());
  1685. // All instructions after this are dead.
  1686. unsigned NumInstrsRemoved = 0;
  1687. BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
  1688. while (BBI != BBE) {
  1689. if (!BBI->use_empty())
  1690. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  1691. BB->getInstList().erase(BBI++);
  1692. ++NumInstrsRemoved;
  1693. }
  1694. if (DTU)
  1695. DTU->applyUpdatesPermissive(Updates);
  1696. return NumInstrsRemoved;
  1697. }
  1698. /// changeToCall - Convert the specified invoke into a normal call.
  1699. static void changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr) {
  1700. SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
  1701. SmallVector<OperandBundleDef, 1> OpBundles;
  1702. II->getOperandBundlesAsDefs(OpBundles);
  1703. CallInst *NewCall = CallInst::Create(
  1704. II->getFunctionType(), II->getCalledValue(), Args, OpBundles, "", II);
  1705. NewCall->takeName(II);
  1706. NewCall->setCallingConv(II->getCallingConv());
  1707. NewCall->setAttributes(II->getAttributes());
  1708. NewCall->setDebugLoc(II->getDebugLoc());
  1709. NewCall->copyMetadata(*II);
  1710. II->replaceAllUsesWith(NewCall);
  1711. // Follow the call by a branch to the normal destination.
  1712. BasicBlock *NormalDestBB = II->getNormalDest();
  1713. BranchInst::Create(NormalDestBB, II);
  1714. // Update PHI nodes in the unwind destination
  1715. BasicBlock *BB = II->getParent();
  1716. BasicBlock *UnwindDestBB = II->getUnwindDest();
  1717. UnwindDestBB->removePredecessor(BB);
  1718. II->eraseFromParent();
  1719. if (DTU)
  1720. DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
  1721. }
  1722. BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
  1723. BasicBlock *UnwindEdge) {
  1724. BasicBlock *BB = CI->getParent();
  1725. // Convert this function call into an invoke instruction. First, split the
  1726. // basic block.
  1727. BasicBlock *Split =
  1728. BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
  1729. // Delete the unconditional branch inserted by splitBasicBlock
  1730. BB->getInstList().pop_back();
  1731. // Create the new invoke instruction.
  1732. SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
  1733. SmallVector<OperandBundleDef, 1> OpBundles;
  1734. CI->getOperandBundlesAsDefs(OpBundles);
  1735. // Note: we're round tripping operand bundles through memory here, and that
  1736. // can potentially be avoided with a cleverer API design that we do not have
  1737. // as of this time.
  1738. InvokeInst *II =
  1739. InvokeInst::Create(CI->getFunctionType(), CI->getCalledValue(), Split,
  1740. UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
  1741. II->setDebugLoc(CI->getDebugLoc());
  1742. II->setCallingConv(CI->getCallingConv());
  1743. II->setAttributes(CI->getAttributes());
  1744. // Make sure that anything using the call now uses the invoke! This also
  1745. // updates the CallGraph if present, because it uses a WeakTrackingVH.
  1746. CI->replaceAllUsesWith(II);
  1747. // Delete the original call
  1748. Split->getInstList().pop_front();
  1749. return Split;
  1750. }
  1751. static bool markAliveBlocks(Function &F,
  1752. SmallPtrSetImpl<BasicBlock *> &Reachable,
  1753. DomTreeUpdater *DTU = nullptr) {
  1754. SmallVector<BasicBlock*, 128> Worklist;
  1755. BasicBlock *BB = &F.front();
  1756. Worklist.push_back(BB);
  1757. Reachable.insert(BB);
  1758. bool Changed = false;
  1759. do {
  1760. BB = Worklist.pop_back_val();
  1761. // Do a quick scan of the basic block, turning any obviously unreachable
  1762. // instructions into LLVM unreachable insts. The instruction combining pass
  1763. // canonicalizes unreachable insts into stores to null or undef.
  1764. for (Instruction &I : *BB) {
  1765. if (auto *CI = dyn_cast<CallInst>(&I)) {
  1766. Value *Callee = CI->getCalledValue();
  1767. // Handle intrinsic calls.
  1768. if (Function *F = dyn_cast<Function>(Callee)) {
  1769. auto IntrinsicID = F->getIntrinsicID();
  1770. // Assumptions that are known to be false are equivalent to
  1771. // unreachable. Also, if the condition is undefined, then we make the
  1772. // choice most beneficial to the optimizer, and choose that to also be
  1773. // unreachable.
  1774. if (IntrinsicID == Intrinsic::assume) {
  1775. if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
  1776. // Don't insert a call to llvm.trap right before the unreachable.
  1777. changeToUnreachable(CI, false, false, DTU);
  1778. Changed = true;
  1779. break;
  1780. }
  1781. } else if (IntrinsicID == Intrinsic::experimental_guard) {
  1782. // A call to the guard intrinsic bails out of the current
  1783. // compilation unit if the predicate passed to it is false. If the
  1784. // predicate is a constant false, then we know the guard will bail
  1785. // out of the current compile unconditionally, so all code following
  1786. // it is dead.
  1787. //
  1788. // Note: unlike in llvm.assume, it is not "obviously profitable" for
  1789. // guards to treat `undef` as `false` since a guard on `undef` can
  1790. // still be useful for widening.
  1791. if (match(CI->getArgOperand(0), m_Zero()))
  1792. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1793. changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
  1794. false, DTU);
  1795. Changed = true;
  1796. break;
  1797. }
  1798. }
  1799. } else if ((isa<ConstantPointerNull>(Callee) &&
  1800. !NullPointerIsDefined(CI->getFunction())) ||
  1801. isa<UndefValue>(Callee)) {
  1802. changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
  1803. Changed = true;
  1804. break;
  1805. }
  1806. if (CI->doesNotReturn() && !CI->isMustTailCall()) {
  1807. // If we found a call to a no-return function, insert an unreachable
  1808. // instruction after it. Make sure there isn't *already* one there
  1809. // though.
  1810. if (!isa<UnreachableInst>(CI->getNextNode())) {
  1811. // Don't insert a call to llvm.trap right before the unreachable.
  1812. changeToUnreachable(CI->getNextNode(), false, false, DTU);
  1813. Changed = true;
  1814. }
  1815. break;
  1816. }
  1817. } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1818. // Store to undef and store to null are undefined and used to signal
  1819. // that they should be changed to unreachable by passes that can't
  1820. // modify the CFG.
  1821. // Don't touch volatile stores.
  1822. if (SI->isVolatile()) continue;
  1823. Value *Ptr = SI->getOperand(1);
  1824. if (isa<UndefValue>(Ptr) ||
  1825. (isa<ConstantPointerNull>(Ptr) &&
  1826. !NullPointerIsDefined(SI->getFunction(),
  1827. SI->getPointerAddressSpace()))) {
  1828. changeToUnreachable(SI, true, false, DTU);
  1829. Changed = true;
  1830. break;
  1831. }
  1832. }
  1833. }
  1834. Instruction *Terminator = BB->getTerminator();
  1835. if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
  1836. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1837. Value *Callee = II->getCalledValue();
  1838. if ((isa<ConstantPointerNull>(Callee) &&
  1839. !NullPointerIsDefined(BB->getParent())) ||
  1840. isa<UndefValue>(Callee)) {
  1841. changeToUnreachable(II, true, false, DTU);
  1842. Changed = true;
  1843. } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
  1844. if (II->use_empty() && II->onlyReadsMemory()) {
  1845. // jump to the normal destination branch.
  1846. BasicBlock *NormalDestBB = II->getNormalDest();
  1847. BasicBlock *UnwindDestBB = II->getUnwindDest();
  1848. BranchInst::Create(NormalDestBB, II);
  1849. UnwindDestBB->removePredecessor(II->getParent());
  1850. II->eraseFromParent();
  1851. if (DTU)
  1852. DTU->applyUpdatesPermissive(
  1853. {{DominatorTree::Delete, BB, UnwindDestBB}});
  1854. } else
  1855. changeToCall(II, DTU);
  1856. Changed = true;
  1857. }
  1858. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
  1859. // Remove catchpads which cannot be reached.
  1860. struct CatchPadDenseMapInfo {
  1861. static CatchPadInst *getEmptyKey() {
  1862. return DenseMapInfo<CatchPadInst *>::getEmptyKey();
  1863. }
  1864. static CatchPadInst *getTombstoneKey() {
  1865. return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
  1866. }
  1867. static unsigned getHashValue(CatchPadInst *CatchPad) {
  1868. return static_cast<unsigned>(hash_combine_range(
  1869. CatchPad->value_op_begin(), CatchPad->value_op_end()));
  1870. }
  1871. static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
  1872. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  1873. RHS == getEmptyKey() || RHS == getTombstoneKey())
  1874. return LHS == RHS;
  1875. return LHS->isIdenticalTo(RHS);
  1876. }
  1877. };
  1878. // Set of unique CatchPads.
  1879. SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
  1880. CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
  1881. HandlerSet;
  1882. detail::DenseSetEmpty Empty;
  1883. for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
  1884. E = CatchSwitch->handler_end();
  1885. I != E; ++I) {
  1886. BasicBlock *HandlerBB = *I;
  1887. auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
  1888. if (!HandlerSet.insert({CatchPad, Empty}).second) {
  1889. CatchSwitch->removeHandler(I);
  1890. --I;
  1891. --E;
  1892. Changed = true;
  1893. }
  1894. }
  1895. }
  1896. Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
  1897. for (BasicBlock *Successor : successors(BB))
  1898. if (Reachable.insert(Successor).second)
  1899. Worklist.push_back(Successor);
  1900. } while (!Worklist.empty());
  1901. return Changed;
  1902. }
  1903. void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
  1904. Instruction *TI = BB->getTerminator();
  1905. if (auto *II = dyn_cast<InvokeInst>(TI)) {
  1906. changeToCall(II, DTU);
  1907. return;
  1908. }
  1909. Instruction *NewTI;
  1910. BasicBlock *UnwindDest;
  1911. if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
  1912. NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
  1913. UnwindDest = CRI->getUnwindDest();
  1914. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
  1915. auto *NewCatchSwitch = CatchSwitchInst::Create(
  1916. CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
  1917. CatchSwitch->getName(), CatchSwitch);
  1918. for (BasicBlock *PadBB : CatchSwitch->handlers())
  1919. NewCatchSwitch->addHandler(PadBB);
  1920. NewTI = NewCatchSwitch;
  1921. UnwindDest = CatchSwitch->getUnwindDest();
  1922. } else {
  1923. llvm_unreachable("Could not find unwind successor");
  1924. }
  1925. NewTI->takeName(TI);
  1926. NewTI->setDebugLoc(TI->getDebugLoc());
  1927. UnwindDest->removePredecessor(BB);
  1928. TI->replaceAllUsesWith(NewTI);
  1929. TI->eraseFromParent();
  1930. if (DTU)
  1931. DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
  1932. }
  1933. /// removeUnreachableBlocks - Remove blocks that are not reachable, even
  1934. /// if they are in a dead cycle. Return true if a change was made, false
  1935. /// otherwise. If `LVI` is passed, this function preserves LazyValueInfo
  1936. /// after modifying the CFG.
  1937. bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI,
  1938. DomTreeUpdater *DTU,
  1939. MemorySSAUpdater *MSSAU) {
  1940. SmallPtrSet<BasicBlock*, 16> Reachable;
  1941. bool Changed = markAliveBlocks(F, Reachable, DTU);
  1942. // If there are unreachable blocks in the CFG...
  1943. if (Reachable.size() == F.size())
  1944. return Changed;
  1945. assert(Reachable.size() < F.size());
  1946. NumRemoved += F.size()-Reachable.size();
  1947. SmallPtrSet<BasicBlock *, 16> DeadBlockSet;
  1948. for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ++I) {
  1949. auto *BB = &*I;
  1950. if (Reachable.count(BB))
  1951. continue;
  1952. DeadBlockSet.insert(BB);
  1953. }
  1954. if (MSSAU)
  1955. MSSAU->removeBlocks(DeadBlockSet);
  1956. // Loop over all of the basic blocks that are not reachable, dropping all of
  1957. // their internal references. Update DTU and LVI if available.
  1958. std::vector<DominatorTree::UpdateType> Updates;
  1959. for (auto *BB : DeadBlockSet) {
  1960. for (BasicBlock *Successor : successors(BB)) {
  1961. if (!DeadBlockSet.count(Successor))
  1962. Successor->removePredecessor(BB);
  1963. if (DTU)
  1964. Updates.push_back({DominatorTree::Delete, BB, Successor});
  1965. }
  1966. if (LVI)
  1967. LVI->eraseBlock(BB);
  1968. BB->dropAllReferences();
  1969. }
  1970. for (Function::iterator I = ++F.begin(); I != F.end();) {
  1971. auto *BB = &*I;
  1972. if (Reachable.count(BB)) {
  1973. ++I;
  1974. continue;
  1975. }
  1976. if (DTU) {
  1977. // Remove the terminator of BB to clear the successor list of BB.
  1978. if (BB->getTerminator())
  1979. BB->getInstList().pop_back();
  1980. new UnreachableInst(BB->getContext(), BB);
  1981. assert(succ_empty(BB) && "The successor list of BB isn't empty before "
  1982. "applying corresponding DTU updates.");
  1983. ++I;
  1984. } else {
  1985. I = F.getBasicBlockList().erase(I);
  1986. }
  1987. }
  1988. if (DTU) {
  1989. DTU->applyUpdatesPermissive(Updates);
  1990. bool Deleted = false;
  1991. for (auto *BB : DeadBlockSet) {
  1992. if (DTU->isBBPendingDeletion(BB))
  1993. --NumRemoved;
  1994. else
  1995. Deleted = true;
  1996. DTU->deleteBB(BB);
  1997. }
  1998. if (!Deleted)
  1999. return false;
  2000. }
  2001. return true;
  2002. }
  2003. void llvm::combineMetadata(Instruction *K, const Instruction *J,
  2004. ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
  2005. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  2006. K->dropUnknownNonDebugMetadata(KnownIDs);
  2007. K->getAllMetadataOtherThanDebugLoc(Metadata);
  2008. for (const auto &MD : Metadata) {
  2009. unsigned Kind = MD.first;
  2010. MDNode *JMD = J->getMetadata(Kind);
  2011. MDNode *KMD = MD.second;
  2012. switch (Kind) {
  2013. default:
  2014. K->setMetadata(Kind, nullptr); // Remove unknown metadata
  2015. break;
  2016. case LLVMContext::MD_dbg:
  2017. llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
  2018. case LLVMContext::MD_tbaa:
  2019. K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
  2020. break;
  2021. case LLVMContext::MD_alias_scope:
  2022. K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
  2023. break;
  2024. case LLVMContext::MD_noalias:
  2025. case LLVMContext::MD_mem_parallel_loop_access:
  2026. K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
  2027. break;
  2028. case LLVMContext::MD_access_group:
  2029. K->setMetadata(LLVMContext::MD_access_group,
  2030. intersectAccessGroups(K, J));
  2031. break;
  2032. case LLVMContext::MD_range:
  2033. // If K does move, use most generic range. Otherwise keep the range of
  2034. // K.
  2035. if (DoesKMove)
  2036. // FIXME: If K does move, we should drop the range info and nonnull.
  2037. // Currently this function is used with DoesKMove in passes
  2038. // doing hoisting/sinking and the current behavior of using the
  2039. // most generic range is correct in those cases.
  2040. K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
  2041. break;
  2042. case LLVMContext::MD_fpmath:
  2043. K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
  2044. break;
  2045. case LLVMContext::MD_invariant_load:
  2046. // Only set the !invariant.load if it is present in both instructions.
  2047. K->setMetadata(Kind, JMD);
  2048. break;
  2049. case LLVMContext::MD_nonnull:
  2050. // If K does move, keep nonull if it is present in both instructions.
  2051. if (DoesKMove)
  2052. K->setMetadata(Kind, JMD);
  2053. break;
  2054. case LLVMContext::MD_invariant_group:
  2055. // Preserve !invariant.group in K.
  2056. break;
  2057. case LLVMContext::MD_align:
  2058. K->setMetadata(Kind,
  2059. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  2060. break;
  2061. case LLVMContext::MD_dereferenceable:
  2062. case LLVMContext::MD_dereferenceable_or_null:
  2063. K->setMetadata(Kind,
  2064. MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
  2065. break;
  2066. }
  2067. }
  2068. // Set !invariant.group from J if J has it. If both instructions have it
  2069. // then we will just pick it from J - even when they are different.
  2070. // Also make sure that K is load or store - f.e. combining bitcast with load
  2071. // could produce bitcast with invariant.group metadata, which is invalid.
  2072. // FIXME: we should try to preserve both invariant.group md if they are
  2073. // different, but right now instruction can only have one invariant.group.
  2074. if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
  2075. if (isa<LoadInst>(K) || isa<StoreInst>(K))
  2076. K->setMetadata(LLVMContext::MD_invariant_group, JMD);
  2077. }
  2078. void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
  2079. bool KDominatesJ) {
  2080. unsigned KnownIDs[] = {
  2081. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  2082. LLVMContext::MD_noalias, LLVMContext::MD_range,
  2083. LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
  2084. LLVMContext::MD_invariant_group, LLVMContext::MD_align,
  2085. LLVMContext::MD_dereferenceable,
  2086. LLVMContext::MD_dereferenceable_or_null,
  2087. LLVMContext::MD_access_group};
  2088. combineMetadata(K, J, KnownIDs, KDominatesJ);
  2089. }
  2090. void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
  2091. auto *ReplInst = dyn_cast<Instruction>(Repl);
  2092. if (!ReplInst)
  2093. return;
  2094. // Patch the replacement so that it is not more restrictive than the value
  2095. // being replaced.
  2096. // Note that if 'I' is a load being replaced by some operation,
  2097. // for example, by an arithmetic operation, then andIRFlags()
  2098. // would just erase all math flags from the original arithmetic
  2099. // operation, which is clearly not wanted and not needed.
  2100. if (!isa<LoadInst>(I))
  2101. ReplInst->andIRFlags(I);
  2102. // FIXME: If both the original and replacement value are part of the
  2103. // same control-flow region (meaning that the execution of one
  2104. // guarantees the execution of the other), then we can combine the
  2105. // noalias scopes here and do better than the general conservative
  2106. // answer used in combineMetadata().
  2107. // In general, GVN unifies expressions over different control-flow
  2108. // regions, and so we need a conservative combination of the noalias
  2109. // scopes.
  2110. static const unsigned KnownIDs[] = {
  2111. LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  2112. LLVMContext::MD_noalias, LLVMContext::MD_range,
  2113. LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
  2114. LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
  2115. LLVMContext::MD_access_group};
  2116. combineMetadata(ReplInst, I, KnownIDs, false);
  2117. }
  2118. template <typename RootType, typename DominatesFn>
  2119. static unsigned replaceDominatedUsesWith(Value *From, Value *To,
  2120. const RootType &Root,
  2121. const DominatesFn &Dominates) {
  2122. assert(From->getType() == To->getType());
  2123. unsigned Count = 0;
  2124. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  2125. UI != UE;) {
  2126. Use &U = *UI++;
  2127. if (!Dominates(Root, U))
  2128. continue;
  2129. U.set(To);
  2130. LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
  2131. << "' as " << *To << " in " << *U << "\n");
  2132. ++Count;
  2133. }
  2134. return Count;
  2135. }
  2136. unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
  2137. assert(From->getType() == To->getType());
  2138. auto *BB = From->getParent();
  2139. unsigned Count = 0;
  2140. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  2141. UI != UE;) {
  2142. Use &U = *UI++;
  2143. auto *I = cast<Instruction>(U.getUser());
  2144. if (I->getParent() == BB)
  2145. continue;
  2146. U.set(To);
  2147. ++Count;
  2148. }
  2149. return Count;
  2150. }
  2151. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  2152. DominatorTree &DT,
  2153. const BasicBlockEdge &Root) {
  2154. auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
  2155. return DT.dominates(Root, U);
  2156. };
  2157. return ::replaceDominatedUsesWith(From, To, Root, Dominates);
  2158. }
  2159. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  2160. DominatorTree &DT,
  2161. const BasicBlock *BB) {
  2162. auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
  2163. auto *I = cast<Instruction>(U.getUser())->getParent();
  2164. return DT.properlyDominates(BB, I);
  2165. };
  2166. return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
  2167. }
  2168. bool llvm::callsGCLeafFunction(const CallBase *Call,
  2169. const TargetLibraryInfo &TLI) {
  2170. // Check if the function is specifically marked as a gc leaf function.
  2171. if (Call->hasFnAttr("gc-leaf-function"))
  2172. return true;
  2173. if (const Function *F = Call->getCalledFunction()) {
  2174. if (F->hasFnAttribute("gc-leaf-function"))
  2175. return true;
  2176. if (auto IID = F->getIntrinsicID())
  2177. // Most LLVM intrinsics do not take safepoints.
  2178. return IID != Intrinsic::experimental_gc_statepoint &&
  2179. IID != Intrinsic::experimental_deoptimize;
  2180. }
  2181. // Lib calls can be materialized by some passes, and won't be
  2182. // marked as 'gc-leaf-function.' All available Libcalls are
  2183. // GC-leaf.
  2184. LibFunc LF;
  2185. if (TLI.getLibFunc(ImmutableCallSite(Call), LF)) {
  2186. return TLI.has(LF);
  2187. }
  2188. return false;
  2189. }
  2190. void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
  2191. LoadInst &NewLI) {
  2192. auto *NewTy = NewLI.getType();
  2193. // This only directly applies if the new type is also a pointer.
  2194. if (NewTy->isPointerTy()) {
  2195. NewLI.setMetadata(LLVMContext::MD_nonnull, N);
  2196. return;
  2197. }
  2198. // The only other translation we can do is to integral loads with !range
  2199. // metadata.
  2200. if (!NewTy->isIntegerTy())
  2201. return;
  2202. MDBuilder MDB(NewLI.getContext());
  2203. const Value *Ptr = OldLI.getPointerOperand();
  2204. auto *ITy = cast<IntegerType>(NewTy);
  2205. auto *NullInt = ConstantExpr::getPtrToInt(
  2206. ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
  2207. auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
  2208. NewLI.setMetadata(LLVMContext::MD_range,
  2209. MDB.createRange(NonNullInt, NullInt));
  2210. }
  2211. void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
  2212. MDNode *N, LoadInst &NewLI) {
  2213. auto *NewTy = NewLI.getType();
  2214. // Give up unless it is converted to a pointer where there is a single very
  2215. // valuable mapping we can do reliably.
  2216. // FIXME: It would be nice to propagate this in more ways, but the type
  2217. // conversions make it hard.
  2218. if (!NewTy->isPointerTy())
  2219. return;
  2220. unsigned BitWidth = DL.getIndexTypeSizeInBits(NewTy);
  2221. if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
  2222. MDNode *NN = MDNode::get(OldLI.getContext(), None);
  2223. NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
  2224. }
  2225. }
  2226. void llvm::dropDebugUsers(Instruction &I) {
  2227. SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
  2228. findDbgUsers(DbgUsers, &I);
  2229. for (auto *DII : DbgUsers)
  2230. DII->eraseFromParent();
  2231. }
  2232. void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
  2233. BasicBlock *BB) {
  2234. // Since we are moving the instructions out of its basic block, we do not
  2235. // retain their original debug locations (DILocations) and debug intrinsic
  2236. // instructions.
  2237. //
  2238. // Doing so would degrade the debugging experience and adversely affect the
  2239. // accuracy of profiling information.
  2240. //
  2241. // Currently, when hoisting the instructions, we take the following actions:
  2242. // - Remove their debug intrinsic instructions.
  2243. // - Set their debug locations to the values from the insertion point.
  2244. //
  2245. // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
  2246. // need to be deleted, is because there will not be any instructions with a
  2247. // DILocation in either branch left after performing the transformation. We
  2248. // can only insert a dbg.value after the two branches are joined again.
  2249. //
  2250. // See PR38762, PR39243 for more details.
  2251. //
  2252. // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
  2253. // encode predicated DIExpressions that yield different results on different
  2254. // code paths.
  2255. for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
  2256. Instruction *I = &*II;
  2257. I->dropUnknownNonDebugMetadata();
  2258. if (I->isUsedByMetadata())
  2259. dropDebugUsers(*I);
  2260. if (isa<DbgInfoIntrinsic>(I)) {
  2261. // Remove DbgInfo Intrinsics.
  2262. II = I->eraseFromParent();
  2263. continue;
  2264. }
  2265. I->setDebugLoc(InsertPt->getDebugLoc());
  2266. ++II;
  2267. }
  2268. DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
  2269. BB->begin(),
  2270. BB->getTerminator()->getIterator());
  2271. }
  2272. namespace {
  2273. /// A potential constituent of a bitreverse or bswap expression. See
  2274. /// collectBitParts for a fuller explanation.
  2275. struct BitPart {
  2276. BitPart(Value *P, unsigned BW) : Provider(P) {
  2277. Provenance.resize(BW);
  2278. }
  2279. /// The Value that this is a bitreverse/bswap of.
  2280. Value *Provider;
  2281. /// The "provenance" of each bit. Provenance[A] = B means that bit A
  2282. /// in Provider becomes bit B in the result of this expression.
  2283. SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
  2284. enum { Unset = -1 };
  2285. };
  2286. } // end anonymous namespace
  2287. /// Analyze the specified subexpression and see if it is capable of providing
  2288. /// pieces of a bswap or bitreverse. The subexpression provides a potential
  2289. /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
  2290. /// the output of the expression came from a corresponding bit in some other
  2291. /// value. This function is recursive, and the end result is a mapping of
  2292. /// bitnumber to bitnumber. It is the caller's responsibility to validate that
  2293. /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
  2294. ///
  2295. /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
  2296. /// that the expression deposits the low byte of %X into the high byte of the
  2297. /// result and that all other bits are zero. This expression is accepted and a
  2298. /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
  2299. /// [0-7].
  2300. ///
  2301. /// To avoid revisiting values, the BitPart results are memoized into the
  2302. /// provided map. To avoid unnecessary copying of BitParts, BitParts are
  2303. /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
  2304. /// store BitParts objects, not pointers. As we need the concept of a nullptr
  2305. /// BitParts (Value has been analyzed and the analysis failed), we an Optional
  2306. /// type instead to provide the same functionality.
  2307. ///
  2308. /// Because we pass around references into \c BPS, we must use a container that
  2309. /// does not invalidate internal references (std::map instead of DenseMap).
  2310. static const Optional<BitPart> &
  2311. collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
  2312. std::map<Value *, Optional<BitPart>> &BPS) {
  2313. auto I = BPS.find(V);
  2314. if (I != BPS.end())
  2315. return I->second;
  2316. auto &Result = BPS[V] = None;
  2317. auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
  2318. if (Instruction *I = dyn_cast<Instruction>(V)) {
  2319. // If this is an or instruction, it may be an inner node of the bswap.
  2320. if (I->getOpcode() == Instruction::Or) {
  2321. auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
  2322. MatchBitReversals, BPS);
  2323. auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
  2324. MatchBitReversals, BPS);
  2325. if (!A || !B)
  2326. return Result;
  2327. // Try and merge the two together.
  2328. if (!A->Provider || A->Provider != B->Provider)
  2329. return Result;
  2330. Result = BitPart(A->Provider, BitWidth);
  2331. for (unsigned i = 0; i < A->Provenance.size(); ++i) {
  2332. if (A->Provenance[i] != BitPart::Unset &&
  2333. B->Provenance[i] != BitPart::Unset &&
  2334. A->Provenance[i] != B->Provenance[i])
  2335. return Result = None;
  2336. if (A->Provenance[i] == BitPart::Unset)
  2337. Result->Provenance[i] = B->Provenance[i];
  2338. else
  2339. Result->Provenance[i] = A->Provenance[i];
  2340. }
  2341. return Result;
  2342. }
  2343. // If this is a logical shift by a constant, recurse then shift the result.
  2344. if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
  2345. unsigned BitShift =
  2346. cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
  2347. // Ensure the shift amount is defined.
  2348. if (BitShift > BitWidth)
  2349. return Result;
  2350. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2351. MatchBitReversals, BPS);
  2352. if (!Res)
  2353. return Result;
  2354. Result = Res;
  2355. // Perform the "shift" on BitProvenance.
  2356. auto &P = Result->Provenance;
  2357. if (I->getOpcode() == Instruction::Shl) {
  2358. P.erase(std::prev(P.end(), BitShift), P.end());
  2359. P.insert(P.begin(), BitShift, BitPart::Unset);
  2360. } else {
  2361. P.erase(P.begin(), std::next(P.begin(), BitShift));
  2362. P.insert(P.end(), BitShift, BitPart::Unset);
  2363. }
  2364. return Result;
  2365. }
  2366. // If this is a logical 'and' with a mask that clears bits, recurse then
  2367. // unset the appropriate bits.
  2368. if (I->getOpcode() == Instruction::And &&
  2369. isa<ConstantInt>(I->getOperand(1))) {
  2370. APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
  2371. const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
  2372. // Check that the mask allows a multiple of 8 bits for a bswap, for an
  2373. // early exit.
  2374. unsigned NumMaskedBits = AndMask.countPopulation();
  2375. if (!MatchBitReversals && NumMaskedBits % 8 != 0)
  2376. return Result;
  2377. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2378. MatchBitReversals, BPS);
  2379. if (!Res)
  2380. return Result;
  2381. Result = Res;
  2382. for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
  2383. // If the AndMask is zero for this bit, clear the bit.
  2384. if ((AndMask & Bit) == 0)
  2385. Result->Provenance[i] = BitPart::Unset;
  2386. return Result;
  2387. }
  2388. // If this is a zext instruction zero extend the result.
  2389. if (I->getOpcode() == Instruction::ZExt) {
  2390. auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
  2391. MatchBitReversals, BPS);
  2392. if (!Res)
  2393. return Result;
  2394. Result = BitPart(Res->Provider, BitWidth);
  2395. auto NarrowBitWidth =
  2396. cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
  2397. for (unsigned i = 0; i < NarrowBitWidth; ++i)
  2398. Result->Provenance[i] = Res->Provenance[i];
  2399. for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
  2400. Result->Provenance[i] = BitPart::Unset;
  2401. return Result;
  2402. }
  2403. }
  2404. // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
  2405. // the input value to the bswap/bitreverse.
  2406. Result = BitPart(V, BitWidth);
  2407. for (unsigned i = 0; i < BitWidth; ++i)
  2408. Result->Provenance[i] = i;
  2409. return Result;
  2410. }
  2411. static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
  2412. unsigned BitWidth) {
  2413. if (From % 8 != To % 8)
  2414. return false;
  2415. // Convert from bit indices to byte indices and check for a byte reversal.
  2416. From >>= 3;
  2417. To >>= 3;
  2418. BitWidth >>= 3;
  2419. return From == BitWidth - To - 1;
  2420. }
  2421. static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
  2422. unsigned BitWidth) {
  2423. return From == BitWidth - To - 1;
  2424. }
  2425. bool llvm::recognizeBSwapOrBitReverseIdiom(
  2426. Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
  2427. SmallVectorImpl<Instruction *> &InsertedInsts) {
  2428. if (Operator::getOpcode(I) != Instruction::Or)
  2429. return false;
  2430. if (!MatchBSwaps && !MatchBitReversals)
  2431. return false;
  2432. IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
  2433. if (!ITy || ITy->getBitWidth() > 128)
  2434. return false; // Can't do vectors or integers > 128 bits.
  2435. unsigned BW = ITy->getBitWidth();
  2436. unsigned DemandedBW = BW;
  2437. IntegerType *DemandedTy = ITy;
  2438. if (I->hasOneUse()) {
  2439. if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
  2440. DemandedTy = cast<IntegerType>(Trunc->getType());
  2441. DemandedBW = DemandedTy->getBitWidth();
  2442. }
  2443. }
  2444. // Try to find all the pieces corresponding to the bswap.
  2445. std::map<Value *, Optional<BitPart>> BPS;
  2446. auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
  2447. if (!Res)
  2448. return false;
  2449. auto &BitProvenance = Res->Provenance;
  2450. // Now, is the bit permutation correct for a bswap or a bitreverse? We can
  2451. // only byteswap values with an even number of bytes.
  2452. bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
  2453. for (unsigned i = 0; i < DemandedBW; ++i) {
  2454. OKForBSwap &=
  2455. bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
  2456. OKForBitReverse &=
  2457. bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
  2458. }
  2459. Intrinsic::ID Intrin;
  2460. if (OKForBSwap && MatchBSwaps)
  2461. Intrin = Intrinsic::bswap;
  2462. else if (OKForBitReverse && MatchBitReversals)
  2463. Intrin = Intrinsic::bitreverse;
  2464. else
  2465. return false;
  2466. if (ITy != DemandedTy) {
  2467. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
  2468. Value *Provider = Res->Provider;
  2469. IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
  2470. // We may need to truncate the provider.
  2471. if (DemandedTy != ProviderTy) {
  2472. auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
  2473. "trunc", I);
  2474. InsertedInsts.push_back(Trunc);
  2475. Provider = Trunc;
  2476. }
  2477. auto *CI = CallInst::Create(F, Provider, "rev", I);
  2478. InsertedInsts.push_back(CI);
  2479. auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
  2480. InsertedInsts.push_back(ExtInst);
  2481. return true;
  2482. }
  2483. Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
  2484. InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
  2485. return true;
  2486. }
  2487. // CodeGen has special handling for some string functions that may replace
  2488. // them with target-specific intrinsics. Since that'd skip our interceptors
  2489. // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
  2490. // we mark affected calls as NoBuiltin, which will disable optimization
  2491. // in CodeGen.
  2492. void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
  2493. CallInst *CI, const TargetLibraryInfo *TLI) {
  2494. Function *F = CI->getCalledFunction();
  2495. LibFunc Func;
  2496. if (F && !F->hasLocalLinkage() && F->hasName() &&
  2497. TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
  2498. !F->doesNotAccessMemory())
  2499. CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
  2500. }
  2501. bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
  2502. // We can't have a PHI with a metadata type.
  2503. if (I->getOperand(OpIdx)->getType()->isMetadataTy())
  2504. return false;
  2505. // Early exit.
  2506. if (!isa<Constant>(I->getOperand(OpIdx)))
  2507. return true;
  2508. switch (I->getOpcode()) {
  2509. default:
  2510. return true;
  2511. case Instruction::Call:
  2512. case Instruction::Invoke:
  2513. // Can't handle inline asm. Skip it.
  2514. if (isa<InlineAsm>(ImmutableCallSite(I).getCalledValue()))
  2515. return false;
  2516. // Many arithmetic intrinsics have no issue taking a
  2517. // variable, however it's hard to distingish these from
  2518. // specials such as @llvm.frameaddress that require a constant.
  2519. if (isa<IntrinsicInst>(I))
  2520. return false;
  2521. // Constant bundle operands may need to retain their constant-ness for
  2522. // correctness.
  2523. if (ImmutableCallSite(I).isBundleOperand(OpIdx))
  2524. return false;
  2525. return true;
  2526. case Instruction::ShuffleVector:
  2527. // Shufflevector masks are constant.
  2528. return OpIdx != 2;
  2529. case Instruction::Switch:
  2530. case Instruction::ExtractValue:
  2531. // All operands apart from the first are constant.
  2532. return OpIdx == 0;
  2533. case Instruction::InsertValue:
  2534. // All operands apart from the first and the second are constant.
  2535. return OpIdx < 2;
  2536. case Instruction::Alloca:
  2537. // Static allocas (constant size in the entry block) are handled by
  2538. // prologue/epilogue insertion so they're free anyway. We definitely don't
  2539. // want to make them non-constant.
  2540. return !cast<AllocaInst>(I)->isStaticAlloca();
  2541. case Instruction::GetElementPtr:
  2542. if (OpIdx == 0)
  2543. return true;
  2544. gep_type_iterator It = gep_type_begin(I);
  2545. for (auto E = std::next(It, OpIdx); It != E; ++It)
  2546. if (It.isStruct())
  2547. return false;
  2548. return true;
  2549. }
  2550. }
  2551. using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
  2552. AllocaInst *llvm::findAllocaForValue(Value *V,
  2553. AllocaForValueMapTy &AllocaForValue) {
  2554. if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
  2555. return AI;
  2556. // See if we've already calculated (or started to calculate) alloca for a
  2557. // given value.
  2558. AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
  2559. if (I != AllocaForValue.end())
  2560. return I->second;
  2561. // Store 0 while we're calculating alloca for value V to avoid
  2562. // infinite recursion if the value references itself.
  2563. AllocaForValue[V] = nullptr;
  2564. AllocaInst *Res = nullptr;
  2565. if (CastInst *CI = dyn_cast<CastInst>(V))
  2566. Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
  2567. else if (PHINode *PN = dyn_cast<PHINode>(V)) {
  2568. for (Value *IncValue : PN->incoming_values()) {
  2569. // Allow self-referencing phi-nodes.
  2570. if (IncValue == PN)
  2571. continue;
  2572. AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
  2573. // AI for incoming values should exist and should all be equal.
  2574. if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
  2575. return nullptr;
  2576. Res = IncValueAI;
  2577. }
  2578. } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
  2579. Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
  2580. } else {
  2581. LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
  2582. << *V << "\n");
  2583. }
  2584. if (Res)
  2585. AllocaForValue[V] = Res;
  2586. return Res;
  2587. }