Local.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/Hashing.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/LibCallSemantics.h"
  23. #include "llvm/Analysis/MemoryBuiltins.h"
  24. #include "llvm/Analysis/ValueTracking.h"
  25. #include "llvm/IR/CFG.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DIBuilder.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/IR/GetElementPtrTypeIterator.h"
  33. #include "llvm/IR/GlobalAlias.h"
  34. #include "llvm/IR/GlobalVariable.h"
  35. #include "llvm/IR/IRBuilder.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/IntrinsicInst.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/MDBuilder.h"
  40. #include "llvm/IR/Metadata.h"
  41. #include "llvm/IR/Operator.h"
  42. #include "llvm/IR/ValueHandle.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/MathExtras.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "dxc/DXIL/DxilMetadataHelper.h" // HLSL Change - combine dxil metadata.
  47. using namespace llvm;
  48. #define DEBUG_TYPE "local"
  49. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  50. //===----------------------------------------------------------------------===//
  51. // Local constant propagation.
  52. //
  53. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  54. /// constant value, convert it into an unconditional branch to the constant
  55. /// destination. This is a nontrivial operation because the successors of this
  56. /// basic block must have their PHI nodes updated.
  57. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  58. /// conditions and indirectbr addresses this might make dead if
  59. /// DeleteDeadConditions is true.
  60. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  61. const TargetLibraryInfo *TLI) {
  62. TerminatorInst *T = BB->getTerminator();
  63. IRBuilder<> Builder(T);
  64. // Branch - See if we are conditional jumping on constant
  65. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  66. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  67. BasicBlock *Dest1 = BI->getSuccessor(0);
  68. BasicBlock *Dest2 = BI->getSuccessor(1);
  69. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  70. // Are we branching on constant?
  71. // YES. Change to unconditional branch...
  72. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  73. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  74. //cerr << "Function: " << T->getParent()->getParent()
  75. // << "\nRemoving branch from " << T->getParent()
  76. // << "\n\nTo: " << OldDest << endl;
  77. // Let the basic block know that we are letting go of it. Based on this,
  78. // it will adjust it's PHI nodes.
  79. OldDest->removePredecessor(BB);
  80. // Replace the conditional branch with an unconditional one.
  81. Builder.CreateBr(Destination);
  82. BI->eraseFromParent();
  83. return true;
  84. }
  85. if (Dest2 == Dest1) { // Conditional branch to same location?
  86. // This branch matches something like this:
  87. // br bool %cond, label %Dest, label %Dest
  88. // and changes it into: br label %Dest
  89. // Let the basic block know that we are letting go of one copy of it.
  90. assert(BI->getParent() && "Terminator not inserted in block!");
  91. Dest1->removePredecessor(BI->getParent());
  92. // Replace the conditional branch with an unconditional one.
  93. Builder.CreateBr(Dest1);
  94. Value *Cond = BI->getCondition();
  95. BI->eraseFromParent();
  96. if (DeleteDeadConditions)
  97. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  98. return true;
  99. }
  100. return false;
  101. }
  102. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  103. // If we are switching on a constant, we can convert the switch to an
  104. // unconditional branch.
  105. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  106. BasicBlock *DefaultDest = SI->getDefaultDest();
  107. BasicBlock *TheOnlyDest = DefaultDest;
  108. // If the default is unreachable, ignore it when searching for TheOnlyDest.
  109. if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
  110. SI->getNumCases() > 0) {
  111. TheOnlyDest = SI->case_begin().getCaseSuccessor();
  112. }
  113. // Figure out which case it goes to.
  114. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  115. i != e; ++i) {
  116. // Found case matching a constant operand?
  117. if (i.getCaseValue() == CI) {
  118. TheOnlyDest = i.getCaseSuccessor();
  119. break;
  120. }
  121. // Check to see if this branch is going to the same place as the default
  122. // dest. If so, eliminate it as an explicit compare.
  123. if (i.getCaseSuccessor() == DefaultDest) {
  124. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  125. unsigned NCases = SI->getNumCases();
  126. // Fold the case metadata into the default if there will be any branches
  127. // left, unless the metadata doesn't match the switch.
  128. if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
  129. // Collect branch weights into a vector.
  130. SmallVector<uint32_t, 8> Weights;
  131. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  132. ++MD_i) {
  133. ConstantInt *CI =
  134. mdconst::dyn_extract<ConstantInt>(MD->getOperand(MD_i));
  135. assert(CI);
  136. Weights.push_back(CI->getValue().getZExtValue());
  137. }
  138. // Merge weight of this case to the default weight.
  139. unsigned idx = i.getCaseIndex();
  140. Weights[0] += Weights[idx+1];
  141. // Remove weight for this case.
  142. std::swap(Weights[idx+1], Weights.back());
  143. Weights.pop_back();
  144. SI->setMetadata(LLVMContext::MD_prof,
  145. MDBuilder(BB->getContext()).
  146. createBranchWeights(Weights));
  147. }
  148. // Remove this entry.
  149. DefaultDest->removePredecessor(SI->getParent());
  150. SI->removeCase(i);
  151. --i; --e;
  152. continue;
  153. }
  154. // Otherwise, check to see if the switch only branches to one destination.
  155. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  156. // destinations.
  157. if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
  158. }
  159. if (CI && !TheOnlyDest) {
  160. // Branching on a constant, but not any of the cases, go to the default
  161. // successor.
  162. TheOnlyDest = SI->getDefaultDest();
  163. }
  164. // If we found a single destination that we can fold the switch into, do so
  165. // now.
  166. if (TheOnlyDest) {
  167. // Insert the new branch.
  168. Builder.CreateBr(TheOnlyDest);
  169. BasicBlock *BB = SI->getParent();
  170. // Remove entries from PHI nodes which we no longer branch to...
  171. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  172. // Found case matching a constant operand?
  173. BasicBlock *Succ = SI->getSuccessor(i);
  174. if (Succ == TheOnlyDest)
  175. TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
  176. else
  177. Succ->removePredecessor(BB);
  178. }
  179. // Delete the old switch.
  180. Value *Cond = SI->getCondition();
  181. SI->eraseFromParent();
  182. if (DeleteDeadConditions)
  183. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  184. return true;
  185. }
  186. if (SI->getNumCases() == 1) {
  187. // Otherwise, we can fold this switch into a conditional branch
  188. // instruction if it has only one non-default destination.
  189. SwitchInst::CaseIt FirstCase = SI->case_begin();
  190. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  191. FirstCase.getCaseValue(), "cond");
  192. // Insert the new branch.
  193. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  194. FirstCase.getCaseSuccessor(),
  195. SI->getDefaultDest());
  196. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  197. if (MD && MD->getNumOperands() == 3) {
  198. ConstantInt *SICase =
  199. mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
  200. ConstantInt *SIDef =
  201. mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
  202. assert(SICase && SIDef);
  203. // The TrueWeight should be the weight for the single case of SI.
  204. NewBr->setMetadata(LLVMContext::MD_prof,
  205. MDBuilder(BB->getContext()).
  206. createBranchWeights(SICase->getValue().getZExtValue(),
  207. SIDef->getValue().getZExtValue()));
  208. }
  209. // Delete the old switch.
  210. SI->eraseFromParent();
  211. return true;
  212. }
  213. return false;
  214. }
  215. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  216. // indirectbr blockaddress(@F, @BB) -> br label @BB
  217. if (BlockAddress *BA =
  218. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  219. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  220. // Insert the new branch.
  221. Builder.CreateBr(TheOnlyDest);
  222. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  223. if (IBI->getDestination(i) == TheOnlyDest)
  224. TheOnlyDest = nullptr;
  225. else
  226. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  227. }
  228. Value *Address = IBI->getAddress();
  229. IBI->eraseFromParent();
  230. if (DeleteDeadConditions)
  231. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  232. // If we didn't find our destination in the IBI successor list, then we
  233. // have undefined behavior. Replace the unconditional branch with an
  234. // 'unreachable' instruction.
  235. if (TheOnlyDest) {
  236. BB->getTerminator()->eraseFromParent();
  237. new UnreachableInst(BB->getContext(), BB);
  238. }
  239. return true;
  240. }
  241. }
  242. return false;
  243. }
  244. //===----------------------------------------------------------------------===//
  245. // Local dead code elimination.
  246. //
  247. /// isInstructionTriviallyDead - Return true if the result produced by the
  248. /// instruction is not used, and the instruction has no side effects.
  249. ///
  250. bool llvm::isInstructionTriviallyDead(Instruction *I,
  251. const TargetLibraryInfo *TLI) {
  252. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  253. // We don't want the landingpad instruction removed by anything this general.
  254. if (isa<LandingPadInst>(I))
  255. return false;
  256. // We don't want debug info removed by anything this general, unless
  257. // debug info is empty.
  258. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  259. if (DDI->getAddress())
  260. return false;
  261. return true;
  262. }
  263. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  264. if (DVI->getValue())
  265. return false;
  266. return true;
  267. }
  268. if (!I->mayHaveSideEffects()) return true;
  269. // Special case intrinsics that "may have side effects" but can be deleted
  270. // when dead.
  271. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  272. // Safe to delete llvm.stacksave if dead.
  273. if (II->getIntrinsicID() == Intrinsic::stacksave)
  274. return true;
  275. // Lifetime intrinsics are dead when their right-hand is undef.
  276. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  277. II->getIntrinsicID() == Intrinsic::lifetime_end)
  278. return isa<UndefValue>(II->getArgOperand(1));
  279. // Assumptions are dead if their condition is trivially true.
  280. if (II->getIntrinsicID() == Intrinsic::assume) {
  281. if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
  282. return !Cond->isZero();
  283. return false;
  284. }
  285. }
  286. if (isAllocLikeFn(I, TLI)) return true;
  287. if (CallInst *CI = isFreeCall(I, TLI))
  288. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  289. return C->isNullValue() || isa<UndefValue>(C);
  290. return false;
  291. }
  292. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  293. /// trivially dead instruction, delete it. If that makes any of its operands
  294. /// trivially dead, delete them too, recursively. Return true if any
  295. /// instructions were deleted.
  296. bool
  297. llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
  298. const TargetLibraryInfo *TLI) {
  299. Instruction *I = dyn_cast<Instruction>(V);
  300. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
  301. return false;
  302. SmallVector<Instruction*, 16> DeadInsts;
  303. DeadInsts.push_back(I);
  304. do {
  305. I = DeadInsts.pop_back_val();
  306. // Null out all of the instruction's operands to see if any operand becomes
  307. // dead as we go.
  308. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  309. Value *OpV = I->getOperand(i);
  310. I->setOperand(i, nullptr);
  311. if (!OpV->use_empty()) continue;
  312. // If the operand is an instruction that became dead as we nulled out the
  313. // operand, and if it is 'trivially' dead, delete it in a future loop
  314. // iteration.
  315. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  316. if (isInstructionTriviallyDead(OpI, TLI))
  317. DeadInsts.push_back(OpI);
  318. }
  319. I->eraseFromParent();
  320. } while (!DeadInsts.empty());
  321. return true;
  322. }
  323. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  324. /// This is similar to Instruction::hasOneUse() except this will also return
  325. /// true when there are no uses or multiple uses that all refer to the same
  326. /// value.
  327. static bool areAllUsesEqual(Instruction *I) {
  328. Value::user_iterator UI = I->user_begin();
  329. Value::user_iterator UE = I->user_end();
  330. if (UI == UE)
  331. return true;
  332. User *TheUse = *UI;
  333. for (++UI; UI != UE; ++UI) {
  334. if (*UI != TheUse)
  335. return false;
  336. }
  337. return true;
  338. }
  339. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  340. /// dead PHI node, due to being a def-use chain of single-use nodes that
  341. /// either forms a cycle or is terminated by a trivially dead instruction,
  342. /// delete it. If that makes any of its operands trivially dead, delete them
  343. /// too, recursively. Return true if a change was made.
  344. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  345. const TargetLibraryInfo *TLI) {
  346. SmallPtrSet<Instruction*, 4> Visited;
  347. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  348. I = cast<Instruction>(*I->user_begin())) {
  349. if (I->use_empty())
  350. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  351. // If we find an instruction more than once, we're on a cycle that
  352. // won't prove fruitful.
  353. if (!Visited.insert(I).second) {
  354. // Break the cycle and delete the instruction and its operands.
  355. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  356. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  357. return true;
  358. }
  359. }
  360. return false;
  361. }
  362. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  363. /// simplify any instructions in it and recursively delete dead instructions.
  364. ///
  365. /// This returns true if it changed the code, note that it can delete
  366. /// instructions in other blocks as well in this block.
  367. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
  368. const TargetLibraryInfo *TLI) {
  369. bool MadeChange = false;
  370. #ifndef NDEBUG
  371. // In debug builds, ensure that the terminator of the block is never replaced
  372. // or deleted by these simplifications. The idea of simplification is that it
  373. // cannot introduce new instructions, and there is no way to replace the
  374. // terminator of a block without introducing a new instruction.
  375. AssertingVH<Instruction> TerminatorVH(--BB->end());
  376. #endif
  377. for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
  378. assert(!BI->isTerminator());
  379. Instruction *Inst = BI++;
  380. WeakVH BIHandle(BI);
  381. if (recursivelySimplifyInstruction(Inst, TLI)) {
  382. MadeChange = true;
  383. if (BIHandle != BI)
  384. BI = BB->begin();
  385. continue;
  386. }
  387. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
  388. if (BIHandle != BI)
  389. BI = BB->begin();
  390. }
  391. return MadeChange;
  392. }
  393. //===----------------------------------------------------------------------===//
  394. // Control Flow Graph Restructuring.
  395. //
  396. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  397. /// method is called when we're about to delete Pred as a predecessor of BB. If
  398. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  399. ///
  400. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  401. /// nodes that collapse into identity values. For example, if we have:
  402. /// x = phi(1, 0, 0, 0)
  403. /// y = and x, z
  404. ///
  405. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  406. /// recursively fold the and to 0.
  407. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
  408. // This only adjusts blocks with PHI nodes.
  409. if (!isa<PHINode>(BB->begin()))
  410. return;
  411. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  412. // them down. This will leave us with single entry phi nodes and other phis
  413. // that can be removed.
  414. BB->removePredecessor(Pred, true);
  415. WeakVH PhiIt = &BB->front();
  416. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  417. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  418. Value *OldPhiIt = PhiIt;
  419. if (!recursivelySimplifyInstruction(PN))
  420. continue;
  421. // If recursive simplification ended up deleting the next PHI node we would
  422. // iterate to, then our iterator is invalid, restart scanning from the top
  423. // of the block.
  424. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  425. }
  426. }
  427. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  428. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  429. /// between them, moving the instructions in the predecessor into DestBB and
  430. /// deleting the predecessor block.
  431. ///
  432. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
  433. // If BB has single-entry PHI nodes, fold them.
  434. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  435. Value *NewVal = PN->getIncomingValue(0);
  436. // Replace self referencing PHI with undef, it must be dead.
  437. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  438. PN->replaceAllUsesWith(NewVal);
  439. PN->eraseFromParent();
  440. }
  441. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  442. assert(PredBB && "Block doesn't have a single predecessor!");
  443. // Zap anything that took the address of DestBB. Not doing this will give the
  444. // address an invalid value.
  445. if (DestBB->hasAddressTaken()) {
  446. BlockAddress *BA = BlockAddress::get(DestBB);
  447. Constant *Replacement =
  448. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  449. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  450. BA->getType()));
  451. BA->destroyConstant();
  452. }
  453. // Anything that branched to PredBB now branches to DestBB.
  454. PredBB->replaceAllUsesWith(DestBB);
  455. // Splice all the instructions from PredBB to DestBB.
  456. PredBB->getTerminator()->eraseFromParent();
  457. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  458. // If the PredBB is the entry block of the function, move DestBB up to
  459. // become the entry block after we erase PredBB.
  460. if (PredBB == &DestBB->getParent()->getEntryBlock())
  461. DestBB->moveAfter(PredBB);
  462. if (DT) {
  463. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  464. DT->changeImmediateDominator(DestBB, PredBBIDom);
  465. DT->eraseNode(PredBB);
  466. }
  467. // Nuke BB.
  468. PredBB->eraseFromParent();
  469. }
  470. /// CanMergeValues - Return true if we can choose one of these values to use
  471. /// in place of the other. Note that we will always choose the non-undef
  472. /// value to keep.
  473. static bool CanMergeValues(Value *First, Value *Second) {
  474. return First == Second;
  475. // HLSL Change Begin -Not merge undef.
  476. // || isa<UndefValue>(First) || isa<UndefValue>(Second);
  477. // HLSL Change End.
  478. }
  479. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  480. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  481. ///
  482. /// Assumption: Succ is the single successor for BB.
  483. ///
  484. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  485. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  486. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  487. << Succ->getName() << "\n");
  488. // Shortcut, if there is only a single predecessor it must be BB and merging
  489. // is always safe
  490. if (Succ->getSinglePredecessor()) return true;
  491. // Make a list of the predecessors of BB
  492. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  493. // Look at all the phi nodes in Succ, to see if they present a conflict when
  494. // merging these blocks
  495. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  496. PHINode *PN = cast<PHINode>(I);
  497. // If the incoming value from BB is again a PHINode in
  498. // BB which has the same incoming value for *PI as PN does, we can
  499. // merge the phi nodes and then the blocks can still be merged
  500. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  501. if (BBPN && BBPN->getParent() == BB) {
  502. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  503. BasicBlock *IBB = PN->getIncomingBlock(PI);
  504. if (BBPreds.count(IBB) &&
  505. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  506. PN->getIncomingValue(PI))) {
  507. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  508. << Succ->getName() << " is conflicting with "
  509. << BBPN->getName() << " with regard to common predecessor "
  510. << IBB->getName() << "\n");
  511. return false;
  512. }
  513. }
  514. } else {
  515. Value* Val = PN->getIncomingValueForBlock(BB);
  516. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  517. // See if the incoming value for the common predecessor is equal to the
  518. // one for BB, in which case this phi node will not prevent the merging
  519. // of the block.
  520. BasicBlock *IBB = PN->getIncomingBlock(PI);
  521. if (BBPreds.count(IBB) &&
  522. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  523. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  524. << Succ->getName() << " is conflicting with regard to common "
  525. << "predecessor " << IBB->getName() << "\n");
  526. return false;
  527. }
  528. }
  529. }
  530. }
  531. return true;
  532. }
  533. typedef SmallVector<BasicBlock *, 16> PredBlockVector;
  534. typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
  535. /// \brief Determines the value to use as the phi node input for a block.
  536. ///
  537. /// Select between \p OldVal any value that we know flows from \p BB
  538. /// to a particular phi on the basis of which one (if either) is not
  539. /// undef. Update IncomingValues based on the selected value.
  540. ///
  541. /// \param OldVal The value we are considering selecting.
  542. /// \param BB The block that the value flows in from.
  543. /// \param IncomingValues A map from block-to-value for other phi inputs
  544. /// that we have examined.
  545. ///
  546. /// \returns the selected value.
  547. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  548. IncomingValueMap &IncomingValues) {
  549. if (!isa<UndefValue>(OldVal)) {
  550. assert((!IncomingValues.count(BB) ||
  551. IncomingValues.find(BB)->second == OldVal) &&
  552. "Expected OldVal to match incoming value from BB!");
  553. IncomingValues.insert(std::make_pair(BB, OldVal));
  554. return OldVal;
  555. }
  556. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  557. if (It != IncomingValues.end()) return It->second;
  558. return OldVal;
  559. }
  560. /// \brief Create a map from block to value for the operands of a
  561. /// given phi.
  562. ///
  563. /// Create a map from block to value for each non-undef value flowing
  564. /// into \p PN.
  565. ///
  566. /// \param PN The phi we are collecting the map for.
  567. /// \param IncomingValues [out] The map from block to value for this phi.
  568. static void gatherIncomingValuesToPhi(PHINode *PN,
  569. IncomingValueMap &IncomingValues) {
  570. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  571. BasicBlock *BB = PN->getIncomingBlock(i);
  572. Value *V = PN->getIncomingValue(i);
  573. if (!isa<UndefValue>(V))
  574. IncomingValues.insert(std::make_pair(BB, V));
  575. }
  576. }
  577. /// \brief Replace the incoming undef values to a phi with the values
  578. /// from a block-to-value map.
  579. ///
  580. /// \param PN The phi we are replacing the undefs in.
  581. /// \param IncomingValues A map from block to value.
  582. static void replaceUndefValuesInPhi(PHINode *PN,
  583. const IncomingValueMap &IncomingValues) {
  584. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  585. Value *V = PN->getIncomingValue(i);
  586. if (!isa<UndefValue>(V)) continue;
  587. BasicBlock *BB = PN->getIncomingBlock(i);
  588. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  589. if (It == IncomingValues.end()) continue;
  590. PN->setIncomingValue(i, It->second);
  591. }
  592. }
  593. /// \brief Replace a value flowing from a block to a phi with
  594. /// potentially multiple instances of that value flowing from the
  595. /// block's predecessors to the phi.
  596. ///
  597. /// \param BB The block with the value flowing into the phi.
  598. /// \param BBPreds The predecessors of BB.
  599. /// \param PN The phi that we are updating.
  600. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  601. const PredBlockVector &BBPreds,
  602. PHINode *PN) {
  603. Value *OldVal = PN->removeIncomingValue(BB, false);
  604. assert(OldVal && "No entry in PHI for Pred BB!");
  605. IncomingValueMap IncomingValues;
  606. // We are merging two blocks - BB, and the block containing PN - and
  607. // as a result we need to redirect edges from the predecessors of BB
  608. // to go to the block containing PN, and update PN
  609. // accordingly. Since we allow merging blocks in the case where the
  610. // predecessor and successor blocks both share some predecessors,
  611. // and where some of those common predecessors might have undef
  612. // values flowing into PN, we want to rewrite those values to be
  613. // consistent with the non-undef values.
  614. gatherIncomingValuesToPhi(PN, IncomingValues);
  615. // If this incoming value is one of the PHI nodes in BB, the new entries
  616. // in the PHI node are the entries from the old PHI.
  617. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  618. PHINode *OldValPN = cast<PHINode>(OldVal);
  619. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  620. // Note that, since we are merging phi nodes and BB and Succ might
  621. // have common predecessors, we could end up with a phi node with
  622. // identical incoming branches. This will be cleaned up later (and
  623. // will trigger asserts if we try to clean it up now, without also
  624. // simplifying the corresponding conditional branch).
  625. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  626. Value *PredVal = OldValPN->getIncomingValue(i);
  627. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  628. IncomingValues);
  629. // And add a new incoming value for this predecessor for the
  630. // newly retargeted branch.
  631. PN->addIncoming(Selected, PredBB);
  632. }
  633. } else {
  634. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  635. // Update existing incoming values in PN for this
  636. // predecessor of BB.
  637. BasicBlock *PredBB = BBPreds[i];
  638. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  639. IncomingValues);
  640. // And add a new incoming value for this predecessor for the
  641. // newly retargeted branch.
  642. PN->addIncoming(Selected, PredBB);
  643. }
  644. }
  645. replaceUndefValuesInPhi(PN, IncomingValues);
  646. }
  647. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  648. /// unconditional branch, and contains no instructions other than PHI nodes,
  649. /// potential side-effect free intrinsics and the branch. If possible,
  650. /// eliminate BB by rewriting all the predecessors to branch to the successor
  651. /// block and return true. If we can't transform, return false.
  652. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  653. assert(BB != &BB->getParent()->getEntryBlock() &&
  654. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  655. // We can't eliminate infinite loops.
  656. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  657. if (BB == Succ) return false;
  658. // Check to see if merging these blocks would cause conflicts for any of the
  659. // phi nodes in BB or Succ. If not, we can safely merge.
  660. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  661. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  662. // has uses which will not disappear when the PHI nodes are merged. It is
  663. // possible to handle such cases, but difficult: it requires checking whether
  664. // BB dominates Succ, which is non-trivial to calculate in the case where
  665. // Succ has multiple predecessors. Also, it requires checking whether
  666. // constructing the necessary self-referential PHI node doesn't introduce any
  667. // conflicts; this isn't too difficult, but the previous code for doing this
  668. // was incorrect.
  669. //
  670. // Note that if this check finds a live use, BB dominates Succ, so BB is
  671. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  672. // folding the branch isn't profitable in that case anyway.
  673. if (!Succ->getSinglePredecessor()) {
  674. BasicBlock::iterator BBI = BB->begin();
  675. while (isa<PHINode>(*BBI)) {
  676. for (Use &U : BBI->uses()) {
  677. if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
  678. if (PN->getIncomingBlock(U) != BB)
  679. return false;
  680. } else {
  681. return false;
  682. }
  683. }
  684. ++BBI;
  685. }
  686. }
  687. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  688. if (isa<PHINode>(Succ->begin())) {
  689. // If there is more than one pred of succ, and there are PHI nodes in
  690. // the successor, then we need to add incoming edges for the PHI nodes
  691. //
  692. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  693. // Loop over all of the PHI nodes in the successor of BB.
  694. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  695. PHINode *PN = cast<PHINode>(I);
  696. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  697. }
  698. }
  699. if (Succ->getSinglePredecessor()) {
  700. // BB is the only predecessor of Succ, so Succ will end up with exactly
  701. // the same predecessors BB had.
  702. // Copy over any phi, debug or lifetime instruction.
  703. BB->getTerminator()->eraseFromParent();
  704. Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
  705. } else {
  706. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  707. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  708. assert(PN->use_empty() && "There shouldn't be any uses here!");
  709. PN->eraseFromParent();
  710. }
  711. }
  712. // Everything that jumped to BB now goes to Succ.
  713. BB->replaceAllUsesWith(Succ);
  714. if (!Succ->hasName()) Succ->takeName(BB);
  715. BB->eraseFromParent(); // Delete the old basic block.
  716. return true;
  717. }
  718. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  719. /// nodes in this block. This doesn't try to be clever about PHI nodes
  720. /// which differ only in the order of the incoming values, but instcombine
  721. /// orders them so it usually won't matter.
  722. ///
  723. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  724. // This implementation doesn't currently consider undef operands
  725. // specially. Theoretically, two phis which are identical except for
  726. // one having an undef where the other doesn't could be collapsed.
  727. struct PHIDenseMapInfo {
  728. static PHINode *getEmptyKey() {
  729. return DenseMapInfo<PHINode *>::getEmptyKey();
  730. }
  731. static PHINode *getTombstoneKey() {
  732. return DenseMapInfo<PHINode *>::getTombstoneKey();
  733. }
  734. static unsigned getHashValue(PHINode *PN) {
  735. // Compute a hash value on the operands. Instcombine will likely have
  736. // sorted them, which helps expose duplicates, but we have to check all
  737. // the operands to be safe in case instcombine hasn't run.
  738. return static_cast<unsigned>(hash_combine(
  739. hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
  740. hash_combine_range(PN->block_begin(), PN->block_end())));
  741. }
  742. static bool isEqual(PHINode *LHS, PHINode *RHS) {
  743. if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
  744. RHS == getEmptyKey() || RHS == getTombstoneKey())
  745. return LHS == RHS;
  746. return LHS->isIdenticalTo(RHS);
  747. }
  748. };
  749. // Set of unique PHINodes.
  750. DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
  751. // Examine each PHI.
  752. bool Changed = false;
  753. for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
  754. auto Inserted = PHISet.insert(PN);
  755. if (!Inserted.second) {
  756. // A duplicate. Replace this PHI with its duplicate.
  757. PN->replaceAllUsesWith(*Inserted.first);
  758. PN->eraseFromParent();
  759. Changed = true;
  760. }
  761. }
  762. return Changed;
  763. }
  764. /// enforceKnownAlignment - If the specified pointer points to an object that
  765. /// we control, modify the object's alignment to PrefAlign. This isn't
  766. /// often possible though. If alignment is important, a more reliable approach
  767. /// is to simply align all global variables and allocation instructions to
  768. /// their preferred alignment from the beginning.
  769. ///
  770. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  771. unsigned PrefAlign,
  772. const DataLayout &DL) {
  773. V = V->stripPointerCasts();
  774. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  775. // If the preferred alignment is greater than the natural stack alignment
  776. // then don't round up. This avoids dynamic stack realignment.
  777. if (DL.exceedsNaturalStackAlignment(PrefAlign))
  778. return Align;
  779. // If there is a requested alignment and if this is an alloca, round up.
  780. if (AI->getAlignment() >= PrefAlign)
  781. return AI->getAlignment();
  782. AI->setAlignment(PrefAlign);
  783. return PrefAlign;
  784. }
  785. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  786. // If there is a large requested alignment and we can, bump up the alignment
  787. // of the global. If the memory we set aside for the global may not be the
  788. // memory used by the final program then it is impossible for us to reliably
  789. // enforce the preferred alignment.
  790. if (!GO->isStrongDefinitionForLinker())
  791. return Align;
  792. if (GO->getAlignment() >= PrefAlign)
  793. return GO->getAlignment();
  794. // We can only increase the alignment of the global if it has no alignment
  795. // specified or if it is not assigned a section. If it is assigned a
  796. // section, the global could be densely packed with other objects in the
  797. // section, increasing the alignment could cause padding issues.
  798. if (!GO->hasSection() || GO->getAlignment() == 0)
  799. GO->setAlignment(PrefAlign);
  800. return GO->getAlignment();
  801. }
  802. return Align;
  803. }
  804. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  805. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  806. /// and it is more than the alignment of the ultimate object, see if we can
  807. /// increase the alignment of the ultimate object, making this check succeed.
  808. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  809. const DataLayout &DL,
  810. const Instruction *CxtI,
  811. AssumptionCache *AC,
  812. const DominatorTree *DT) {
  813. assert(V->getType()->isPointerTy() &&
  814. "getOrEnforceKnownAlignment expects a pointer!");
  815. unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
  816. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  817. computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
  818. unsigned TrailZ = KnownZero.countTrailingOnes();
  819. // Avoid trouble with ridiculously large TrailZ values, such as
  820. // those computed from a null pointer.
  821. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  822. unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
  823. // LLVM doesn't support alignments larger than this currently.
  824. Align = std::min(Align, +Value::MaximumAlignment);
  825. if (PrefAlign > Align)
  826. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  827. // We don't need to make any adjustment.
  828. return Align;
  829. }
  830. ///===---------------------------------------------------------------------===//
  831. /// Dbg Intrinsic utilities
  832. ///
  833. /// See if there is a dbg.value intrinsic for DIVar before I.
  834. static bool LdStHasDebugValue(const DILocalVariable *DIVar, Instruction *I) {
  835. // Since we can't guarantee that the original dbg.declare instrinsic
  836. // is removed by LowerDbgDeclare(), we need to make sure that we are
  837. // not inserting the same dbg.value intrinsic over and over.
  838. llvm::BasicBlock::InstListType::iterator PrevI(I);
  839. if (PrevI != I->getParent()->getInstList().begin()) {
  840. --PrevI;
  841. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  842. if (DVI->getValue() == I->getOperand(0) &&
  843. DVI->getOffset() == 0 &&
  844. DVI->getVariable() == DIVar)
  845. return true;
  846. }
  847. return false;
  848. }
  849. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  850. /// that has an associated llvm.dbg.decl intrinsic.
  851. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  852. StoreInst *SI, DIBuilder &Builder) {
  853. auto *DIVar = DDI->getVariable();
  854. auto *DIExpr = DDI->getExpression();
  855. assert(DIVar && "Missing variable");
  856. if (LdStHasDebugValue(DIVar, SI))
  857. return true;
  858. // If an argument is zero extended then use argument directly. The ZExt
  859. // may be zapped by an optimization pass in future.
  860. Argument *ExtendedArg = nullptr;
  861. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  862. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  863. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  864. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  865. if (ExtendedArg)
  866. Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, DIExpr,
  867. DDI->getDebugLoc(), SI);
  868. else
  869. Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
  870. DDI->getDebugLoc(), SI);
  871. return true;
  872. }
  873. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  874. /// that has an associated llvm.dbg.decl intrinsic.
  875. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  876. LoadInst *LI, DIBuilder &Builder) {
  877. auto *DIVar = DDI->getVariable();
  878. auto *DIExpr = DDI->getExpression();
  879. assert(DIVar && "Missing variable");
  880. if (LdStHasDebugValue(DIVar, LI))
  881. return true;
  882. Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0, DIVar, DIExpr,
  883. DDI->getDebugLoc(), LI);
  884. return true;
  885. }
  886. /// Determine whether this alloca is either a VLA or an array.
  887. static bool isArray(AllocaInst *AI) {
  888. return AI->isArrayAllocation() ||
  889. AI->getType()->getElementType()->isArrayTy();
  890. }
  891. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  892. /// of llvm.dbg.value intrinsics.
  893. bool llvm::LowerDbgDeclare(Function &F) {
  894. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  895. SmallVector<DbgDeclareInst *, 4> Dbgs;
  896. for (auto &FI : F)
  897. for (BasicBlock::iterator BI : FI)
  898. if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
  899. Dbgs.push_back(DDI);
  900. if (Dbgs.empty())
  901. return false;
  902. for (auto &I : Dbgs) {
  903. DbgDeclareInst *DDI = I;
  904. AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
  905. // If this is an alloca for a scalar variable, insert a dbg.value
  906. // at each load and store to the alloca and erase the dbg.declare.
  907. // The dbg.values allow tracking a variable even if it is not
  908. // stored on the stack, while the dbg.declare can only describe
  909. // the stack slot (and at a lexical-scope granularity). Later
  910. // passes will attempt to elide the stack slot.
  911. if (AI && !isArray(AI)) {
  912. for (User *U : AI->users())
  913. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  914. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  915. else if (LoadInst *LI = dyn_cast<LoadInst>(U))
  916. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  917. else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  918. // This is a call by-value or some other instruction that
  919. // takes a pointer to the variable. Insert a *value*
  920. // intrinsic that describes the alloca.
  921. DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
  922. DDI->getExpression(), DDI->getDebugLoc(),
  923. CI);
  924. }
  925. DDI->eraseFromParent();
  926. }
  927. }
  928. return true;
  929. }
  930. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
  931. /// alloca 'V', if any.
  932. DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
  933. if (auto *L = LocalAsMetadata::getIfExists(V))
  934. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
  935. for (User *U : MDV->users())
  936. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  937. return DDI;
  938. return nullptr;
  939. }
  940. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  941. DIBuilder &Builder, bool Deref) {
  942. DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
  943. if (!DDI)
  944. return false;
  945. DebugLoc Loc = DDI->getDebugLoc();
  946. auto *DIVar = DDI->getVariable();
  947. auto *DIExpr = DDI->getExpression();
  948. assert(DIVar && "Missing variable");
  949. if (Deref) {
  950. // Create a copy of the original DIDescriptor for user variable, prepending
  951. // "deref" operation to a list of address elements, as new llvm.dbg.declare
  952. // will take a value storing address of the memory for variable, not
  953. // alloca itself.
  954. SmallVector<uint64_t, 4> NewDIExpr;
  955. NewDIExpr.push_back(dwarf::DW_OP_deref);
  956. if (DIExpr)
  957. NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
  958. DIExpr = Builder.createExpression(NewDIExpr);
  959. }
  960. // Insert llvm.dbg.declare in the same basic block as the original alloca,
  961. // and remove old llvm.dbg.declare.
  962. BasicBlock *BB = AI->getParent();
  963. Builder.insertDeclare(NewAllocaAddress, DIVar, DIExpr, Loc, BB);
  964. DDI->eraseFromParent();
  965. return true;
  966. }
  967. /// changeToUnreachable - Insert an unreachable instruction before the specified
  968. /// instruction, making it and the rest of the code in the block dead.
  969. static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
  970. BasicBlock *BB = I->getParent();
  971. // Loop over all of the successors, removing BB's entry from any PHI
  972. // nodes.
  973. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  974. (*SI)->removePredecessor(BB);
  975. // Insert a call to llvm.trap right before this. This turns the undefined
  976. // behavior into a hard fail instead of falling through into random code.
  977. if (UseLLVMTrap) {
  978. Function *TrapFn =
  979. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  980. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  981. CallTrap->setDebugLoc(I->getDebugLoc());
  982. }
  983. new UnreachableInst(I->getContext(), I);
  984. // All instructions after this are dead.
  985. BasicBlock::iterator BBI = I, BBE = BB->end();
  986. while (BBI != BBE) {
  987. if (!BBI->use_empty())
  988. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  989. BB->getInstList().erase(BBI++);
  990. }
  991. }
  992. /// changeToCall - Convert the specified invoke into a normal call.
  993. static void changeToCall(InvokeInst *II) {
  994. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  995. CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
  996. NewCall->takeName(II);
  997. NewCall->setCallingConv(II->getCallingConv());
  998. NewCall->setAttributes(II->getAttributes());
  999. NewCall->setDebugLoc(II->getDebugLoc());
  1000. II->replaceAllUsesWith(NewCall);
  1001. // Follow the call by a branch to the normal destination.
  1002. BranchInst::Create(II->getNormalDest(), II);
  1003. // Update PHI nodes in the unwind destination
  1004. II->getUnwindDest()->removePredecessor(II->getParent());
  1005. II->eraseFromParent();
  1006. }
  1007. static bool markAliveBlocks(Function &F,
  1008. SmallPtrSetImpl<BasicBlock*> &Reachable) {
  1009. SmallVector<BasicBlock*, 128> Worklist;
  1010. BasicBlock *BB = F.begin();
  1011. Worklist.push_back(BB);
  1012. Reachable.insert(BB);
  1013. bool Changed = false;
  1014. do {
  1015. BB = Worklist.pop_back_val();
  1016. // Do a quick scan of the basic block, turning any obviously unreachable
  1017. // instructions into LLVM unreachable insts. The instruction combining pass
  1018. // canonicalizes unreachable insts into stores to null or undef.
  1019. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
  1020. // Assumptions that are known to be false are equivalent to unreachable.
  1021. // Also, if the condition is undefined, then we make the choice most
  1022. // beneficial to the optimizer, and choose that to also be unreachable.
  1023. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BBI))
  1024. if (II->getIntrinsicID() == Intrinsic::assume) {
  1025. bool MakeUnreachable = false;
  1026. if (isa<UndefValue>(II->getArgOperand(0)))
  1027. MakeUnreachable = true;
  1028. else if (ConstantInt *Cond =
  1029. dyn_cast<ConstantInt>(II->getArgOperand(0)))
  1030. MakeUnreachable = Cond->isZero();
  1031. if (MakeUnreachable) {
  1032. // Don't insert a call to llvm.trap right before the unreachable.
  1033. changeToUnreachable(BBI, false);
  1034. Changed = true;
  1035. break;
  1036. }
  1037. }
  1038. if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
  1039. if (CI->doesNotReturn()) {
  1040. // If we found a call to a no-return function, insert an unreachable
  1041. // instruction after it. Make sure there isn't *already* one there
  1042. // though.
  1043. ++BBI;
  1044. if (!isa<UnreachableInst>(BBI)) {
  1045. // Don't insert a call to llvm.trap right before the unreachable.
  1046. changeToUnreachable(BBI, false);
  1047. Changed = true;
  1048. }
  1049. break;
  1050. }
  1051. }
  1052. // Store to undef and store to null are undefined and used to signal that
  1053. // they should be changed to unreachable by passes that can't modify the
  1054. // CFG.
  1055. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  1056. // Don't touch volatile stores.
  1057. if (SI->isVolatile()) continue;
  1058. Value *Ptr = SI->getOperand(1);
  1059. if (isa<UndefValue>(Ptr) ||
  1060. (isa<ConstantPointerNull>(Ptr) &&
  1061. SI->getPointerAddressSpace() == 0)) {
  1062. changeToUnreachable(SI, true);
  1063. Changed = true;
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1069. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
  1070. Value *Callee = II->getCalledValue();
  1071. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1072. changeToUnreachable(II, true);
  1073. Changed = true;
  1074. } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
  1075. if (II->use_empty() && II->onlyReadsMemory()) {
  1076. // jump to the normal destination branch.
  1077. BranchInst::Create(II->getNormalDest(), II);
  1078. II->getUnwindDest()->removePredecessor(II->getParent());
  1079. II->eraseFromParent();
  1080. } else
  1081. changeToCall(II);
  1082. Changed = true;
  1083. }
  1084. }
  1085. Changed |= ConstantFoldTerminator(BB, true);
  1086. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  1087. if (Reachable.insert(*SI).second)
  1088. Worklist.push_back(*SI);
  1089. } while (!Worklist.empty());
  1090. return Changed;
  1091. }
  1092. /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
  1093. /// if they are in a dead cycle. Return true if a change was made, false
  1094. /// otherwise.
  1095. bool llvm::removeUnreachableBlocks(Function &F) {
  1096. SmallPtrSet<BasicBlock*, 128> Reachable;
  1097. bool Changed = markAliveBlocks(F, Reachable);
  1098. // If there are unreachable blocks in the CFG...
  1099. if (Reachable.size() == F.size())
  1100. return Changed;
  1101. assert(Reachable.size() < F.size());
  1102. NumRemoved += F.size()-Reachable.size();
  1103. // Loop over all of the basic blocks that are not reachable, dropping all of
  1104. // their internal references...
  1105. for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
  1106. if (Reachable.count(BB))
  1107. continue;
  1108. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  1109. if (Reachable.count(*SI))
  1110. (*SI)->removePredecessor(BB);
  1111. BB->dropAllReferences();
  1112. }
  1113. for (Function::iterator I = ++F.begin(); I != F.end();)
  1114. if (!Reachable.count(I))
  1115. I = F.getBasicBlockList().erase(I);
  1116. else
  1117. ++I;
  1118. return true;
  1119. }
  1120. void llvm::combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs) {
  1121. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  1122. K->dropUnknownMetadata(KnownIDs);
  1123. K->getAllMetadataOtherThanDebugLoc(Metadata);
  1124. for (unsigned i = 0, n = Metadata.size(); i < n; ++i) {
  1125. unsigned Kind = Metadata[i].first;
  1126. MDNode *JMD = J->getMetadata(Kind);
  1127. MDNode *KMD = Metadata[i].second;
  1128. switch (Kind) {
  1129. default:
  1130. K->setMetadata(Kind, nullptr); // Remove unknown metadata
  1131. break;
  1132. case LLVMContext::MD_dbg:
  1133. llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
  1134. case LLVMContext::MD_tbaa:
  1135. K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
  1136. break;
  1137. case LLVMContext::MD_alias_scope:
  1138. K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
  1139. break;
  1140. case LLVMContext::MD_noalias:
  1141. K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
  1142. break;
  1143. case LLVMContext::MD_range:
  1144. K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
  1145. break;
  1146. case LLVMContext::MD_fpmath:
  1147. K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
  1148. break;
  1149. case LLVMContext::MD_invariant_load:
  1150. // Only set the !invariant.load if it is present in both instructions.
  1151. K->setMetadata(Kind, JMD);
  1152. break;
  1153. case LLVMContext::MD_nonnull:
  1154. // Only set the !nonnull if it is present in both instructions.
  1155. K->setMetadata(Kind, JMD);
  1156. break;
  1157. }
  1158. }
  1159. // HLSL Change Begin - combine dxil metadata.
  1160. hlsl::DxilMDHelper::combineDxilMetadata(K, J);
  1161. // HLSL Change End.
  1162. }
  1163. unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
  1164. DominatorTree &DT,
  1165. const BasicBlockEdge &Root) {
  1166. assert(From->getType() == To->getType());
  1167. unsigned Count = 0;
  1168. for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
  1169. UI != UE; ) {
  1170. Use &U = *UI++;
  1171. if (DT.dominates(Root, U)) {
  1172. U.set(To);
  1173. DEBUG(dbgs() << "Replace dominated use of '"
  1174. << From->getName() << "' as "
  1175. << *To << " in " << *U << "\n");
  1176. ++Count;
  1177. }
  1178. }
  1179. return Count;
  1180. }