SwiftErrorValueTracking.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //===-- SwiftErrorValueTracking.cpp --------------------------------------===//
  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 implements a limited mem2reg-like analysis to promote uses of function
  10. // arguments and allocas marked with swiftalloc from memory into virtual
  11. // registers tracked by this class.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/CodeGen/MachineRegisterInfo.h"
  17. #include "llvm/CodeGen/MachineInstrBuilder.h"
  18. #include "llvm/CodeGen/TargetInstrInfo.h"
  19. #include "llvm/CodeGen/TargetLowering.h"
  20. #include "llvm/IR/Value.h"
  21. using namespace llvm;
  22. Register SwiftErrorValueTracking::getOrCreateVReg(const MachineBasicBlock *MBB,
  23. const Value *Val) {
  24. auto Key = std::make_pair(MBB, Val);
  25. auto It = VRegDefMap.find(Key);
  26. // If this is the first use of this swifterror value in this basic block,
  27. // create a new virtual register.
  28. // After we processed all basic blocks we will satisfy this "upwards exposed
  29. // use" by inserting a copy or phi at the beginning of this block.
  30. if (It == VRegDefMap.end()) {
  31. auto &DL = MF->getDataLayout();
  32. const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
  33. auto VReg = MF->getRegInfo().createVirtualRegister(RC);
  34. VRegDefMap[Key] = VReg;
  35. VRegUpwardsUse[Key] = VReg;
  36. return VReg;
  37. } else
  38. return It->second;
  39. }
  40. void SwiftErrorValueTracking::setCurrentVReg(const MachineBasicBlock *MBB,
  41. const Value *Val, Register VReg) {
  42. VRegDefMap[std::make_pair(MBB, Val)] = VReg;
  43. }
  44. Register SwiftErrorValueTracking::getOrCreateVRegDefAt(
  45. const Instruction *I, const MachineBasicBlock *MBB, const Value *Val) {
  46. auto Key = PointerIntPair<const Instruction *, 1, bool>(I, true);
  47. auto It = VRegDefUses.find(Key);
  48. if (It != VRegDefUses.end())
  49. return It->second;
  50. auto &DL = MF->getDataLayout();
  51. const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
  52. Register VReg = MF->getRegInfo().createVirtualRegister(RC);
  53. VRegDefUses[Key] = VReg;
  54. setCurrentVReg(MBB, Val, VReg);
  55. return VReg;
  56. }
  57. Register SwiftErrorValueTracking::getOrCreateVRegUseAt(
  58. const Instruction *I, const MachineBasicBlock *MBB, const Value *Val) {
  59. auto Key = PointerIntPair<const Instruction *, 1, bool>(I, false);
  60. auto It = VRegDefUses.find(Key);
  61. if (It != VRegDefUses.end())
  62. return It->second;
  63. Register VReg = getOrCreateVReg(MBB, Val);
  64. VRegDefUses[Key] = VReg;
  65. return VReg;
  66. }
  67. /// Set up SwiftErrorVals by going through the function. If the function has
  68. /// swifterror argument, it will be the first entry.
  69. void SwiftErrorValueTracking::setFunction(MachineFunction &mf) {
  70. MF = &mf;
  71. Fn = &MF->getFunction();
  72. TLI = MF->getSubtarget().getTargetLowering();
  73. TII = MF->getSubtarget().getInstrInfo();
  74. if (!TLI->supportSwiftError())
  75. return;
  76. SwiftErrorVals.clear();
  77. VRegDefMap.clear();
  78. VRegUpwardsUse.clear();
  79. VRegDefUses.clear();
  80. SwiftErrorArg = nullptr;
  81. // Check if function has a swifterror argument.
  82. bool HaveSeenSwiftErrorArg = false;
  83. for (Function::const_arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
  84. AI != AE; ++AI)
  85. if (AI->hasSwiftErrorAttr()) {
  86. assert(!HaveSeenSwiftErrorArg &&
  87. "Must have only one swifterror parameter");
  88. (void)HaveSeenSwiftErrorArg; // silence warning.
  89. HaveSeenSwiftErrorArg = true;
  90. SwiftErrorArg = &*AI;
  91. SwiftErrorVals.push_back(&*AI);
  92. }
  93. for (const auto &LLVMBB : *Fn)
  94. for (const auto &Inst : LLVMBB) {
  95. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst))
  96. if (Alloca->isSwiftError())
  97. SwiftErrorVals.push_back(Alloca);
  98. }
  99. }
  100. bool SwiftErrorValueTracking::createEntriesInEntryBlock(DebugLoc DbgLoc) {
  101. if (!TLI->supportSwiftError())
  102. return false;
  103. // We only need to do this when we have swifterror parameter or swifterror
  104. // alloc.
  105. if (SwiftErrorVals.empty())
  106. return false;
  107. MachineBasicBlock *MBB = &*MF->begin();
  108. auto &DL = MF->getDataLayout();
  109. auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
  110. bool Inserted = false;
  111. for (const auto *SwiftErrorVal : SwiftErrorVals) {
  112. // We will always generate a copy from the argument. It is always used at
  113. // least by the 'return' of the swifterror.
  114. if (SwiftErrorArg && SwiftErrorArg == SwiftErrorVal)
  115. continue;
  116. Register VReg = MF->getRegInfo().createVirtualRegister(RC);
  117. // Assign Undef to Vreg. We construct MI directly to make sure it works
  118. // with FastISel.
  119. BuildMI(*MBB, MBB->getFirstNonPHI(), DbgLoc,
  120. TII->get(TargetOpcode::IMPLICIT_DEF), VReg);
  121. setCurrentVReg(MBB, SwiftErrorVal, VReg);
  122. Inserted = true;
  123. }
  124. return Inserted;
  125. }
  126. /// Propagate swifterror values through the machine function CFG.
  127. void SwiftErrorValueTracking::propagateVRegs() {
  128. if (!TLI->supportSwiftError())
  129. return;
  130. // We only need to do this when we have swifterror parameter or swifterror
  131. // alloc.
  132. if (SwiftErrorVals.empty())
  133. return;
  134. // For each machine basic block in reverse post order.
  135. ReversePostOrderTraversal<MachineFunction *> RPOT(MF);
  136. for (MachineBasicBlock *MBB : RPOT) {
  137. // For each swifterror value in the function.
  138. for (const auto *SwiftErrorVal : SwiftErrorVals) {
  139. auto Key = std::make_pair(MBB, SwiftErrorVal);
  140. auto UUseIt = VRegUpwardsUse.find(Key);
  141. auto VRegDefIt = VRegDefMap.find(Key);
  142. bool UpwardsUse = UUseIt != VRegUpwardsUse.end();
  143. Register UUseVReg = UpwardsUse ? UUseIt->second : Register();
  144. bool DownwardDef = VRegDefIt != VRegDefMap.end();
  145. assert(!(UpwardsUse && !DownwardDef) &&
  146. "We can't have an upwards use but no downwards def");
  147. // If there is no upwards exposed use and an entry for the swifterror in
  148. // the def map for this value we don't need to do anything: We already
  149. // have a downward def for this basic block.
  150. if (!UpwardsUse && DownwardDef)
  151. continue;
  152. // Otherwise we either have an upwards exposed use vreg that we need to
  153. // materialize or need to forward the downward def from predecessors.
  154. // Check whether we have a single vreg def from all predecessors.
  155. // Otherwise we need a phi.
  156. SmallVector<std::pair<MachineBasicBlock *, Register>, 4> VRegs;
  157. SmallSet<const MachineBasicBlock *, 8> Visited;
  158. for (auto *Pred : MBB->predecessors()) {
  159. if (!Visited.insert(Pred).second)
  160. continue;
  161. VRegs.push_back(std::make_pair(
  162. Pred, getOrCreateVReg(Pred, SwiftErrorVal)));
  163. if (Pred != MBB)
  164. continue;
  165. // We have a self-edge.
  166. // If there was no upwards use in this basic block there is now one: the
  167. // phi needs to use it self.
  168. if (!UpwardsUse) {
  169. UpwardsUse = true;
  170. UUseIt = VRegUpwardsUse.find(Key);
  171. assert(UUseIt != VRegUpwardsUse.end());
  172. UUseVReg = UUseIt->second;
  173. }
  174. }
  175. // We need a phi node if we have more than one predecessor with different
  176. // downward defs.
  177. bool needPHI =
  178. VRegs.size() >= 1 &&
  179. std::find_if(
  180. VRegs.begin(), VRegs.end(),
  181. [&](const std::pair<const MachineBasicBlock *, Register> &V)
  182. -> bool { return V.second != VRegs[0].second; }) !=
  183. VRegs.end();
  184. // If there is no upwards exposed used and we don't need a phi just
  185. // forward the swifterror vreg from the predecessor(s).
  186. if (!UpwardsUse && !needPHI) {
  187. assert(!VRegs.empty() &&
  188. "No predecessors? The entry block should bail out earlier");
  189. // Just forward the swifterror vreg from the predecessor(s).
  190. setCurrentVReg(MBB, SwiftErrorVal, VRegs[0].second);
  191. continue;
  192. }
  193. auto DLoc = isa<Instruction>(SwiftErrorVal)
  194. ? cast<Instruction>(SwiftErrorVal)->getDebugLoc()
  195. : DebugLoc();
  196. const auto *TII = MF->getSubtarget().getInstrInfo();
  197. // If we don't need a phi create a copy to the upward exposed vreg.
  198. if (!needPHI) {
  199. assert(UpwardsUse);
  200. assert(!VRegs.empty() &&
  201. "No predecessors? Is the Calling Convention correct?");
  202. Register DestReg = UUseVReg;
  203. BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY),
  204. DestReg)
  205. .addReg(VRegs[0].second);
  206. continue;
  207. }
  208. // We need a phi: if there is an upwards exposed use we already have a
  209. // destination virtual register number otherwise we generate a new one.
  210. auto &DL = MF->getDataLayout();
  211. auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
  212. Register PHIVReg =
  213. UpwardsUse ? UUseVReg : MF->getRegInfo().createVirtualRegister(RC);
  214. MachineInstrBuilder PHI =
  215. BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc,
  216. TII->get(TargetOpcode::PHI), PHIVReg);
  217. for (auto BBRegPair : VRegs) {
  218. PHI.addReg(BBRegPair.second).addMBB(BBRegPair.first);
  219. }
  220. // We did not have a definition in this block before: store the phi's vreg
  221. // as this block downward exposed def.
  222. if (!UpwardsUse)
  223. setCurrentVReg(MBB, SwiftErrorVal, PHIVReg);
  224. }
  225. }
  226. }
  227. void SwiftErrorValueTracking::preassignVRegs(
  228. MachineBasicBlock *MBB, BasicBlock::const_iterator Begin,
  229. BasicBlock::const_iterator End) {
  230. if (!TLI->supportSwiftError() || SwiftErrorVals.empty())
  231. return;
  232. // Iterator over instructions and assign vregs to swifterror defs and uses.
  233. for (auto It = Begin; It != End; ++It) {
  234. ImmutableCallSite CS(&*It);
  235. if (CS) {
  236. // A call-site with a swifterror argument is both use and def.
  237. const Value *SwiftErrorAddr = nullptr;
  238. for (auto &Arg : CS.args()) {
  239. if (!Arg->isSwiftError())
  240. continue;
  241. // Use of swifterror.
  242. assert(!SwiftErrorAddr && "Cannot have multiple swifterror arguments");
  243. SwiftErrorAddr = &*Arg;
  244. assert(SwiftErrorAddr->isSwiftError() &&
  245. "Must have a swifterror value argument");
  246. getOrCreateVRegUseAt(&*It, MBB, SwiftErrorAddr);
  247. }
  248. if (!SwiftErrorAddr)
  249. continue;
  250. // Def of swifterror.
  251. getOrCreateVRegDefAt(&*It, MBB, SwiftErrorAddr);
  252. // A load is a use.
  253. } else if (const LoadInst *LI = dyn_cast<const LoadInst>(&*It)) {
  254. const Value *V = LI->getOperand(0);
  255. if (!V->isSwiftError())
  256. continue;
  257. getOrCreateVRegUseAt(LI, MBB, V);
  258. // A store is a def.
  259. } else if (const StoreInst *SI = dyn_cast<const StoreInst>(&*It)) {
  260. const Value *SwiftErrorAddr = SI->getOperand(1);
  261. if (!SwiftErrorAddr->isSwiftError())
  262. continue;
  263. // Def of swifterror.
  264. getOrCreateVRegDefAt(&*It, MBB, SwiftErrorAddr);
  265. // A return in a swiferror returning function is a use.
  266. } else if (const ReturnInst *R = dyn_cast<const ReturnInst>(&*It)) {
  267. const Function *F = R->getParent()->getParent();
  268. if (!F->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  269. continue;
  270. getOrCreateVRegUseAt(R, MBB, SwiftErrorArg);
  271. }
  272. }
  273. }