LegalizeTypes.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
  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 implements the SelectionDAG::LegalizeTypes method. It transforms
  10. // an arbitrary well-formed SelectionDAG to only consist of legal types. This
  11. // is common code shared among the LegalizeTypes*.cpp files.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "LegalizeTypes.h"
  15. #include "SDNodeDbgValue.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/CodeGen/MachineFunction.h"
  18. #include "llvm/IR/CallingConv.h"
  19. #include "llvm/IR/DataLayout.h"
  20. #include "llvm/Support/CommandLine.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace llvm;
  24. #define DEBUG_TYPE "legalize-types"
  25. static cl::opt<bool>
  26. EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
  27. /// Do extensive, expensive, sanity checking.
  28. void DAGTypeLegalizer::PerformExpensiveChecks() {
  29. // If a node is not processed, then none of its values should be mapped by any
  30. // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
  31. // If a node is processed, then each value with an illegal type must be mapped
  32. // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
  33. // Values with a legal type may be mapped by ReplacedValues, but not by any of
  34. // the other maps.
  35. // Note that these invariants may not hold momentarily when processing a node:
  36. // the node being processed may be put in a map before being marked Processed.
  37. // Note that it is possible to have nodes marked NewNode in the DAG. This can
  38. // occur in two ways. Firstly, a node may be created during legalization but
  39. // never passed to the legalization core. This is usually due to the implicit
  40. // folding that occurs when using the DAG.getNode operators. Secondly, a new
  41. // node may be passed to the legalization core, but when analyzed may morph
  42. // into a different node, leaving the original node as a NewNode in the DAG.
  43. // A node may morph if one of its operands changes during analysis. Whether
  44. // it actually morphs or not depends on whether, after updating its operands,
  45. // it is equivalent to an existing node: if so, it morphs into that existing
  46. // node (CSE). An operand can change during analysis if the operand is a new
  47. // node that morphs, or it is a processed value that was mapped to some other
  48. // value (as recorded in ReplacedValues) in which case the operand is turned
  49. // into that other value. If a node morphs then the node it morphed into will
  50. // be used instead of it for legalization, however the original node continues
  51. // to live on in the DAG.
  52. // The conclusion is that though there may be nodes marked NewNode in the DAG,
  53. // all uses of such nodes are also marked NewNode: the result is a fungus of
  54. // NewNodes growing on top of the useful nodes, and perhaps using them, but
  55. // not used by them.
  56. // If a value is mapped by ReplacedValues, then it must have no uses, except
  57. // by nodes marked NewNode (see above).
  58. // The final node obtained by mapping by ReplacedValues is not marked NewNode.
  59. // Note that ReplacedValues should be applied iteratively.
  60. // Note that the ReplacedValues map may also map deleted nodes (by iterating
  61. // over the DAG we never dereference deleted nodes). This means that it may
  62. // also map nodes marked NewNode if the deallocated memory was reallocated as
  63. // another node, and that new node was not seen by the LegalizeTypes machinery
  64. // (for example because it was created but not used). In general, we cannot
  65. // distinguish between new nodes and deleted nodes.
  66. SmallVector<SDNode*, 16> NewNodes;
  67. for (SDNode &Node : DAG.allnodes()) {
  68. // Remember nodes marked NewNode - they are subject to extra checking below.
  69. if (Node.getNodeId() == NewNode)
  70. NewNodes.push_back(&Node);
  71. for (unsigned i = 0, e = Node.getNumValues(); i != e; ++i) {
  72. SDValue Res(&Node, i);
  73. bool Failed = false;
  74. // Don't create a value in map.
  75. auto ResId = (ValueToIdMap.count(Res)) ? ValueToIdMap[Res] : 0;
  76. unsigned Mapped = 0;
  77. if (ResId && (ReplacedValues.find(ResId) != ReplacedValues.end())) {
  78. Mapped |= 1;
  79. // Check that remapped values are only used by nodes marked NewNode.
  80. for (SDNode::use_iterator UI = Node.use_begin(), UE = Node.use_end();
  81. UI != UE; ++UI)
  82. if (UI.getUse().getResNo() == i)
  83. assert(UI->getNodeId() == NewNode &&
  84. "Remapped value has non-trivial use!");
  85. // Check that the final result of applying ReplacedValues is not
  86. // marked NewNode.
  87. auto NewValId = ReplacedValues[ResId];
  88. auto I = ReplacedValues.find(NewValId);
  89. while (I != ReplacedValues.end()) {
  90. NewValId = I->second;
  91. I = ReplacedValues.find(NewValId);
  92. }
  93. SDValue NewVal = getSDValue(NewValId);
  94. (void)NewVal;
  95. assert(NewVal.getNode()->getNodeId() != NewNode &&
  96. "ReplacedValues maps to a new node!");
  97. }
  98. if (ResId && PromotedIntegers.find(ResId) != PromotedIntegers.end())
  99. Mapped |= 2;
  100. if (ResId && SoftenedFloats.find(ResId) != SoftenedFloats.end())
  101. Mapped |= 4;
  102. if (ResId && ScalarizedVectors.find(ResId) != ScalarizedVectors.end())
  103. Mapped |= 8;
  104. if (ResId && ExpandedIntegers.find(ResId) != ExpandedIntegers.end())
  105. Mapped |= 16;
  106. if (ResId && ExpandedFloats.find(ResId) != ExpandedFloats.end())
  107. Mapped |= 32;
  108. if (ResId && SplitVectors.find(ResId) != SplitVectors.end())
  109. Mapped |= 64;
  110. if (ResId && WidenedVectors.find(ResId) != WidenedVectors.end())
  111. Mapped |= 128;
  112. if (ResId && PromotedFloats.find(ResId) != PromotedFloats.end())
  113. Mapped |= 256;
  114. if (Node.getNodeId() != Processed) {
  115. // Since we allow ReplacedValues to map deleted nodes, it may map nodes
  116. // marked NewNode too, since a deleted node may have been reallocated as
  117. // another node that has not been seen by the LegalizeTypes machinery.
  118. if ((Node.getNodeId() == NewNode && Mapped > 1) ||
  119. (Node.getNodeId() != NewNode && Mapped != 0)) {
  120. dbgs() << "Unprocessed value in a map!";
  121. Failed = true;
  122. }
  123. } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(&Node)) {
  124. if (Mapped > 1) {
  125. dbgs() << "Value with legal type was transformed!";
  126. Failed = true;
  127. }
  128. } else {
  129. if (Mapped == 0) {
  130. dbgs() << "Processed value not in any map!";
  131. Failed = true;
  132. } else if (Mapped & (Mapped - 1)) {
  133. dbgs() << "Value in multiple maps!";
  134. Failed = true;
  135. }
  136. }
  137. if (Failed) {
  138. if (Mapped & 1)
  139. dbgs() << " ReplacedValues";
  140. if (Mapped & 2)
  141. dbgs() << " PromotedIntegers";
  142. if (Mapped & 4)
  143. dbgs() << " SoftenedFloats";
  144. if (Mapped & 8)
  145. dbgs() << " ScalarizedVectors";
  146. if (Mapped & 16)
  147. dbgs() << " ExpandedIntegers";
  148. if (Mapped & 32)
  149. dbgs() << " ExpandedFloats";
  150. if (Mapped & 64)
  151. dbgs() << " SplitVectors";
  152. if (Mapped & 128)
  153. dbgs() << " WidenedVectors";
  154. if (Mapped & 256)
  155. dbgs() << " PromotedFloats";
  156. dbgs() << "\n";
  157. llvm_unreachable(nullptr);
  158. }
  159. }
  160. }
  161. // Checked that NewNodes are only used by other NewNodes.
  162. for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
  163. SDNode *N = NewNodes[i];
  164. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  165. UI != UE; ++UI)
  166. assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
  167. }
  168. }
  169. /// This is the main entry point for the type legalizer. This does a top-down
  170. /// traversal of the dag, legalizing types as it goes. Returns "true" if it made
  171. /// any changes.
  172. bool DAGTypeLegalizer::run() {
  173. bool Changed = false;
  174. // Create a dummy node (which is not added to allnodes), that adds a reference
  175. // to the root node, preventing it from being deleted, and tracking any
  176. // changes of the root.
  177. HandleSDNode Dummy(DAG.getRoot());
  178. Dummy.setNodeId(Unanalyzed);
  179. // The root of the dag may dangle to deleted nodes until the type legalizer is
  180. // done. Set it to null to avoid confusion.
  181. DAG.setRoot(SDValue());
  182. // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
  183. // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
  184. // non-leaves.
  185. for (SDNode &Node : DAG.allnodes()) {
  186. if (Node.getNumOperands() == 0) {
  187. AddToWorklist(&Node);
  188. } else {
  189. Node.setNodeId(Unanalyzed);
  190. }
  191. }
  192. // Now that we have a set of nodes to process, handle them all.
  193. while (!Worklist.empty()) {
  194. #ifndef EXPENSIVE_CHECKS
  195. if (EnableExpensiveChecks)
  196. #endif
  197. PerformExpensiveChecks();
  198. SDNode *N = Worklist.back();
  199. Worklist.pop_back();
  200. assert(N->getNodeId() == ReadyToProcess &&
  201. "Node should be ready if on worklist!");
  202. LLVM_DEBUG(dbgs() << "Legalizing node: "; N->dump(&DAG));
  203. if (IgnoreNodeResults(N)) {
  204. LLVM_DEBUG(dbgs() << "Ignoring node results\n");
  205. goto ScanOperands;
  206. }
  207. // Scan the values produced by the node, checking to see if any result
  208. // types are illegal.
  209. for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
  210. EVT ResultVT = N->getValueType(i);
  211. LLVM_DEBUG(dbgs() << "Analyzing result type: " << ResultVT.getEVTString()
  212. << "\n");
  213. switch (getTypeAction(ResultVT)) {
  214. case TargetLowering::TypeLegal:
  215. LLVM_DEBUG(dbgs() << "Legal result type\n");
  216. break;
  217. // The following calls must take care of *all* of the node's results,
  218. // not just the illegal result they were passed (this includes results
  219. // with a legal type). Results can be remapped using ReplaceValueWith,
  220. // or their promoted/expanded/etc values registered in PromotedIntegers,
  221. // ExpandedIntegers etc.
  222. case TargetLowering::TypePromoteInteger:
  223. PromoteIntegerResult(N, i);
  224. Changed = true;
  225. goto NodeDone;
  226. case TargetLowering::TypeExpandInteger:
  227. ExpandIntegerResult(N, i);
  228. Changed = true;
  229. goto NodeDone;
  230. case TargetLowering::TypeSoftenFloat:
  231. SoftenFloatResult(N, i);
  232. Changed = true;
  233. goto NodeDone;
  234. case TargetLowering::TypeExpandFloat:
  235. ExpandFloatResult(N, i);
  236. Changed = true;
  237. goto NodeDone;
  238. case TargetLowering::TypeScalarizeVector:
  239. ScalarizeVectorResult(N, i);
  240. Changed = true;
  241. goto NodeDone;
  242. case TargetLowering::TypeSplitVector:
  243. SplitVectorResult(N, i);
  244. Changed = true;
  245. goto NodeDone;
  246. case TargetLowering::TypeWidenVector:
  247. WidenVectorResult(N, i);
  248. Changed = true;
  249. goto NodeDone;
  250. case TargetLowering::TypePromoteFloat:
  251. PromoteFloatResult(N, i);
  252. Changed = true;
  253. goto NodeDone;
  254. }
  255. }
  256. ScanOperands:
  257. // Scan the operand list for the node, handling any nodes with operands that
  258. // are illegal.
  259. {
  260. unsigned NumOperands = N->getNumOperands();
  261. bool NeedsReanalyzing = false;
  262. unsigned i;
  263. for (i = 0; i != NumOperands; ++i) {
  264. if (IgnoreNodeResults(N->getOperand(i).getNode()))
  265. continue;
  266. const auto Op = N->getOperand(i);
  267. LLVM_DEBUG(dbgs() << "Analyzing operand: "; Op.dump(&DAG));
  268. EVT OpVT = Op.getValueType();
  269. switch (getTypeAction(OpVT)) {
  270. case TargetLowering::TypeLegal:
  271. LLVM_DEBUG(dbgs() << "Legal operand\n");
  272. continue;
  273. // The following calls must either replace all of the node's results
  274. // using ReplaceValueWith, and return "false"; or update the node's
  275. // operands in place, and return "true".
  276. case TargetLowering::TypePromoteInteger:
  277. NeedsReanalyzing = PromoteIntegerOperand(N, i);
  278. Changed = true;
  279. break;
  280. case TargetLowering::TypeExpandInteger:
  281. NeedsReanalyzing = ExpandIntegerOperand(N, i);
  282. Changed = true;
  283. break;
  284. case TargetLowering::TypeSoftenFloat:
  285. NeedsReanalyzing = SoftenFloatOperand(N, i);
  286. Changed = true;
  287. break;
  288. case TargetLowering::TypeExpandFloat:
  289. NeedsReanalyzing = ExpandFloatOperand(N, i);
  290. Changed = true;
  291. break;
  292. case TargetLowering::TypeScalarizeVector:
  293. NeedsReanalyzing = ScalarizeVectorOperand(N, i);
  294. Changed = true;
  295. break;
  296. case TargetLowering::TypeSplitVector:
  297. NeedsReanalyzing = SplitVectorOperand(N, i);
  298. Changed = true;
  299. break;
  300. case TargetLowering::TypeWidenVector:
  301. NeedsReanalyzing = WidenVectorOperand(N, i);
  302. Changed = true;
  303. break;
  304. case TargetLowering::TypePromoteFloat:
  305. NeedsReanalyzing = PromoteFloatOperand(N, i);
  306. Changed = true;
  307. break;
  308. }
  309. break;
  310. }
  311. // The sub-method updated N in place. Check to see if any operands are new,
  312. // and if so, mark them. If the node needs revisiting, don't add all users
  313. // to the worklist etc.
  314. if (NeedsReanalyzing) {
  315. assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
  316. N->setNodeId(NewNode);
  317. // Recompute the NodeId and correct processed operands, adding the node to
  318. // the worklist if ready.
  319. SDNode *M = AnalyzeNewNode(N);
  320. if (M == N)
  321. // The node didn't morph - nothing special to do, it will be revisited.
  322. continue;
  323. // The node morphed - this is equivalent to legalizing by replacing every
  324. // value of N with the corresponding value of M. So do that now.
  325. assert(N->getNumValues() == M->getNumValues() &&
  326. "Node morphing changed the number of results!");
  327. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  328. // Replacing the value takes care of remapping the new value.
  329. ReplaceValueWith(SDValue(N, i), SDValue(M, i));
  330. assert(N->getNodeId() == NewNode && "Unexpected node state!");
  331. // The node continues to live on as part of the NewNode fungus that
  332. // grows on top of the useful nodes. Nothing more needs to be done
  333. // with it - move on to the next node.
  334. continue;
  335. }
  336. if (i == NumOperands) {
  337. LLVM_DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG);
  338. dbgs() << "\n");
  339. }
  340. }
  341. NodeDone:
  342. // If we reach here, the node was processed, potentially creating new nodes.
  343. // Mark it as processed and add its users to the worklist as appropriate.
  344. assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
  345. N->setNodeId(Processed);
  346. for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
  347. UI != E; ++UI) {
  348. SDNode *User = *UI;
  349. int NodeId = User->getNodeId();
  350. // This node has two options: it can either be a new node or its Node ID
  351. // may be a count of the number of operands it has that are not ready.
  352. if (NodeId > 0) {
  353. User->setNodeId(NodeId-1);
  354. // If this was the last use it was waiting on, add it to the ready list.
  355. if (NodeId-1 == ReadyToProcess)
  356. Worklist.push_back(User);
  357. continue;
  358. }
  359. // If this is an unreachable new node, then ignore it. If it ever becomes
  360. // reachable by being used by a newly created node then it will be handled
  361. // by AnalyzeNewNode.
  362. if (NodeId == NewNode)
  363. continue;
  364. // Otherwise, this node is new: this is the first operand of it that
  365. // became ready. Its new NodeId is the number of operands it has minus 1
  366. // (as this node is now processed).
  367. assert(NodeId == Unanalyzed && "Unknown node ID!");
  368. User->setNodeId(User->getNumOperands() - 1);
  369. // If the node only has a single operand, it is now ready.
  370. if (User->getNumOperands() == 1)
  371. Worklist.push_back(User);
  372. }
  373. }
  374. #ifndef EXPENSIVE_CHECKS
  375. if (EnableExpensiveChecks)
  376. #endif
  377. PerformExpensiveChecks();
  378. // If the root changed (e.g. it was a dead load) update the root.
  379. DAG.setRoot(Dummy.getValue());
  380. // Remove dead nodes. This is important to do for cleanliness but also before
  381. // the checking loop below. Implicit folding by the DAG.getNode operators and
  382. // node morphing can cause unreachable nodes to be around with their flags set
  383. // to new.
  384. DAG.RemoveDeadNodes();
  385. // In a debug build, scan all the nodes to make sure we found them all. This
  386. // ensures that there are no cycles and that everything got processed.
  387. #ifndef NDEBUG
  388. for (SDNode &Node : DAG.allnodes()) {
  389. bool Failed = false;
  390. // Check that all result types are legal.
  391. if (!IgnoreNodeResults(&Node))
  392. for (unsigned i = 0, NumVals = Node.getNumValues(); i < NumVals; ++i)
  393. if (!isTypeLegal(Node.getValueType(i))) {
  394. dbgs() << "Result type " << i << " illegal: ";
  395. Node.dump(&DAG);
  396. Failed = true;
  397. }
  398. // Check that all operand types are legal.
  399. for (unsigned i = 0, NumOps = Node.getNumOperands(); i < NumOps; ++i)
  400. if (!IgnoreNodeResults(Node.getOperand(i).getNode()) &&
  401. !isTypeLegal(Node.getOperand(i).getValueType())) {
  402. dbgs() << "Operand type " << i << " illegal: ";
  403. Node.getOperand(i).dump(&DAG);
  404. Failed = true;
  405. }
  406. if (Node.getNodeId() != Processed) {
  407. if (Node.getNodeId() == NewNode)
  408. dbgs() << "New node not analyzed?\n";
  409. else if (Node.getNodeId() == Unanalyzed)
  410. dbgs() << "Unanalyzed node not noticed?\n";
  411. else if (Node.getNodeId() > 0)
  412. dbgs() << "Operand not processed?\n";
  413. else if (Node.getNodeId() == ReadyToProcess)
  414. dbgs() << "Not added to worklist?\n";
  415. Failed = true;
  416. }
  417. if (Failed) {
  418. Node.dump(&DAG); dbgs() << "\n";
  419. llvm_unreachable(nullptr);
  420. }
  421. }
  422. #endif
  423. return Changed;
  424. }
  425. /// The specified node is the root of a subtree of potentially new nodes.
  426. /// Correct any processed operands (this may change the node) and calculate the
  427. /// NodeId. If the node itself changes to a processed node, it is not remapped -
  428. /// the caller needs to take care of this. Returns the potentially changed node.
  429. SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
  430. // If this was an existing node that is already done, we're done.
  431. if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
  432. return N;
  433. // Okay, we know that this node is new. Recursively walk all of its operands
  434. // to see if they are new also. The depth of this walk is bounded by the size
  435. // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
  436. // about revisiting of nodes.
  437. //
  438. // As we walk the operands, keep track of the number of nodes that are
  439. // processed. If non-zero, this will become the new nodeid of this node.
  440. // Operands may morph when they are analyzed. If so, the node will be
  441. // updated after all operands have been analyzed. Since this is rare,
  442. // the code tries to minimize overhead in the non-morphing case.
  443. std::vector<SDValue> NewOps;
  444. unsigned NumProcessed = 0;
  445. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  446. SDValue OrigOp = N->getOperand(i);
  447. SDValue Op = OrigOp;
  448. AnalyzeNewValue(Op); // Op may morph.
  449. if (Op.getNode()->getNodeId() == Processed)
  450. ++NumProcessed;
  451. if (!NewOps.empty()) {
  452. // Some previous operand changed. Add this one to the list.
  453. NewOps.push_back(Op);
  454. } else if (Op != OrigOp) {
  455. // This is the first operand to change - add all operands so far.
  456. NewOps.insert(NewOps.end(), N->op_begin(), N->op_begin() + i);
  457. NewOps.push_back(Op);
  458. }
  459. }
  460. // Some operands changed - update the node.
  461. if (!NewOps.empty()) {
  462. SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
  463. if (M != N) {
  464. // The node morphed into a different node. Normally for this to happen
  465. // the original node would have to be marked NewNode. However this can
  466. // in theory momentarily not be the case while ReplaceValueWith is doing
  467. // its stuff. Mark the original node NewNode to help sanity checking.
  468. N->setNodeId(NewNode);
  469. if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
  470. // It morphed into a previously analyzed node - nothing more to do.
  471. return M;
  472. // It morphed into a different new node. Do the equivalent of passing
  473. // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
  474. // to remap the operands, since they are the same as the operands we
  475. // remapped above.
  476. N = M;
  477. }
  478. }
  479. // Calculate the NodeId.
  480. N->setNodeId(N->getNumOperands() - NumProcessed);
  481. if (N->getNodeId() == ReadyToProcess)
  482. Worklist.push_back(N);
  483. return N;
  484. }
  485. /// Call AnalyzeNewNode, updating the node in Val if needed.
  486. /// If the node changes to a processed node, then remap it.
  487. void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
  488. Val.setNode(AnalyzeNewNode(Val.getNode()));
  489. if (Val.getNode()->getNodeId() == Processed)
  490. // We were passed a processed node, or it morphed into one - remap it.
  491. RemapValue(Val);
  492. }
  493. /// If the specified value was already legalized to another value,
  494. /// replace it by that value.
  495. void DAGTypeLegalizer::RemapValue(SDValue &V) {
  496. auto Id = getTableId(V);
  497. V = getSDValue(Id);
  498. }
  499. void DAGTypeLegalizer::RemapId(TableId &Id) {
  500. auto I = ReplacedValues.find(Id);
  501. if (I != ReplacedValues.end()) {
  502. assert(Id != I->second && "Id is mapped to itself.");
  503. // Use path compression to speed up future lookups if values get multiply
  504. // replaced with other values.
  505. RemapId(I->second);
  506. Id = I->second;
  507. // Note that N = IdToValueMap[Id] it is possible to have
  508. // N.getNode()->getNodeId() == NewNode at this point because it is possible
  509. // for a node to be put in the map before being processed.
  510. }
  511. }
  512. namespace {
  513. /// This class is a DAGUpdateListener that listens for updates to nodes and
  514. /// recomputes their ready state.
  515. class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
  516. DAGTypeLegalizer &DTL;
  517. SmallSetVector<SDNode*, 16> &NodesToAnalyze;
  518. public:
  519. explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
  520. SmallSetVector<SDNode*, 16> &nta)
  521. : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
  522. DTL(dtl), NodesToAnalyze(nta) {}
  523. void NodeDeleted(SDNode *N, SDNode *E) override {
  524. assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
  525. N->getNodeId() != DAGTypeLegalizer::Processed &&
  526. "Invalid node ID for RAUW deletion!");
  527. // It is possible, though rare, for the deleted node N to occur as a
  528. // target in a map, so note the replacement N -> E in ReplacedValues.
  529. assert(E && "Node not replaced?");
  530. DTL.NoteDeletion(N, E);
  531. // In theory the deleted node could also have been scheduled for analysis.
  532. // So remove it from the set of nodes which will be analyzed.
  533. NodesToAnalyze.remove(N);
  534. // In general nothing needs to be done for E, since it didn't change but
  535. // only gained new uses. However N -> E was just added to ReplacedValues,
  536. // and the result of a ReplacedValues mapping is not allowed to be marked
  537. // NewNode. So if E is marked NewNode, then it needs to be analyzed.
  538. if (E->getNodeId() == DAGTypeLegalizer::NewNode)
  539. NodesToAnalyze.insert(E);
  540. }
  541. void NodeUpdated(SDNode *N) override {
  542. // Node updates can mean pretty much anything. It is possible that an
  543. // operand was set to something already processed (f.e.) in which case
  544. // this node could become ready. Recompute its flags.
  545. assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
  546. N->getNodeId() != DAGTypeLegalizer::Processed &&
  547. "Invalid node ID for RAUW deletion!");
  548. N->setNodeId(DAGTypeLegalizer::NewNode);
  549. NodesToAnalyze.insert(N);
  550. }
  551. };
  552. }
  553. /// The specified value was legalized to the specified other value.
  554. /// Update the DAG and NodeIds replacing any uses of From to use To instead.
  555. void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
  556. assert(From.getNode() != To.getNode() && "Potential legalization loop!");
  557. // If expansion produced new nodes, make sure they are properly marked.
  558. AnalyzeNewValue(To);
  559. // Anything that used the old node should now use the new one. Note that this
  560. // can potentially cause recursive merging.
  561. SmallSetVector<SDNode*, 16> NodesToAnalyze;
  562. NodeUpdateListener NUL(*this, NodesToAnalyze);
  563. do {
  564. // The old node may be present in a map like ExpandedIntegers or
  565. // PromotedIntegers. Inform maps about the replacement.
  566. auto FromId = getTableId(From);
  567. auto ToId = getTableId(To);
  568. if (FromId != ToId)
  569. ReplacedValues[FromId] = ToId;
  570. DAG.ReplaceAllUsesOfValueWith(From, To);
  571. // Process the list of nodes that need to be reanalyzed.
  572. while (!NodesToAnalyze.empty()) {
  573. SDNode *N = NodesToAnalyze.back();
  574. NodesToAnalyze.pop_back();
  575. if (N->getNodeId() != DAGTypeLegalizer::NewNode)
  576. // The node was analyzed while reanalyzing an earlier node - it is safe
  577. // to skip. Note that this is not a morphing node - otherwise it would
  578. // still be marked NewNode.
  579. continue;
  580. // Analyze the node's operands and recalculate the node ID.
  581. SDNode *M = AnalyzeNewNode(N);
  582. if (M != N) {
  583. // The node morphed into a different node. Make everyone use the new
  584. // node instead.
  585. assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
  586. assert(N->getNumValues() == M->getNumValues() &&
  587. "Node morphing changed the number of results!");
  588. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
  589. SDValue OldVal(N, i);
  590. SDValue NewVal(M, i);
  591. if (M->getNodeId() == Processed)
  592. RemapValue(NewVal);
  593. // OldVal may be a target of the ReplacedValues map which was marked
  594. // NewNode to force reanalysis because it was updated. Ensure that
  595. // anything that ReplacedValues mapped to OldVal will now be mapped
  596. // all the way to NewVal.
  597. auto OldValId = getTableId(OldVal);
  598. auto NewValId = getTableId(NewVal);
  599. DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
  600. if (OldValId != NewValId)
  601. ReplacedValues[OldValId] = NewValId;
  602. }
  603. // The original node continues to exist in the DAG, marked NewNode.
  604. }
  605. }
  606. // When recursively update nodes with new nodes, it is possible to have
  607. // new uses of From due to CSE. If this happens, replace the new uses of
  608. // From with To.
  609. } while (!From.use_empty());
  610. }
  611. void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
  612. assert(Result.getValueType() ==
  613. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  614. "Invalid type for promoted integer");
  615. AnalyzeNewValue(Result);
  616. auto &OpIdEntry = PromotedIntegers[getTableId(Op)];
  617. assert((OpIdEntry == 0) && "Node is already promoted!");
  618. OpIdEntry = getTableId(Result);
  619. Result->setFlags(Op->getFlags());
  620. DAG.transferDbgValues(Op, Result);
  621. }
  622. void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
  623. assert(Result.getValueType() ==
  624. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  625. "Invalid type for softened float");
  626. AnalyzeNewValue(Result);
  627. auto &OpIdEntry = SoftenedFloats[getTableId(Op)];
  628. assert((OpIdEntry == 0) && "Node is already converted to integer!");
  629. OpIdEntry = getTableId(Result);
  630. }
  631. void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
  632. assert(Result.getValueType() ==
  633. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  634. "Invalid type for promoted float");
  635. AnalyzeNewValue(Result);
  636. auto &OpIdEntry = PromotedFloats[getTableId(Op)];
  637. assert((OpIdEntry == 0) && "Node is already promoted!");
  638. OpIdEntry = getTableId(Result);
  639. }
  640. void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
  641. // Note that in some cases vector operation operands may be greater than
  642. // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
  643. // a constant i8 operand.
  644. assert(Result.getValueSizeInBits() >= Op.getScalarValueSizeInBits() &&
  645. "Invalid type for scalarized vector");
  646. AnalyzeNewValue(Result);
  647. auto &OpIdEntry = ScalarizedVectors[getTableId(Op)];
  648. assert((OpIdEntry == 0) && "Node is already scalarized!");
  649. OpIdEntry = getTableId(Result);
  650. }
  651. void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
  652. SDValue &Hi) {
  653. std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(Op)];
  654. assert((Entry.first != 0) && "Operand isn't expanded");
  655. Lo = getSDValue(Entry.first);
  656. Hi = getSDValue(Entry.second);
  657. }
  658. void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
  659. SDValue Hi) {
  660. assert(Lo.getValueType() ==
  661. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  662. Hi.getValueType() == Lo.getValueType() &&
  663. "Invalid type for expanded integer");
  664. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  665. AnalyzeNewValue(Lo);
  666. AnalyzeNewValue(Hi);
  667. // Transfer debug values. Don't invalidate the source debug value until it's
  668. // been transferred to the high and low bits.
  669. if (DAG.getDataLayout().isBigEndian()) {
  670. DAG.transferDbgValues(Op, Hi, 0, Hi.getValueSizeInBits(), false);
  671. DAG.transferDbgValues(Op, Lo, Hi.getValueSizeInBits(),
  672. Lo.getValueSizeInBits());
  673. } else {
  674. DAG.transferDbgValues(Op, Lo, 0, Lo.getValueSizeInBits(), false);
  675. DAG.transferDbgValues(Op, Hi, Lo.getValueSizeInBits(),
  676. Hi.getValueSizeInBits());
  677. }
  678. // Remember that this is the result of the node.
  679. std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(Op)];
  680. assert((Entry.first == 0) && "Node already expanded");
  681. Entry.first = getTableId(Lo);
  682. Entry.second = getTableId(Hi);
  683. }
  684. void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
  685. SDValue &Hi) {
  686. std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(Op)];
  687. assert((Entry.first != 0) && "Operand isn't expanded");
  688. Lo = getSDValue(Entry.first);
  689. Hi = getSDValue(Entry.second);
  690. }
  691. void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
  692. SDValue Hi) {
  693. assert(Lo.getValueType() ==
  694. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  695. Hi.getValueType() == Lo.getValueType() &&
  696. "Invalid type for expanded float");
  697. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  698. AnalyzeNewValue(Lo);
  699. AnalyzeNewValue(Hi);
  700. std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(Op)];
  701. assert((Entry.first == 0) && "Node already expanded");
  702. Entry.first = getTableId(Lo);
  703. Entry.second = getTableId(Hi);
  704. }
  705. void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
  706. SDValue &Hi) {
  707. std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(Op)];
  708. Lo = getSDValue(Entry.first);
  709. Hi = getSDValue(Entry.second);
  710. assert(Lo.getNode() && "Operand isn't split");
  711. ;
  712. }
  713. void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
  714. SDValue Hi) {
  715. assert(Lo.getValueType().getVectorElementType() ==
  716. Op.getValueType().getVectorElementType() &&
  717. 2*Lo.getValueType().getVectorNumElements() ==
  718. Op.getValueType().getVectorNumElements() &&
  719. Hi.getValueType() == Lo.getValueType() &&
  720. "Invalid type for split vector");
  721. // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
  722. AnalyzeNewValue(Lo);
  723. AnalyzeNewValue(Hi);
  724. // Remember that this is the result of the node.
  725. std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(Op)];
  726. assert((Entry.first == 0) && "Node already split");
  727. Entry.first = getTableId(Lo);
  728. Entry.second = getTableId(Hi);
  729. }
  730. void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
  731. assert(Result.getValueType() ==
  732. TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
  733. "Invalid type for widened vector");
  734. AnalyzeNewValue(Result);
  735. auto &OpIdEntry = WidenedVectors[getTableId(Op)];
  736. assert((OpIdEntry == 0) && "Node already widened!");
  737. OpIdEntry = getTableId(Result);
  738. }
  739. //===----------------------------------------------------------------------===//
  740. // Utilities.
  741. //===----------------------------------------------------------------------===//
  742. /// Convert to an integer of the same size.
  743. SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
  744. unsigned BitWidth = Op.getValueSizeInBits();
  745. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  746. EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
  747. }
  748. /// Convert to a vector of integers of the same size.
  749. SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
  750. assert(Op.getValueType().isVector() && "Only applies to vectors!");
  751. unsigned EltWidth = Op.getScalarValueSizeInBits();
  752. EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
  753. auto EltCnt = Op.getValueType().getVectorElementCount();
  754. return DAG.getNode(ISD::BITCAST, SDLoc(Op),
  755. EVT::getVectorVT(*DAG.getContext(), EltNVT, EltCnt), Op);
  756. }
  757. SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
  758. EVT DestVT) {
  759. SDLoc dl(Op);
  760. // Create the stack frame object. Make sure it is aligned for both
  761. // the source and destination types.
  762. SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
  763. // Emit a store to the stack slot.
  764. SDValue Store =
  765. DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, MachinePointerInfo());
  766. // Result is a load from the stack slot.
  767. return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo());
  768. }
  769. /// Replace the node's results with custom code provided by the target and
  770. /// return "true", or do nothing and return "false".
  771. /// The last parameter is FALSE if we are dealing with a node with legal
  772. /// result types and illegal operand. The second parameter denotes the type of
  773. /// illegal OperandNo in that case.
  774. /// The last parameter being TRUE means we are dealing with a
  775. /// node with illegal result types. The second parameter denotes the type of
  776. /// illegal ResNo in that case.
  777. bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
  778. // See if the target wants to custom lower this node.
  779. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  780. return false;
  781. SmallVector<SDValue, 8> Results;
  782. if (LegalizeResult)
  783. TLI.ReplaceNodeResults(N, Results, DAG);
  784. else
  785. TLI.LowerOperationWrapper(N, Results, DAG);
  786. if (Results.empty())
  787. // The target didn't want to custom lower it after all.
  788. return false;
  789. // When called from DAGTypeLegalizer::ExpandIntegerResult, we might need to
  790. // provide the same kind of custom splitting behavior.
  791. if (Results.size() == N->getNumValues() + 1 && LegalizeResult) {
  792. // We've legalized a return type by splitting it. If there is a chain,
  793. // replace that too.
  794. SetExpandedInteger(SDValue(N, 0), Results[0], Results[1]);
  795. if (N->getNumValues() > 1)
  796. ReplaceValueWith(SDValue(N, 1), Results[2]);
  797. return true;
  798. }
  799. // Make everything that once used N's values now use those in Results instead.
  800. assert(Results.size() == N->getNumValues() &&
  801. "Custom lowering returned the wrong number of results!");
  802. for (unsigned i = 0, e = Results.size(); i != e; ++i) {
  803. ReplaceValueWith(SDValue(N, i), Results[i]);
  804. }
  805. return true;
  806. }
  807. /// Widen the node's results with custom code provided by the target and return
  808. /// "true", or do nothing and return "false".
  809. bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
  810. // See if the target wants to custom lower this node.
  811. if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
  812. return false;
  813. SmallVector<SDValue, 8> Results;
  814. TLI.ReplaceNodeResults(N, Results, DAG);
  815. if (Results.empty())
  816. // The target didn't want to custom widen lower its result after all.
  817. return false;
  818. // Update the widening map.
  819. assert(Results.size() == N->getNumValues() &&
  820. "Custom lowering returned the wrong number of results!");
  821. for (unsigned i = 0, e = Results.size(); i != e; ++i) {
  822. // If this is a chain output just replace it.
  823. if (Results[i].getValueType() == MVT::Other)
  824. ReplaceValueWith(SDValue(N, i), Results[i]);
  825. else
  826. SetWidenedVector(SDValue(N, i), Results[i]);
  827. }
  828. return true;
  829. }
  830. SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
  831. for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
  832. if (i != ResNo)
  833. ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
  834. return SDValue(N->getOperand(ResNo));
  835. }
  836. /// Use ISD::EXTRACT_ELEMENT nodes to extract the low and high parts of the
  837. /// given value.
  838. void DAGTypeLegalizer::GetPairElements(SDValue Pair,
  839. SDValue &Lo, SDValue &Hi) {
  840. SDLoc dl(Pair);
  841. EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
  842. Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  843. DAG.getIntPtrConstant(0, dl));
  844. Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
  845. DAG.getIntPtrConstant(1, dl));
  846. }
  847. /// Build an integer with low bits Lo and high bits Hi.
  848. SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
  849. // Arbitrarily use dlHi for result SDLoc
  850. SDLoc dlHi(Hi);
  851. SDLoc dlLo(Lo);
  852. EVT LVT = Lo.getValueType();
  853. EVT HVT = Hi.getValueType();
  854. EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
  855. LVT.getSizeInBits() + HVT.getSizeInBits());
  856. EVT ShiftAmtVT = TLI.getShiftAmountTy(NVT, DAG.getDataLayout(), false);
  857. Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
  858. Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
  859. Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
  860. DAG.getConstant(LVT.getSizeInBits(), dlHi, ShiftAmtVT));
  861. return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
  862. }
  863. /// Convert the node into a libcall with the same prototype.
  864. SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
  865. bool isSigned) {
  866. TargetLowering::MakeLibCallOptions CallOptions;
  867. CallOptions.setSExt(isSigned);
  868. unsigned NumOps = N->getNumOperands();
  869. SDLoc dl(N);
  870. if (NumOps == 0) {
  871. return TLI.makeLibCall(DAG, LC, N->getValueType(0), None, CallOptions,
  872. dl).first;
  873. } else if (NumOps == 1) {
  874. SDValue Op = N->getOperand(0);
  875. return TLI.makeLibCall(DAG, LC, N->getValueType(0), Op, CallOptions,
  876. dl).first;
  877. } else if (NumOps == 2) {
  878. SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
  879. return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, CallOptions,
  880. dl).first;
  881. }
  882. SmallVector<SDValue, 8> Ops(NumOps);
  883. for (unsigned i = 0; i < NumOps; ++i)
  884. Ops[i] = N->getOperand(i);
  885. return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, CallOptions, dl).first;
  886. }
  887. /// Expand a node into a call to a libcall. Similar to ExpandLibCall except that
  888. /// the first operand is the in-chain.
  889. std::pair<SDValue, SDValue>
  890. DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC, SDNode *Node,
  891. bool isSigned) {
  892. SDValue InChain = Node->getOperand(0);
  893. TargetLowering::ArgListTy Args;
  894. TargetLowering::ArgListEntry Entry;
  895. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
  896. EVT ArgVT = Node->getOperand(i).getValueType();
  897. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  898. Entry.Node = Node->getOperand(i);
  899. Entry.Ty = ArgTy;
  900. Entry.IsSExt = isSigned;
  901. Entry.IsZExt = !isSigned;
  902. Args.push_back(Entry);
  903. }
  904. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  905. TLI.getPointerTy(DAG.getDataLayout()));
  906. Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
  907. TargetLowering::CallLoweringInfo CLI(DAG);
  908. CLI.setDebugLoc(SDLoc(Node))
  909. .setChain(InChain)
  910. .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
  911. std::move(Args))
  912. .setSExtResult(isSigned)
  913. .setZExtResult(!isSigned);
  914. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  915. return CallInfo;
  916. }
  917. /// Promote the given target boolean to a target boolean of the given type.
  918. /// A target boolean is an integer value, not necessarily of type i1, the bits
  919. /// of which conform to getBooleanContents.
  920. ///
  921. /// ValVT is the type of values that produced the boolean.
  922. SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
  923. SDLoc dl(Bool);
  924. EVT BoolVT = getSetCCResultType(ValVT);
  925. ISD::NodeType ExtendCode =
  926. TargetLowering::getExtendForContent(TLI.getBooleanContents(ValVT));
  927. return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
  928. }
  929. /// Return the lower LoVT bits of Op in Lo and the upper HiVT bits in Hi.
  930. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  931. EVT LoVT, EVT HiVT,
  932. SDValue &Lo, SDValue &Hi) {
  933. SDLoc dl(Op);
  934. assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
  935. Op.getValueSizeInBits() && "Invalid integer splitting!");
  936. Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
  937. unsigned ReqShiftAmountInBits =
  938. Log2_32_Ceil(Op.getValueType().getSizeInBits());
  939. MVT ShiftAmountTy =
  940. TLI.getScalarShiftAmountTy(DAG.getDataLayout(), Op.getValueType());
  941. if (ReqShiftAmountInBits > ShiftAmountTy.getSizeInBits())
  942. ShiftAmountTy = MVT::getIntegerVT(NextPowerOf2(ReqShiftAmountInBits));
  943. Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
  944. DAG.getConstant(LoVT.getSizeInBits(), dl, ShiftAmountTy));
  945. Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
  946. }
  947. /// Return the lower and upper halves of Op's bits in a value type half the
  948. /// size of Op's.
  949. void DAGTypeLegalizer::SplitInteger(SDValue Op,
  950. SDValue &Lo, SDValue &Hi) {
  951. EVT HalfVT =
  952. EVT::getIntegerVT(*DAG.getContext(), Op.getValueSizeInBits() / 2);
  953. SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
  954. }
  955. //===----------------------------------------------------------------------===//
  956. // Entry Point
  957. //===----------------------------------------------------------------------===//
  958. /// This transforms the SelectionDAG into a SelectionDAG that only uses types
  959. /// natively supported by the target. Returns "true" if it made any changes.
  960. ///
  961. /// Note that this is an involved process that may invalidate pointers into
  962. /// the graph.
  963. bool SelectionDAG::LegalizeTypes() {
  964. return DAGTypeLegalizer(*this).run();
  965. }