StatepointLowering.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
  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 file includes support code use by SelectionDAGBuilder when lowering a
  10. // statepoint sequence in SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "StatepointLowering.h"
  14. #include "SelectionDAGBuilder.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  22. #include "llvm/CodeGen/GCMetadata.h"
  23. #include "llvm/CodeGen/ISDOpcodes.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineFunction.h"
  26. #include "llvm/CodeGen/MachineMemOperand.h"
  27. #include "llvm/CodeGen/RuntimeLibcalls.h"
  28. #include "llvm/CodeGen/SelectionDAG.h"
  29. #include "llvm/CodeGen/StackMaps.h"
  30. #include "llvm/CodeGen/TargetLowering.h"
  31. #include "llvm/CodeGen/TargetOpcodes.h"
  32. #include "llvm/IR/CallingConv.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/GCStrategy.h"
  35. #include "llvm/IR/Instruction.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/LLVMContext.h"
  38. #include "llvm/IR/Statepoint.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/MachineValueType.h"
  43. #include "llvm/Target/TargetMachine.h"
  44. #include "llvm/Target/TargetOptions.h"
  45. #include <cassert>
  46. #include <cstddef>
  47. #include <cstdint>
  48. #include <iterator>
  49. #include <tuple>
  50. #include <utility>
  51. using namespace llvm;
  52. #define DEBUG_TYPE "statepoint-lowering"
  53. STATISTIC(NumSlotsAllocatedForStatepoints,
  54. "Number of stack slots allocated for statepoints");
  55. STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
  56. STATISTIC(StatepointMaxSlotsRequired,
  57. "Maximum number of stack slots required for a singe statepoint");
  58. cl::opt<bool> UseRegistersForDeoptValues(
  59. "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
  60. cl::desc("Allow using registers for non pointer deopt args"));
  61. cl::opt<bool> UseRegistersForGCPointersInLandingPad(
  62. "use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false),
  63. cl::desc("Allow using registers for gc pointer in landing pad"));
  64. cl::opt<unsigned> MaxRegistersForGCPointers(
  65. "max-registers-for-gc-values", cl::Hidden, cl::init(0),
  66. cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
  67. typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
  68. static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
  69. SelectionDAGBuilder &Builder, uint64_t Value) {
  70. SDLoc L = Builder.getCurSDLoc();
  71. Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
  72. MVT::i64));
  73. Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
  74. }
  75. void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
  76. // Consistency check
  77. assert(PendingGCRelocateCalls.empty() &&
  78. "Trying to visit statepoint before finished processing previous one");
  79. Locations.clear();
  80. NextSlotToAllocate = 0;
  81. // Need to resize this on each safepoint - we need the two to stay in sync and
  82. // the clear patterns of a SelectionDAGBuilder have no relation to
  83. // FunctionLoweringInfo. Also need to ensure used bits get cleared.
  84. AllocatedStackSlots.clear();
  85. AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
  86. }
  87. void StatepointLoweringState::clear() {
  88. Locations.clear();
  89. AllocatedStackSlots.clear();
  90. assert(PendingGCRelocateCalls.empty() &&
  91. "cleared before statepoint sequence completed");
  92. }
  93. SDValue
  94. StatepointLoweringState::allocateStackSlot(EVT ValueType,
  95. SelectionDAGBuilder &Builder) {
  96. NumSlotsAllocatedForStatepoints++;
  97. MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
  98. unsigned SpillSize = ValueType.getStoreSize();
  99. assert((SpillSize * 8) ==
  100. (-8u & (7 + ValueType.getSizeInBits())) && // Round up modulo 8.
  101. "Size not in bytes?");
  102. // First look for a previously created stack slot which is not in
  103. // use (accounting for the fact arbitrary slots may already be
  104. // reserved), or to create a new stack slot and use it.
  105. const size_t NumSlots = AllocatedStackSlots.size();
  106. assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
  107. assert(AllocatedStackSlots.size() ==
  108. Builder.FuncInfo.StatepointStackSlots.size() &&
  109. "Broken invariant");
  110. for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
  111. if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
  112. const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
  113. if (MFI.getObjectSize(FI) == SpillSize) {
  114. AllocatedStackSlots.set(NextSlotToAllocate);
  115. // TODO: Is ValueType the right thing to use here?
  116. return Builder.DAG.getFrameIndex(FI, ValueType);
  117. }
  118. }
  119. }
  120. // Couldn't find a free slot, so create a new one:
  121. SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
  122. const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
  123. MFI.markAsStatepointSpillSlotObjectIndex(FI);
  124. Builder.FuncInfo.StatepointStackSlots.push_back(FI);
  125. AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
  126. assert(AllocatedStackSlots.size() ==
  127. Builder.FuncInfo.StatepointStackSlots.size() &&
  128. "Broken invariant");
  129. StatepointMaxSlotsRequired.updateMax(
  130. Builder.FuncInfo.StatepointStackSlots.size());
  131. return SpillSlot;
  132. }
  133. /// Utility function for reservePreviousStackSlotForValue. Tries to find
  134. /// stack slot index to which we have spilled value for previous statepoints.
  135. /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
  136. static Optional<int> findPreviousSpillSlot(const Value *Val,
  137. SelectionDAGBuilder &Builder,
  138. int LookUpDepth) {
  139. // Can not look any further - give up now
  140. if (LookUpDepth <= 0)
  141. return None;
  142. // Spill location is known for gc relocates
  143. if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
  144. const auto &RelocationMap =
  145. Builder.FuncInfo.StatepointRelocationMaps[Relocate->getStatepoint()];
  146. auto It = RelocationMap.find(Relocate->getDerivedPtr());
  147. if (It == RelocationMap.end())
  148. return None;
  149. auto &Record = It->second;
  150. if (Record.type != RecordType::Spill)
  151. return None;
  152. return Record.payload.FI;
  153. }
  154. // Look through bitcast instructions.
  155. if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
  156. return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
  157. // Look through phi nodes
  158. // All incoming values should have same known stack slot, otherwise result
  159. // is unknown.
  160. if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
  161. Optional<int> MergedResult = None;
  162. for (auto &IncomingValue : Phi->incoming_values()) {
  163. Optional<int> SpillSlot =
  164. findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
  165. if (!SpillSlot.hasValue())
  166. return None;
  167. if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
  168. return None;
  169. MergedResult = SpillSlot;
  170. }
  171. return MergedResult;
  172. }
  173. // TODO: We can do better for PHI nodes. In cases like this:
  174. // ptr = phi(relocated_pointer, not_relocated_pointer)
  175. // statepoint(ptr)
  176. // We will return that stack slot for ptr is unknown. And later we might
  177. // assign different stack slots for ptr and relocated_pointer. This limits
  178. // llvm's ability to remove redundant stores.
  179. // Unfortunately it's hard to accomplish in current infrastructure.
  180. // We use this function to eliminate spill store completely, while
  181. // in example we still need to emit store, but instead of any location
  182. // we need to use special "preferred" location.
  183. // TODO: handle simple updates. If a value is modified and the original
  184. // value is no longer live, it would be nice to put the modified value in the
  185. // same slot. This allows folding of the memory accesses for some
  186. // instructions types (like an increment).
  187. // statepoint (i)
  188. // i1 = i+1
  189. // statepoint (i1)
  190. // However we need to be careful for cases like this:
  191. // statepoint(i)
  192. // i1 = i+1
  193. // statepoint(i, i1)
  194. // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
  195. // put handling of simple modifications in this function like it's done
  196. // for bitcasts we might end up reserving i's slot for 'i+1' because order in
  197. // which we visit values is unspecified.
  198. // Don't know any information about this instruction
  199. return None;
  200. }
  201. /// Return true if-and-only-if the given SDValue can be lowered as either a
  202. /// constant argument or a stack reference. The key point is that the value
  203. /// doesn't need to be spilled or tracked as a vreg use.
  204. static bool willLowerDirectly(SDValue Incoming) {
  205. // We are making an unchecked assumption that the frame size <= 2^16 as that
  206. // is the largest offset which can be encoded in the stackmap format.
  207. if (isa<FrameIndexSDNode>(Incoming))
  208. return true;
  209. // The largest constant describeable in the StackMap format is 64 bits.
  210. // Potential Optimization: Constants values are sign extended by consumer,
  211. // and thus there are many constants of static type > 64 bits whose value
  212. // happens to be sext(Con64) and could thus be lowered directly.
  213. if (Incoming.getValueType().getSizeInBits() > 64)
  214. return false;
  215. return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
  216. Incoming.isUndef());
  217. }
  218. /// Try to find existing copies of the incoming values in stack slots used for
  219. /// statepoint spilling. If we can find a spill slot for the incoming value,
  220. /// mark that slot as allocated, and reuse the same slot for this safepoint.
  221. /// This helps to avoid series of loads and stores that only serve to reshuffle
  222. /// values on the stack between calls.
  223. static void reservePreviousStackSlotForValue(const Value *IncomingValue,
  224. SelectionDAGBuilder &Builder) {
  225. SDValue Incoming = Builder.getValue(IncomingValue);
  226. // If we won't spill this, we don't need to check for previously allocated
  227. // stack slots.
  228. if (willLowerDirectly(Incoming))
  229. return;
  230. SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
  231. if (OldLocation.getNode())
  232. // Duplicates in input
  233. return;
  234. const int LookUpDepth = 6;
  235. Optional<int> Index =
  236. findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
  237. if (!Index.hasValue())
  238. return;
  239. const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
  240. auto SlotIt = find(StatepointSlots, *Index);
  241. assert(SlotIt != StatepointSlots.end() &&
  242. "Value spilled to the unknown stack slot");
  243. // This is one of our dedicated lowering slots
  244. const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
  245. if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
  246. // stack slot already assigned to someone else, can't use it!
  247. // TODO: currently we reserve space for gc arguments after doing
  248. // normal allocation for deopt arguments. We should reserve for
  249. // _all_ deopt and gc arguments, then start allocating. This
  250. // will prevent some moves being inserted when vm state changes,
  251. // but gc state doesn't between two calls.
  252. return;
  253. }
  254. // Reserve this stack slot
  255. Builder.StatepointLowering.reserveStackSlot(Offset);
  256. // Cache this slot so we find it when going through the normal
  257. // assignment loop.
  258. SDValue Loc =
  259. Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
  260. Builder.StatepointLowering.setLocation(Incoming, Loc);
  261. }
  262. /// Extract call from statepoint, lower it and return pointer to the
  263. /// call node. Also update NodeMap so that getValue(statepoint) will
  264. /// reference lowered call result
  265. static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
  266. SelectionDAGBuilder::StatepointLoweringInfo &SI,
  267. SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
  268. SDValue ReturnValue, CallEndVal;
  269. std::tie(ReturnValue, CallEndVal) =
  270. Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
  271. SDNode *CallEnd = CallEndVal.getNode();
  272. // Get a call instruction from the call sequence chain. Tail calls are not
  273. // allowed. The following code is essentially reverse engineering X86's
  274. // LowerCallTo.
  275. //
  276. // We are expecting DAG to have the following form:
  277. //
  278. // ch = eh_label (only in case of invoke statepoint)
  279. // ch, glue = callseq_start ch
  280. // ch, glue = X86::Call ch, glue
  281. // ch, glue = callseq_end ch, glue
  282. // get_return_value ch, glue
  283. //
  284. // get_return_value can either be a sequence of CopyFromReg instructions
  285. // to grab the return value from the return register(s), or it can be a LOAD
  286. // to load a value returned by reference via a stack slot.
  287. bool HasDef = !SI.CLI.RetTy->isVoidTy();
  288. if (HasDef) {
  289. if (CallEnd->getOpcode() == ISD::LOAD)
  290. CallEnd = CallEnd->getOperand(0).getNode();
  291. else
  292. while (CallEnd->getOpcode() == ISD::CopyFromReg)
  293. CallEnd = CallEnd->getOperand(0).getNode();
  294. }
  295. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
  296. return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
  297. }
  298. static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
  299. FrameIndexSDNode &FI) {
  300. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
  301. auto MMOFlags = MachineMemOperand::MOStore |
  302. MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  303. auto &MFI = MF.getFrameInfo();
  304. return MF.getMachineMemOperand(PtrInfo, MMOFlags,
  305. MFI.getObjectSize(FI.getIndex()),
  306. MFI.getObjectAlign(FI.getIndex()));
  307. }
  308. /// Spill a value incoming to the statepoint. It might be either part of
  309. /// vmstate
  310. /// or gcstate. In both cases unconditionally spill it on the stack unless it
  311. /// is a null constant. Return pair with first element being frame index
  312. /// containing saved value and second element with outgoing chain from the
  313. /// emitted store
  314. static std::tuple<SDValue, SDValue, MachineMemOperand*>
  315. spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
  316. SelectionDAGBuilder &Builder) {
  317. SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
  318. MachineMemOperand* MMO = nullptr;
  319. // Emit new store if we didn't do it for this ptr before
  320. if (!Loc.getNode()) {
  321. Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
  322. Builder);
  323. int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
  324. // We use TargetFrameIndex so that isel will not select it into LEA
  325. Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
  326. // Right now we always allocate spill slots that are of the same
  327. // size as the value we're about to spill (the size of spillee can
  328. // vary since we spill vectors of pointers too). At some point we
  329. // can consider allowing spills of smaller values to larger slots
  330. // (i.e. change the '==' in the assert below to a '>=').
  331. MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
  332. assert((MFI.getObjectSize(Index) * 8) ==
  333. (-8 & (7 + // Round up modulo 8.
  334. (int64_t)Incoming.getValueSizeInBits())) &&
  335. "Bad spill: stack slot does not match!");
  336. // Note: Using the alignment of the spill slot (rather than the abi or
  337. // preferred alignment) is required for correctness when dealing with spill
  338. // slots with preferred alignments larger than frame alignment..
  339. auto &MF = Builder.DAG.getMachineFunction();
  340. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
  341. auto *StoreMMO = MF.getMachineMemOperand(
  342. PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
  343. MFI.getObjectAlign(Index));
  344. Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
  345. StoreMMO);
  346. MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
  347. Builder.StatepointLowering.setLocation(Incoming, Loc);
  348. }
  349. assert(Loc.getNode());
  350. return std::make_tuple(Loc, Chain, MMO);
  351. }
  352. /// Lower a single value incoming to a statepoint node. This value can be
  353. /// either a deopt value or a gc value, the handling is the same. We special
  354. /// case constants and allocas, then fall back to spilling if required.
  355. static void
  356. lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
  357. SmallVectorImpl<SDValue> &Ops,
  358. SmallVectorImpl<MachineMemOperand *> &MemRefs,
  359. SelectionDAGBuilder &Builder) {
  360. if (willLowerDirectly(Incoming)) {
  361. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
  362. // This handles allocas as arguments to the statepoint (this is only
  363. // really meaningful for a deopt value. For GC, we'd be trying to
  364. // relocate the address of the alloca itself?)
  365. assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
  366. "Incoming value is a frame index!");
  367. Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
  368. Builder.getFrameIndexTy()));
  369. auto &MF = Builder.DAG.getMachineFunction();
  370. auto *MMO = getMachineMemOperand(MF, *FI);
  371. MemRefs.push_back(MMO);
  372. return;
  373. }
  374. assert(Incoming.getValueType().getSizeInBits() <= 64);
  375. if (Incoming.isUndef()) {
  376. // Put an easily recognized constant that's unlikely to be a valid
  377. // value so that uses of undef by the consumer of the stackmap is
  378. // easily recognized. This is legal since the compiler is always
  379. // allowed to chose an arbitrary value for undef.
  380. pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
  381. return;
  382. }
  383. // If the original value was a constant, make sure it gets recorded as
  384. // such in the stackmap. This is required so that the consumer can
  385. // parse any internal format to the deopt state. It also handles null
  386. // pointers and other constant pointers in GC states.
  387. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
  388. pushStackMapConstant(Ops, Builder, C->getSExtValue());
  389. return;
  390. } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
  391. pushStackMapConstant(Ops, Builder,
  392. C->getValueAPF().bitcastToAPInt().getZExtValue());
  393. return;
  394. }
  395. llvm_unreachable("unhandled direct lowering case");
  396. }
  397. if (!RequireSpillSlot) {
  398. // If this value is live in (not live-on-return, or live-through), we can
  399. // treat it the same way patchpoint treats it's "live in" values. We'll
  400. // end up folding some of these into stack references, but they'll be
  401. // handled by the register allocator. Note that we do not have the notion
  402. // of a late use so these values might be placed in registers which are
  403. // clobbered by the call. This is fine for live-in. For live-through
  404. // fix-up pass should be executed to force spilling of such registers.
  405. Ops.push_back(Incoming);
  406. } else {
  407. // Otherwise, locate a spill slot and explicitly spill it so it can be
  408. // found by the runtime later. Note: We know all of these spills are
  409. // independent, but don't bother to exploit that chain wise. DAGCombine
  410. // will happily do so as needed, so doing it here would be a small compile
  411. // time win at most.
  412. SDValue Chain = Builder.getRoot();
  413. auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
  414. Ops.push_back(std::get<0>(Res));
  415. if (auto *MMO = std::get<2>(Res))
  416. MemRefs.push_back(MMO);
  417. Chain = std::get<1>(Res);;
  418. Builder.DAG.setRoot(Chain);
  419. }
  420. }
  421. /// Return true if value V represents the GC value. The behavior is conservative
  422. /// in case it is not sure that value is not GC the function returns true.
  423. static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder) {
  424. auto *Ty = V->getType();
  425. if (!Ty->isPtrOrPtrVectorTy())
  426. return false;
  427. if (auto *GFI = Builder.GFI)
  428. if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
  429. return *IsManaged;
  430. return true; // conservative
  431. }
  432. /// Lower deopt state and gc pointer arguments of the statepoint. The actual
  433. /// lowering is described in lowerIncomingStatepointValue. This function is
  434. /// responsible for lowering everything in the right position and playing some
  435. /// tricks to avoid redundant stack manipulation where possible. On
  436. /// completion, 'Ops' will contain ready to use operands for machine code
  437. /// statepoint. The chain nodes will have already been created and the DAG root
  438. /// will be set to the last value spilled (if any were).
  439. static void
  440. lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
  441. SmallVectorImpl<MachineMemOperand *> &MemRefs,
  442. SmallVectorImpl<SDValue> &GCPtrs,
  443. DenseMap<SDValue, int> &LowerAsVReg,
  444. SelectionDAGBuilder::StatepointLoweringInfo &SI,
  445. SelectionDAGBuilder &Builder) {
  446. // Lower the deopt and gc arguments for this statepoint. Layout will be:
  447. // deopt argument length, deopt arguments.., gc arguments...
  448. #ifndef NDEBUG
  449. if (auto *GFI = Builder.GFI) {
  450. // Check that each of the gc pointer and bases we've gotten out of the
  451. // safepoint is something the strategy thinks might be a pointer (or vector
  452. // of pointers) into the GC heap. This is basically just here to help catch
  453. // errors during statepoint insertion. TODO: This should actually be in the
  454. // Verifier, but we can't get to the GCStrategy from there (yet).
  455. GCStrategy &S = GFI->getStrategy();
  456. for (const Value *V : SI.Bases) {
  457. auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
  458. if (Opt.hasValue()) {
  459. assert(Opt.getValue() &&
  460. "non gc managed base pointer found in statepoint");
  461. }
  462. }
  463. for (const Value *V : SI.Ptrs) {
  464. auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
  465. if (Opt.hasValue()) {
  466. assert(Opt.getValue() &&
  467. "non gc managed derived pointer found in statepoint");
  468. }
  469. }
  470. assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
  471. } else {
  472. assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
  473. assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
  474. }
  475. #endif
  476. // Figure out what lowering strategy we're going to use for each part
  477. // Note: Is is conservatively correct to lower both "live-in" and "live-out"
  478. // as "live-through". A "live-through" variable is one which is "live-in",
  479. // "live-out", and live throughout the lifetime of the call (i.e. we can find
  480. // it from any PC within the transitive callee of the statepoint). In
  481. // particular, if the callee spills callee preserved registers we may not
  482. // be able to find a value placed in that register during the call. This is
  483. // fine for live-out, but not for live-through. If we were willing to make
  484. // assumptions about the code generator producing the callee, we could
  485. // potentially allow live-through values in callee saved registers.
  486. const bool LiveInDeopt =
  487. SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
  488. // Decide which deriver pointers will go on VRegs
  489. unsigned MaxVRegPtrs = MaxRegistersForGCPointers.getValue();
  490. // Pointers used on exceptional path of invoke statepoint.
  491. // We cannot assing them to VRegs.
  492. SmallSet<SDValue, 8> LPadPointers;
  493. if (!UseRegistersForGCPointersInLandingPad)
  494. if (auto *StInvoke = dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
  495. LandingPadInst *LPI = StInvoke->getLandingPadInst();
  496. for (auto *Relocate : SI.GCRelocates)
  497. if (Relocate->getOperand(0) == LPI) {
  498. LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
  499. LPadPointers.insert(Builder.getValue(Relocate->getDerivedPtr()));
  500. }
  501. }
  502. LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n");
  503. // List of unique lowered GC Pointer values.
  504. SmallSetVector<SDValue, 16> LoweredGCPtrs;
  505. // Map lowered GC Pointer value to the index in above vector
  506. DenseMap<SDValue, unsigned> GCPtrIndexMap;
  507. unsigned CurNumVRegs = 0;
  508. auto canPassGCPtrOnVReg = [&](SDValue SD) {
  509. if (SD.getValueType().isVector())
  510. return false;
  511. if (LPadPointers.count(SD))
  512. return false;
  513. return !willLowerDirectly(SD);
  514. };
  515. auto processGCPtr = [&](const Value *V) {
  516. SDValue PtrSD = Builder.getValue(V);
  517. if (!LoweredGCPtrs.insert(PtrSD))
  518. return; // skip duplicates
  519. GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
  520. assert(!LowerAsVReg.count(PtrSD) && "must not have been seen");
  521. if (LowerAsVReg.size() == MaxVRegPtrs)
  522. return;
  523. assert(V->getType()->isVectorTy() == PtrSD.getValueType().isVector() &&
  524. "IR and SD types disagree");
  525. if (!canPassGCPtrOnVReg(PtrSD)) {
  526. LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
  527. return;
  528. }
  529. LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
  530. LowerAsVReg[PtrSD] = CurNumVRegs++;
  531. };
  532. // Process derived pointers first to give them more chance to go on VReg.
  533. for (const Value *V : SI.Ptrs)
  534. processGCPtr(V);
  535. for (const Value *V : SI.Bases)
  536. processGCPtr(V);
  537. LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n");
  538. auto requireSpillSlot = [&](const Value *V) {
  539. if (!Builder.DAG.getTargetLoweringInfo().isTypeLegal(
  540. Builder.getValue(V).getValueType()))
  541. return true;
  542. if (isGCValue(V, Builder))
  543. return !LowerAsVReg.count(Builder.getValue(V));
  544. return !(LiveInDeopt || UseRegistersForDeoptValues);
  545. };
  546. // Before we actually start lowering (and allocating spill slots for values),
  547. // reserve any stack slots which we judge to be profitable to reuse for a
  548. // particular value. This is purely an optimization over the code below and
  549. // doesn't change semantics at all. It is important for performance that we
  550. // reserve slots for both deopt and gc values before lowering either.
  551. for (const Value *V : SI.DeoptState) {
  552. if (requireSpillSlot(V))
  553. reservePreviousStackSlotForValue(V, Builder);
  554. }
  555. for (const Value *V : SI.Ptrs) {
  556. SDValue SDV = Builder.getValue(V);
  557. if (!LowerAsVReg.count(SDV))
  558. reservePreviousStackSlotForValue(V, Builder);
  559. }
  560. for (const Value *V : SI.Bases) {
  561. SDValue SDV = Builder.getValue(V);
  562. if (!LowerAsVReg.count(SDV))
  563. reservePreviousStackSlotForValue(V, Builder);
  564. }
  565. // First, prefix the list with the number of unique values to be
  566. // lowered. Note that this is the number of *Values* not the
  567. // number of SDValues required to lower them.
  568. const int NumVMSArgs = SI.DeoptState.size();
  569. pushStackMapConstant(Ops, Builder, NumVMSArgs);
  570. // The vm state arguments are lowered in an opaque manner. We do not know
  571. // what type of values are contained within.
  572. LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
  573. for (const Value *V : SI.DeoptState) {
  574. SDValue Incoming;
  575. // If this is a function argument at a static frame index, generate it as
  576. // the frame index.
  577. if (const Argument *Arg = dyn_cast<Argument>(V)) {
  578. int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
  579. if (FI != INT_MAX)
  580. Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
  581. }
  582. if (!Incoming.getNode())
  583. Incoming = Builder.getValue(V);
  584. LLVM_DEBUG(dbgs() << "Value " << *V
  585. << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
  586. lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
  587. Builder);
  588. }
  589. // Finally, go ahead and lower all the gc arguments.
  590. pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
  591. for (SDValue SDV : LoweredGCPtrs)
  592. lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
  593. Builder);
  594. // Copy to out vector. LoweredGCPtrs will be empty after this point.
  595. GCPtrs = LoweredGCPtrs.takeVector();
  596. // If there are any explicit spill slots passed to the statepoint, record
  597. // them, but otherwise do not do anything special. These are user provided
  598. // allocas and give control over placement to the consumer. In this case,
  599. // it is the contents of the slot which may get updated, not the pointer to
  600. // the alloca
  601. SmallVector<SDValue, 4> Allocas;
  602. for (Value *V : SI.GCArgs) {
  603. SDValue Incoming = Builder.getValue(V);
  604. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
  605. // This handles allocas as arguments to the statepoint
  606. assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
  607. "Incoming value is a frame index!");
  608. Allocas.push_back(Builder.DAG.getTargetFrameIndex(
  609. FI->getIndex(), Builder.getFrameIndexTy()));
  610. auto &MF = Builder.DAG.getMachineFunction();
  611. auto *MMO = getMachineMemOperand(MF, *FI);
  612. MemRefs.push_back(MMO);
  613. }
  614. }
  615. pushStackMapConstant(Ops, Builder, Allocas.size());
  616. Ops.append(Allocas.begin(), Allocas.end());
  617. // Now construct GC base/derived map;
  618. pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
  619. SDLoc L = Builder.getCurSDLoc();
  620. for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
  621. SDValue Base = Builder.getValue(SI.Bases[i]);
  622. assert(GCPtrIndexMap.count(Base) && "base not found in index map");
  623. Ops.push_back(
  624. Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
  625. SDValue Derived = Builder.getValue(SI.Ptrs[i]);
  626. assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
  627. Ops.push_back(
  628. Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
  629. }
  630. }
  631. SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
  632. SelectionDAGBuilder::StatepointLoweringInfo &SI) {
  633. // The basic scheme here is that information about both the original call and
  634. // the safepoint is encoded in the CallInst. We create a temporary call and
  635. // lower it, then reverse engineer the calling sequence.
  636. NumOfStatepoints++;
  637. // Clear state
  638. StatepointLowering.startNewStatepoint(*this);
  639. assert(SI.Bases.size() == SI.Ptrs.size());
  640. LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n");
  641. #ifndef NDEBUG
  642. for (auto *Reloc : SI.GCRelocates)
  643. if (Reloc->getParent() == SI.StatepointInstr->getParent())
  644. StatepointLowering.scheduleRelocCall(*Reloc);
  645. #endif
  646. // Lower statepoint vmstate and gcstate arguments
  647. // All lowered meta args.
  648. SmallVector<SDValue, 10> LoweredMetaArgs;
  649. // Lowered GC pointers (subset of above).
  650. SmallVector<SDValue, 16> LoweredGCArgs;
  651. SmallVector<MachineMemOperand*, 16> MemRefs;
  652. // Maps derived pointer SDValue to statepoint result of relocated pointer.
  653. DenseMap<SDValue, int> LowerAsVReg;
  654. lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
  655. SI, *this);
  656. // Now that we've emitted the spills, we need to update the root so that the
  657. // call sequence is ordered correctly.
  658. SI.CLI.setChain(getRoot());
  659. // Get call node, we will replace it later with statepoint
  660. SDValue ReturnVal;
  661. SDNode *CallNode;
  662. std::tie(ReturnVal, CallNode) =
  663. lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
  664. // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
  665. // nodes with all the appropriate arguments and return values.
  666. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  667. SDValue Chain = CallNode->getOperand(0);
  668. SDValue Glue;
  669. bool CallHasIncomingGlue = CallNode->getGluedNode();
  670. if (CallHasIncomingGlue) {
  671. // Glue is always last operand
  672. Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
  673. }
  674. // Build the GC_TRANSITION_START node if necessary.
  675. //
  676. // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
  677. // order in which they appear in the call to the statepoint intrinsic. If
  678. // any of the operands is a pointer-typed, that operand is immediately
  679. // followed by a SRCVALUE for the pointer that may be used during lowering
  680. // (e.g. to form MachinePointerInfo values for loads/stores).
  681. const bool IsGCTransition =
  682. (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
  683. (uint64_t)StatepointFlags::GCTransition;
  684. if (IsGCTransition) {
  685. SmallVector<SDValue, 8> TSOps;
  686. // Add chain
  687. TSOps.push_back(Chain);
  688. // Add GC transition arguments
  689. for (const Value *V : SI.GCTransitionArgs) {
  690. TSOps.push_back(getValue(V));
  691. if (V->getType()->isPointerTy())
  692. TSOps.push_back(DAG.getSrcValue(V));
  693. }
  694. // Add glue if necessary
  695. if (CallHasIncomingGlue)
  696. TSOps.push_back(Glue);
  697. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  698. SDValue GCTransitionStart =
  699. DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
  700. Chain = GCTransitionStart.getValue(0);
  701. Glue = GCTransitionStart.getValue(1);
  702. }
  703. // TODO: Currently, all of these operands are being marked as read/write in
  704. // PrologEpilougeInserter.cpp, we should special case the VMState arguments
  705. // and flags to be read-only.
  706. SmallVector<SDValue, 40> Ops;
  707. // Add the <id> and <numBytes> constants.
  708. Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
  709. Ops.push_back(
  710. DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
  711. // Calculate and push starting position of vmstate arguments
  712. // Get number of arguments incoming directly into call node
  713. unsigned NumCallRegArgs =
  714. CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
  715. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
  716. // Add call target
  717. SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
  718. Ops.push_back(CallTarget);
  719. // Add call arguments
  720. // Get position of register mask in the call
  721. SDNode::op_iterator RegMaskIt;
  722. if (CallHasIncomingGlue)
  723. RegMaskIt = CallNode->op_end() - 2;
  724. else
  725. RegMaskIt = CallNode->op_end() - 1;
  726. Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
  727. // Add a constant argument for the calling convention
  728. pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
  729. // Add a constant argument for the flags
  730. uint64_t Flags = SI.StatepointFlags;
  731. assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
  732. "Unknown flag used");
  733. pushStackMapConstant(Ops, *this, Flags);
  734. // Insert all vmstate and gcstate arguments
  735. llvm::append_range(Ops, LoweredMetaArgs);
  736. // Add register mask from call node
  737. Ops.push_back(*RegMaskIt);
  738. // Add chain
  739. Ops.push_back(Chain);
  740. // Same for the glue, but we add it only if original call had it
  741. if (Glue.getNode())
  742. Ops.push_back(Glue);
  743. // Compute return values. Provide a glue output since we consume one as
  744. // input. This allows someone else to chain off us as needed.
  745. SmallVector<EVT, 8> NodeTys;
  746. for (auto SD : LoweredGCArgs) {
  747. if (!LowerAsVReg.count(SD))
  748. continue;
  749. NodeTys.push_back(SD.getValueType());
  750. }
  751. LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
  752. assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
  753. NodeTys.push_back(MVT::Other);
  754. NodeTys.push_back(MVT::Glue);
  755. unsigned NumResults = NodeTys.size();
  756. MachineSDNode *StatepointMCNode =
  757. DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
  758. DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
  759. // For values lowered to tied-defs, create the virtual registers. Note that
  760. // for simplicity, we *always* create a vreg even within a single block.
  761. DenseMap<SDValue, Register> VirtRegs;
  762. for (const auto *Relocate : SI.GCRelocates) {
  763. Value *Derived = Relocate->getDerivedPtr();
  764. SDValue SD = getValue(Derived);
  765. if (!LowerAsVReg.count(SD))
  766. continue;
  767. // Handle multiple gc.relocates of the same input efficiently.
  768. if (VirtRegs.count(SD))
  769. continue;
  770. SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
  771. auto *RetTy = Relocate->getType();
  772. Register Reg = FuncInfo.CreateRegs(RetTy);
  773. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  774. DAG.getDataLayout(), Reg, RetTy, None);
  775. SDValue Chain = DAG.getRoot();
  776. RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
  777. PendingExports.push_back(Chain);
  778. VirtRegs[SD] = Reg;
  779. }
  780. // Record for later use how each relocation was lowered. This is needed to
  781. // allow later gc.relocates to mirror the lowering chosen.
  782. const Instruction *StatepointInstr = SI.StatepointInstr;
  783. auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
  784. for (const GCRelocateInst *Relocate : SI.GCRelocates) {
  785. const Value *V = Relocate->getDerivedPtr();
  786. SDValue SDV = getValue(V);
  787. SDValue Loc = StatepointLowering.getLocation(SDV);
  788. RecordType Record;
  789. if (LowerAsVReg.count(SDV)) {
  790. Record.type = RecordType::VReg;
  791. assert(VirtRegs.count(SDV));
  792. Record.payload.Reg = VirtRegs[SDV];
  793. } else if (Loc.getNode()) {
  794. Record.type = RecordType::Spill;
  795. Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
  796. } else {
  797. Record.type = RecordType::NoRelocate;
  798. // If we didn't relocate a value, we'll essentialy end up inserting an
  799. // additional use of the original value when lowering the gc.relocate.
  800. // We need to make sure the value is available at the new use, which
  801. // might be in another block.
  802. if (Relocate->getParent() != StatepointInstr->getParent())
  803. ExportFromCurrentBlock(V);
  804. }
  805. RelocationMap[V] = Record;
  806. }
  807. SDNode *SinkNode = StatepointMCNode;
  808. // Build the GC_TRANSITION_END node if necessary.
  809. //
  810. // See the comment above regarding GC_TRANSITION_START for the layout of
  811. // the operands to the GC_TRANSITION_END node.
  812. if (IsGCTransition) {
  813. SmallVector<SDValue, 8> TEOps;
  814. // Add chain
  815. TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
  816. // Add GC transition arguments
  817. for (const Value *V : SI.GCTransitionArgs) {
  818. TEOps.push_back(getValue(V));
  819. if (V->getType()->isPointerTy())
  820. TEOps.push_back(DAG.getSrcValue(V));
  821. }
  822. // Add glue
  823. TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
  824. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  825. SDValue GCTransitionStart =
  826. DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
  827. SinkNode = GCTransitionStart.getNode();
  828. }
  829. // Replace original call
  830. // Call: ch,glue = CALL ...
  831. // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
  832. unsigned NumSinkValues = SinkNode->getNumValues();
  833. SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
  834. SDValue(SinkNode, NumSinkValues - 1)};
  835. DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
  836. // Remove original call node
  837. DAG.DeleteNode(CallNode);
  838. // Since we always emit CopyToRegs (even for local relocates), we must
  839. // update root, so that they are emitted before any local uses.
  840. (void)getControlRoot();
  841. // TODO: A better future implementation would be to emit a single variable
  842. // argument, variable return value STATEPOINT node here and then hookup the
  843. // return value of each gc.relocate to the respective output of the
  844. // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
  845. // to actually be possible today.
  846. return ReturnVal;
  847. }
  848. /// Return two gc.results if present. First result is a block local
  849. /// gc.result, second result is a non-block local gc.result. Corresponding
  850. /// entry will be nullptr if not present.
  851. static std::pair<const GCResultInst*, const GCResultInst*>
  852. getGCResultLocality(const GCStatepointInst &S) {
  853. std::pair<const GCResultInst *, const GCResultInst*> Res(nullptr, nullptr);
  854. for (auto *U : S.users()) {
  855. auto *GRI = dyn_cast<GCResultInst>(U);
  856. if (!GRI)
  857. continue;
  858. if (GRI->getParent() == S.getParent())
  859. Res.first = GRI;
  860. else
  861. Res.second = GRI;
  862. }
  863. return Res;
  864. }
  865. void
  866. SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
  867. const BasicBlock *EHPadBB /*= nullptr*/) {
  868. assert(I.getCallingConv() != CallingConv::AnyReg &&
  869. "anyregcc is not supported on statepoints!");
  870. #ifndef NDEBUG
  871. // Check that the associated GCStrategy expects to encounter statepoints.
  872. assert(GFI->getStrategy().useStatepoints() &&
  873. "GCStrategy does not expect to encounter statepoints");
  874. #endif
  875. SDValue ActualCallee;
  876. SDValue Callee = getValue(I.getActualCalledOperand());
  877. if (I.getNumPatchBytes() > 0) {
  878. // If we've been asked to emit a nop sequence instead of a call instruction
  879. // for this statepoint then don't lower the call target, but use a constant
  880. // `undef` instead. Not lowering the call target lets statepoint clients
  881. // get away without providing a physical address for the symbolic call
  882. // target at link time.
  883. ActualCallee = DAG.getUNDEF(Callee.getValueType());
  884. } else {
  885. ActualCallee = Callee;
  886. }
  887. StatepointLoweringInfo SI(DAG);
  888. populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
  889. I.getNumCallArgs(), ActualCallee,
  890. I.getActualReturnType(), false /* IsPatchPoint */);
  891. // There may be duplication in the gc.relocate list; such as two copies of
  892. // each relocation on normal and exceptional path for an invoke. We only
  893. // need to spill once and record one copy in the stackmap, but we need to
  894. // reload once per gc.relocate. (Dedupping gc.relocates is trickier and best
  895. // handled as a CSE problem elsewhere.)
  896. // TODO: There a couple of major stackmap size optimizations we could do
  897. // here if we wished.
  898. // 1) If we've encountered a derived pair {B, D}, we don't need to actually
  899. // record {B,B} if it's seen later.
  900. // 2) Due to rematerialization, actual derived pointers are somewhat rare;
  901. // given that, we could change the format to record base pointer relocations
  902. // separately with half the space. This would require a format rev and a
  903. // fairly major rework of the STATEPOINT node though.
  904. SmallSet<SDValue, 8> Seen;
  905. for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
  906. SI.GCRelocates.push_back(Relocate);
  907. SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
  908. if (Seen.insert(DerivedSD).second) {
  909. SI.Bases.push_back(Relocate->getBasePtr());
  910. SI.Ptrs.push_back(Relocate->getDerivedPtr());
  911. }
  912. }
  913. // If we find a deopt value which isn't explicitly added, we need to
  914. // ensure it gets lowered such that gc cycles occurring before the
  915. // deoptimization event during the lifetime of the call don't invalidate
  916. // the pointer we're deopting with. Note that we assume that all
  917. // pointers passed to deopt are base pointers; relaxing that assumption
  918. // would require relatively large changes to how we represent relocations.
  919. for (Value *V : I.deopt_operands()) {
  920. if (!isGCValue(V, *this))
  921. continue;
  922. if (Seen.insert(getValue(V)).second) {
  923. SI.Bases.push_back(V);
  924. SI.Ptrs.push_back(V);
  925. }
  926. }
  927. SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
  928. SI.StatepointInstr = &I;
  929. SI.ID = I.getID();
  930. SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
  931. SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
  932. I.gc_transition_args_end());
  933. SI.StatepointFlags = I.getFlags();
  934. SI.NumPatchBytes = I.getNumPatchBytes();
  935. SI.EHPadBB = EHPadBB;
  936. SDValue ReturnValue = LowerAsSTATEPOINT(SI);
  937. // Export the result value if needed
  938. const auto GCResultLocality = getGCResultLocality(I);
  939. if (!GCResultLocality.first && !GCResultLocality.second) {
  940. // The return value is not needed, just generate a poison value.
  941. // Note: This covers the void return case.
  942. setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
  943. return;
  944. }
  945. if (GCResultLocality.first) {
  946. // Result value will be used in a same basic block. Don't export it or
  947. // perform any explicit register copies. The gc_result will simply grab
  948. // this value.
  949. setValue(&I, ReturnValue);
  950. }
  951. if (!GCResultLocality.second)
  952. return;
  953. // Result value will be used in a different basic block so we need to export
  954. // it now. Default exporting mechanism will not work here because statepoint
  955. // call has a different type than the actual call. It means that by default
  956. // llvm will create export register of the wrong type (always i32 in our
  957. // case). So instead we need to create export register with correct type
  958. // manually.
  959. // TODO: To eliminate this problem we can remove gc.result intrinsics
  960. // completely and make statepoint call to return a tuple.
  961. Type *RetTy = GCResultLocality.second->getType();
  962. unsigned Reg = FuncInfo.CreateRegs(RetTy);
  963. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  964. DAG.getDataLayout(), Reg, RetTy,
  965. I.getCallingConv());
  966. SDValue Chain = DAG.getEntryNode();
  967. RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
  968. PendingExports.push_back(Chain);
  969. FuncInfo.ValueMap[&I] = Reg;
  970. }
  971. void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
  972. const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
  973. bool VarArgDisallowed, bool ForceVoidReturnTy) {
  974. StatepointLoweringInfo SI(DAG);
  975. unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
  976. populateCallLoweringInfo(
  977. SI.CLI, Call, ArgBeginIndex, Call->arg_size(), Callee,
  978. ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
  979. false);
  980. if (!VarArgDisallowed)
  981. SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
  982. auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
  983. unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
  984. auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
  985. SI.ID = SD.StatepointID.getValueOr(DefaultID);
  986. SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
  987. SI.DeoptState =
  988. ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
  989. SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
  990. SI.EHPadBB = EHPadBB;
  991. // NB! The GC arguments are deliberately left empty.
  992. if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
  993. ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
  994. setValue(Call, ReturnVal);
  995. }
  996. }
  997. void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
  998. const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
  999. LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
  1000. /* VarArgDisallowed = */ false,
  1001. /* ForceVoidReturnTy = */ false);
  1002. }
  1003. void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
  1004. // The result value of the gc_result is simply the result of the actual
  1005. // call. We've already emitted this, so just grab the value.
  1006. const GCStatepointInst *SI = CI.getStatepoint();
  1007. if (SI->getParent() == CI.getParent()) {
  1008. setValue(&CI, getValue(SI));
  1009. return;
  1010. }
  1011. // Statepoint is in different basic block so we should have stored call
  1012. // result in a virtual register.
  1013. // We can not use default getValue() functionality to copy value from this
  1014. // register because statepoint and actual call return types can be
  1015. // different, and getValue() will use CopyFromReg of the wrong type,
  1016. // which is always i32 in our case.
  1017. Type *RetTy = CI.getType();
  1018. SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
  1019. assert(CopyFromReg.getNode());
  1020. setValue(&CI, CopyFromReg);
  1021. }
  1022. void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
  1023. #ifndef NDEBUG
  1024. // Consistency check
  1025. // We skip this check for relocates not in the same basic block as their
  1026. // statepoint. It would be too expensive to preserve validation info through
  1027. // different basic blocks.
  1028. if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
  1029. StatepointLowering.relocCallVisited(Relocate);
  1030. auto *Ty = Relocate.getType()->getScalarType();
  1031. if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
  1032. assert(*IsManaged && "Non gc managed pointer relocated!");
  1033. #endif
  1034. const Value *DerivedPtr = Relocate.getDerivedPtr();
  1035. auto &RelocationMap =
  1036. FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
  1037. auto SlotIt = RelocationMap.find(DerivedPtr);
  1038. assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value");
  1039. const RecordType &Record = SlotIt->second;
  1040. // If relocation was done via virtual register..
  1041. if (Record.type == RecordType::VReg) {
  1042. Register InReg = Record.payload.Reg;
  1043. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1044. DAG.getDataLayout(), InReg, Relocate.getType(),
  1045. None); // This is not an ABI copy.
  1046. // We generate copy to/from regs even for local uses, hence we must
  1047. // chain with current root to ensure proper ordering of copies w.r.t.
  1048. // statepoint.
  1049. SDValue Chain = DAG.getRoot();
  1050. SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  1051. Chain, nullptr, nullptr);
  1052. setValue(&Relocate, Relocation);
  1053. return;
  1054. }
  1055. if (Record.type == RecordType::Spill) {
  1056. unsigned Index = Record.payload.FI;
  1057. SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
  1058. // All the reloads are independent and are reading memory only modified by
  1059. // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
  1060. // this this let's CSE kick in for free and allows reordering of
  1061. // instructions if possible. The lowering for statepoint sets the root,
  1062. // so this is ordering all reloads with the either
  1063. // a) the statepoint node itself, or
  1064. // b) the entry of the current block for an invoke statepoint.
  1065. const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
  1066. auto &MF = DAG.getMachineFunction();
  1067. auto &MFI = MF.getFrameInfo();
  1068. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
  1069. auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
  1070. MFI.getObjectSize(Index),
  1071. MFI.getObjectAlign(Index));
  1072. auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  1073. Relocate.getType());
  1074. SDValue SpillLoad =
  1075. DAG.getLoad(LoadVT, getCurSDLoc(), Chain, SpillSlot, LoadMMO);
  1076. PendingLoads.push_back(SpillLoad.getValue(1));
  1077. assert(SpillLoad.getNode());
  1078. setValue(&Relocate, SpillLoad);
  1079. return;
  1080. }
  1081. assert(Record.type == RecordType::NoRelocate);
  1082. SDValue SD = getValue(DerivedPtr);
  1083. if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
  1084. // Lowering relocate(undef) as arbitrary constant. Current constant value
  1085. // is chosen such that it's unlikely to be a valid pointer.
  1086. setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
  1087. return;
  1088. }
  1089. // We didn't need to spill these special cases (constants and allocas).
  1090. // See the handling in spillIncomingValueForStatepoint for detail.
  1091. setValue(&Relocate, SD);
  1092. }
  1093. void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
  1094. const auto &TLI = DAG.getTargetLoweringInfo();
  1095. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
  1096. TLI.getPointerTy(DAG.getDataLayout()));
  1097. // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
  1098. // call. We also do not lower the return value to any virtual register, and
  1099. // change the immediately following return to a trap instruction.
  1100. LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
  1101. /* VarArgDisallowed = */ true,
  1102. /* ForceVoidReturnTy = */ true);
  1103. }
  1104. void SelectionDAGBuilder::LowerDeoptimizingReturn() {
  1105. // We do not lower the return value from llvm.deoptimize to any virtual
  1106. // register, and change the immediately following return to a trap
  1107. // instruction.
  1108. if (DAG.getTarget().Options.TrapUnreachable)
  1109. DAG.setRoot(
  1110. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  1111. }