StatepointLowering.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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/DenseMap.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  23. #include "llvm/CodeGen/GCMetadata.h"
  24. #include "llvm/CodeGen/GCStrategy.h"
  25. #include "llvm/CodeGen/ISDOpcodes.h"
  26. #include "llvm/CodeGen/MachineFrameInfo.h"
  27. #include "llvm/CodeGen/MachineFunction.h"
  28. #include "llvm/CodeGen/MachineMemOperand.h"
  29. #include "llvm/CodeGen/RuntimeLibcalls.h"
  30. #include "llvm/CodeGen/SelectionDAG.h"
  31. #include "llvm/CodeGen/SelectionDAGNodes.h"
  32. #include "llvm/CodeGen/StackMaps.h"
  33. #include "llvm/CodeGen/TargetLowering.h"
  34. #include "llvm/CodeGen/TargetOpcodes.h"
  35. #include "llvm/IR/CallingConv.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Instruction.h"
  38. #include "llvm/IR/Instructions.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/Statepoint.h"
  41. #include "llvm/IR/Type.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/MachineValueType.h"
  44. #include "llvm/Target/TargetMachine.h"
  45. #include "llvm/Target/TargetOptions.h"
  46. #include <cassert>
  47. #include <cstddef>
  48. #include <cstdint>
  49. #include <iterator>
  50. #include <tuple>
  51. #include <utility>
  52. using namespace llvm;
  53. #define DEBUG_TYPE "statepoint-lowering"
  54. STATISTIC(NumSlotsAllocatedForStatepoints,
  55. "Number of stack slots allocated for statepoints");
  56. STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
  57. STATISTIC(StatepointMaxSlotsRequired,
  58. "Maximum number of stack slots required for a singe statepoint");
  59. static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
  60. SelectionDAGBuilder &Builder, uint64_t Value) {
  61. SDLoc L = Builder.getCurSDLoc();
  62. Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
  63. MVT::i64));
  64. Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
  65. }
  66. void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
  67. // Consistency check
  68. assert(PendingGCRelocateCalls.empty() &&
  69. "Trying to visit statepoint before finished processing previous one");
  70. Locations.clear();
  71. NextSlotToAllocate = 0;
  72. // Need to resize this on each safepoint - we need the two to stay in sync and
  73. // the clear patterns of a SelectionDAGBuilder have no relation to
  74. // FunctionLoweringInfo. Also need to ensure used bits get cleared.
  75. AllocatedStackSlots.clear();
  76. AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
  77. }
  78. void StatepointLoweringState::clear() {
  79. Locations.clear();
  80. AllocatedStackSlots.clear();
  81. assert(PendingGCRelocateCalls.empty() &&
  82. "cleared before statepoint sequence completed");
  83. }
  84. SDValue
  85. StatepointLoweringState::allocateStackSlot(EVT ValueType,
  86. SelectionDAGBuilder &Builder) {
  87. NumSlotsAllocatedForStatepoints++;
  88. MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
  89. unsigned SpillSize = ValueType.getStoreSize();
  90. assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
  91. // First look for a previously created stack slot which is not in
  92. // use (accounting for the fact arbitrary slots may already be
  93. // reserved), or to create a new stack slot and use it.
  94. const size_t NumSlots = AllocatedStackSlots.size();
  95. assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
  96. assert(AllocatedStackSlots.size() ==
  97. Builder.FuncInfo.StatepointStackSlots.size() &&
  98. "Broken invariant");
  99. for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
  100. if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
  101. const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
  102. if (MFI.getObjectSize(FI) == SpillSize) {
  103. AllocatedStackSlots.set(NextSlotToAllocate);
  104. // TODO: Is ValueType the right thing to use here?
  105. return Builder.DAG.getFrameIndex(FI, ValueType);
  106. }
  107. }
  108. }
  109. // Couldn't find a free slot, so create a new one:
  110. SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
  111. const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
  112. MFI.markAsStatepointSpillSlotObjectIndex(FI);
  113. Builder.FuncInfo.StatepointStackSlots.push_back(FI);
  114. AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
  115. assert(AllocatedStackSlots.size() ==
  116. Builder.FuncInfo.StatepointStackSlots.size() &&
  117. "Broken invariant");
  118. StatepointMaxSlotsRequired.updateMax(
  119. Builder.FuncInfo.StatepointStackSlots.size());
  120. return SpillSlot;
  121. }
  122. /// Utility function for reservePreviousStackSlotForValue. Tries to find
  123. /// stack slot index to which we have spilled value for previous statepoints.
  124. /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
  125. static Optional<int> findPreviousSpillSlot(const Value *Val,
  126. SelectionDAGBuilder &Builder,
  127. int LookUpDepth) {
  128. // Can not look any further - give up now
  129. if (LookUpDepth <= 0)
  130. return None;
  131. // Spill location is known for gc relocates
  132. if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
  133. const auto &SpillMap =
  134. Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
  135. auto It = SpillMap.find(Relocate->getDerivedPtr());
  136. if (It == SpillMap.end())
  137. return None;
  138. return It->second;
  139. }
  140. // Look through bitcast instructions.
  141. if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
  142. return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
  143. // Look through phi nodes
  144. // All incoming values should have same known stack slot, otherwise result
  145. // is unknown.
  146. if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
  147. Optional<int> MergedResult = None;
  148. for (auto &IncomingValue : Phi->incoming_values()) {
  149. Optional<int> SpillSlot =
  150. findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
  151. if (!SpillSlot.hasValue())
  152. return None;
  153. if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
  154. return None;
  155. MergedResult = SpillSlot;
  156. }
  157. return MergedResult;
  158. }
  159. // TODO: We can do better for PHI nodes. In cases like this:
  160. // ptr = phi(relocated_pointer, not_relocated_pointer)
  161. // statepoint(ptr)
  162. // We will return that stack slot for ptr is unknown. And later we might
  163. // assign different stack slots for ptr and relocated_pointer. This limits
  164. // llvm's ability to remove redundant stores.
  165. // Unfortunately it's hard to accomplish in current infrastructure.
  166. // We use this function to eliminate spill store completely, while
  167. // in example we still need to emit store, but instead of any location
  168. // we need to use special "preferred" location.
  169. // TODO: handle simple updates. If a value is modified and the original
  170. // value is no longer live, it would be nice to put the modified value in the
  171. // same slot. This allows folding of the memory accesses for some
  172. // instructions types (like an increment).
  173. // statepoint (i)
  174. // i1 = i+1
  175. // statepoint (i1)
  176. // However we need to be careful for cases like this:
  177. // statepoint(i)
  178. // i1 = i+1
  179. // statepoint(i, i1)
  180. // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
  181. // put handling of simple modifications in this function like it's done
  182. // for bitcasts we might end up reserving i's slot for 'i+1' because order in
  183. // which we visit values is unspecified.
  184. // Don't know any information about this instruction
  185. return None;
  186. }
  187. /// Try to find existing copies of the incoming values in stack slots used for
  188. /// statepoint spilling. If we can find a spill slot for the incoming value,
  189. /// mark that slot as allocated, and reuse the same slot for this safepoint.
  190. /// This helps to avoid series of loads and stores that only serve to reshuffle
  191. /// values on the stack between calls.
  192. static void reservePreviousStackSlotForValue(const Value *IncomingValue,
  193. SelectionDAGBuilder &Builder) {
  194. SDValue Incoming = Builder.getValue(IncomingValue);
  195. if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
  196. // We won't need to spill this, so no need to check for previously
  197. // allocated stack slots
  198. return;
  199. }
  200. SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
  201. if (OldLocation.getNode())
  202. // Duplicates in input
  203. return;
  204. const int LookUpDepth = 6;
  205. Optional<int> Index =
  206. findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
  207. if (!Index.hasValue())
  208. return;
  209. const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
  210. auto SlotIt = find(StatepointSlots, *Index);
  211. assert(SlotIt != StatepointSlots.end() &&
  212. "Value spilled to the unknown stack slot");
  213. // This is one of our dedicated lowering slots
  214. const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
  215. if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
  216. // stack slot already assigned to someone else, can't use it!
  217. // TODO: currently we reserve space for gc arguments after doing
  218. // normal allocation for deopt arguments. We should reserve for
  219. // _all_ deopt and gc arguments, then start allocating. This
  220. // will prevent some moves being inserted when vm state changes,
  221. // but gc state doesn't between two calls.
  222. return;
  223. }
  224. // Reserve this stack slot
  225. Builder.StatepointLowering.reserveStackSlot(Offset);
  226. // Cache this slot so we find it when going through the normal
  227. // assignment loop.
  228. SDValue Loc =
  229. Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
  230. Builder.StatepointLowering.setLocation(Incoming, Loc);
  231. }
  232. /// Remove any duplicate (as SDValues) from the derived pointer pairs. This
  233. /// is not required for correctness. It's purpose is to reduce the size of
  234. /// StackMap section. It has no effect on the number of spill slots required
  235. /// or the actual lowering.
  236. static void
  237. removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
  238. SmallVectorImpl<const Value *> &Ptrs,
  239. SmallVectorImpl<const GCRelocateInst *> &Relocs,
  240. SelectionDAGBuilder &Builder,
  241. FunctionLoweringInfo::StatepointSpillMap &SSM) {
  242. DenseMap<SDValue, const Value *> Seen;
  243. SmallVector<const Value *, 64> NewBases, NewPtrs;
  244. SmallVector<const GCRelocateInst *, 64> NewRelocs;
  245. for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
  246. SDValue SD = Builder.getValue(Ptrs[i]);
  247. auto SeenIt = Seen.find(SD);
  248. if (SeenIt == Seen.end()) {
  249. // Only add non-duplicates
  250. NewBases.push_back(Bases[i]);
  251. NewPtrs.push_back(Ptrs[i]);
  252. NewRelocs.push_back(Relocs[i]);
  253. Seen[SD] = Ptrs[i];
  254. } else {
  255. // Duplicate pointer found, note in SSM and move on:
  256. SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
  257. }
  258. }
  259. assert(Bases.size() >= NewBases.size());
  260. assert(Ptrs.size() >= NewPtrs.size());
  261. assert(Relocs.size() >= NewRelocs.size());
  262. Bases = NewBases;
  263. Ptrs = NewPtrs;
  264. Relocs = NewRelocs;
  265. assert(Ptrs.size() == Bases.size());
  266. assert(Ptrs.size() == Relocs.size());
  267. }
  268. /// Extract call from statepoint, lower it and return pointer to the
  269. /// call node. Also update NodeMap so that getValue(statepoint) will
  270. /// reference lowered call result
  271. static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
  272. SelectionDAGBuilder::StatepointLoweringInfo &SI,
  273. SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
  274. SDValue ReturnValue, CallEndVal;
  275. std::tie(ReturnValue, CallEndVal) =
  276. Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
  277. SDNode *CallEnd = CallEndVal.getNode();
  278. // Get a call instruction from the call sequence chain. Tail calls are not
  279. // allowed. The following code is essentially reverse engineering X86's
  280. // LowerCallTo.
  281. //
  282. // We are expecting DAG to have the following form:
  283. //
  284. // ch = eh_label (only in case of invoke statepoint)
  285. // ch, glue = callseq_start ch
  286. // ch, glue = X86::Call ch, glue
  287. // ch, glue = callseq_end ch, glue
  288. // get_return_value ch, glue
  289. //
  290. // get_return_value can either be a sequence of CopyFromReg instructions
  291. // to grab the return value from the return register(s), or it can be a LOAD
  292. // to load a value returned by reference via a stack slot.
  293. bool HasDef = !SI.CLI.RetTy->isVoidTy();
  294. if (HasDef) {
  295. if (CallEnd->getOpcode() == ISD::LOAD)
  296. CallEnd = CallEnd->getOperand(0).getNode();
  297. else
  298. while (CallEnd->getOpcode() == ISD::CopyFromReg)
  299. CallEnd = CallEnd->getOperand(0).getNode();
  300. }
  301. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
  302. return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
  303. }
  304. static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
  305. FrameIndexSDNode &FI) {
  306. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
  307. auto MMOFlags = MachineMemOperand::MOStore |
  308. MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  309. auto &MFI = MF.getFrameInfo();
  310. return MF.getMachineMemOperand(PtrInfo, MMOFlags,
  311. MFI.getObjectSize(FI.getIndex()),
  312. MFI.getObjectAlignment(FI.getIndex()));
  313. }
  314. /// Spill a value incoming to the statepoint. It might be either part of
  315. /// vmstate
  316. /// or gcstate. In both cases unconditionally spill it on the stack unless it
  317. /// is a null constant. Return pair with first element being frame index
  318. /// containing saved value and second element with outgoing chain from the
  319. /// emitted store
  320. static std::tuple<SDValue, SDValue, MachineMemOperand*>
  321. spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
  322. SelectionDAGBuilder &Builder) {
  323. SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
  324. MachineMemOperand* MMO = nullptr;
  325. // Emit new store if we didn't do it for this ptr before
  326. if (!Loc.getNode()) {
  327. Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
  328. Builder);
  329. int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
  330. // We use TargetFrameIndex so that isel will not select it into LEA
  331. Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
  332. // Right now we always allocate spill slots that are of the same
  333. // size as the value we're about to spill (the size of spillee can
  334. // vary since we spill vectors of pointers too). At some point we
  335. // can consider allowing spills of smaller values to larger slots
  336. // (i.e. change the '==' in the assert below to a '>=').
  337. MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
  338. assert((MFI.getObjectSize(Index) * 8) == Incoming.getValueSizeInBits() &&
  339. "Bad spill: stack slot does not match!");
  340. // Note: Using the alignment of the spill slot (rather than the abi or
  341. // preferred alignment) is required for correctness when dealing with spill
  342. // slots with preferred alignments larger than frame alignment..
  343. auto &MF = Builder.DAG.getMachineFunction();
  344. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
  345. auto *StoreMMO =
  346. MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
  347. MFI.getObjectSize(Index),
  348. MFI.getObjectAlignment(Index));
  349. Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
  350. StoreMMO);
  351. MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
  352. Builder.StatepointLowering.setLocation(Incoming, Loc);
  353. }
  354. assert(Loc.getNode());
  355. return std::make_tuple(Loc, Chain, MMO);
  356. }
  357. /// Lower a single value incoming to a statepoint node. This value can be
  358. /// either a deopt value or a gc value, the handling is the same. We special
  359. /// case constants and allocas, then fall back to spilling if required.
  360. static void lowerIncomingStatepointValue(SDValue Incoming, bool LiveInOnly,
  361. SmallVectorImpl<SDValue> &Ops,
  362. SmallVectorImpl<MachineMemOperand*> &MemRefs,
  363. SelectionDAGBuilder &Builder) {
  364. // Note: We know all of these spills are independent, but don't bother to
  365. // exploit that chain wise. DAGCombine will happily do so as needed, so
  366. // doing it here would be a small compile time win at most.
  367. SDValue Chain = Builder.getRoot();
  368. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
  369. // If the original value was a constant, make sure it gets recorded as
  370. // such in the stackmap. This is required so that the consumer can
  371. // parse any internal format to the deopt state. It also handles null
  372. // pointers and other constant pointers in GC states. Note the constant
  373. // vectors do not appear to actually hit this path and that anything larger
  374. // than an i64 value (not type!) will fail asserts here.
  375. pushStackMapConstant(Ops, Builder, C->getSExtValue());
  376. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
  377. // This handles allocas as arguments to the statepoint (this is only
  378. // really meaningful for a deopt value. For GC, we'd be trying to
  379. // relocate the address of the alloca itself?)
  380. assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
  381. "Incoming value is a frame index!");
  382. Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
  383. Builder.getFrameIndexTy()));
  384. auto &MF = Builder.DAG.getMachineFunction();
  385. auto *MMO = getMachineMemOperand(MF, *FI);
  386. MemRefs.push_back(MMO);
  387. } else if (LiveInOnly) {
  388. // If this value is live in (not live-on-return, or live-through), we can
  389. // treat it the same way patchpoint treats it's "live in" values. We'll
  390. // end up folding some of these into stack references, but they'll be
  391. // handled by the register allocator. Note that we do not have the notion
  392. // of a late use so these values might be placed in registers which are
  393. // clobbered by the call. This is fine for live-in.
  394. Ops.push_back(Incoming);
  395. } else {
  396. // Otherwise, locate a spill slot and explicitly spill it so it
  397. // can be found by the runtime later. We currently do not support
  398. // tracking values through callee saved registers to their eventual
  399. // spill location. This would be a useful optimization, but would
  400. // need to be optional since it requires a lot of complexity on the
  401. // runtime side which not all would support.
  402. auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
  403. Ops.push_back(std::get<0>(Res));
  404. if (auto *MMO = std::get<2>(Res))
  405. MemRefs.push_back(MMO);
  406. Chain = std::get<1>(Res);;
  407. }
  408. Builder.DAG.setRoot(Chain);
  409. }
  410. /// Lower deopt state and gc pointer arguments of the statepoint. The actual
  411. /// lowering is described in lowerIncomingStatepointValue. This function is
  412. /// responsible for lowering everything in the right position and playing some
  413. /// tricks to avoid redundant stack manipulation where possible. On
  414. /// completion, 'Ops' will contain ready to use operands for machine code
  415. /// statepoint. The chain nodes will have already been created and the DAG root
  416. /// will be set to the last value spilled (if any were).
  417. static void
  418. lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
  419. SmallVectorImpl<MachineMemOperand*> &MemRefs, SelectionDAGBuilder::StatepointLoweringInfo &SI,
  420. SelectionDAGBuilder &Builder) {
  421. // Lower the deopt and gc arguments for this statepoint. Layout will be:
  422. // deopt argument length, deopt arguments.., gc arguments...
  423. #ifndef NDEBUG
  424. if (auto *GFI = Builder.GFI) {
  425. // Check that each of the gc pointer and bases we've gotten out of the
  426. // safepoint is something the strategy thinks might be a pointer (or vector
  427. // of pointers) into the GC heap. This is basically just here to help catch
  428. // errors during statepoint insertion. TODO: This should actually be in the
  429. // Verifier, but we can't get to the GCStrategy from there (yet).
  430. GCStrategy &S = GFI->getStrategy();
  431. for (const Value *V : SI.Bases) {
  432. auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
  433. if (Opt.hasValue()) {
  434. assert(Opt.getValue() &&
  435. "non gc managed base pointer found in statepoint");
  436. }
  437. }
  438. for (const Value *V : SI.Ptrs) {
  439. auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
  440. if (Opt.hasValue()) {
  441. assert(Opt.getValue() &&
  442. "non gc managed derived pointer found in statepoint");
  443. }
  444. }
  445. assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
  446. } else {
  447. assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
  448. assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
  449. }
  450. #endif
  451. // Figure out what lowering strategy we're going to use for each part
  452. // Note: Is is conservatively correct to lower both "live-in" and "live-out"
  453. // as "live-through". A "live-through" variable is one which is "live-in",
  454. // "live-out", and live throughout the lifetime of the call (i.e. we can find
  455. // it from any PC within the transitive callee of the statepoint). In
  456. // particular, if the callee spills callee preserved registers we may not
  457. // be able to find a value placed in that register during the call. This is
  458. // fine for live-out, but not for live-through. If we were willing to make
  459. // assumptions about the code generator producing the callee, we could
  460. // potentially allow live-through values in callee saved registers.
  461. const bool LiveInDeopt =
  462. SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
  463. auto isGCValue =[&](const Value *V) {
  464. return is_contained(SI.Ptrs, V) || is_contained(SI.Bases, V);
  465. };
  466. // Before we actually start lowering (and allocating spill slots for values),
  467. // reserve any stack slots which we judge to be profitable to reuse for a
  468. // particular value. This is purely an optimization over the code below and
  469. // doesn't change semantics at all. It is important for performance that we
  470. // reserve slots for both deopt and gc values before lowering either.
  471. for (const Value *V : SI.DeoptState) {
  472. if (!LiveInDeopt || isGCValue(V))
  473. reservePreviousStackSlotForValue(V, Builder);
  474. }
  475. for (unsigned i = 0; i < SI.Bases.size(); ++i) {
  476. reservePreviousStackSlotForValue(SI.Bases[i], Builder);
  477. reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
  478. }
  479. // First, prefix the list with the number of unique values to be
  480. // lowered. Note that this is the number of *Values* not the
  481. // number of SDValues required to lower them.
  482. const int NumVMSArgs = SI.DeoptState.size();
  483. pushStackMapConstant(Ops, Builder, NumVMSArgs);
  484. // The vm state arguments are lowered in an opaque manner. We do not know
  485. // what type of values are contained within.
  486. for (const Value *V : SI.DeoptState) {
  487. SDValue Incoming;
  488. // If this is a function argument at a static frame index, generate it as
  489. // the frame index.
  490. if (const Argument *Arg = dyn_cast<Argument>(V)) {
  491. int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
  492. if (FI != INT_MAX)
  493. Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
  494. }
  495. if (!Incoming.getNode())
  496. Incoming = Builder.getValue(V);
  497. const bool LiveInValue = LiveInDeopt && !isGCValue(V);
  498. lowerIncomingStatepointValue(Incoming, LiveInValue, Ops, MemRefs, Builder);
  499. }
  500. // Finally, go ahead and lower all the gc arguments. There's no prefixed
  501. // length for this one. After lowering, we'll have the base and pointer
  502. // arrays interwoven with each (lowered) base pointer immediately followed by
  503. // it's (lowered) derived pointer. i.e
  504. // (base[0], ptr[0], base[1], ptr[1], ...)
  505. for (unsigned i = 0; i < SI.Bases.size(); ++i) {
  506. const Value *Base = SI.Bases[i];
  507. lowerIncomingStatepointValue(Builder.getValue(Base), /*LiveInOnly*/ false,
  508. Ops, MemRefs, Builder);
  509. const Value *Ptr = SI.Ptrs[i];
  510. lowerIncomingStatepointValue(Builder.getValue(Ptr), /*LiveInOnly*/ false,
  511. Ops, MemRefs, Builder);
  512. }
  513. // If there are any explicit spill slots passed to the statepoint, record
  514. // them, but otherwise do not do anything special. These are user provided
  515. // allocas and give control over placement to the consumer. In this case,
  516. // it is the contents of the slot which may get updated, not the pointer to
  517. // the alloca
  518. for (Value *V : SI.GCArgs) {
  519. SDValue Incoming = Builder.getValue(V);
  520. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
  521. // This handles allocas as arguments to the statepoint
  522. assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
  523. "Incoming value is a frame index!");
  524. Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
  525. Builder.getFrameIndexTy()));
  526. auto &MF = Builder.DAG.getMachineFunction();
  527. auto *MMO = getMachineMemOperand(MF, *FI);
  528. MemRefs.push_back(MMO);
  529. }
  530. }
  531. // Record computed locations for all lowered values.
  532. // This can not be embedded in lowering loops as we need to record *all*
  533. // values, while previous loops account only values with unique SDValues.
  534. const Instruction *StatepointInstr = SI.StatepointInstr;
  535. auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
  536. for (const GCRelocateInst *Relocate : SI.GCRelocates) {
  537. const Value *V = Relocate->getDerivedPtr();
  538. SDValue SDV = Builder.getValue(V);
  539. SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
  540. if (Loc.getNode()) {
  541. SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
  542. } else {
  543. // Record value as visited, but not spilled. This is case for allocas
  544. // and constants. For this values we can avoid emitting spill load while
  545. // visiting corresponding gc_relocate.
  546. // Actually we do not need to record them in this map at all.
  547. // We do this only to check that we are not relocating any unvisited
  548. // value.
  549. SpillMap.SlotMap[V] = None;
  550. // Default llvm mechanisms for exporting values which are used in
  551. // different basic blocks does not work for gc relocates.
  552. // Note that it would be incorrect to teach llvm that all relocates are
  553. // uses of the corresponding values so that it would automatically
  554. // export them. Relocates of the spilled values does not use original
  555. // value.
  556. if (Relocate->getParent() != StatepointInstr->getParent())
  557. Builder.ExportFromCurrentBlock(V);
  558. }
  559. }
  560. }
  561. SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
  562. SelectionDAGBuilder::StatepointLoweringInfo &SI) {
  563. // The basic scheme here is that information about both the original call and
  564. // the safepoint is encoded in the CallInst. We create a temporary call and
  565. // lower it, then reverse engineer the calling sequence.
  566. NumOfStatepoints++;
  567. // Clear state
  568. StatepointLowering.startNewStatepoint(*this);
  569. #ifndef NDEBUG
  570. // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
  571. // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
  572. for (auto *Reloc : SI.GCRelocates)
  573. if (Reloc->getParent() == SI.StatepointInstr->getParent())
  574. StatepointLowering.scheduleRelocCall(*Reloc);
  575. #endif
  576. // Remove any redundant llvm::Values which map to the same SDValue as another
  577. // input. Also has the effect of removing duplicates in the original
  578. // llvm::Value input list as well. This is a useful optimization for
  579. // reducing the size of the StackMap section. It has no other impact.
  580. removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
  581. FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
  582. assert(SI.Bases.size() == SI.Ptrs.size() &&
  583. SI.Ptrs.size() == SI.GCRelocates.size());
  584. // Lower statepoint vmstate and gcstate arguments
  585. SmallVector<SDValue, 10> LoweredMetaArgs;
  586. SmallVector<MachineMemOperand*, 16> MemRefs;
  587. lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, SI, *this);
  588. // Now that we've emitted the spills, we need to update the root so that the
  589. // call sequence is ordered correctly.
  590. SI.CLI.setChain(getRoot());
  591. // Get call node, we will replace it later with statepoint
  592. SDValue ReturnVal;
  593. SDNode *CallNode;
  594. std::tie(ReturnVal, CallNode) =
  595. lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
  596. // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
  597. // nodes with all the appropriate arguments and return values.
  598. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  599. SDValue Chain = CallNode->getOperand(0);
  600. SDValue Glue;
  601. bool CallHasIncomingGlue = CallNode->getGluedNode();
  602. if (CallHasIncomingGlue) {
  603. // Glue is always last operand
  604. Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
  605. }
  606. // Build the GC_TRANSITION_START node if necessary.
  607. //
  608. // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
  609. // order in which they appear in the call to the statepoint intrinsic. If
  610. // any of the operands is a pointer-typed, that operand is immediately
  611. // followed by a SRCVALUE for the pointer that may be used during lowering
  612. // (e.g. to form MachinePointerInfo values for loads/stores).
  613. const bool IsGCTransition =
  614. (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
  615. (uint64_t)StatepointFlags::GCTransition;
  616. if (IsGCTransition) {
  617. SmallVector<SDValue, 8> TSOps;
  618. // Add chain
  619. TSOps.push_back(Chain);
  620. // Add GC transition arguments
  621. for (const Value *V : SI.GCTransitionArgs) {
  622. TSOps.push_back(getValue(V));
  623. if (V->getType()->isPointerTy())
  624. TSOps.push_back(DAG.getSrcValue(V));
  625. }
  626. // Add glue if necessary
  627. if (CallHasIncomingGlue)
  628. TSOps.push_back(Glue);
  629. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  630. SDValue GCTransitionStart =
  631. DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
  632. Chain = GCTransitionStart.getValue(0);
  633. Glue = GCTransitionStart.getValue(1);
  634. }
  635. // TODO: Currently, all of these operands are being marked as read/write in
  636. // PrologEpilougeInserter.cpp, we should special case the VMState arguments
  637. // and flags to be read-only.
  638. SmallVector<SDValue, 40> Ops;
  639. // Add the <id> and <numBytes> constants.
  640. Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
  641. Ops.push_back(
  642. DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
  643. // Calculate and push starting position of vmstate arguments
  644. // Get number of arguments incoming directly into call node
  645. unsigned NumCallRegArgs =
  646. CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
  647. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
  648. // Add call target
  649. SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
  650. Ops.push_back(CallTarget);
  651. // Add call arguments
  652. // Get position of register mask in the call
  653. SDNode::op_iterator RegMaskIt;
  654. if (CallHasIncomingGlue)
  655. RegMaskIt = CallNode->op_end() - 2;
  656. else
  657. RegMaskIt = CallNode->op_end() - 1;
  658. Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
  659. // Add a constant argument for the calling convention
  660. pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
  661. // Add a constant argument for the flags
  662. uint64_t Flags = SI.StatepointFlags;
  663. assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
  664. "Unknown flag used");
  665. pushStackMapConstant(Ops, *this, Flags);
  666. // Insert all vmstate and gcstate arguments
  667. Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
  668. // Add register mask from call node
  669. Ops.push_back(*RegMaskIt);
  670. // Add chain
  671. Ops.push_back(Chain);
  672. // Same for the glue, but we add it only if original call had it
  673. if (Glue.getNode())
  674. Ops.push_back(Glue);
  675. // Compute return values. Provide a glue output since we consume one as
  676. // input. This allows someone else to chain off us as needed.
  677. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  678. MachineSDNode *StatepointMCNode =
  679. DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
  680. DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
  681. SDNode *SinkNode = StatepointMCNode;
  682. // Build the GC_TRANSITION_END node if necessary.
  683. //
  684. // See the comment above regarding GC_TRANSITION_START for the layout of
  685. // the operands to the GC_TRANSITION_END node.
  686. if (IsGCTransition) {
  687. SmallVector<SDValue, 8> TEOps;
  688. // Add chain
  689. TEOps.push_back(SDValue(StatepointMCNode, 0));
  690. // Add GC transition arguments
  691. for (const Value *V : SI.GCTransitionArgs) {
  692. TEOps.push_back(getValue(V));
  693. if (V->getType()->isPointerTy())
  694. TEOps.push_back(DAG.getSrcValue(V));
  695. }
  696. // Add glue
  697. TEOps.push_back(SDValue(StatepointMCNode, 1));
  698. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  699. SDValue GCTransitionStart =
  700. DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
  701. SinkNode = GCTransitionStart.getNode();
  702. }
  703. // Replace original call
  704. DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
  705. // Remove original call node
  706. DAG.DeleteNode(CallNode);
  707. // DON'T set the root - under the assumption that it's already set past the
  708. // inserted node we created.
  709. // TODO: A better future implementation would be to emit a single variable
  710. // argument, variable return value STATEPOINT node here and then hookup the
  711. // return value of each gc.relocate to the respective output of the
  712. // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
  713. // to actually be possible today.
  714. return ReturnVal;
  715. }
  716. void
  717. SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
  718. const BasicBlock *EHPadBB /*= nullptr*/) {
  719. assert(ISP.getCall()->getCallingConv() != CallingConv::AnyReg &&
  720. "anyregcc is not supported on statepoints!");
  721. #ifndef NDEBUG
  722. // If this is a malformed statepoint, report it early to simplify debugging.
  723. // This should catch any IR level mistake that's made when constructing or
  724. // transforming statepoints.
  725. ISP.verify();
  726. // Check that the associated GCStrategy expects to encounter statepoints.
  727. assert(GFI->getStrategy().useStatepoints() &&
  728. "GCStrategy does not expect to encounter statepoints");
  729. #endif
  730. SDValue ActualCallee;
  731. if (ISP.getNumPatchBytes() > 0) {
  732. // If we've been asked to emit a nop sequence instead of a call instruction
  733. // for this statepoint then don't lower the call target, but use a constant
  734. // `null` instead. Not lowering the call target lets statepoint clients get
  735. // away without providing a physical address for the symbolic call target at
  736. // link time.
  737. const auto &TLI = DAG.getTargetLoweringInfo();
  738. const auto &DL = DAG.getDataLayout();
  739. unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
  740. ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
  741. } else {
  742. ActualCallee = getValue(ISP.getCalledValue());
  743. }
  744. StatepointLoweringInfo SI(DAG);
  745. populateCallLoweringInfo(SI.CLI, ISP.getCall(),
  746. ImmutableStatepoint::CallArgsBeginPos,
  747. ISP.getNumCallArgs(), ActualCallee,
  748. ISP.getActualReturnType(), false /* IsPatchPoint */);
  749. for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
  750. SI.GCRelocates.push_back(Relocate);
  751. SI.Bases.push_back(Relocate->getBasePtr());
  752. SI.Ptrs.push_back(Relocate->getDerivedPtr());
  753. }
  754. SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
  755. SI.StatepointInstr = ISP.getInstruction();
  756. SI.GCTransitionArgs =
  757. ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
  758. SI.ID = ISP.getID();
  759. SI.DeoptState = ArrayRef<const Use>(ISP.deopt_begin(), ISP.deopt_end());
  760. SI.StatepointFlags = ISP.getFlags();
  761. SI.NumPatchBytes = ISP.getNumPatchBytes();
  762. SI.EHPadBB = EHPadBB;
  763. SDValue ReturnValue = LowerAsSTATEPOINT(SI);
  764. // Export the result value if needed
  765. const GCResultInst *GCResult = ISP.getGCResult();
  766. Type *RetTy = ISP.getActualReturnType();
  767. if (!RetTy->isVoidTy() && GCResult) {
  768. if (GCResult->getParent() != ISP.getCall()->getParent()) {
  769. // Result value will be used in a different basic block so we need to
  770. // export it now. Default exporting mechanism will not work here because
  771. // statepoint call has a different type than the actual call. It means
  772. // that by default llvm will create export register of the wrong type
  773. // (always i32 in our case). So instead we need to create export register
  774. // with correct type manually.
  775. // TODO: To eliminate this problem we can remove gc.result intrinsics
  776. // completely and make statepoint call to return a tuple.
  777. unsigned Reg = FuncInfo.CreateRegs(RetTy);
  778. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  779. DAG.getDataLayout(), Reg, RetTy,
  780. ISP.getCall()->getCallingConv());
  781. SDValue Chain = DAG.getEntryNode();
  782. RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
  783. PendingExports.push_back(Chain);
  784. FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
  785. } else {
  786. // Result value will be used in a same basic block. Don't export it or
  787. // perform any explicit register copies.
  788. // We'll replace the actuall call node shortly. gc_result will grab
  789. // this value.
  790. setValue(ISP.getInstruction(), ReturnValue);
  791. }
  792. } else {
  793. // The token value is never used from here on, just generate a poison value
  794. setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
  795. }
  796. }
  797. void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
  798. const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
  799. bool VarArgDisallowed, bool ForceVoidReturnTy) {
  800. StatepointLoweringInfo SI(DAG);
  801. unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
  802. populateCallLoweringInfo(
  803. SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
  804. ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
  805. false);
  806. if (!VarArgDisallowed)
  807. SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
  808. auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
  809. unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
  810. auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
  811. SI.ID = SD.StatepointID.getValueOr(DefaultID);
  812. SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
  813. SI.DeoptState =
  814. ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
  815. SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
  816. SI.EHPadBB = EHPadBB;
  817. // NB! The GC arguments are deliberately left empty.
  818. if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
  819. ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
  820. setValue(Call, ReturnVal);
  821. }
  822. }
  823. void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
  824. const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
  825. LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
  826. /* VarArgDisallowed = */ false,
  827. /* ForceVoidReturnTy = */ false);
  828. }
  829. void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
  830. // The result value of the gc_result is simply the result of the actual
  831. // call. We've already emitted this, so just grab the value.
  832. const Instruction *I = CI.getStatepoint();
  833. if (I->getParent() != CI.getParent()) {
  834. // Statepoint is in different basic block so we should have stored call
  835. // result in a virtual register.
  836. // We can not use default getValue() functionality to copy value from this
  837. // register because statepoint and actual call return types can be
  838. // different, and getValue() will use CopyFromReg of the wrong type,
  839. // which is always i32 in our case.
  840. PointerType *CalleeType = cast<PointerType>(
  841. ImmutableStatepoint(I).getCalledValue()->getType());
  842. Type *RetTy =
  843. cast<FunctionType>(CalleeType->getElementType())->getReturnType();
  844. SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
  845. assert(CopyFromReg.getNode());
  846. setValue(&CI, CopyFromReg);
  847. } else {
  848. setValue(&CI, getValue(I));
  849. }
  850. }
  851. void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
  852. #ifndef NDEBUG
  853. // Consistency check
  854. // We skip this check for relocates not in the same basic block as their
  855. // statepoint. It would be too expensive to preserve validation info through
  856. // different basic blocks.
  857. if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
  858. StatepointLowering.relocCallVisited(Relocate);
  859. auto *Ty = Relocate.getType()->getScalarType();
  860. if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
  861. assert(*IsManaged && "Non gc managed pointer relocated!");
  862. #endif
  863. const Value *DerivedPtr = Relocate.getDerivedPtr();
  864. SDValue SD = getValue(DerivedPtr);
  865. auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
  866. auto SlotIt = SpillMap.find(DerivedPtr);
  867. assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
  868. Optional<int> DerivedPtrLocation = SlotIt->second;
  869. // We didn't need to spill these special cases (constants and allocas).
  870. // See the handling in spillIncomingValueForStatepoint for detail.
  871. if (!DerivedPtrLocation) {
  872. setValue(&Relocate, SD);
  873. return;
  874. }
  875. unsigned Index = *DerivedPtrLocation;
  876. SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
  877. // Note: We know all of these reloads are independent, but don't bother to
  878. // exploit that chain wise. DAGCombine will happily do so as needed, so
  879. // doing it here would be a small compile time win at most.
  880. SDValue Chain = getRoot();
  881. auto &MF = DAG.getMachineFunction();
  882. auto &MFI = MF.getFrameInfo();
  883. auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
  884. auto *LoadMMO =
  885. MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
  886. MFI.getObjectSize(Index),
  887. MFI.getObjectAlignment(Index));
  888. auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  889. Relocate.getType());
  890. SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
  891. SpillSlot, LoadMMO);
  892. DAG.setRoot(SpillLoad.getValue(1));
  893. assert(SpillLoad.getNode());
  894. setValue(&Relocate, SpillLoad);
  895. }
  896. void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
  897. const auto &TLI = DAG.getTargetLoweringInfo();
  898. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
  899. TLI.getPointerTy(DAG.getDataLayout()));
  900. // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
  901. // call. We also do not lower the return value to any virtual register, and
  902. // change the immediately following return to a trap instruction.
  903. LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
  904. /* VarArgDisallowed = */ true,
  905. /* ForceVoidReturnTy = */ true);
  906. }
  907. void SelectionDAGBuilder::LowerDeoptimizingReturn() {
  908. // We do not lower the return value from llvm.deoptimize to any virtual
  909. // register, and change the immediately following return to a trap
  910. // instruction.
  911. if (DAG.getTarget().Options.TrapUnreachable)
  912. DAG.setRoot(
  913. DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  914. }