LegalizeTypes.cpp 45 KB

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