LLVM 24.0.0git
LegalizeDAG.cpp
Go to the documentation of this file.
1//===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
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::Legalize method.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/APFloat.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Type.h"
46#include "llvm/Support/Debug.h"
52#include <cassert>
53#include <cstdint>
54#include <tuple>
55#include <utility>
56
57using namespace llvm;
58
59#define DEBUG_TYPE "legalizedag"
60
61namespace {
62
63/// Keeps track of state when getting the sign of a floating-point value as an
64/// integer.
65struct FloatSignAsInt {
66 EVT FloatVT;
67 SDValue Chain;
68 SDValue FloatPtr;
69 SDValue IntPtr;
70 MachinePointerInfo IntPointerInfo;
71 MachinePointerInfo FloatPointerInfo;
72 SDValue IntValue;
73 APInt SignMask;
74 uint8_t SignBit;
75};
76
77//===----------------------------------------------------------------------===//
78/// This takes an arbitrary SelectionDAG as input and
79/// hacks on it until the target machine can handle it. This involves
80/// eliminating value sizes the machine cannot handle (promoting small sizes to
81/// large sizes or splitting up large values into small values) as well as
82/// eliminating operations the machine cannot handle.
83///
84/// This code also does a small amount of optimization and recognition of idioms
85/// as part of its processing. For example, if a target does not support a
86/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
87/// will attempt merge setcc and brc instructions into brcc's.
88class SelectionDAGLegalize {
89 const TargetMachine &TM;
90 const TargetLowering &TLI;
91 SelectionDAG &DAG;
92
93 /// The set of nodes which have already been legalized. We hold a
94 /// reference to it in order to update as necessary on node deletion.
95 SmallPtrSetImpl<SDNode *> &LegalizedNodes;
96
97 /// A set of all the nodes updated during legalization.
98 SmallSetVector<SDNode *, 16> *UpdatedNodes;
99
100 EVT getSetCCResultType(EVT VT) const {
101 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
102 }
103
104 // Libcall insertion helpers.
105
106public:
107 SelectionDAGLegalize(SelectionDAG &DAG,
108 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
109 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
110 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
111 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
112
113 /// Legalizes the given operation.
114 void LegalizeOp(SDNode *Node);
115
116private:
117 SDValue OptimizeFloatStore(StoreSDNode *ST);
118
119 void LegalizeLoadOps(SDNode *Node);
120 void LegalizeStoreOps(SDNode *Node);
121
122 SDValue ExpandINSERT_VECTOR_ELT(SDValue Op);
123
124 /// Return a vector shuffle operation which
125 /// performs the same shuffe in terms of order or result bytes, but on a type
126 /// whose vector element type is narrower than the original shuffle type.
127 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
128 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
129 SDValue N1, SDValue N2,
130 ArrayRef<int> Mask) const;
131
132 std::pair<SDValue, SDValue> ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
134 bool IsSigned, EVT RetVT);
135 std::pair<SDValue, SDValue> ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
136
137 void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall LC,
139
140 void
141 ExpandFastFPLibCall(SDNode *Node, bool IsFast,
142 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F32,
143 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F64,
144 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F80,
145 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F128,
146 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_PPCF128,
148
149 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I8,
150 RTLIB::Libcall Call_I16, RTLIB::Libcall Call_I32,
151 RTLIB::Libcall Call_I64, RTLIB::Libcall Call_I128);
152 void ExpandArgFPLibCall(SDNode *Node,
153 RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
154 RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
155 RTLIB::Libcall Call_PPCF128,
157 SDValue ExpandBitCountingLibCall(SDNode *Node, RTLIB::Libcall CallI32,
158 RTLIB::Libcall CallI64,
159 RTLIB::Libcall CallI128);
160 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
161
162 SDValue ExpandSincosStretLibCall(SDNode *Node) const;
163
164 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
165 const SDLoc &dl);
166 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
167 const SDLoc &dl, SDValue ChainIn);
168 SDValue ExpandBUILD_VECTOR(SDNode *Node);
169 SDValue ExpandSPLAT_VECTOR(SDNode *Node);
170 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
171 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
173 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
174 SDValue Value) const;
175 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
176 SDValue NewIntValue) const;
177 SDValue ExpandFCOPYSIGN(SDNode *Node) const;
178 SDValue ExpandFABS(SDNode *Node) const;
179 SDValue ExpandFNEG(SDNode *Node) const;
180 SDValue expandLdexp(SDNode *Node) const;
181 SDValue expandFrexp(SDNode *Node) const;
182 SDValue expandModf(SDNode *Node) const;
183
184 SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain);
185 void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl,
187 void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
189 SDValue PromoteLegalFP_TO_INT_SAT(SDNode *Node, const SDLoc &dl);
190
191 /// Implements vector reduce operation promotion.
192 ///
193 /// All vector operands are promoted to a vector type with larger element
194 /// type, and the start value is promoted to a larger scalar type. Then the
195 /// result is truncated back to the original scalar type.
196 SDValue PromoteReduction(SDNode *Node);
197
198 SDValue ExpandPARITY(SDValue Op, const SDLoc &dl);
199
200 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
201 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
202 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
203 SDValue ExpandConcatVectors(SDNode *Node);
204
205 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
206 SDValue ExpandConstant(ConstantSDNode *CP);
207
208 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
209 bool ExpandNode(SDNode *Node);
210 void ConvertNodeToLibcall(SDNode *Node);
211 void PromoteNode(SDNode *Node);
212
213public:
214 // Node replacement helpers
215
216 void ReplacedNode(SDNode *N) {
217 LegalizedNodes.erase(N);
218 if (UpdatedNodes)
219 UpdatedNodes->insert(N);
220 }
221
222 void ReplaceNode(SDNode *Old, SDNode *New) {
223 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
224 dbgs() << " with: "; New->dump(&DAG));
225
226 assert(Old->getNumValues() == New->getNumValues() &&
227 "Replacing one node with another that produces a different number "
228 "of values!");
229 DAG.ReplaceAllUsesWith(Old, New);
230 if (UpdatedNodes)
231 UpdatedNodes->insert(New);
232 ReplacedNode(Old);
233 }
234
235 void ReplaceNode(SDValue Old, SDValue New) {
236 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
237 dbgs() << " with: "; New->dump(&DAG));
238
239 DAG.ReplaceAllUsesWith(Old, New);
240 if (UpdatedNodes)
241 UpdatedNodes->insert(New.getNode());
242 ReplacedNode(Old.getNode());
243 }
244
245 void ReplaceNode(SDNode *Old, const SDValue *New) {
246 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
247
248 DAG.ReplaceAllUsesWith(Old, New);
249 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
250 LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
251 New[i]->dump(&DAG));
252 if (UpdatedNodes)
253 UpdatedNodes->insert(New[i].getNode());
254 }
255 ReplacedNode(Old);
256 }
257
258 void ReplaceNodeWithValue(SDValue Old, SDValue New) {
259 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
260 dbgs() << " with: "; New->dump(&DAG));
261
262 DAG.ReplaceAllUsesOfValueWith(Old, New);
263 if (UpdatedNodes)
264 UpdatedNodes->insert(New.getNode());
265 ReplacedNode(Old.getNode());
266 }
267};
268
269} // end anonymous namespace
270
271// Helper function that generates an MMO that considers the alignment of the
272// stack, and the size of the stack object
274 MachineFunction &MF,
275 bool isObjectScalable) {
276 auto &MFI = MF.getFrameInfo();
277 int FI = cast<FrameIndexSDNode>(StackPtr)->getIndex();
279 LocationSize ObjectSize = isObjectScalable
281 : LocationSize::precise(MFI.getObjectSize(FI));
283 ObjectSize, MFI.getObjectAlign(FI));
284}
285
286/// Return a vector shuffle operation which
287/// performs the same shuffle in terms of order or result bytes, but on a type
288/// whose vector element type is narrower than the original shuffle type.
289/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
290SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
291 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
292 ArrayRef<int> Mask) const {
293 unsigned NumMaskElts = VT.getVectorNumElements();
294 unsigned NumDestElts = NVT.getVectorNumElements();
295 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
296
297 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
298
299 if (NumEltsGrowth == 1)
300 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
301
302 SmallVector<int, 8> NewMask;
303 for (unsigned i = 0; i != NumMaskElts; ++i) {
304 int Idx = Mask[i];
305 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
306 if (Idx < 0)
307 NewMask.push_back(-1);
308 else
309 NewMask.push_back(Idx * NumEltsGrowth + j);
310 }
311 }
312 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
313 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
314 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
315}
316
317/// Expands the ConstantFP node to an integer constant or
318/// a load from the constant pool.
320SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
321 bool Extend = false;
322 SDLoc dl(CFP);
323
324 // If a FP immediate is precise when represented as a float and if the
325 // target can do an extending load from float to double, we put it into
326 // the constant pool as a float, even if it's is statically typed as a
327 // double. This shrinks FP constants and canonicalizes them for targets where
328 // an FP extending load is the same cost as a normal load (such as on the x87
329 // fp stack or PPC FP unit).
330 EVT VT = CFP->getValueType(0);
331 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
332 if (!UseCP) {
333 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
334 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
335 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
336 }
337
338 APFloat APF = CFP->getValueAPF();
339 EVT OrigVT = VT;
340 EVT SVT = VT;
341
342 // We don't want to shrink SNaNs. Converting the SNaN back to its real type
343 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
344 if (!APF.isSignaling()) {
345 while (SVT != MVT::f32 && SVT != MVT::f16 && SVT != MVT::bf16) {
346 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
348 // Only do this if the target has a native EXTLOAD instruction from
349 // smaller type.
350 TLI.isLoadLegal(
351 OrigVT, SVT,
353 SVT.getTypeForEVT(*DAG.getContext()))),
355 .getAddrSpace(),
356 ISD::EXTLOAD, false) &&
357 TLI.ShouldShrinkFPConstant(OrigVT)) {
358 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
360 Instruction::FPTrunc, LLVMC, SType, DAG.getDataLayout()));
361 VT = SVT;
362 Extend = true;
363 }
364 }
365 }
366
367 SDValue CPIdx =
368 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
369 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
370 if (Extend) {
372 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
374 Alignment);
375 return Result;
376 }
377 SDValue Result = DAG.getLoad(
378 OrigVT, dl, DAG.getEntryNode(), CPIdx,
380 return Result;
381}
382
383/// Expands the Constant node to a load from the constant pool.
384SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
385 SDLoc dl(CP);
386 EVT VT = CP->getValueType(0);
388 TLI.getPointerTy(DAG.getDataLayout()));
389 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
390 SDValue Result = DAG.getLoad(
391 VT, dl, DAG.getEntryNode(), CPIdx,
393 return Result;
394}
395
396SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Op) {
397 SDValue Vec = Op.getOperand(0);
398 SDValue Val = Op.getOperand(1);
399 SDValue Idx = Op.getOperand(2);
400 SDLoc dl(Op);
401
402 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
403 // SCALAR_TO_VECTOR requires that the type of the value being inserted
404 // match the element type of the vector being created, except for
405 // integers in which case the inserted value can be over width.
406 EVT EltVT = Vec.getValueType().getVectorElementType();
407 if (Val.getValueType() == EltVT ||
408 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
409 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
410 Vec.getValueType(), Val);
411
412 unsigned NumElts = Vec.getValueType().getVectorNumElements();
413 // We generate a shuffle of InVec and ScVec, so the shuffle mask
414 // should be 0,1,2,3,4,5... with the appropriate element replaced with
415 // elt 0 of the RHS.
416 SmallVector<int, 8> ShufOps;
417 for (unsigned i = 0; i != NumElts; ++i)
418 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
419
420 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
421 }
422 }
423 return ExpandInsertToVectorThroughStack(Op);
424}
425
426SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
427 if (!ISD::isNormalStore(ST))
428 return SDValue();
429
430 LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
431 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
432 // FIXME: move this to the DAG Combiner! Note that we can't regress due
433 // to phase ordering between legalized code and the dag combiner. This
434 // probably means that we need to integrate dag combiner and legalizer
435 // together.
436 // We generally can't do this one for long doubles.
437 SDValue Chain = ST->getChain();
438 SDValue Ptr = ST->getBasePtr();
439 SDValue Value = ST->getValue();
440 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
441 AAMDNodes AAInfo = ST->getAAInfo();
442 SDLoc dl(ST);
443
444 // Don't optimise TargetConstantFP
445 if (Value.getOpcode() == ISD::TargetConstantFP)
446 return SDValue();
447
448 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
449 if (CFP->getValueType(0) == MVT::f32 &&
450 TLI.isTypeLegal(MVT::i32)) {
451 SDValue Con = DAG.getConstant(CFP->getValueAPF().
452 bitcastToAPInt().zextOrTrunc(32),
453 SDLoc(CFP), MVT::i32);
454 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
455 ST->getBaseAlign(), MMOFlags, AAInfo);
456 }
457
458 if (CFP->getValueType(0) == MVT::f64 &&
459 !TLI.isFPImmLegal(CFP->getValueAPF(), MVT::f64)) {
460 // If this target supports 64-bit registers, do a single 64-bit store.
461 if (TLI.isTypeLegal(MVT::i64)) {
463 zextOrTrunc(64), SDLoc(CFP), MVT::i64);
464 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
465 ST->getBaseAlign(), MMOFlags, AAInfo);
466 }
467
468 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
469 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
470 // stores. If the target supports neither 32- nor 64-bits, this
471 // xform is certainly not worth it.
472 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
473 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
474 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
475 if (DAG.getDataLayout().isBigEndian())
476 std::swap(Lo, Hi);
477
478 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(),
479 ST->getBaseAlign(), MMOFlags, AAInfo);
480 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(4), dl);
481 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
482 ST->getPointerInfo().getWithOffset(4),
483 ST->getBaseAlign(), MMOFlags, AAInfo);
484
485 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
486 }
487 }
488 }
489 return SDValue();
490}
491
492void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
493 StoreSDNode *ST = cast<StoreSDNode>(Node);
494 SDValue Chain = ST->getChain();
495 SDValue Ptr = ST->getBasePtr();
496 SDLoc dl(Node);
497
498 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
499 AAMDNodes AAInfo = ST->getAAInfo();
500
501 if (!ST->isTruncatingStore()) {
502 LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
503 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
504 ReplaceNode(ST, OptStore);
505 return;
506 }
507
508 SDValue Value = ST->getValue();
509 MVT VT = Value.getSimpleValueType();
510 switch (TLI.getOperationAction(ISD::STORE, VT)) {
511 default: llvm_unreachable("This action is not supported yet!");
512 case TargetLowering::Legal: {
513 // If this is an unaligned store and the target doesn't support it,
514 // expand it.
515 EVT MemVT = ST->getMemoryVT();
516 const DataLayout &DL = DAG.getDataLayout();
517 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
518 *ST->getMemOperand())) {
519 LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
520 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
521 ReplaceNode(SDValue(ST, 0), Result);
522 } else
523 LLVM_DEBUG(dbgs() << "Legal store\n");
524 break;
525 }
526 case TargetLowering::Custom: {
527 LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
528 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
529 if (Res && Res != SDValue(Node, 0))
530 ReplaceNode(SDValue(Node, 0), Res);
531 return;
532 }
533 case TargetLowering::Promote: {
534 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
535 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
536 "Can only promote stores to same size type");
537 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
538 SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
539 ST->getBaseAlign(), MMOFlags, AAInfo);
540 ReplaceNode(SDValue(Node, 0), Result);
541 break;
542 }
543 }
544 return;
545 }
546
547 LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
548 SDValue Value = ST->getValue();
549 EVT StVT = ST->getMemoryVT();
550 TypeSize StWidth = StVT.getSizeInBits();
551 TypeSize StSize = StVT.getStoreSizeInBits();
552 auto &DL = DAG.getDataLayout();
553
554 if (StWidth != StSize) {
555 // Promote to a byte-sized store with upper bits zero if not
556 // storing an integral number of bytes. For example, promote
557 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
558 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), StSize.getFixedValue());
559 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
561 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
562 ST->getBaseAlign(), MMOFlags, AAInfo);
563 ReplaceNode(SDValue(Node, 0), Result);
564 } else if (!StVT.isVector() && !isPowerOf2_64(StWidth.getFixedValue())) {
565 // If not storing a power-of-2 number of bits, expand as two stores.
566 assert(!StVT.isVector() && "Unsupported truncstore!");
567 unsigned StWidthBits = StWidth.getFixedValue();
568 unsigned LogStWidth = Log2_32(StWidthBits);
569 assert(LogStWidth < 32);
570 unsigned RoundWidth = 1 << LogStWidth;
571 assert(RoundWidth < StWidthBits);
572 unsigned ExtraWidth = StWidthBits - RoundWidth;
573 assert(ExtraWidth < RoundWidth);
574 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
575 "Store size not an integral number of bytes!");
576 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
577 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
578 SDValue Lo, Hi;
579 unsigned IncrementSize;
580
581 if (DL.isLittleEndian()) {
582 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
583 // Store the bottom RoundWidth bits.
584 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
585 RoundVT, ST->getBaseAlign(), MMOFlags, AAInfo);
586
587 // Store the remaining ExtraWidth bits.
588 IncrementSize = RoundWidth / 8;
589 Ptr =
590 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
591 Hi = DAG.getNode(
592 ISD::SRL, dl, Value.getValueType(), Value,
593 DAG.getShiftAmountConstant(RoundWidth, Value.getValueType(), dl));
594 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
595 ST->getPointerInfo().getWithOffset(IncrementSize),
596 ExtraVT, ST->getBaseAlign(), MMOFlags, AAInfo);
597 } else {
598 // Big endian - avoid unaligned stores.
599 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
600 // Store the top RoundWidth bits.
601 Hi = DAG.getNode(
602 ISD::SRL, dl, Value.getValueType(), Value,
603 DAG.getShiftAmountConstant(ExtraWidth, Value.getValueType(), dl));
604 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT,
605 ST->getBaseAlign(), MMOFlags, AAInfo);
606
607 // Store the remaining ExtraWidth bits.
608 IncrementSize = RoundWidth / 8;
609 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
610 DAG.getConstant(IncrementSize, dl,
611 Ptr.getValueType()));
612 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
613 ST->getPointerInfo().getWithOffset(IncrementSize),
614 ExtraVT, ST->getBaseAlign(), MMOFlags, AAInfo);
615 }
616
617 // The order of the stores doesn't matter.
618 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
619 ReplaceNode(SDValue(Node, 0), Result);
620 } else {
621 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT,
622 ST->getAlign(), ST->getAddressSpace())) {
623 default:
624 llvm_unreachable("This action is not supported yet!");
625 case TargetLowering::Legal: {
626 EVT MemVT = ST->getMemoryVT();
627 // If this is an unaligned store and the target doesn't support it,
628 // expand it.
629 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
630 *ST->getMemOperand())) {
631 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
632 ReplaceNode(SDValue(ST, 0), Result);
633 }
634 break;
635 }
636 case TargetLowering::Custom: {
637 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
638 if (Res && Res != SDValue(Node, 0))
639 ReplaceNode(SDValue(Node, 0), Res);
640 return;
641 }
642 case TargetLowering::Expand:
643 assert(!StVT.isVector() &&
644 "Vector Stores are handled in LegalizeVectorOps");
645
647
648 // TRUNCSTORE:i16 i32 -> STORE i16
649 if (TLI.isTypeLegal(StVT)) {
650 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
651 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
652 ST->getBaseAlign(), MMOFlags, AAInfo);
653 } else {
654 // The in-memory type isn't legal. Truncate to the type it would promote
655 // to, and then do a truncstore.
656 Value = DAG.getNode(ISD::TRUNCATE, dl,
657 TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
658 Value);
659 Result = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
660 StVT, ST->getBaseAlign(), MMOFlags, AAInfo);
661 }
662
663 ReplaceNode(SDValue(Node, 0), Result);
664 break;
665 }
666 }
667}
668
669void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
670 LoadSDNode *LD = cast<LoadSDNode>(Node);
671 SDValue Chain = LD->getChain(); // The chain.
672 SDValue Ptr = LD->getBasePtr(); // The base pointer.
673 SDValue Value; // The value returned by the load op.
674 SDLoc dl(Node);
675
676 ISD::LoadExtType ExtType = LD->getExtensionType();
677 if (ExtType == ISD::NON_EXTLOAD) {
678 LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
679 MVT VT = Node->getSimpleValueType(0);
680 SDValue RVal = SDValue(Node, 0);
681 SDValue RChain = SDValue(Node, 1);
682
683 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
684 default: llvm_unreachable("This action is not supported yet!");
685 case TargetLowering::Legal: {
686 EVT MemVT = LD->getMemoryVT();
687 const DataLayout &DL = DAG.getDataLayout();
688 // If this is an unaligned load and the target doesn't support it,
689 // expand it.
690 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
691 *LD->getMemOperand())) {
692 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
693 }
694 break;
695 }
696 case TargetLowering::Custom:
697 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
698 RVal = Res;
699 RChain = Res.getValue(1);
700 }
701 break;
702
703 case TargetLowering::Promote: {
704 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
705 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
706 "Can only promote loads to same size type");
707
708 // If the range metadata type does not match the legalized memory
709 // operation type, remove the range metadata.
710 if (const MDNode *MD = LD->getRanges()) {
711 ConstantInt *Lower = mdconst::extract<ConstantInt>(MD->getOperand(0));
712 if (Lower->getBitWidth() != NVT.getScalarSizeInBits() ||
713 !NVT.isInteger())
714 LD->getMemOperand()->clearRanges();
715 }
716 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
717 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
718 RChain = Res.getValue(1);
719 break;
720 }
721 }
722 if (RChain.getNode() != Node) {
723 assert(RVal.getNode() != Node && "Load must be completely replaced");
724 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
725 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
726 if (UpdatedNodes) {
727 UpdatedNodes->insert(RVal.getNode());
728 UpdatedNodes->insert(RChain.getNode());
729 }
730 ReplacedNode(Node);
731 }
732 return;
733 }
734
735 LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
736 EVT SrcVT = LD->getMemoryVT();
737 TypeSize SrcWidth = SrcVT.getSizeInBits();
738 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
739 AAMDNodes AAInfo = LD->getAAInfo();
740
741 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
742 // Some targets pretend to have an i1 loading operation, and actually
743 // load an i8. This trick is correct for ZEXTLOAD because the top 7
744 // bits are guaranteed to be zero; it helps the optimizers understand
745 // that these bits are zero. It is also useful for EXTLOAD, since it
746 // tells the optimizers that those bits are undefined. It would be
747 // nice to have an effective generic way of getting these benefits...
748 // Until such a way is found, don't insist on promoting i1 here.
749 (SrcVT != MVT::i1 ||
750 TLI.getLoadAction(Node->getValueType(0), MVT::i1, LD->getAlign(),
751 LD->getAddressSpace(), ExtType,
752 false) == TargetLowering::Promote)) {
753 // Promote to a byte-sized load if not loading an integral number of
754 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
755 unsigned NewWidth = SrcVT.getStoreSizeInBits();
756 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
757 SDValue Ch;
758
759 // The extra bits are guaranteed to be zero, since we stored them that
760 // way. A zext load from NVT thus automatically gives zext from SrcVT.
761
762 ISD::LoadExtType NewExtType =
764
765 SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
766 Chain, Ptr, LD->getPointerInfo(), NVT,
767 LD->getBaseAlign(), MMOFlags, AAInfo);
768
769 Ch = Result.getValue(1); // The chain.
770
771 if (ExtType == ISD::SEXTLOAD)
772 // Having the top bits zero doesn't help when sign extending.
774 Result.getValueType(),
775 Result, DAG.getValueType(SrcVT));
776 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
777 // All the top bits are guaranteed to be zero - inform the optimizers.
779 Result.getValueType(), Result,
780 DAG.getValueType(SrcVT));
781
782 Value = Result;
783 Chain = Ch;
784 } else if (!isPowerOf2_64(SrcWidth.getKnownMinValue())) {
785 // If not loading a power-of-2 number of bits, expand as two loads.
786 assert(!SrcVT.isVector() && "Unsupported extload!");
787 unsigned SrcWidthBits = SrcWidth.getFixedValue();
788 unsigned LogSrcWidth = Log2_32(SrcWidthBits);
789 assert(LogSrcWidth < 32);
790 unsigned RoundWidth = 1 << LogSrcWidth;
791 assert(RoundWidth < SrcWidthBits);
792 unsigned ExtraWidth = SrcWidthBits - RoundWidth;
793 assert(ExtraWidth < RoundWidth);
794 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
795 "Load size not an integral number of bytes!");
796 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
797 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
798 SDValue Lo, Hi, Ch;
799 unsigned IncrementSize;
800 auto &DL = DAG.getDataLayout();
801
802 if (DL.isLittleEndian()) {
803 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
804 // Load the bottom RoundWidth bits.
805 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
806 LD->getPointerInfo(), RoundVT, LD->getBaseAlign(),
807 MMOFlags, AAInfo);
808
809 // Load the remaining ExtraWidth bits.
810 IncrementSize = RoundWidth / 8;
811 Ptr =
812 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
813 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
814 LD->getPointerInfo().getWithOffset(IncrementSize),
815 ExtraVT, LD->getBaseAlign(), MMOFlags, AAInfo);
816
817 // Build a factor node to remember that this load is independent of
818 // the other one.
819 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
820 Hi.getValue(1));
821
822 // Move the top bits to the right place.
823 Hi = DAG.getNode(
824 ISD::SHL, dl, Hi.getValueType(), Hi,
825 DAG.getShiftAmountConstant(RoundWidth, Hi.getValueType(), dl));
826
827 // Join the hi and lo parts.
828 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
829 } else {
830 // Big endian - avoid unaligned loads.
831 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
832 // Load the top RoundWidth bits.
833 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
834 LD->getPointerInfo(), RoundVT, LD->getBaseAlign(),
835 MMOFlags, AAInfo);
836
837 // Load the remaining ExtraWidth bits.
838 IncrementSize = RoundWidth / 8;
839 Ptr =
840 DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(IncrementSize), dl);
841 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
842 LD->getPointerInfo().getWithOffset(IncrementSize),
843 ExtraVT, LD->getBaseAlign(), MMOFlags, AAInfo);
844
845 // Build a factor node to remember that this load is independent of
846 // the other one.
847 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
848 Hi.getValue(1));
849
850 // Move the top bits to the right place.
851 Hi = DAG.getNode(
852 ISD::SHL, dl, Hi.getValueType(), Hi,
853 DAG.getShiftAmountConstant(ExtraWidth, Hi.getValueType(), dl));
854
855 // Join the hi and lo parts.
856 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
857 }
858
859 Chain = Ch;
860 } else {
861 bool isCustom = false;
862 switch (TLI.getLoadAction(Node->getValueType(0), SrcVT.getSimpleVT(),
863 LD->getAlign(), LD->getAddressSpace(), ExtType,
864 false)) {
865 default:
866 llvm_unreachable("This action is not supported yet!");
867 case TargetLowering::Custom:
868 isCustom = true;
869 [[fallthrough]];
870 case TargetLowering::Legal:
871 Value = SDValue(Node, 0);
872 Chain = SDValue(Node, 1);
873
874 if (isCustom) {
875 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
876 Value = Res;
877 Chain = Res.getValue(1);
878 }
879 } else {
880 // If this is an unaligned load and the target doesn't support it,
881 // expand it.
882 EVT MemVT = LD->getMemoryVT();
883 const DataLayout &DL = DAG.getDataLayout();
884 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
885 *LD->getMemOperand())) {
886 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
887 }
888 }
889 break;
890
891 case TargetLowering::Expand: {
892 EVT DestVT = Node->getValueType(0);
893 if (!TLI.isLoadLegal(DestVT, SrcVT, LD->getAlign(), LD->getAddressSpace(),
894 ISD::EXTLOAD, false)) {
895 // If the source type is not legal, see if there is a legal extload to
896 // an intermediate type that we can then extend further.
897 EVT LoadVT =
898 TLI.getRegisterType(*DAG.getContext(), SrcVT.getSimpleVT());
899 if ((LoadVT.isFloatingPoint() == SrcVT.isFloatingPoint()) &&
900 (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
901 TLI.isLoadLegal(LoadVT, SrcVT, LD->getAlign(),
902 LD->getAddressSpace(), ExtType, false))) {
903 // If we are loading a legal type, this is a non-extload followed by a
904 // full extend.
905 ISD::LoadExtType MidExtType =
906 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
907
908 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
909 SrcVT, LD->getMemOperand());
910 unsigned ExtendOp =
912 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
913 Chain = Load.getValue(1);
914 break;
915 }
916
917 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
918 // normal undefined upper bits behavior to allow using an in-reg extend
919 // with the illegal FP type, so load as an integer and do the
920 // from-integer conversion.
921 EVT SVT = SrcVT.getScalarType();
922 if (SVT == MVT::f16 || SVT == MVT::bf16) {
923 EVT ISrcVT = SrcVT.changeTypeToInteger();
924 EVT IDestVT = DestVT.changeTypeToInteger();
925 EVT ILoadVT =
926 TLI.getRegisterType(*DAG.getContext(), IDestVT.getSimpleVT());
927
928 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
929 Ptr, ISrcVT, LD->getMemOperand());
930 Value =
931 DAG.getNode(SVT == MVT::f16 ? ISD::FP16_TO_FP : ISD::BF16_TO_FP,
932 dl, DestVT, Result);
933 Chain = Result.getValue(1);
934 break;
935 }
936 }
937
938 assert(!SrcVT.isVector() &&
939 "Vector Loads are handled in LegalizeVectorOps");
940
941 // FIXME: This does not work for vectors on most targets. Sign-
942 // and zero-extend operations are currently folded into extending
943 // loads, whether they are legal or not, and then we end up here
944 // without any support for legalizing them.
945 assert(ExtType != ISD::EXTLOAD &&
946 "EXTLOAD should always be supported!");
947 // Turn the unsupported load into an EXTLOAD followed by an
948 // explicit zero/sign extend inreg.
950 Node->getValueType(0),
951 Chain, Ptr, SrcVT,
952 LD->getMemOperand());
953 SDValue ValRes;
954 if (ExtType == ISD::SEXTLOAD)
955 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
956 Result.getValueType(),
957 Result, DAG.getValueType(SrcVT));
958 else
959 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
960 Value = ValRes;
961 Chain = Result.getValue(1);
962 break;
963 }
964 }
965 }
966
967 // Since loads produce two values, make sure to remember that we legalized
968 // both of them.
969 if (Chain.getNode() != Node) {
970 assert(Value.getNode() != Node && "Load must be completely replaced");
972 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
973 if (UpdatedNodes) {
974 UpdatedNodes->insert(Value.getNode());
975 UpdatedNodes->insert(Chain.getNode());
976 }
977 ReplacedNode(Node);
978 }
979}
980
981/// Return a legal replacement for the given operation, with all legal operands.
982void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
983 LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
984
985 // Allow illegal target nodes and illegal registers.
986 if (Node->getOpcode() == ISD::TargetConstant ||
987 Node->getOpcode() == ISD::Register)
988 return;
989
990#ifndef NDEBUG
991 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
992 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
993 TargetLowering::TypeLegal &&
994 "Unexpected illegal type!");
995
996 for (const SDValue &Op : Node->op_values())
997 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
998 TargetLowering::TypeLegal ||
999 Op.getOpcode() == ISD::TargetConstant ||
1000 Op.getOpcode() == ISD::Register) &&
1001 "Unexpected illegal type!");
1002#endif
1003
1004 // Figure out the correct action; the way to query this varies by opcode
1005 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1006 bool SimpleFinishLegalizing = true;
1007 switch (Node->getOpcode()) {
1011 case ISD::STACKSAVE:
1012 case ISD::STACKADDRESS:
1013 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1014 break;
1016 Action = TLI.getOperationAction(Node->getOpcode(),
1017 Node->getValueType(0));
1018 break;
1019 case ISD::VAARG:
1020 Action = TLI.getOperationAction(Node->getOpcode(),
1021 Node->getValueType(0));
1022 if (Action != TargetLowering::Promote)
1023 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1024 break;
1025 case ISD::SET_FPENV:
1026 case ISD::SET_FPMODE:
1027 Action = TLI.getOperationAction(Node->getOpcode(),
1028 Node->getOperand(1).getValueType());
1029 break;
1030 case ISD::FP_TO_FP16:
1031 case ISD::FP_TO_BF16:
1032 case ISD::SINT_TO_FP:
1033 case ISD::UINT_TO_FP:
1035 case ISD::LROUND:
1036 case ISD::LLROUND:
1037 case ISD::LRINT:
1038 case ISD::LLRINT:
1039 Action = TLI.getOperationAction(Node->getOpcode(),
1040 Node->getOperand(0).getValueType());
1041 break;
1046 case ISD::STRICT_LRINT:
1047 case ISD::STRICT_LLRINT:
1048 case ISD::STRICT_LROUND:
1050 // These pseudo-ops are the same as the other STRICT_ ops except
1051 // they are registered with setOperationAction() using the input type
1052 // instead of the output type.
1053 Action = TLI.getOperationAction(Node->getOpcode(),
1054 Node->getOperand(1).getValueType());
1055 break;
1057 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1058 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1059 break;
1060 }
1061 case ISD::ATOMIC_STORE:
1062 Action = TLI.getOperationAction(Node->getOpcode(),
1063 Node->getOperand(1).getValueType());
1064 break;
1065 case ISD::SELECT_CC:
1066 case ISD::STRICT_FSETCC:
1068 case ISD::SETCC:
1069 case ISD::SETCCCARRY:
1070 case ISD::BR_CC: {
1071 unsigned Opc = Node->getOpcode();
1072 unsigned CCOperand = Opc == ISD::SELECT_CC ? 4
1073 : Opc == ISD::STRICT_FSETCC ? 3
1074 : Opc == ISD::STRICT_FSETCCS ? 3
1075 : Opc == ISD::SETCCCARRY ? 3
1076 : Opc == ISD::SETCC ? 2
1077 : 1;
1078 unsigned CompareOperand = Opc == ISD::BR_CC ? 2
1079 : Opc == ISD::STRICT_FSETCC ? 1
1080 : Opc == ISD::STRICT_FSETCCS ? 1
1081 : 0;
1082 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1083 ISD::CondCode CCCode =
1084 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1085 Action = TLI.getCondCodeAction(CCCode, OpVT);
1086 if (Action == TargetLowering::Legal) {
1087 if (Node->getOpcode() == ISD::SELECT_CC)
1088 Action = TLI.getOperationAction(Node->getOpcode(),
1089 Node->getValueType(0));
1090 else
1091 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1092 }
1093 break;
1094 }
1095 case ISD::LOAD:
1096 case ISD::STORE:
1097 // FIXME: Model these properly. LOAD and STORE are complicated, and
1098 // STORE expects the unlegalized operand in some cases.
1099 SimpleFinishLegalizing = false;
1100 break;
1101 case ISD::CALLSEQ_START:
1102 case ISD::CALLSEQ_END:
1103 // FIXME: This shouldn't be necessary. These nodes have special properties
1104 // dealing with the recursive nature of legalization. Removing this
1105 // special case should be done as part of making LegalizeDAG non-recursive.
1106 SimpleFinishLegalizing = false;
1107 break;
1109 case ISD::GET_ROUNDING:
1110 case ISD::MERGE_VALUES:
1111 case ISD::EH_RETURN:
1113 case ISD::EH_DWARF_CFA:
1117 // These operations lie about being legal: when they claim to be legal,
1118 // they should actually be expanded.
1119 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1120 if (Action == TargetLowering::Legal)
1121 Action = TargetLowering::Expand;
1122 break;
1125 case ISD::FRAMEADDR:
1126 case ISD::RETURNADDR:
1128 case ISD::SPONENTRY:
1129 // These operations lie about being legal: when they claim to be legal,
1130 // they should actually be custom-lowered.
1131 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1132 if (Action == TargetLowering::Legal)
1133 Action = TargetLowering::Custom;
1134 break;
1135 case ISD::CLEAR_CACHE:
1136 // This operation is typically going to be LibCall unless the target wants
1137 // something differrent.
1138 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1139 break;
1142 // READCYCLECOUNTER and READSTEADYCOUNTER return a i64, even if type
1143 // legalization might have expanded that to several smaller types.
1144 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1145 break;
1146 case ISD::READ_REGISTER:
1148 // Named register is legal in the DAG, but blocked by register name
1149 // selection if not implemented by target (to chose the correct register)
1150 // They'll be converted to Copy(To/From)Reg.
1151 Action = TargetLowering::Legal;
1152 break;
1153 case ISD::UBSANTRAP:
1154 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1155 if (Action == TargetLowering::Expand) {
1156 // replace ISD::UBSANTRAP with ISD::TRAP
1157 SDValue NewVal;
1158 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1159 Node->getOperand(0));
1160 ReplaceNode(Node, NewVal.getNode());
1161 LegalizeOp(NewVal.getNode());
1162 return;
1163 }
1164 break;
1165 case ISD::DEBUGTRAP:
1166 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1167 if (Action == TargetLowering::Expand) {
1168 // replace ISD::DEBUGTRAP with ISD::TRAP
1169 SDValue NewVal;
1170 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1171 Node->getOperand(0));
1172 ReplaceNode(Node, NewVal.getNode());
1173 LegalizeOp(NewVal.getNode());
1174 return;
1175 }
1176 break;
1177 case ISD::SADDSAT:
1178 case ISD::UADDSAT:
1179 case ISD::SSUBSAT:
1180 case ISD::USUBSAT:
1181 case ISD::SSHLSAT:
1182 case ISD::USHLSAT:
1183 case ISD::SCMP:
1184 case ISD::UCMP:
1187 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1188 break;
1189 case ISD::SMULFIX:
1190 case ISD::SMULFIXSAT:
1191 case ISD::UMULFIX:
1192 case ISD::UMULFIXSAT:
1193 case ISD::SDIVFIX:
1194 case ISD::SDIVFIXSAT:
1195 case ISD::UDIVFIX:
1196 case ISD::UDIVFIXSAT: {
1197 unsigned Scale = Node->getConstantOperandVal(2);
1198 Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1199 Node->getValueType(0), Scale);
1200 break;
1201 }
1202 case ISD::MSCATTER:
1203 Action = TLI.getOperationAction(Node->getOpcode(),
1204 cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1205 break;
1206 case ISD::MSTORE:
1207 Action = TLI.getOperationAction(Node->getOpcode(),
1208 cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1209 break;
1210 case ISD::VP_SCATTER:
1211 Action = TLI.getOperationAction(
1212 Node->getOpcode(),
1213 cast<VPScatterSDNode>(Node)->getValue().getValueType());
1214 break;
1215 case ISD::VP_STORE:
1216 Action = TLI.getOperationAction(
1217 Node->getOpcode(),
1218 cast<VPStoreSDNode>(Node)->getValue().getValueType());
1219 break;
1220 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1221 Action = TLI.getOperationAction(
1222 Node->getOpcode(),
1223 cast<VPStridedStoreSDNode>(Node)->getValue().getValueType());
1224 break;
1227 case ISD::VECREDUCE_ADD:
1228 case ISD::VECREDUCE_MUL:
1229 case ISD::VECREDUCE_AND:
1230 case ISD::VECREDUCE_OR:
1231 case ISD::VECREDUCE_XOR:
1240 case ISD::IS_FPCLASS:
1241 Action = TLI.getOperationAction(
1242 Node->getOpcode(), Node->getOperand(0).getValueType());
1243 break;
1246 case ISD::VP_REDUCE_FADD:
1247 case ISD::VP_REDUCE_FMUL:
1248 case ISD::VP_REDUCE_ADD:
1249 case ISD::VP_REDUCE_MUL:
1250 case ISD::VP_REDUCE_AND:
1251 case ISD::VP_REDUCE_OR:
1252 case ISD::VP_REDUCE_XOR:
1253 case ISD::VP_REDUCE_SMAX:
1254 case ISD::VP_REDUCE_SMIN:
1255 case ISD::VP_REDUCE_UMAX:
1256 case ISD::VP_REDUCE_UMIN:
1257 case ISD::VP_REDUCE_FMAX:
1258 case ISD::VP_REDUCE_FMIN:
1259 case ISD::VP_REDUCE_FMAXIMUM:
1260 case ISD::VP_REDUCE_FMINIMUM:
1261 case ISD::VP_REDUCE_SEQ_FADD:
1262 case ISD::VP_REDUCE_SEQ_FMUL:
1263 Action = TLI.getOperationAction(
1264 Node->getOpcode(), Node->getOperand(1).getValueType());
1265 break;
1266 case ISD::CTTZ_ELTS:
1268 case ISD::VP_CTTZ_ELTS:
1269 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
1270 Action = TLI.getOperationAction(Node->getOpcode(),
1271 Node->getOperand(0).getValueType());
1272 break;
1274 Action = TLI.getOperationAction(
1275 Node->getOpcode(),
1276 cast<MaskedHistogramSDNode>(Node)->getIndex().getValueType());
1277 break;
1278 default:
1279 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1280 Action = TLI.getCustomOperationAction(*Node);
1281 } else {
1282 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1283 }
1284 break;
1285 }
1286
1287 if (SimpleFinishLegalizing) {
1288 SDNode *NewNode = Node;
1289 switch (Node->getOpcode()) {
1290 default: break;
1291 case ISD::SHL:
1292 case ISD::SRL:
1293 case ISD::SRA:
1294 case ISD::ROTL:
1295 case ISD::ROTR:
1296 case ISD::SSHLSAT:
1297 case ISD::USHLSAT: {
1298 // Legalizing shifts/rotates requires adjusting the shift amount
1299 // to the appropriate width.
1300 SDValue Op0 = Node->getOperand(0);
1301 SDValue Op1 = Node->getOperand(1);
1302 if (!Op1.getValueType().isVector()) {
1303 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1304 // The getShiftAmountOperand() may create a new operand node or
1305 // return the existing one. If new operand is created we need
1306 // to update the parent node.
1307 // Do not try to legalize SAO here! It will be automatically legalized
1308 // in the next round.
1309 if (SAO != Op1)
1310 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1311 }
1312 break;
1313 }
1314 case ISD::FSHL:
1315 case ISD::FSHR:
1316 case ISD::SRL_PARTS:
1317 case ISD::SRA_PARTS:
1318 case ISD::SHL_PARTS: {
1319 // Legalizing shifts/rotates requires adjusting the shift amount
1320 // to the appropriate width.
1321 SDValue Op0 = Node->getOperand(0);
1322 SDValue Op1 = Node->getOperand(1);
1323 SDValue Op2 = Node->getOperand(2);
1324 if (!Op2.getValueType().isVector()) {
1325 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1326 // The getShiftAmountOperand() may create a new operand node or
1327 // return the existing one. If new operand is created we need
1328 // to update the parent node.
1329 if (SAO != Op2)
1330 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1331 }
1332 break;
1333 }
1334 }
1335
1336 if (NewNode != Node) {
1337 ReplaceNode(Node, NewNode);
1338 Node = NewNode;
1339 }
1340 switch (Action) {
1341 case TargetLowering::Legal:
1342 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1343 return;
1344 case TargetLowering::Custom:
1345 LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1346 // FIXME: The handling for custom lowering with multiple results is
1347 // a complete mess.
1348 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1349 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1350 return;
1351
1352 if (Node->getNumValues() == 1) {
1353 // Verify the new types match the original. Glue is waived because
1354 // ISD::ADDC can be legalized by replacing Glue with an integer type.
1355 assert((Res.getValueType() == Node->getValueType(0) ||
1356 Node->getValueType(0) == MVT::Glue) &&
1357 "Type mismatch for custom legalized operation");
1358 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1359 // We can just directly replace this node with the lowered value.
1360 ReplaceNode(SDValue(Node, 0), Res);
1361 return;
1362 }
1363
1364 SmallVector<SDValue, 8> ResultVals;
1365 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1366 // Verify the new types match the original. Glue is waived because
1367 // ISD::ADDC can be legalized by replacing Glue with an integer type.
1368 assert((Res->getValueType(i) == Node->getValueType(i) ||
1369 Node->getValueType(i) == MVT::Glue) &&
1370 "Type mismatch for custom legalized operation");
1371 ResultVals.push_back(Res.getValue(i));
1372 }
1373 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1374 ReplaceNode(Node, ResultVals.data());
1375 return;
1376 }
1377 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1378 [[fallthrough]];
1379 case TargetLowering::Expand:
1380 if (ExpandNode(Node))
1381 return;
1382 [[fallthrough]];
1383 case TargetLowering::LibCall:
1384 ConvertNodeToLibcall(Node);
1385 return;
1386 case TargetLowering::Promote:
1387 PromoteNode(Node);
1388 return;
1389 }
1390 }
1391
1392 switch (Node->getOpcode()) {
1393 default:
1394#ifndef NDEBUG
1395 dbgs() << "NODE: ";
1396 Node->dump( &DAG);
1397 dbgs() << "\n";
1398#endif
1399 llvm_unreachable("Do not know how to legalize this operator!");
1400
1401 case ISD::CALLSEQ_START:
1402 case ISD::CALLSEQ_END:
1403 break;
1404 case ISD::LOAD:
1405 return LegalizeLoadOps(Node);
1406 case ISD::STORE:
1407 return LegalizeStoreOps(Node);
1408 }
1409}
1410
1411SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1412 SDValue Vec = Op.getOperand(0);
1413 SDValue Idx = Op.getOperand(1);
1414 SDLoc dl(Op);
1415
1416 // Before we generate a new store to a temporary stack slot, see if there is
1417 // already one that we can use. There often is because when we scalarize
1418 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1419 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1420 // the vector. If all are expanded here, we don't want one store per vector
1421 // element.
1422
1423 // Caches for hasPredecessorHelper
1424 SmallPtrSet<const SDNode *, 32> Visited;
1426 Visited.insert(Op.getNode());
1427 Worklist.push_back(Idx.getNode());
1428 SDValue StackPtr, Ch;
1429 for (SDNode *User : Vec.getNode()->users()) {
1430 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1431 if (ST->isIndexed() || ST->isTruncatingStore() ||
1432 ST->getValue() != Vec)
1433 continue;
1434
1435 // Make sure that nothing else could have stored into the destination of
1436 // this store.
1437 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1438 continue;
1439
1440 // If the index is dependent on the store we will introduce a cycle when
1441 // creating the load (the load uses the index, and by replacing the chain
1442 // we will make the index dependent on the load). Also, the store might be
1443 // dependent on the extractelement and introduce a cycle when creating
1444 // the load.
1445 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1446 ST->hasPredecessor(Op.getNode()))
1447 continue;
1448
1449 StackPtr = ST->getBasePtr();
1450 Ch = SDValue(ST, 0);
1451 break;
1452 }
1453 }
1454
1455 EVT VecVT = Vec.getValueType();
1456
1457 if (!Ch.getNode()) {
1458 // Store the value to a temporary stack slot, then LOAD the returned part.
1459 StackPtr = DAG.CreateStackTemporary(VecVT);
1460 MachineMemOperand *StoreMMO = getStackAlignedMMO(
1461 StackPtr, DAG.getMachineFunction(), VecVT.isScalableVector());
1462 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, StoreMMO);
1463 }
1464
1465 SDValue NewLoad;
1466 Align ElementAlignment =
1467 std::min(cast<StoreSDNode>(Ch)->getAlign(),
1469 Op.getValueType().getTypeForEVT(*DAG.getContext())));
1470
1471 if (Op.getValueType().isVector()) {
1472 StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT,
1473 Op.getValueType(), Idx);
1474 NewLoad = DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,
1475 MachinePointerInfo(), ElementAlignment);
1476 } else {
1477 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1478 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1479 MachinePointerInfo(), VecVT.getVectorElementType(),
1480 ElementAlignment);
1481 }
1482
1483 // Replace the chain going out of the store, by the one out of the load.
1484 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1485
1486 // We introduced a cycle though, so update the loads operands, making sure
1487 // to use the original store's chain as an incoming chain.
1488 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->ops());
1489 NewLoadOperands[0] = Ch;
1490 NewLoad =
1491 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1492 return NewLoad;
1493}
1494
1495SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1496 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1497
1498 SDValue Vec = Op.getOperand(0);
1499 SDValue Part = Op.getOperand(1);
1500 SDValue Idx = Op.getOperand(2);
1501 SDLoc dl(Op);
1502
1503 // Store the value to a temporary stack slot, then LOAD the returned part.
1504 EVT VecVT = Vec.getValueType();
1505 EVT PartVT = Part.getValueType();
1507 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1508 MachinePointerInfo PtrInfo =
1510
1511 // First store the whole vector.
1512 Align BaseVecAlignment =
1514 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1515 BaseVecAlignment);
1516
1517 // Freeze the index so we don't poison the clamping code we're about to emit.
1518 Idx = DAG.getFreeze(Idx);
1519
1520 Type *PartTy = PartVT.getTypeForEVT(*DAG.getContext());
1521 Align PartAlignment = DAG.getDataLayout().getPrefTypeAlign(PartTy);
1522
1523 // Then store the inserted part.
1524 if (PartVT.isVector()) {
1525 SDValue SubStackPtr =
1526 TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, PartVT, Idx);
1527
1528 // Store the subvector.
1529 Ch = DAG.getStore(
1530 Ch, dl, Part, SubStackPtr,
1532 PartAlignment);
1533 } else {
1534 SDValue SubStackPtr =
1535 TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1536
1537 // Store the scalar value.
1538 Ch = DAG.getTruncStore(
1539 Ch, dl, Part, SubStackPtr,
1541 VecVT.getVectorElementType(), PartAlignment);
1542 }
1543
1544 assert(cast<StoreSDNode>(Ch)->getAlign() == PartAlignment &&
1545 "ElementAlignment does not match!");
1546
1547 // Finally, load the updated vector.
1548 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1549 BaseVecAlignment);
1550}
1551
1552SDValue SelectionDAGLegalize::ExpandConcatVectors(SDNode *Node) {
1553 assert(Node->getOpcode() == ISD::CONCAT_VECTORS && "Unexpected opcode!");
1554 SDLoc DL(Node);
1556 unsigned NumOperands = Node->getNumOperands();
1557 MVT VectorIdxType = TLI.getVectorIdxTy(DAG.getDataLayout());
1558 EVT VectorValueType = Node->getOperand(0).getValueType();
1559 unsigned NumSubElem = VectorValueType.getVectorNumElements();
1560 EVT ElementValueType = TLI.getTypeToTransformTo(
1561 *DAG.getContext(), VectorValueType.getVectorElementType());
1562 for (unsigned I = 0; I < NumOperands; ++I) {
1563 SDValue SubOp = Node->getOperand(I);
1564 for (unsigned Idx = 0; Idx < NumSubElem; ++Idx) {
1565 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElementValueType,
1566 SubOp,
1567 DAG.getConstant(Idx, DL, VectorIdxType)));
1568 }
1569 }
1570 return DAG.getBuildVector(Node->getValueType(0), DL, Ops);
1571}
1572
1573SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1574 assert((Node->getOpcode() == ISD::BUILD_VECTOR ||
1575 Node->getOpcode() == ISD::CONCAT_VECTORS) &&
1576 "Unexpected opcode!");
1577
1578 // We can't handle this case efficiently. Allocate a sufficiently
1579 // aligned object on the stack, store each operand into it, then load
1580 // the result as a vector.
1581 // Create the stack frame object.
1582 EVT VT = Node->getValueType(0);
1583 EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType()
1584 : Node->getOperand(0).getValueType();
1585 SDLoc dl(Node);
1586 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1587 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1588 MachinePointerInfo PtrInfo =
1590
1591 // Emit a store of each element to the stack slot.
1593 unsigned TypeByteSize = MemVT.getSizeInBits() / 8;
1594 assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1595
1596 // If the destination vector element type of a BUILD_VECTOR is narrower than
1597 // the source element type, only store the bits necessary.
1598 bool Truncate = isa<BuildVectorSDNode>(Node) &&
1599 MemVT.bitsLT(Node->getOperand(0).getValueType());
1600
1601 // Store (in the right endianness) the elements to memory.
1602 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1603 // Ignore undef elements.
1604 if (Node->getOperand(i).isUndef()) continue;
1605
1606 unsigned Offset = TypeByteSize*i;
1607
1608 SDValue Idx =
1610
1611 if (Truncate)
1612 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1613 Node->getOperand(i), Idx,
1614 PtrInfo.getWithOffset(Offset), MemVT));
1615 else
1616 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1617 Idx, PtrInfo.getWithOffset(Offset)));
1618 }
1619
1620 SDValue StoreChain;
1621 if (!Stores.empty()) // Not all undef elements?
1622 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1623 else
1624 StoreChain = DAG.getEntryNode();
1625
1626 // Result is a load from the stack slot.
1627 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1628}
1629
1630/// Bitcast a floating-point value to an integer value. Only bitcast the part
1631/// containing the sign bit if the target has no integer value capable of
1632/// holding all bits of the floating-point value.
1633void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1634 const SDLoc &DL,
1635 SDValue Value) const {
1636 EVT FloatVT = Value.getValueType();
1637 unsigned NumBits = FloatVT.getScalarSizeInBits();
1638 State.FloatVT = FloatVT;
1639 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1640 // Convert to an integer of the same size.
1641 if (TLI.isTypeLegal(IVT)) {
1642 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1643 State.SignMask = APInt::getSignMask(NumBits);
1644 State.SignBit = NumBits - 1;
1645 return;
1646 }
1647
1648 auto &DataLayout = DAG.getDataLayout();
1649 // Store the float to memory, then load the sign part out as an integer.
1650 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1651 // First create a temporary that is aligned for both the load and store.
1652 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1653 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1654 // Then store the float to it.
1655 State.FloatPtr = StackPtr;
1657 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1658 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1659 State.FloatPointerInfo);
1660
1661 SDValue IntPtr;
1662 if (DataLayout.isBigEndian()) {
1663 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1664 // Load out a legal integer with the same sign bit as the float.
1665 IntPtr = StackPtr;
1666 State.IntPointerInfo = State.FloatPointerInfo;
1667 } else {
1668 // Advance the pointer so that the loaded byte will contain the sign bit.
1669 unsigned ByteOffset = (NumBits / 8) - 1;
1670 IntPtr =
1671 DAG.getMemBasePlusOffset(StackPtr, TypeSize::getFixed(ByteOffset), DL);
1672 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1673 ByteOffset);
1674 }
1675
1676 State.IntPtr = IntPtr;
1677 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1678 State.IntPointerInfo, MVT::i8);
1679 State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7);
1680 State.SignBit = 7;
1681}
1682
1683/// Replace the integer value produced by getSignAsIntValue() with a new value
1684/// and cast the result back to a floating-point type.
1685SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1686 const SDLoc &DL,
1687 SDValue NewIntValue) const {
1688 if (!State.Chain)
1689 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1690
1691 // Override the part containing the sign bit in the value stored on the stack.
1692 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1693 State.IntPointerInfo, MVT::i8);
1694 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1695 State.FloatPointerInfo);
1696}
1697
1698SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1699 SDLoc DL(Node);
1700 SDValue Mag = Node->getOperand(0);
1701 SDValue Sign = Node->getOperand(1);
1702
1703 if (Sign.getValueType().isVector())
1704 return DAG.UnrollVectorOp(Node);
1705
1706 // Get sign bit into an integer value.
1707 FloatSignAsInt SignAsInt;
1708 getSignAsIntValue(SignAsInt, DL, Sign);
1709
1710 EVT IntVT = SignAsInt.IntValue.getValueType();
1711 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1712 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1713 SignMask);
1714
1715 // If FABS is legal transform
1716 // FCOPYSIGN(x, y) => SignBit(y) ? -FABS(x) : FABS(x)
1717 EVT FloatVT = Mag.getValueType();
1718 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1719 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1720 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1721 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1722 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1723 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1724 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1725 }
1726
1727 // Transform Mag value to integer, and clear the sign bit.
1728 FloatSignAsInt MagAsInt;
1729 getSignAsIntValue(MagAsInt, DL, Mag);
1730 EVT MagVT = MagAsInt.IntValue.getValueType();
1731 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1732 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1733 ClearSignMask);
1734
1735 // Get the signbit at the right position for MagAsInt.
1736 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1737 EVT ShiftVT = IntVT;
1738 if (SignBit.getScalarValueSizeInBits() <
1739 ClearedSign.getScalarValueSizeInBits()) {
1740 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1741 ShiftVT = MagVT;
1742 }
1743 if (ShiftAmount > 0) {
1744 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1745 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1746 } else if (ShiftAmount < 0) {
1747 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1748 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1749 }
1750 if (SignBit.getScalarValueSizeInBits() >
1751 ClearedSign.getScalarValueSizeInBits()) {
1752 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1753 }
1754
1755 // Store the part with the modified sign and convert back to float.
1756 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit,
1758
1759 return modifySignAsInt(MagAsInt, DL, CopiedSign);
1760}
1761
1762SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const {
1763 // Get the sign bit as an integer.
1764 SDLoc DL(Node);
1765 if (Node->getValueType(0).isVector())
1766 return DAG.UnrollVectorOp(Node);
1767
1768 FloatSignAsInt SignAsInt;
1769 getSignAsIntValue(SignAsInt, DL, Node->getOperand(0));
1770 EVT IntVT = SignAsInt.IntValue.getValueType();
1771
1772 // Flip the sign.
1773 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1774 SDValue SignFlip =
1775 DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask);
1776
1777 // Convert back to float.
1778 return modifySignAsInt(SignAsInt, DL, SignFlip);
1779}
1780
1781SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1782 SDLoc DL(Node);
1783 SDValue Value = Node->getOperand(0);
1784
1785 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1786 EVT FloatVT = Value.getValueType();
1787 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1788 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1789 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1790 }
1791
1792 if (FloatVT.isVector())
1793 return DAG.UnrollVectorOp(Node);
1794
1795 // Transform value to integer, clear the sign bit and transform back.
1796 FloatSignAsInt ValueAsInt;
1797 getSignAsIntValue(ValueAsInt, DL, Value);
1798 EVT IntVT = ValueAsInt.IntValue.getValueType();
1799 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1800 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1801 ClearSignMask);
1802 return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1803}
1804
1805void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1806 SmallVectorImpl<SDValue> &Results) {
1808 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1809 " not tell us which reg is the stack pointer!");
1810 SDLoc dl(Node);
1811 EVT VT = Node->getValueType(0);
1812 SDValue Tmp1 = SDValue(Node, 0);
1813 SDValue Tmp2 = SDValue(Node, 1);
1814 SDValue Tmp3 = Node->getOperand(2);
1815 SDValue Chain = Tmp1.getOperand(0);
1816
1817 // Chain the dynamic stack allocation so that it doesn't modify the stack
1818 // pointer when other instructions are using the stack.
1819 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1820
1821 SDValue Size = Tmp2.getOperand(1);
1822 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1823 Chain = SP.getValue(1);
1824 Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue();
1825 const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering();
1826 unsigned Opc =
1829
1830 Align StackAlign = TFL->getStackAlign();
1831 Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value
1832 if (Alignment > StackAlign)
1833 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1834 DAG.getSignedConstant(-Alignment.value(), dl, VT));
1835 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1836
1837 Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
1838
1839 Results.push_back(Tmp1);
1840 Results.push_back(Tmp2);
1841}
1842
1843/// Emit a store/load combination to the stack. This stores
1844/// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1845/// a load from the stack slot to DestVT, extending it if needed.
1846/// The resultant code need not be legal.
1847SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1848 EVT DestVT, const SDLoc &dl) {
1849 return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1850}
1851
1852SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1853 EVT DestVT, const SDLoc &dl,
1854 SDValue Chain) {
1855 EVT SrcVT = SrcOp.getValueType();
1856 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1857 Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType);
1858
1859 // Don't convert with stack if the load/store is expensive.
1860 if ((SrcVT.bitsGT(SlotVT) && !TLI.isTruncStoreLegalOrCustom(
1861 SrcOp.getValueType(), SlotVT, DestAlign,
1863 (SlotVT.bitsLT(DestVT) &&
1864 !TLI.isLoadLegalOrCustom(DestVT, SlotVT, DestAlign,
1866 ISD::EXTLOAD, false)))
1867 return SDValue();
1868
1869 // Create the stack frame object.
1870 Align SrcAlign = DAG.getDataLayout().getPrefTypeAlign(
1871 SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1872 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
1873
1874 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1875 int SPFI = StackPtrFI->getIndex();
1876 MachinePointerInfo PtrInfo =
1878
1879 // Emit a store to the stack slot. Use a truncstore if the input value is
1880 // later than DestVT.
1881 SDValue Store;
1882
1883 if (SrcVT.bitsGT(SlotVT))
1884 Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
1885 SlotVT, SrcAlign);
1886 else {
1887 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
1888 Store = DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1889 }
1890
1891 // Result is a load from the stack slot.
1892 if (SlotVT.bitsEq(DestVT))
1893 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1894
1895 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
1896 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1897 DestAlign);
1898}
1899
1900SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1901 SDLoc dl(Node);
1902 // Create a vector sized/aligned stack slot, store the value to element #0,
1903 // then load the whole vector back out.
1904 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1905
1906 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1907 int SPFI = StackPtrFI->getIndex();
1908
1909 SDValue Ch = DAG.getTruncStore(
1910 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1912 Node->getValueType(0).getVectorElementType());
1913 return DAG.getLoad(
1914 Node->getValueType(0), dl, Ch, StackPtr,
1916}
1917
1918static bool
1920 const TargetLowering &TLI, SDValue &Res) {
1921 unsigned NumElems = Node->getNumOperands();
1922 SDLoc dl(Node);
1923 EVT VT = Node->getValueType(0);
1924
1925 // Try to group the scalars into pairs, shuffle the pairs together, then
1926 // shuffle the pairs of pairs together, etc. until the vector has
1927 // been built. This will work only if all of the necessary shuffle masks
1928 // are legal.
1929
1930 // We do this in two phases; first to check the legality of the shuffles,
1931 // and next, assuming that all shuffles are legal, to create the new nodes.
1932 for (int Phase = 0; Phase < 2; ++Phase) {
1934 NewIntermedVals;
1935 for (unsigned i = 0; i < NumElems; ++i) {
1936 SDValue V = Node->getOperand(i);
1937 if (V.isUndef())
1938 continue;
1939
1940 SDValue Vec;
1941 if (Phase)
1942 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1943 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1944 }
1945
1946 while (IntermedVals.size() > 2) {
1947 NewIntermedVals.clear();
1948 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1949 // This vector and the next vector are shuffled together (simply to
1950 // append the one to the other).
1951 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1952
1953 SmallVector<int, 16> FinalIndices;
1954 FinalIndices.reserve(IntermedVals[i].second.size() +
1955 IntermedVals[i+1].second.size());
1956
1957 int k = 0;
1958 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1959 ++j, ++k) {
1960 ShuffleVec[k] = j;
1961 FinalIndices.push_back(IntermedVals[i].second[j]);
1962 }
1963 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1964 ++j, ++k) {
1965 ShuffleVec[k] = NumElems + j;
1966 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1967 }
1968
1969 SDValue Shuffle;
1970 if (Phase)
1971 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1972 IntermedVals[i+1].first,
1973 ShuffleVec);
1974 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1975 return false;
1976 NewIntermedVals.push_back(
1977 std::make_pair(Shuffle, std::move(FinalIndices)));
1978 }
1979
1980 // If we had an odd number of defined values, then append the last
1981 // element to the array of new vectors.
1982 if ((IntermedVals.size() & 1) != 0)
1983 NewIntermedVals.push_back(IntermedVals.back());
1984
1985 IntermedVals.swap(NewIntermedVals);
1986 }
1987
1988 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1989 "Invalid number of intermediate vectors");
1990 SDValue Vec1 = IntermedVals[0].first;
1991 SDValue Vec2;
1992 if (IntermedVals.size() > 1)
1993 Vec2 = IntermedVals[1].first;
1994 else if (Phase)
1995 Vec2 = DAG.getPOISON(VT);
1996
1997 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1998 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1999 ShuffleVec[IntermedVals[0].second[i]] = i;
2000 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
2001 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
2002
2003 if (Phase)
2004 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
2005 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
2006 return false;
2007 }
2008
2009 return true;
2010}
2011
2012/// Expand a BUILD_VECTOR node on targets that don't
2013/// support the operation, but do support the resultant vector type.
2014SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2015 unsigned NumElems = Node->getNumOperands();
2016 SDValue Value1, Value2;
2017 SDLoc dl(Node);
2018 EVT VT = Node->getValueType(0);
2019 EVT OpVT = Node->getOperand(0).getValueType();
2020 EVT EltVT = VT.getVectorElementType();
2021
2022 // If the only non-undef value is the low element, turn this into a
2023 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
2024 bool isOnlyLowElement = true;
2025 bool MoreThanTwoValues = false;
2026 bool isConstant = true;
2027 for (unsigned i = 0; i < NumElems; ++i) {
2028 SDValue V = Node->getOperand(i);
2029 if (V.isUndef())
2030 continue;
2031 if (i > 0)
2032 isOnlyLowElement = false;
2034 isConstant = false;
2035
2036 if (!Value1.getNode()) {
2037 Value1 = V;
2038 } else if (!Value2.getNode()) {
2039 if (V != Value1)
2040 Value2 = V;
2041 } else if (V != Value1 && V != Value2) {
2042 MoreThanTwoValues = true;
2043 }
2044 }
2045
2046 if (!Value1.getNode())
2047 return DAG.getUNDEF(VT);
2048
2049 if (isOnlyLowElement)
2050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2051
2052 // If all elements are constants, create a load from the constant pool.
2053 if (isConstant) {
2055 for (unsigned i = 0, e = NumElems; i != e; ++i) {
2056 if (ConstantFPSDNode *V =
2057 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2058 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2059 } else if (ConstantSDNode *V =
2060 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2061 if (OpVT==EltVT)
2062 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2063 else {
2064 // If OpVT and EltVT don't match, EltVT is not legal and the
2065 // element values have been promoted/truncated earlier. Undo this;
2066 // we don't want a v16i8 to become a v16i32 for example.
2067 const ConstantInt *CI = V->getConstantIntValue();
2068 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2069 CI->getZExtValue(), /*IsSigned=*/false,
2070 /*ImplicitTrunc=*/true));
2071 }
2072 } else {
2073 assert(Node->getOperand(i).isUndef());
2074 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2075 CV.push_back(UndefValue::get(OpNTy));
2076 }
2077 }
2078 Constant *CP = ConstantVector::get(CV);
2079 SDValue CPIdx =
2080 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
2081 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
2082 return DAG.getLoad(
2083 VT, dl, DAG.getEntryNode(), CPIdx,
2085 Alignment);
2086 }
2087
2088 SmallSet<SDValue, 16> DefinedValues;
2089 for (unsigned i = 0; i < NumElems; ++i) {
2090 if (Node->getOperand(i).isUndef())
2091 continue;
2092 DefinedValues.insert(Node->getOperand(i));
2093 }
2094
2095 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
2096 if (!MoreThanTwoValues) {
2097 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2098 for (unsigned i = 0; i < NumElems; ++i) {
2099 SDValue V = Node->getOperand(i);
2100 if (V.isUndef())
2101 continue;
2102 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2103 }
2104 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2105 // Get the splatted value into the low element of a vector register.
2106 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2107 SDValue Vec2;
2108 if (Value2.getNode())
2109 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2110 else
2111 Vec2 = DAG.getPOISON(VT);
2112
2113 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2114 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
2115 }
2116 } else {
2117 SDValue Res;
2118 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2119 return Res;
2120 }
2121 }
2122
2123 // Otherwise, we can't handle this case efficiently.
2124 return ExpandVectorBuildThroughStack(Node);
2125}
2126
2127SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) {
2128 SDLoc DL(Node);
2129 EVT VT = Node->getValueType(0);
2130 SDValue SplatVal = Node->getOperand(0);
2131
2132 return DAG.getSplatBuildVector(VT, DL, SplatVal);
2133}
2134
2135// Expand a node into a call to a libcall, returning the value as the first
2136// result and the chain as the second. If the result value does not fit into a
2137// register, return the lo part and set the hi part to the by-reg argument in
2138// the first. If it does fit into a single register, return the result and
2139// leave the Hi part unset.
2140std::pair<SDValue, SDValue>
2141SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2142 TargetLowering::ArgListTy &&Args,
2143 bool IsSigned, EVT RetVT) {
2144 EVT CodePtrTy = TLI.getPointerTy(DAG.getDataLayout());
2146 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
2147 if (LCImpl != RTLIB::Unsupported)
2148 Callee = DAG.getExternalSymbol(LCImpl, CodePtrTy);
2149 else {
2150 Callee = DAG.getPOISON(CodePtrTy);
2151 DAG.getContext()->emitError(Twine("no libcall available for ") +
2152 Node->getOperationName(&DAG));
2153 }
2154
2155 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2156
2157 // By default, the input chain to this libcall is the entry node of the
2158 // function. If the libcall is going to be emitted as a tail call then
2159 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2160 // node which is being folded has a non-entry input chain.
2161 SDValue InChain = DAG.getEntryNode();
2162
2163 // isTailCall may be true since the callee does not reference caller stack
2164 // frame. Check if it's in the right position and that the return types match.
2165 SDValue TCChain = InChain;
2166 const Function &F = DAG.getMachineFunction().getFunction();
2167 bool isTailCall =
2168 TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2169 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()) &&
2170 // Lowering doesn't support tail calling inside a function with
2171 // a swifterror argument yet.
2172 !DAG.hasSwiftErrorArg();
2173 if (isTailCall)
2174 InChain = TCChain;
2175
2176 TargetLowering::CallLoweringInfo CLI(DAG);
2177 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2178 CLI.setDebugLoc(SDLoc(Node))
2179 .setChain(InChain)
2180 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LCImpl), RetTy,
2181 Callee, std::move(Args))
2182 .setTailCall(isTailCall)
2183 .setSExtResult(signExtend)
2184 .setZExtResult(!signExtend)
2185 .setIsPostTypeLegalization(true);
2186
2187 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2188
2189 if (!CallInfo.second.getNode()) {
2190 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
2191 // It's a tailcall, return the chain (which is the DAG root).
2192 return {DAG.getRoot(), DAG.getRoot()};
2193 }
2194
2195 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
2196 return CallInfo;
2197}
2198
2199std::pair<SDValue, SDValue> SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2200 bool isSigned) {
2201 TargetLowering::ArgListTy Args;
2202 for (const SDValue &Op : Node->op_values()) {
2203 EVT ArgVT = Op.getValueType();
2204 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2205 TargetLowering::ArgListEntry Entry(Op, ArgTy);
2206 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, isSigned);
2207 Entry.IsZExt = !Entry.IsSExt;
2208 Args.push_back(Entry);
2209 }
2210
2211 return ExpandLibCall(LC, Node, std::move(Args), isSigned,
2212 Node->getValueType(0));
2213}
2214
2215void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2216 RTLIB::Libcall LC,
2217 SmallVectorImpl<SDValue> &Results) {
2218 if (LC == RTLIB::UNKNOWN_LIBCALL)
2219 llvm_unreachable("Can't create an unknown libcall!");
2220
2221 if (Node->isStrictFPOpcode()) {
2222 EVT RetVT = Node->getValueType(0);
2223 RTLIB::LibcallImpl LCImpl = DAG.getLibcalls().getLibcallImpl(LC);
2224 if (LCImpl == RTLIB::Unsupported) {
2225 DAG.getContext()->emitError(Twine("no libcall available for ") +
2226 Node->getOperationName(&DAG));
2227 Results.push_back(DAG.getPOISON(RetVT));
2228 Results.push_back(Node->getOperand(0));
2229 return;
2230 }
2232 TargetLowering::MakeLibCallOptions CallOptions;
2233 CallOptions.IsPostTypeLegalization = true;
2234 // FIXME: This doesn't support tail calls.
2235 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
2236 DAG, LCImpl, RetVT, Ops, CallOptions, SDLoc(Node), Node->getOperand(0));
2237 Results.push_back(Tmp.first);
2238 Results.push_back(Tmp.second);
2239 } else {
2240 bool IsSignedArgument = Node->getOpcode() == ISD::FLDEXP;
2241 SDValue Tmp = ExpandLibCall(LC, Node, IsSignedArgument).first;
2242 Results.push_back(Tmp);
2243 }
2244}
2245
2246/// Expand the node to a libcall based on the result type.
2247void SelectionDAGLegalize::ExpandFastFPLibCall(
2248 SDNode *Node, bool IsFast,
2249 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F32,
2250 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F64,
2251 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F80,
2252 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_F128,
2253 std::pair<RTLIB::Libcall, RTLIB::Libcall> Call_PPCF128,
2254 SmallVectorImpl<SDValue> &Results) {
2255
2256 EVT VT = Node->getSimpleValueType(0);
2257
2258 RTLIB::Libcall LC;
2259
2260 // FIXME: Probably should define fast to respect nan/inf and only be
2261 // approximate functions.
2262
2263 if (IsFast) {
2264 LC = RTLIB::getFPLibCall(VT, Call_F32.first, Call_F64.first, Call_F80.first,
2265 Call_F128.first, Call_PPCF128.first);
2266 }
2267
2268 if (!IsFast || DAG.getLibcalls().getLibcallImpl(LC) == RTLIB::Unsupported) {
2269 // Fall back if we don't have a fast implementation.
2270 LC = RTLIB::getFPLibCall(VT, Call_F32.second, Call_F64.second,
2271 Call_F80.second, Call_F128.second,
2272 Call_PPCF128.second);
2273 }
2274
2275 ExpandFPLibCall(Node, LC, Results);
2276}
2277
2278SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2279 RTLIB::Libcall Call_I8,
2280 RTLIB::Libcall Call_I16,
2281 RTLIB::Libcall Call_I32,
2282 RTLIB::Libcall Call_I64,
2283 RTLIB::Libcall Call_I128) {
2284 RTLIB::Libcall LC;
2285 switch (Node->getSimpleValueType(0).SimpleTy) {
2286 default: llvm_unreachable("Unexpected request for libcall!");
2287 case MVT::i8: LC = Call_I8; break;
2288 case MVT::i16: LC = Call_I16; break;
2289 case MVT::i32: LC = Call_I32; break;
2290 case MVT::i64: LC = Call_I64; break;
2291 case MVT::i128: LC = Call_I128; break;
2292 }
2293 return ExpandLibCall(LC, Node, isSigned).first;
2294}
2295
2296/// Expand the node to a libcall based on first argument type (for instance
2297/// lround and its variant).
2298void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2299 RTLIB::Libcall Call_F32,
2300 RTLIB::Libcall Call_F64,
2301 RTLIB::Libcall Call_F80,
2302 RTLIB::Libcall Call_F128,
2303 RTLIB::Libcall Call_PPCF128,
2304 SmallVectorImpl<SDValue> &Results) {
2305 EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType();
2306 RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(),
2307 Call_F32, Call_F64, Call_F80,
2308 Call_F128, Call_PPCF128);
2309 ExpandFPLibCall(Node, LC, Results);
2310}
2311
2312SDValue SelectionDAGLegalize::ExpandBitCountingLibCall(
2313 SDNode *Node, RTLIB::Libcall CallI32, RTLIB::Libcall CallI64,
2314 RTLIB::Libcall CallI128) {
2315 RTLIB::Libcall LC;
2316 switch (Node->getSimpleValueType(0).SimpleTy) {
2317 default:
2318 llvm_unreachable("Unexpected request for libcall!");
2319 case MVT::i32:
2320 LC = CallI32;
2321 break;
2322 case MVT::i64:
2323 LC = CallI64;
2324 break;
2325 case MVT::i128:
2326 LC = CallI128;
2327 break;
2328 }
2329
2330 // Bit-counting libcalls have one unsigned argument and return `int`.
2331 // Note that `int` may be illegal on this target; ExpandLibCall will
2332 // take care of promoting it to a legal type.
2333 SDValue Op = Node->getOperand(0);
2334 EVT IntVT =
2336
2337 EVT ArgVT = Op.getValueType();
2338 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2339 TargetLowering::ArgListEntry Arg(Op, ArgTy);
2340 Arg.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, /*IsSigned=*/false);
2341 Arg.IsZExt = !Arg.IsSExt;
2342
2343 SDValue Res = ExpandLibCall(LC, Node, TargetLowering::ArgListTy{Arg},
2344 /*IsSigned=*/true, IntVT)
2345 .first;
2346
2347 // If ExpandLibCall created a tail call, the result was already
2348 // of the correct type. Otherwise, we need to sign extend it.
2349 if (Res.getValueType() != MVT::Other)
2350 Res = DAG.getSExtOrTrunc(Res, SDLoc(Node), Node->getValueType(0));
2351 return Res;
2352}
2353
2354/// Issue libcalls to __{u}divmod to compute div / rem pairs.
2355void
2356SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2357 SmallVectorImpl<SDValue> &Results) {
2358 unsigned Opcode = Node->getOpcode();
2359 bool isSigned = Opcode == ISD::SDIVREM;
2360
2361 RTLIB::Libcall LC;
2362 switch (Node->getSimpleValueType(0).SimpleTy) {
2363 default: llvm_unreachable("Unexpected request for libcall!");
2364 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2365 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2366 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2367 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2368 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2369 }
2370
2371 // The input chain to this libcall is the entry node of the function.
2372 // Legalizing the call will automatically add the previous call to the
2373 // dependence.
2374 SDValue InChain = DAG.getEntryNode();
2375
2376 EVT RetVT = Node->getValueType(0);
2377 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2378
2379 TargetLowering::ArgListTy Args;
2380 for (const SDValue &Op : Node->op_values()) {
2381 EVT ArgVT = Op.getValueType();
2382 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2383 TargetLowering::ArgListEntry Entry(Op, ArgTy);
2384 Entry.IsSExt = isSigned;
2385 Entry.IsZExt = !isSigned;
2386 Args.push_back(Entry);
2387 }
2388
2389 // Also pass the return address of the remainder.
2390 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2391 TargetLowering::ArgListEntry Entry(
2392 FIPtr, PointerType::getUnqual(RetTy->getContext()));
2393 Entry.IsSExt = isSigned;
2394 Entry.IsZExt = !isSigned;
2395 Args.push_back(Entry);
2396
2397 RTLIB::LibcallImpl LibcallImpl = DAG.getLibcalls().getLibcallImpl(LC);
2398 if (LibcallImpl == RTLIB::Unsupported) {
2399 DAG.getContext()->emitError(Twine("no libcall available for ") +
2400 Node->getOperationName(&DAG));
2401 SDValue Poison = DAG.getPOISON(RetVT);
2402 Results.push_back(Poison);
2403 Results.push_back(Poison);
2404 return;
2405 }
2406
2407 SDValue Callee =
2408 DAG.getExternalSymbol(LibcallImpl, TLI.getPointerTy(DAG.getDataLayout()));
2409
2410 SDLoc dl(Node);
2411 TargetLowering::CallLoweringInfo CLI(DAG);
2412 CLI.setDebugLoc(dl)
2413 .setChain(InChain)
2414 .setLibCallee(DAG.getLibcalls().getLibcallImplCallingConv(LibcallImpl),
2415 RetTy, Callee, std::move(Args))
2416 .setSExtResult(isSigned)
2417 .setZExtResult(!isSigned);
2418
2419 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2420
2421 // Remainder is loaded back from the stack frame.
2422 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
2423 MachinePointerInfo PtrInfo =
2425
2426 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, PtrInfo);
2427 Results.push_back(CallInfo.first);
2428 Results.push_back(Rem);
2429}
2430
2431/// Return true if sincos or __sincos_stret libcall is available.
2433 const LibcallLoweringInfo &Libcalls) {
2434 MVT::SimpleValueType VT = Node->getSimpleValueType(0).SimpleTy;
2435 return Libcalls.getLibcallImpl(RTLIB::getSINCOS(VT)) != RTLIB::Unsupported ||
2436 Libcalls.getLibcallImpl(RTLIB::getSINCOS_STRET(VT)) !=
2437 RTLIB::Unsupported;
2438}
2439
2440/// Only issue sincos libcall if both sin and cos are needed.
2441static bool useSinCos(SDNode *Node) {
2442 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2443 ? ISD::FCOS : ISD::FSIN;
2444
2445 SDValue Op0 = Node->getOperand(0);
2446 for (const SDNode *User : Op0.getNode()->users()) {
2447 if (User == Node)
2448 continue;
2449 // The other user might have been turned into sincos already.
2450 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2451 return true;
2452 }
2453 return false;
2454}
2455
2456SDValue SelectionDAGLegalize::ExpandSincosStretLibCall(SDNode *Node) const {
2457 // For iOS, we want to call an alternative entry point: __sincos_stret,
2458 // which returns the values in two S / D registers.
2459 SDLoc dl(Node);
2460 SDValue Arg = Node->getOperand(0);
2461 EVT ArgVT = Arg.getValueType();
2462 RTLIB::Libcall LC = RTLIB::getSINCOS_STRET(ArgVT);
2463 RTLIB::LibcallImpl SincosStret = DAG.getLibcalls().getLibcallImpl(LC);
2464 if (SincosStret == RTLIB::Unsupported)
2465 return SDValue();
2466
2467 /// There are 3 different ABI cases to handle:
2468 /// - Direct return of separate fields in registers
2469 /// - Single return as vector elements
2470 /// - sret struct
2471
2472 const RTLIB::RuntimeLibcallsInfo &CallsInfo = TLI.getRuntimeLibcallsInfo();
2473
2474 const DataLayout &DL = DAG.getDataLayout();
2475
2476 auto [FuncTy, FuncAttrs] = CallsInfo.getFunctionTy(
2477 *DAG.getContext(), TM.getTargetTriple(), DL, SincosStret);
2478
2479 Type *SincosStretRetTy = FuncTy->getReturnType();
2480 CallingConv::ID CallConv = CallsInfo.getLibcallImplCallingConv(SincosStret);
2481
2482 SDValue Callee =
2483 DAG.getExternalSymbol(SincosStret, TLI.getProgramPointerTy(DL));
2484
2485 TargetLowering::ArgListTy Args;
2486 SDValue SRet;
2487
2488 int FrameIdx;
2489 if (FuncTy->getParamType(0)->isPointerTy()) {
2490 // Uses sret
2491 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2492
2493 AttributeSet PtrAttrs = FuncAttrs.getParamAttrs(0);
2494 Type *StructTy = PtrAttrs.getStructRetType();
2495 const uint64_t ByteSize = DL.getTypeAllocSize(StructTy);
2496 const Align StackAlign = DL.getPrefTypeAlign(StructTy);
2497
2498 FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
2499 SRet = DAG.getFrameIndex(FrameIdx, TLI.getFrameIndexTy(DL));
2500
2501 TargetLowering::ArgListEntry Entry(SRet, FuncTy->getParamType(0));
2502 Entry.IsSRet = true;
2503 Entry.IndirectType = StructTy;
2504 Entry.Alignment = StackAlign;
2505
2506 Args.push_back(Entry);
2507 Args.emplace_back(Arg, FuncTy->getParamType(1));
2508 } else {
2509 Args.emplace_back(Arg, FuncTy->getParamType(0));
2510 }
2511
2512 TargetLowering::CallLoweringInfo CLI(DAG);
2513 CLI.setDebugLoc(dl)
2514 .setChain(DAG.getEntryNode())
2515 .setLibCallee(CallConv, SincosStretRetTy, Callee, std::move(Args))
2516 .setIsPostTypeLegalization();
2517
2518 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
2519
2520 if (SRet) {
2521 MachinePointerInfo PtrInfo =
2523 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet, PtrInfo);
2524
2525 TypeSize StoreSize = ArgVT.getStoreSize();
2526
2527 // Address of cos field.
2528 SDValue Add = DAG.getObjectPtrOffset(dl, SRet, StoreSize);
2529 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
2530 PtrInfo.getWithOffset(StoreSize));
2531
2532 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
2533 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, LoadSin.getValue(0),
2534 LoadCos.getValue(0));
2535 }
2536
2537 if (!CallResult.first.getValueType().isVector())
2538 return CallResult.first;
2539
2540 SDValue SinVal =
2541 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, CallResult.first,
2542 DAG.getVectorIdxConstant(0, dl));
2543 SDValue CosVal =
2544 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, CallResult.first,
2545 DAG.getVectorIdxConstant(1, dl));
2546 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
2547 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
2548}
2549
2550SDValue SelectionDAGLegalize::expandLdexp(SDNode *Node) const {
2551 SDLoc dl(Node);
2552 EVT VT = Node->getValueType(0);
2553 SDValue X = Node->getOperand(0);
2554 SDValue N = Node->getOperand(1);
2555 EVT ExpVT = N.getValueType();
2556 EVT AsIntVT = VT.changeTypeToInteger();
2557 if (AsIntVT == EVT()) // TODO: How to handle f80?
2558 return SDValue();
2559
2560 // The expansion works through the integer-equivalent type; if that is not
2561 // legal, bail out and let the caller use a libcall (or diagnose a missing
2562 // one).
2563 if (!TLI.isTypeLegal(AsIntVT))
2564 return SDValue();
2565
2566 if (Node->getOpcode() == ISD::STRICT_FLDEXP) // TODO
2567 return SDValue();
2568
2569 SDNodeFlags NSW;
2570 NSW.setNoSignedWrap(true);
2571 SDNodeFlags NUW_NSW;
2572 NUW_NSW.setNoUnsignedWrap(true);
2573 NUW_NSW.setNoSignedWrap(true);
2574
2575 EVT SetCCVT =
2576 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ExpVT);
2577 const fltSemantics &FltSem = VT.getFltSemantics();
2578
2579 const APFloat::ExponentType MaxExpVal = APFloat::semanticsMaxExponent(FltSem);
2580 const APFloat::ExponentType MinExpVal = APFloat::semanticsMinExponent(FltSem);
2581 const int Precision = APFloat::semanticsPrecision(FltSem);
2582
2583 const SDValue MaxExp = DAG.getSignedConstant(MaxExpVal, dl, ExpVT);
2584 const SDValue MinExp = DAG.getSignedConstant(MinExpVal, dl, ExpVT);
2585
2586 const SDValue DoubleMaxExp = DAG.getSignedConstant(2 * MaxExpVal, dl, ExpVT);
2587
2588 const APFloat One(FltSem, "1.0");
2589 APFloat ScaleUpK = scalbn(One, MaxExpVal, APFloat::rmNearestTiesToEven);
2590
2591 // Offset by precision to avoid denormal range.
2592 APFloat ScaleDownK =
2593 scalbn(One, MinExpVal + Precision, APFloat::rmNearestTiesToEven);
2594
2595 // TODO: Should really introduce control flow and use a block for the >
2596 // MaxExp, < MinExp cases
2597
2598 // First, handle exponents Exp > MaxExp and scale down.
2599 SDValue NGtMaxExp = DAG.getSetCC(dl, SetCCVT, N, MaxExp, ISD::SETGT);
2600
2601 SDValue DecN0 = DAG.getNode(ISD::SUB, dl, ExpVT, N, MaxExp, NSW);
2602 SDValue ClampMaxVal = DAG.getConstant(3 * MaxExpVal, dl, ExpVT);
2603 SDValue ClampN_Big = DAG.getNode(ISD::SMIN, dl, ExpVT, N, ClampMaxVal);
2604 SDValue DecN1 =
2605 DAG.getNode(ISD::SUB, dl, ExpVT, ClampN_Big, DoubleMaxExp, NSW);
2606
2607 SDValue ScaleUpTwice =
2608 DAG.getSetCC(dl, SetCCVT, N, DoubleMaxExp, ISD::SETUGT);
2609
2610 const SDValue ScaleUpVal = DAG.getConstantFP(ScaleUpK, dl, VT);
2611 SDValue ScaleUp0 = DAG.getNode(ISD::FMUL, dl, VT, X, ScaleUpVal);
2612 SDValue ScaleUp1 = DAG.getNode(ISD::FMUL, dl, VT, ScaleUp0, ScaleUpVal);
2613
2614 SDValue SelectN_Big =
2615 DAG.getNode(ISD::SELECT, dl, ExpVT, ScaleUpTwice, DecN1, DecN0);
2616 SDValue SelectX_Big =
2617 DAG.getNode(ISD::SELECT, dl, VT, ScaleUpTwice, ScaleUp1, ScaleUp0);
2618
2619 // Now handle exponents Exp < MinExp
2620 SDValue NLtMinExp = DAG.getSetCC(dl, SetCCVT, N, MinExp, ISD::SETLT);
2621
2622 SDValue Increment0 = DAG.getConstant(-(MinExpVal + Precision), dl, ExpVT);
2623 SDValue Increment1 = DAG.getConstant(-2 * (MinExpVal + Precision), dl, ExpVT);
2624
2625 SDValue IncN0 = DAG.getNode(ISD::ADD, dl, ExpVT, N, Increment0, NUW_NSW);
2626
2627 SDValue ClampMinVal =
2628 DAG.getSignedConstant(3 * MinExpVal + 2 * Precision, dl, ExpVT);
2629 SDValue ClampN_Small = DAG.getNode(ISD::SMAX, dl, ExpVT, N, ClampMinVal);
2630 SDValue IncN1 =
2631 DAG.getNode(ISD::ADD, dl, ExpVT, ClampN_Small, Increment1, NSW);
2632
2633 const SDValue ScaleDownVal = DAG.getConstantFP(ScaleDownK, dl, VT);
2634 SDValue ScaleDown0 = DAG.getNode(ISD::FMUL, dl, VT, X, ScaleDownVal);
2635 SDValue ScaleDown1 = DAG.getNode(ISD::FMUL, dl, VT, ScaleDown0, ScaleDownVal);
2636
2637 SDValue ScaleDownTwice = DAG.getSetCC(
2638 dl, SetCCVT, N,
2639 DAG.getSignedConstant(2 * MinExpVal + Precision, dl, ExpVT), ISD::SETULT);
2640
2641 SDValue SelectN_Small =
2642 DAG.getNode(ISD::SELECT, dl, ExpVT, ScaleDownTwice, IncN1, IncN0);
2643 SDValue SelectX_Small =
2644 DAG.getNode(ISD::SELECT, dl, VT, ScaleDownTwice, ScaleDown1, ScaleDown0);
2645
2646 // Now combine the two out of range exponent handling cases with the base
2647 // case.
2648 SDValue NewX = DAG.getNode(
2649 ISD::SELECT, dl, VT, NGtMaxExp, SelectX_Big,
2650 DAG.getNode(ISD::SELECT, dl, VT, NLtMinExp, SelectX_Small, X));
2651
2652 SDValue NewN = DAG.getNode(
2653 ISD::SELECT, dl, ExpVT, NGtMaxExp, SelectN_Big,
2654 DAG.getNode(ISD::SELECT, dl, ExpVT, NLtMinExp, SelectN_Small, N));
2655
2656 SDValue BiasedN = DAG.getNode(ISD::ADD, dl, ExpVT, NewN, MaxExp, NSW);
2657
2658 SDValue ExponentShiftAmt =
2659 DAG.getShiftAmountConstant(Precision - 1, ExpVT, dl);
2660 SDValue CastExpToValTy = DAG.getZExtOrTrunc(BiasedN, dl, AsIntVT);
2661
2662 SDValue AsInt = DAG.getNode(ISD::SHL, dl, AsIntVT, CastExpToValTy,
2663 ExponentShiftAmt, NUW_NSW);
2664 SDValue AsFP = DAG.getNode(ISD::BITCAST, dl, VT, AsInt);
2665 return DAG.getNode(ISD::FMUL, dl, VT, NewX, AsFP);
2666}
2667
2668SDValue SelectionDAGLegalize::expandFrexp(SDNode *Node) const {
2669 SDLoc dl(Node);
2670 SDValue Val = Node->getOperand(0);
2671 EVT VT = Val.getValueType();
2672 EVT ExpVT = Node->getValueType(1);
2673 EVT AsIntVT = VT.changeTypeToInteger();
2674 if (AsIntVT == EVT()) // TODO: How to handle f80?
2675 return SDValue();
2676
2677 // The expansion works through the integer-equivalent type; if that is not
2678 // legal, bail out and let the caller use a libcall (or diagnose a missing
2679 // one).
2680 if (!TLI.isTypeLegal(AsIntVT))
2681 return SDValue();
2682
2683 const fltSemantics &FltSem = VT.getFltSemantics();
2684 const APFloat::ExponentType MinExpVal = APFloat::semanticsMinExponent(FltSem);
2685 const unsigned Precision = APFloat::semanticsPrecision(FltSem);
2686 const unsigned BitSize = VT.getScalarSizeInBits();
2687
2688 // TODO: Could introduce control flow and skip over the denormal handling.
2689
2690 // scale_up = fmul value, scalbn(1.0, precision + 1)
2691 // extracted_exp = (bitcast value to uint) >> precision - 1
2692 // biased_exp = extracted_exp + min_exp
2693 // extracted_fract = (bitcast value to uint) & (fract_mask | sign_mask)
2694 //
2695 // is_denormal = val < smallest_normalized
2696 // computed_fract = is_denormal ? scale_up : extracted_fract
2697 // computed_exp = is_denormal ? biased_exp + (-precision - 1) : biased_exp
2698 //
2699 // result_0 = (!isfinite(val) || iszero(val)) ? val : computed_fract
2700 // result_1 = (!isfinite(val) || iszero(val)) ? 0 : computed_exp
2701
2702 SDValue NegSmallestNormalizedInt = DAG.getConstant(
2703 APFloat::getSmallestNormalized(FltSem, true).bitcastToAPInt(), dl,
2704 AsIntVT);
2705
2706 SDValue SmallestNormalizedInt = DAG.getConstant(
2707 APFloat::getSmallestNormalized(FltSem, false).bitcastToAPInt(), dl,
2708 AsIntVT);
2709
2710 // Masks out the exponent bits.
2711 SDValue ExpMask =
2712 DAG.getConstant(APFloat::getInf(FltSem).bitcastToAPInt(), dl, AsIntVT);
2713
2714 // Mask out the exponent part of the value.
2715 //
2716 // e.g, for f32 FractSignMaskVal = 0x807fffff
2717 APInt FractSignMaskVal = APInt::getBitsSet(BitSize, 0, Precision - 1);
2718 FractSignMaskVal.setBit(BitSize - 1); // Set the sign bit
2719
2720 APInt SignMaskVal = APInt::getSignedMaxValue(BitSize);
2721 SDValue SignMask = DAG.getConstant(SignMaskVal, dl, AsIntVT);
2722
2723 SDValue FractSignMask = DAG.getConstant(FractSignMaskVal, dl, AsIntVT);
2724
2725 const APFloat One(FltSem, "1.0");
2726 // Scale a possible denormal input.
2727 // e.g., for f64, 0x1p+54
2728 APFloat ScaleUpKVal =
2729 scalbn(One, Precision + 1, APFloat::rmNearestTiesToEven);
2730
2731 SDValue ScaleUpK = DAG.getConstantFP(ScaleUpKVal, dl, VT);
2732 SDValue ScaleUp = DAG.getNode(ISD::FMUL, dl, VT, Val, ScaleUpK);
2733
2734 EVT SetCCVT =
2735 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2736
2737 SDValue AsInt = DAG.getNode(ISD::BITCAST, dl, AsIntVT, Val);
2738
2739 SDValue Abs = DAG.getNode(ISD::AND, dl, AsIntVT, AsInt, SignMask);
2740
2741 SDValue AddNegSmallestNormal =
2742 DAG.getNode(ISD::ADD, dl, AsIntVT, Abs, NegSmallestNormalizedInt);
2743 SDValue DenormOrZero = DAG.getSetCC(dl, SetCCVT, AddNegSmallestNormal,
2744 NegSmallestNormalizedInt, ISD::SETULE);
2745
2746 SDValue IsDenormal =
2747 DAG.getSetCC(dl, SetCCVT, Abs, SmallestNormalizedInt, ISD::SETULT);
2748
2749 SDValue MinExp = DAG.getSignedConstant(MinExpVal, dl, ExpVT);
2750 SDValue Zero = DAG.getConstant(0, dl, ExpVT);
2751
2752 SDValue ScaledAsInt = DAG.getNode(ISD::BITCAST, dl, AsIntVT, ScaleUp);
2753 SDValue ScaledSelect =
2754 DAG.getNode(ISD::SELECT, dl, AsIntVT, IsDenormal, ScaledAsInt, AsInt);
2755
2756 SDValue ExpMaskScaled =
2757 DAG.getNode(ISD::AND, dl, AsIntVT, ScaledAsInt, ExpMask);
2758
2759 SDValue ScaledValue =
2760 DAG.getNode(ISD::SELECT, dl, AsIntVT, IsDenormal, ExpMaskScaled, Abs);
2761
2762 // Extract the exponent bits.
2763 SDValue ExponentShiftAmt =
2764 DAG.getShiftAmountConstant(Precision - 1, AsIntVT, dl);
2765 SDValue ShiftedExp =
2766 DAG.getNode(ISD::SRL, dl, AsIntVT, ScaledValue, ExponentShiftAmt);
2767 SDValue Exp = DAG.getSExtOrTrunc(ShiftedExp, dl, ExpVT);
2768
2769 SDValue NormalBiasedExp = DAG.getNode(ISD::ADD, dl, ExpVT, Exp, MinExp);
2770 SDValue DenormalOffset = DAG.getConstant(-Precision - 1, dl, ExpVT);
2771 SDValue DenormalExpBias =
2772 DAG.getNode(ISD::SELECT, dl, ExpVT, IsDenormal, DenormalOffset, Zero);
2773
2774 SDValue MaskedFractAsInt =
2775 DAG.getNode(ISD::AND, dl, AsIntVT, ScaledSelect, FractSignMask);
2776 const APFloat Half(FltSem, "0.5");
2777 SDValue FPHalf = DAG.getConstant(Half.bitcastToAPInt(), dl, AsIntVT);
2778 SDValue Or = DAG.getNode(ISD::OR, dl, AsIntVT, MaskedFractAsInt, FPHalf);
2779 SDValue MaskedFract = DAG.getNode(ISD::BITCAST, dl, VT, Or);
2780
2781 SDValue ComputedExp =
2782 DAG.getNode(ISD::ADD, dl, ExpVT, NormalBiasedExp, DenormalExpBias);
2783
2784 SDValue Result0 =
2785 DAG.getNode(ISD::SELECT, dl, VT, DenormOrZero, Val, MaskedFract);
2786
2787 SDValue Result1 =
2788 DAG.getNode(ISD::SELECT, dl, ExpVT, DenormOrZero, Zero, ComputedExp);
2789
2790 return DAG.getMergeValues({Result0, Result1}, dl);
2791}
2792
2793SDValue SelectionDAGLegalize::expandModf(SDNode *Node) const {
2794 SDLoc dl(Node);
2795 SDValue Val = Node->getOperand(0);
2796 EVT VT = Val.getValueType();
2797 SDNodeFlags Flags = Node->getFlags();
2798
2799 SDValue IntPart = DAG.getNode(ISD::FTRUNC, dl, VT, Val, Flags);
2800 SDValue FracPart = DAG.getNode(ISD::FSUB, dl, VT, Val, IntPart, Flags);
2801
2802 SDValue FracToUse;
2803 if (Flags.hasNoInfs()) {
2804 FracToUse = FracPart;
2805 } else {
2806 SDValue Abs = DAG.getNode(ISD::FABS, dl, VT, Val, Flags);
2807 SDValue Inf =
2809 EVT SetCCVT =
2810 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2811 SDValue IsInf = DAG.getSetCC(dl, SetCCVT, Abs, Inf, ISD::SETOEQ);
2812 SDValue Zero = DAG.getConstantFP(0.0, dl, VT);
2813 FracToUse = DAG.getSelect(dl, VT, IsInf, Zero, FracPart);
2814 }
2815
2816 SDValue ResultFrac =
2817 DAG.getNode(ISD::FCOPYSIGN, dl, VT, FracToUse, Val, Flags);
2818 return DAG.getMergeValues({ResultFrac, IntPart}, dl);
2819}
2820
2821/// This function is responsible for legalizing a
2822/// INT_TO_FP operation of the specified operand when the target requests that
2823/// we expand it. At this point, we know that the result and operand types are
2824/// legal for the target.
2825SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node,
2826 SDValue &Chain) {
2827 bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
2828 Node->getOpcode() == ISD::SINT_TO_FP);
2829 EVT DestVT = Node->getValueType(0);
2830 SDLoc dl(Node);
2831 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
2832 SDValue Op0 = Node->getOperand(OpNo);
2833 EVT SrcVT = Op0.getValueType();
2834
2835 // TODO: Should any fast-math-flags be set for the created nodes?
2836 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2837 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) &&
2838 (DestVT.bitsLE(MVT::f64) ||
2839 TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND
2841 DestVT))) {
2842 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2843 "expansion\n");
2844
2845 // Get the stack frame index of a 8 byte buffer.
2846 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2847
2848 SDValue Lo = Op0;
2849 // if signed map to unsigned space
2850 if (isSigned) {
2851 // Invert sign bit (signed to unsigned mapping).
2852 Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo,
2853 DAG.getConstant(0x80000000u, dl, MVT::i32));
2854 }
2855 // Initial hi portion of constructed double.
2856 SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2857
2858 // If this a big endian target, swap the lo and high data.
2859 if (DAG.getDataLayout().isBigEndian())
2860 std::swap(Lo, Hi);
2861
2862 SDValue MemChain = DAG.getEntryNode();
2863
2864 // Store the lo of the constructed double.
2865 SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot,
2866 MachinePointerInfo());
2867 // Store the hi of the constructed double.
2868 SDValue HiPtr =
2869 DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
2870 SDValue Store2 =
2871 DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo());
2872 MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
2873
2874 // load the constructed double
2875 SDValue Load =
2876 DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo());
2877 // FP constant to bias correct the final result
2878 SDValue Bias = DAG.getConstantFP(
2879 isSigned ? llvm::bit_cast<double>(0x4330000080000000ULL)
2880 : llvm::bit_cast<double>(0x4330000000000000ULL),
2881 dl, MVT::f64);
2882 // Subtract the bias and get the final result.
2883 SDValue Sub;
2885 if (Node->isStrictFPOpcode()) {
2886 Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
2887 {Node->getOperand(0), Load, Bias});
2888 Chain = Sub.getValue(1);
2889 if (DestVT != Sub.getValueType()) {
2890 std::pair<SDValue, SDValue> ResultPair;
2891 ResultPair =
2892 DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT);
2893 Result = ResultPair.first;
2894 Chain = ResultPair.second;
2895 }
2896 else
2897 Result = Sub;
2898 } else {
2899 Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2900 Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2901 }
2902 return Result;
2903 }
2904
2905 if (isSigned)
2906 return SDValue();
2907
2908 // TODO: Generalize this for use with other types.
2909 if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) ||
2910 (SrcVT == MVT::i64 && DestVT == MVT::f64)) {
2911 LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n");
2912 // For unsigned conversions, convert them to signed conversions using the
2913 // algorithm from the x86_64 __floatundisf in compiler_rt. That method
2914 // should be valid for i32->f32 as well.
2915
2916 // More generally this transform should be valid if there are 3 more bits
2917 // in the integer type than the significand. Rounding uses the first bit
2918 // after the width of the significand and the OR of all bits after that. So
2919 // we need to be able to OR the shifted out bit into one of the bits that
2920 // participate in the OR.
2921
2922 // TODO: This really should be implemented using a branch rather than a
2923 // select. We happen to get lucky and machinesink does the right
2924 // thing most of the time. This would be a good candidate for a
2925 // pseudo-op, or, even better, for whole-function isel.
2926 EVT SetCCVT = getSetCCResultType(SrcVT);
2927
2928 SDValue SignBitTest = DAG.getSetCC(
2929 dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2930
2931 SDValue ShiftConst = DAG.getShiftAmountConstant(1, SrcVT, dl);
2932 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst);
2933 SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
2934 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst);
2935 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
2936
2937 SDValue Slow, Fast;
2938 if (Node->isStrictFPOpcode()) {
2939 // In strict mode, we must avoid spurious exceptions, and therefore
2940 // must make sure to only emit a single STRICT_SINT_TO_FP.
2941 SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0);
2942 // The STRICT_SINT_TO_FP inherits the exception mode from the
2943 // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can
2944 // never raise any exception.
2945 SDNodeFlags Flags;
2946 Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept());
2947 Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DestVT, MVT::Other},
2948 {Node->getOperand(0), InCvt}, Flags);
2949 Flags.setNoFPExcept(true);
2950 Slow = DAG.getNode(ISD::STRICT_FADD, dl, {DestVT, MVT::Other},
2951 {Fast.getValue(1), Fast, Fast}, Flags);
2952 Chain = Slow.getValue(1);
2953 } else {
2954 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or);
2955 Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt);
2956 Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2957 }
2958
2959 return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast);
2960 }
2961
2962 // Don't expand it if there isn't cheap fadd.
2963 if (!TLI.isOperationLegalOrCustom(
2964 Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT))
2965 return SDValue();
2966
2967 // The following optimization is valid only if every value in SrcVT (when
2968 // treated as signed) is representable in DestVT. Check that the mantissa
2969 // size of DestVT is >= than the number of bits in SrcVT -1.
2970 assert(APFloat::semanticsPrecision(DestVT.getFltSemantics()) >=
2971 SrcVT.getSizeInBits() - 1 &&
2972 "Cannot perform lossless SINT_TO_FP!");
2973
2974 SDValue Tmp1;
2975 if (Node->isStrictFPOpcode()) {
2976 Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2977 { Node->getOperand(0), Op0 });
2978 } else
2979 Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2980
2981 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2982 DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2983 SDValue Zero = DAG.getIntPtrConstant(0, dl),
2984 Four = DAG.getIntPtrConstant(4, dl);
2985 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2986 SignSet, Four, Zero);
2987
2988 // If the sign bit of the integer is set, the large number will be treated
2989 // as a negative number. To counteract this, the dynamic code adds an
2990 // offset depending on the data type.
2991 uint64_t FF;
2992 switch (SrcVT.getSimpleVT().SimpleTy) {
2993 default:
2994 return SDValue();
2995 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2996 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2997 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2998 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2999 }
3000 if (DAG.getDataLayout().isLittleEndian())
3001 FF <<= 32;
3002 Constant *FudgeFactor = ConstantInt::get(
3003 Type::getInt64Ty(*DAG.getContext()), FF);
3004
3005 SDValue CPIdx =
3006 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
3007 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
3008 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
3009 Alignment = commonAlignment(Alignment, 4);
3010 SDValue FudgeInReg;
3011 if (DestVT == MVT::f32)
3012 FudgeInReg = DAG.getLoad(
3013 MVT::f32, dl, DAG.getEntryNode(), CPIdx,
3015 Alignment);
3016 else {
3017 SDValue Load = DAG.getExtLoad(
3018 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
3020 Alignment);
3021 HandleSDNode Handle(Load);
3022 LegalizeOp(Load.getNode());
3023 FudgeInReg = Handle.getValue();
3024 }
3025
3026 if (Node->isStrictFPOpcode()) {
3027 SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
3028 { Tmp1.getValue(1), Tmp1, FudgeInReg });
3029 Chain = Result.getValue(1);
3030 return Result;
3031 }
3032
3033 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
3034}
3035
3036/// This function is responsible for legalizing a
3037/// *INT_TO_FP operation of the specified operand when the target requests that
3038/// we promote it. At this point, we know that the result and operand types are
3039/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3040/// operation that takes a larger input.
3041void SelectionDAGLegalize::PromoteLegalINT_TO_FP(
3042 SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) {
3043 bool IsStrict = N->isStrictFPOpcode();
3044 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
3045 N->getOpcode() == ISD::STRICT_SINT_TO_FP;
3046 EVT DestVT = N->getValueType(0);
3047 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
3048 unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP;
3049 unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP;
3050
3051 // First step, figure out the appropriate *INT_TO_FP operation to use.
3052 EVT NewInTy = LegalOp.getValueType();
3053
3054 unsigned OpToUse = 0;
3055
3056 // Scan for the appropriate larger type to use.
3057 while (true) {
3058 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
3059 assert(NewInTy.isInteger() && "Ran out of possibilities!");
3060
3061 // If the target supports SINT_TO_FP of this type, use it.
3062 if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) {
3063 OpToUse = SIntOp;
3064 break;
3065 }
3066 if (IsSigned)
3067 continue;
3068
3069 // If the target supports UINT_TO_FP of this type, use it.
3070 if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) {
3071 OpToUse = UIntOp;
3072 break;
3073 }
3074
3075 // Otherwise, try a larger type.
3076 }
3077
3078 // Okay, we found the operation and type to use. Zero extend our input to the
3079 // desired type then run the operation on it.
3080 if (IsStrict) {
3081 SDValue Res =
3082 DAG.getNode(OpToUse, dl, {DestVT, MVT::Other},
3083 {N->getOperand(0),
3084 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3085 dl, NewInTy, LegalOp)});
3086 Results.push_back(Res);
3087 Results.push_back(Res.getValue(1));
3088 return;
3089 }
3090
3091 Results.push_back(
3092 DAG.getNode(OpToUse, dl, DestVT,
3093 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3094 dl, NewInTy, LegalOp)));
3095}
3096
3097/// This function is responsible for legalizing a
3098/// FP_TO_*INT operation of the specified operand when the target requests that
3099/// we promote it. At this point, we know that the result and operand types are
3100/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3101/// operation that returns a larger result.
3102void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
3103 SmallVectorImpl<SDValue> &Results) {
3104 bool IsStrict = N->isStrictFPOpcode();
3105 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
3106 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
3107 EVT DestVT = N->getValueType(0);
3108 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
3109 // First step, figure out the appropriate FP_TO*INT operation to use.
3110 EVT NewOutTy = DestVT;
3111
3112 unsigned OpToUse = 0;
3113
3114 // Scan for the appropriate larger type to use.
3115 while (true) {
3116 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
3117 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
3118
3119 // A larger signed type can hold all unsigned values of the requested type,
3120 // so using FP_TO_SINT is valid
3121 OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT;
3122 if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
3123 break;
3124
3125 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
3126 OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT;
3127 if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
3128 break;
3129
3130 // Otherwise, try a larger type.
3131 }
3132
3133 // Okay, we found the operation and type to use.
3135 if (IsStrict) {
3136 SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other);
3137 Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp);
3138 } else
3139 Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
3140
3141 // Truncate the result of the extended FP_TO_*INT operation to the desired
3142 // size.
3143 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
3144 Results.push_back(Trunc);
3145 if (IsStrict)
3146 Results.push_back(Operation.getValue(1));
3147}
3148
3149/// Promote FP_TO_*INT_SAT operation to a larger result type. At this point
3150/// the result and operand types are legal and there must be a legal
3151/// FP_TO_*INT_SAT operation for a larger result type.
3152SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node,
3153 const SDLoc &dl) {
3154 unsigned Opcode = Node->getOpcode();
3155
3156 // Scan for the appropriate larger type to use.
3157 EVT NewOutTy = Node->getValueType(0);
3158 while (true) {
3159 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1);
3160 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
3161
3162 if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy))
3163 break;
3164 }
3165
3166 // Saturation width is determined by second operand, so we don't have to
3167 // perform any fixup and can directly truncate the result.
3168 SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0),
3169 Node->getOperand(1));
3170 return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
3171}
3172
3173/// Open code the operations for PARITY of the specified operation.
3174SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) {
3175 EVT VT = Op.getValueType();
3176 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3177 unsigned Sz = VT.getScalarSizeInBits();
3178
3179 // If CTPOP is legal, use it. Otherwise use shifts and xor.
3182 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
3183 } else {
3184 Result = Op;
3185 for (unsigned i = Log2_32_Ceil(Sz); i != 0;) {
3186 SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result,
3187 DAG.getConstant(1ULL << (--i), dl, ShVT));
3188 Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift);
3189 }
3190 }
3191
3192 return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT));
3193}
3194
3195SDValue SelectionDAGLegalize::PromoteReduction(SDNode *Node) {
3196 bool IsVPOpcode = ISD::isVPOpcode(Node->getOpcode());
3197 MVT VecVT = IsVPOpcode ? Node->getOperand(1).getSimpleValueType()
3198 : Node->getOperand(0).getSimpleValueType();
3199 MVT NewVecVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VecVT);
3200 MVT ScalarVT = Node->getSimpleValueType(0);
3201 MVT NewScalarVT = NewVecVT.getVectorElementType();
3202
3203 SDLoc DL(Node);
3204 SmallVector<SDValue, 4> Operands(Node->getNumOperands());
3205
3206 // FIXME: Support integer.
3207 assert(Node->getOperand(0).getValueType().isFloatingPoint() &&
3208 "Only FP promotion is supported");
3209
3210 for (unsigned j = 0; j != Node->getNumOperands(); ++j)
3211 if (Node->getOperand(j).getValueType().isVector() &&
3212 !(IsVPOpcode &&
3213 ISD::getVPMaskIdx(Node->getOpcode()) == j)) { // Skip mask operand.
3214 // promote the vector operand.
3215 // FIXME: Support integer.
3216 assert(Node->getOperand(j).getValueType().isFloatingPoint() &&
3217 "Only FP promotion is supported");
3218 Operands[j] =
3219 DAG.getNode(ISD::FP_EXTEND, DL, NewVecVT, Node->getOperand(j));
3220 } else if (Node->getOperand(j).getValueType().isFloatingPoint()) {
3221 // promote the initial value.
3222 Operands[j] =
3223 DAG.getNode(ISD::FP_EXTEND, DL, NewScalarVT, Node->getOperand(j));
3224 } else {
3225 Operands[j] = Node->getOperand(j); // Skip VL operand.
3226 }
3227
3228 SDValue Res = DAG.getNode(Node->getOpcode(), DL, NewScalarVT, Operands,
3229 Node->getFlags());
3230
3231 assert(ScalarVT.isFloatingPoint() && "Only FP promotion is supported");
3232 return DAG.getNode(ISD::FP_ROUND, DL, ScalarVT, Res,
3233 DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
3234}
3235
3236bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
3237 LLVM_DEBUG(dbgs() << "Trying to expand node\n");
3239 SDLoc dl(Node);
3240 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
3241 bool NeedInvert;
3242 switch (Node->getOpcode()) {
3243 case ISD::ABS:
3245 if ((Tmp1 = TLI.expandABS(Node, DAG)))
3246 Results.push_back(Tmp1);
3247 break;
3248 case ISD::ABDS:
3249 case ISD::ABDU:
3250 if ((Tmp1 = TLI.expandABD(Node, DAG)))
3251 Results.push_back(Tmp1);
3252 break;
3253 case ISD::AVGCEILS:
3254 case ISD::AVGCEILU:
3255 case ISD::AVGFLOORS:
3256 case ISD::AVGFLOORU:
3257 if ((Tmp1 = TLI.expandAVG(Node, DAG)))
3258 Results.push_back(Tmp1);
3259 break;
3260 case ISD::CTPOP:
3261 if ((Tmp1 = TLI.expandCTPOP(Node, DAG)))
3262 Results.push_back(Tmp1);
3263 break;
3264 case ISD::CTLZ:
3266 if ((Tmp1 = TLI.expandCTLZ(Node, DAG)))
3267 Results.push_back(Tmp1);
3268 break;
3269 case ISD::CTLS:
3270 if ((Tmp1 = TLI.expandCTLS(Node, DAG)))
3271 Results.push_back(Tmp1);
3272 break;
3273 case ISD::CTTZ:
3275 if ((Tmp1 = TLI.expandCTTZ(Node, DAG)))
3276 Results.push_back(Tmp1);
3277 break;
3278 case ISD::BITREVERSE:
3279 if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG)))
3280 Results.push_back(Tmp1);
3281 break;
3282 case ISD::BSWAP:
3283 if ((Tmp1 = TLI.expandBSWAP(Node, DAG)))
3284 Results.push_back(Tmp1);
3285 break;
3286 case ISD::PARITY:
3287 Results.push_back(ExpandPARITY(Node->getOperand(0), dl));
3288 break;
3289 case ISD::FRAMEADDR:
3290 case ISD::RETURNADDR:
3292 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3293 break;
3294 case ISD::EH_DWARF_CFA: {
3295 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
3296 TLI.getPointerTy(DAG.getDataLayout()));
3297 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3298 CfaArg.getValueType(),
3300 CfaArg.getValueType()),
3301 CfaArg);
3302 SDValue FA = DAG.getNode(
3304 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
3305 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
3306 FA, Offset));
3307 break;
3308 }
3309 case ISD::GET_ROUNDING:
3310 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
3311 Results.push_back(Node->getOperand(0));
3312 break;
3313 case ISD::EH_RETURN:
3314 case ISD::EH_LABEL:
3315 case ISD::PREFETCH:
3316 case ISD::VAEND:
3318 // If the target didn't expand these, there's nothing to do, so just
3319 // preserve the chain and be done.
3320 Results.push_back(Node->getOperand(0));
3321 break;
3324 // If the target didn't expand this, just return 'zero' and preserve the
3325 // chain.
3326 Results.append(Node->getNumValues() - 1,
3327 DAG.getConstant(0, dl, Node->getValueType(0)));
3328 Results.push_back(Node->getOperand(0));
3329 break;
3331 // If the target didn't expand this, just return 'zero' and preserve the
3332 // chain.
3333 Results.push_back(DAG.getConstant(0, dl, MVT::i32));
3334 Results.push_back(Node->getOperand(0));
3335 break;
3336 case ISD::ATOMIC_LOAD: {
3337 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
3338 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
3339 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3340 SDValue Swap = DAG.getAtomicCmpSwap(
3341 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3342 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
3343 cast<AtomicSDNode>(Node)->getMemOperand());
3344 Results.push_back(Swap.getValue(0));
3345 Results.push_back(Swap.getValue(1));
3346 break;
3347 }
3348 case ISD::ATOMIC_STORE: {
3349 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
3350 SDValue Swap = DAG.getAtomic(
3351 ISD::ATOMIC_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(),
3352 Node->getOperand(0), Node->getOperand(2), Node->getOperand(1),
3353 cast<AtomicSDNode>(Node)->getMemOperand());
3354 Results.push_back(Swap.getValue(1));
3355 break;
3356 }
3358 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3359 // splits out the success value as a comparison. Expanding the resulting
3360 // ATOMIC_CMP_SWAP will produce a libcall.
3361 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3362 SDValue Res = DAG.getAtomicCmpSwap(
3363 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3364 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3365 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
3366
3367 SDValue ExtRes = Res;
3368 SDValue LHS = Res;
3369 SDValue RHS = Node->getOperand(1);
3370
3371 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
3372 EVT OuterType = Node->getValueType(0);
3373 switch (TLI.getExtendForAtomicOps()) {
3374 case ISD::SIGN_EXTEND:
3375 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
3376 DAG.getValueType(AtomicType));
3377 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
3378 Node->getOperand(2), DAG.getValueType(AtomicType));
3379 ExtRes = LHS;
3380 break;
3381 case ISD::ZERO_EXTEND:
3382 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
3383 DAG.getValueType(AtomicType));
3384 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
3385 ExtRes = LHS;
3386 break;
3387 case ISD::ANY_EXTEND:
3388 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
3389 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
3390 break;
3391 default:
3392 llvm_unreachable("Invalid atomic op extension");
3393 }
3394
3396 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
3397
3398 Results.push_back(ExtRes.getValue(0));
3399 Results.push_back(Success);
3400 Results.push_back(Res.getValue(1));
3401 break;
3402 }
3403 case ISD::ATOMIC_LOAD_SUB: {
3404 SDLoc DL(Node);
3405 EVT VT = Node->getValueType(0);
3406 SDValue RHS = Node->getOperand(2);
3407 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
3408 if (RHS->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3409 cast<VTSDNode>(RHS->getOperand(1))->getVT() == AN->getMemoryVT())
3410 RHS = RHS->getOperand(0);
3411 SDValue NewRHS =
3412 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
3414 Node->getOperand(0), Node->getOperand(1),
3415 NewRHS, AN->getMemOperand());
3416 Results.push_back(Res);
3417 Results.push_back(Res.getValue(1));
3418 break;
3419 }
3421 ExpandDYNAMIC_STACKALLOC(Node, Results);
3422 break;
3423 case ISD::MERGE_VALUES:
3424 for (unsigned i = 0; i < Node->getNumValues(); i++)
3425 Results.push_back(Node->getOperand(i));
3426 break;
3427 case ISD::POISON:
3428 case ISD::UNDEF: {
3429 EVT VT = Node->getValueType(0);
3430 if (VT.isInteger())
3431 Results.push_back(DAG.getConstant(0, dl, VT));
3432 else {
3433 assert(VT.isFloatingPoint() && "Unknown value type!");
3434 Results.push_back(DAG.getConstantFP(0, dl, VT));
3435 }
3436 break;
3437 }
3439 // When strict mode is enforced we can't do expansion because it
3440 // does not honor the "strict" properties. Only libcall is allowed.
3441 if (TLI.isStrictFPEnabled())
3442 break;
3443 // We might as well mutate to FP_ROUND when FP_ROUND operation is legal
3444 // since this operation is more efficient than stack operation.
3445 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3446 Node->getValueType(0))
3447 == TargetLowering::Legal)
3448 break;
3449 // We fall back to use stack operation when the FP_ROUND operation
3450 // isn't available.
3451 if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0),
3452 Node->getValueType(0), dl,
3453 Node->getOperand(0)))) {
3454 ReplaceNode(Node, Tmp1.getNode());
3455 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
3456 return true;
3457 }
3458 break;
3459 case ISD::FP_ROUND: {
3460 if ((Tmp1 = TLI.expandFP_ROUND(Node, DAG))) {
3461 Results.push_back(Tmp1);
3462 break;
3463 }
3464
3465 [[fallthrough]];
3466 }
3467 case ISD::BITCAST:
3468 if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3469 Node->getValueType(0), dl)))
3470 Results.push_back(Tmp1);
3471 break;
3473 // When strict mode is enforced we can't do expansion because it
3474 // does not honor the "strict" properties. Only libcall is allowed.
3475 if (TLI.isStrictFPEnabled())
3476 break;
3477 // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal
3478 // since this operation is more efficient than stack operation.
3479 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3480 Node->getValueType(0))
3481 == TargetLowering::Legal)
3482 break;
3483 // We fall back to use stack operation when the FP_EXTEND operation
3484 // isn't available.
3485 if ((Tmp1 = EmitStackConvert(
3486 Node->getOperand(1), Node->getOperand(1).getValueType(),
3487 Node->getValueType(0), dl, Node->getOperand(0)))) {
3488 ReplaceNode(Node, Tmp1.getNode());
3489 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
3490 return true;
3491 }
3492 break;
3493 case ISD::FP_EXTEND: {
3494 SDValue Op = Node->getOperand(0);
3495 EVT SrcVT = Op.getValueType();
3496 EVT DstVT = Node->getValueType(0);
3497 if (SrcVT.getScalarType() == MVT::bf16) {
3498 Results.push_back(DAG.getNode(ISD::BF16_TO_FP, SDLoc(Node), DstVT, Op));
3499 break;
3500 }
3501
3502 if ((Tmp1 = EmitStackConvert(Op, SrcVT, DstVT, dl)))
3503 Results.push_back(Tmp1);
3504 break;
3505 }
3506 case ISD::BF16_TO_FP: {
3507 // Always expand bf16 to f32 casts, they lower to ext + shift.
3508 //
3509 // Note that the operand of this code can be bf16 or an integer type in case
3510 // bf16 is not supported on the target and was softened.
3511 SDValue Op = Node->getOperand(0);
3512 if (Op.getValueType() == MVT::bf16) {
3513 Op = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32,
3514 DAG.getNode(ISD::BITCAST, dl, MVT::i16, Op));
3515 } else {
3516 Op = DAG.getAnyExtOrTrunc(Op, dl, MVT::i32);
3517 }
3518 Op = DAG.getNode(ISD::SHL, dl, MVT::i32, Op,
3519 DAG.getShiftAmountConstant(16, MVT::i32, dl));
3520 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op);
3521 // Add fp_extend in case the output is bigger than f32.
3522 if (Node->getValueType(0) != MVT::f32)
3523 Op = DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Op);
3524 Results.push_back(Op);
3525 break;
3526 }
3527 case ISD::FP_TO_BF16: {
3528 SDValue Op = Node->getOperand(0);
3529 if (Op.getValueType() != MVT::f32)
3530 Op = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3531 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
3532 // Certain SNaNs will turn into infinities if we do a simple shift right.
3533 if (!DAG.isKnownNeverSNaN(Op)) {
3534 Op = DAG.getNode(ISD::FCANONICALIZE, dl, MVT::f32, Op, Node->getFlags());
3535 }
3536 Op = DAG.getNode(ISD::SRL, dl, MVT::i32,
3537 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op),
3538 DAG.getShiftAmountConstant(16, MVT::i32, dl));
3539 // The result of this node can be bf16 or an integer type in case bf16 is
3540 // not supported on the target and was softened to i16 for storage.
3541 if (Node->getValueType(0) == MVT::bf16) {
3542 Op = DAG.getNode(ISD::BITCAST, dl, MVT::bf16,
3543 DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Op));
3544 } else {
3545 Op = DAG.getAnyExtOrTrunc(Op, dl, Node->getValueType(0));
3546 }
3547 Results.push_back(Op);
3548 break;
3549 }
3551 // Expand conversion from arbitrary FP format stored in an integer to a
3552 // native IEEE float type using integer bit manipulation.
3553 //
3554 // TODO: currently only conversions from FP4, FP6 and FP8 formats from OCP
3555 // specification are expanded. Remaining arbitrary FP types: Float8E4M3,
3556 // Float8E3M4, Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ,
3557 // Float8E8M0FNU.
3558 EVT DstVT = Node->getValueType(0);
3559 if (SDValue Expanded = TLI.expandCONVERT_FROM_ARBITRARY_FP(Node, DAG))
3560 Results.push_back(Expanded);
3561 else
3562 Results.push_back(DAG.getPOISON(DstVT));
3563 break;
3564 }
3566 // Expand conversion from a native IEEE float type to an arbitrary FP
3567 // format, returning the result as an integer using bit manipulation.
3568 //
3569 // TODO: currently only conversions to FP4, FP6 and FP8 formats from OCP
3570 // specification are expanded. Remaining arbitrary FP types: Float8E4M3,
3571 // Float8E3M4, Float8E5M2FNUZ, Float8E4M3FNUZ, Float8E4M3B11FNUZ,
3572 // Float8E8M0FNU.
3573 EVT ResVT = Node->getValueType(0);
3574 if (SDValue Expanded = TLI.expandCONVERT_TO_ARBITRARY_FP(Node, DAG))
3575 Results.push_back(Expanded);
3576 else
3577 Results.push_back(DAG.getPOISON(ResVT));
3578 break;
3579 }
3580 case ISD::FCANONICALIZE: {
3581 SDValue Mul = TLI.expandFCANONICALIZE(Node, DAG);
3582 Results.push_back(Mul);
3583 break;
3584 }
3586 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3587 EVT VT = Node->getValueType(0);
3588
3589 // An in-register sign-extend of a boolean is a negation:
3590 // 'true' (1) sign-extended is -1.
3591 // 'false' (0) sign-extended is 0.
3592 // However, we must mask the high bits of the source operand because the
3593 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
3594
3595 // TODO: Do this for vectors too?
3596 if (ExtraVT.isScalarInteger() && ExtraVT.getSizeInBits() == 1) {
3597 SDValue One = DAG.getConstant(1, dl, VT);
3598 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
3599 SDValue Zero = DAG.getConstant(0, dl, VT);
3600 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
3601 Results.push_back(Neg);
3602 break;
3603 }
3604
3605 // NOTE: we could fall back on load/store here too for targets without
3606 // SRA. However, it is doubtful that any exist.
3607 unsigned BitsDiff = VT.getScalarSizeInBits() -
3608 ExtraVT.getScalarSizeInBits();
3609 SDValue ShiftCst = DAG.getShiftAmountConstant(BitsDiff, VT, dl);
3610 Tmp1 = DAG.getNode(ISD::SHL, dl, VT, Node->getOperand(0), ShiftCst);
3611 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, Tmp1, ShiftCst);
3612 Results.push_back(Tmp1);
3613 break;
3614 }
3615 case ISD::UINT_TO_FP:
3617 if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) {
3618 Results.push_back(Tmp1);
3619 if (Node->isStrictFPOpcode())
3620 Results.push_back(Tmp2);
3621 break;
3622 }
3623 [[fallthrough]];
3624 case ISD::SINT_TO_FP:
3626 if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) {
3627 Results.push_back(Tmp1);
3628 if (Node->isStrictFPOpcode())
3629 Results.push_back(Tmp2);
3630 }
3631 break;
3632 case ISD::FP_TO_SINT:
3633 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3634 Results.push_back(Tmp1);
3635 break;
3637 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
3638 ReplaceNode(Node, Tmp1.getNode());
3639 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
3640 return true;
3641 }
3642 break;
3643 case ISD::FP_TO_UINT:
3644 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
3645 Results.push_back(Tmp1);
3646 break;
3648 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
3649 // Relink the chain.
3650 DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
3651 // Replace the new UINT result.
3652 ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
3653 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
3654 return true;
3655 }
3656 break;
3659 Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG));
3660 break;
3661 case ISD::LROUND:
3662 case ISD::LLROUND: {
3663 SDValue Arg = Node->getOperand(0);
3664 EVT ArgVT = Arg.getValueType();
3665 EVT ResVT = Node->getValueType(0);
3666 SDLoc dl(Node);
3667 SDValue RoundNode = DAG.getNode(ISD::FROUND, dl, ArgVT, Arg);
3668 Results.push_back(DAG.getNode(ISD::FP_TO_SINT, dl, ResVT, RoundNode));
3669 break;
3670 }
3671 case ISD::VAARG:
3672 Results.push_back(DAG.expandVAArg(Node));
3673 Results.push_back(Results[0].getValue(1));
3674 break;
3675 case ISD::VACOPY:
3676 Results.push_back(DAG.expandVACopy(Node));
3677 break;
3679 if (Node->getOperand(0).getValueType().getVectorElementCount().isScalar())
3680 // This must be an access of the only element. Return it.
3681 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3682 Node->getOperand(0));
3683 else
3684 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3685 Results.push_back(Tmp1);
3686 break;
3688 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3689 break;
3691 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3692 break;
3694 if (EVT VectorValueType = Node->getOperand(0).getValueType();
3695 VectorValueType.isScalableVector() ||
3696 TLI.isOperationExpand(ISD::EXTRACT_VECTOR_ELT, VectorValueType))
3697 Results.push_back(ExpandVectorBuildThroughStack(Node));
3698 else
3699 Results.push_back(ExpandConcatVectors(Node));
3700 break;
3702 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3703 break;
3705 Results.push_back(ExpandINSERT_VECTOR_ELT(SDValue(Node, 0)));
3706 break;
3707 case ISD::VECTOR_SHUFFLE: {
3708 SmallVector<int, 32> NewMask;
3709 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3710
3711 EVT VT = Node->getValueType(0);
3712 EVT EltVT = VT.getVectorElementType();
3713 SDValue Op0 = Node->getOperand(0);
3714 SDValue Op1 = Node->getOperand(1);
3715 if (!TLI.isTypeLegal(EltVT)) {
3716 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3717
3718 // BUILD_VECTOR operands are allowed to be wider than the element type.
3719 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3720 // it.
3721 if (NewEltVT.bitsLT(EltVT)) {
3722 // Convert shuffle node.
3723 // If original node was v4i64 and the new EltVT is i32,
3724 // cast operands to v8i32 and re-build the mask.
3725
3726 // Calculate new VT, the size of the new VT should be equal to original.
3727 EVT NewVT =
3728 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3729 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3730 assert(NewVT.bitsEq(VT));
3731
3732 // cast operands to new VT
3733 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3734 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3735
3736 // Convert the shuffle mask
3737 unsigned int factor =
3739
3740 // EltVT gets smaller
3741 assert(factor > 0);
3742
3743 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3744 if (Mask[i] < 0) {
3745 for (unsigned fi = 0; fi < factor; ++fi)
3746 NewMask.push_back(Mask[i]);
3747 }
3748 else {
3749 for (unsigned fi = 0; fi < factor; ++fi)
3750 NewMask.push_back(Mask[i]*factor+fi);
3751 }
3752 }
3753 Mask = NewMask;
3754 VT = NewVT;
3755 }
3756 EltVT = NewEltVT;
3757 }
3758 unsigned NumElems = VT.getVectorNumElements();
3760 for (unsigned i = 0; i != NumElems; ++i) {
3761 if (Mask[i] < 0) {
3762 Ops.push_back(DAG.getUNDEF(EltVT));
3763 continue;
3764 }
3765 unsigned Idx = Mask[i];
3766 if (Idx < NumElems)
3767 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3768 DAG.getVectorIdxConstant(Idx, dl)));
3769 else
3770 Ops.push_back(
3771 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3772 DAG.getVectorIdxConstant(Idx - NumElems, dl)));
3773 }
3774
3775 Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3776 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3777 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3778 Results.push_back(Tmp1);
3779 break;
3780 }
3783 Results.push_back(TLI.expandVectorSplice(Node, DAG));
3784 break;
3785 }
3787 unsigned Factor = Node->getNumOperands();
3788 if (Factor <= 2 || Factor % 2 != 0)
3789 break;
3791 EVT VecVT = Node->getValueType(0);
3792 SmallVector<EVT> HalfVTs(Factor / 2, VecVT);
3793 // Deinterleave at Factor/2 so each result contains two factors interleaved:
3794 // a0b0 c0d0 a1b1 c1d1 -> [a0c0 b0d0] [a1c1 b1d1]
3795 SDValue L = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, dl, HalfVTs,
3796 ArrayRef(Ops).take_front(Factor / 2));
3797 SDValue R = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, dl, HalfVTs,
3798 ArrayRef(Ops).take_back(Factor / 2));
3799 Results.resize(Factor);
3800 // Deinterleave the 2 factors out:
3801 // [a0c0 a1c1] [b0d0 b1d1] -> a0a1 b0b1 c0c1 d0d1
3802 for (unsigned I = 0; I < Factor / 2; I++) {
3804 DAG.getNode(ISD::VECTOR_DEINTERLEAVE, dl, {VecVT, VecVT},
3805 {L.getValue(I), R.getValue(I)});
3806 Results[I] = Deinterleave.getValue(0);
3807 Results[I + Factor / 2] = Deinterleave.getValue(1);
3808 }
3809 break;
3810 }
3812 unsigned Factor = Node->getNumOperands();
3813 if (Factor <= 2 || Factor % 2 != 0)
3814 break;
3815 EVT VecVT = Node->getValueType(0);
3816 SmallVector<EVT> HalfVTs(Factor / 2, VecVT);
3817 SmallVector<SDValue, 8> LOps, ROps;
3818 // Interleave so we have 2 factors per result:
3819 // a0a1 b0b1 c0c1 d0d1 -> [a0c0 b0d0] [a1c1 b1d1]
3820 for (unsigned I = 0; I < Factor / 2; I++) {
3821 SDValue Interleave =
3822 DAG.getNode(ISD::VECTOR_INTERLEAVE, dl, {VecVT, VecVT},
3823 {Node->getOperand(I), Node->getOperand(I + Factor / 2)});
3824 LOps.push_back(Interleave.getValue(0));
3825 ROps.push_back(Interleave.getValue(1));
3826 }
3827 // Interleave at Factor/2:
3828 // [a0c0 b0d0] [a1c1 b1d1] -> a0b0 c0d0 a1b1 c1d1
3829 SDValue L = DAG.getNode(ISD::VECTOR_INTERLEAVE, dl, HalfVTs, LOps);
3830 SDValue R = DAG.getNode(ISD::VECTOR_INTERLEAVE, dl, HalfVTs, ROps);
3831 for (unsigned I = 0; I < Factor / 2; I++)
3832 Results.push_back(L.getValue(I));
3833 for (unsigned I = 0; I < Factor / 2; I++)
3834 Results.push_back(R.getValue(I));
3835 break;
3836 }
3837 case ISD::EXTRACT_ELEMENT: {
3838 EVT OpTy = Node->getOperand(0).getValueType();
3839 if (Node->getConstantOperandVal(1)) {
3840 // 1 -> Hi
3841 Tmp1 = DAG.getNode(
3842 ISD::SRL, dl, OpTy, Node->getOperand(0),
3843 DAG.getShiftAmountConstant(OpTy.getSizeInBits() / 2, OpTy, dl));
3844 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3845 } else {
3846 // 0 -> Lo
3847 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3848 Node->getOperand(0));
3849 }
3850 Results.push_back(Tmp1);
3851 break;
3852 }
3853 case ISD::STACKADDRESS:
3854 case ISD::STACKSAVE:
3855 // Expand to CopyFromReg if the target set
3856 // StackPointerRegisterToSaveRestore.
3858 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3859 Node->getValueType(0)));
3860 Results.push_back(Results[0].getValue(1));
3861 } else {
3862 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3863 Results.push_back(Node->getOperand(0));
3864
3865 StringRef IntrinsicName = Node->getOpcode() == ISD::STACKADDRESS
3866 ? "llvm.stackaddress"
3867 : "llvm.stacksave";
3868 DAG.getContext()->diagnose(DiagnosticInfoLegalizationFailure(
3869 Twine(IntrinsicName) + " is not supported on this target.",
3871 }
3872 break;
3873 case ISD::STACKRESTORE:
3874 // Expand to CopyToReg if the target set
3875 // StackPointerRegisterToSaveRestore.
3877 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3878 Node->getOperand(1)));
3879 } else {
3880 Results.push_back(Node->getOperand(0));
3881 }
3882 break;
3884 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3885 Results.push_back(Results[0].getValue(0));
3886 break;
3887 case ISD::FCOPYSIGN:
3888 Results.push_back(ExpandFCOPYSIGN(Node));
3889 break;
3890 case ISD::FNEG:
3891 Results.push_back(ExpandFNEG(Node));
3892 break;
3893 case ISD::FABS:
3894 Results.push_back(ExpandFABS(Node));
3895 break;
3896 case ISD::IS_FPCLASS: {
3897 auto Test = static_cast<FPClassTest>(Node->getConstantOperandVal(1));
3898 if (SDValue Expanded =
3899 TLI.expandIS_FPCLASS(Node->getValueType(0), Node->getOperand(0),
3900 Test, Node->getFlags(), SDLoc(Node), DAG))
3901 Results.push_back(Expanded);
3902 break;
3903 }
3904 case ISD::SMIN:
3905 case ISD::SMAX:
3906 case ISD::UMIN:
3907 case ISD::UMAX: {
3908 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3909 ISD::CondCode Pred;
3910 switch (Node->getOpcode()) {
3911 default: llvm_unreachable("How did we get here?");
3912 case ISD::SMAX: Pred = ISD::SETGT; break;
3913 case ISD::SMIN: Pred = ISD::SETLT; break;
3914 case ISD::UMAX: Pred = ISD::SETUGT; break;
3915 case ISD::UMIN: Pred = ISD::SETULT; break;
3916 }
3917 Tmp1 = Node->getOperand(0);
3918 Tmp2 = Node->getOperand(1);
3919 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3920 Results.push_back(Tmp1);
3921 break;
3922 }
3923 case ISD::FMINNUM:
3924 case ISD::FMAXNUM: {
3925 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3926 Results.push_back(Expanded);
3927 break;
3928 }
3929 case ISD::FMINIMUM:
3930 case ISD::FMAXIMUM: {
3931 if (SDValue Expanded = TLI.expandFMINIMUM_FMAXIMUM(Node, DAG))
3932 Results.push_back(Expanded);
3933 break;
3934 }
3935 case ISD::FMINIMUMNUM:
3936 case ISD::FMAXIMUMNUM: {
3937 Results.push_back(TLI.expandFMINIMUMNUM_FMAXIMUMNUM(Node, DAG));
3938 break;
3939 }
3940 case ISD::FSIN:
3941 case ISD::FCOS: {
3942 EVT VT = Node->getValueType(0);
3943 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3944 // fcos which share the same operand and both are used.
3945 if ((TLI.isOperationLegal(ISD::FSINCOS, VT) ||
3946 isSinCosLibcallAvailable(Node, DAG.getLibcalls())) &&
3947 useSinCos(Node)) {
3948 SDVTList VTs = DAG.getVTList(VT, VT);
3949 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3950 if (Node->getOpcode() == ISD::FCOS)
3951 Tmp1 = Tmp1.getValue(1);
3952 Results.push_back(Tmp1);
3953 }
3954 break;
3955 }
3956 case ISD::FLDEXP:
3957 case ISD::STRICT_FLDEXP: {
3958 EVT VT = Node->getValueType(0);
3959 RTLIB::Libcall LC = RTLIB::getLDEXP(VT);
3960 // Use the LibCall instead, it is very likely faster
3961 // FIXME: Use separate LibCall action.
3962 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3963 break;
3964
3965 if (SDValue Expanded = expandLdexp(Node)) {
3966 Results.push_back(Expanded);
3967 if (Node->getOpcode() == ISD::STRICT_FLDEXP)
3968 Results.push_back(Expanded.getValue(1));
3969 }
3970
3971 break;
3972 }
3973 case ISD::FFREXP: {
3974 RTLIB::Libcall LC = RTLIB::getFREXP(Node->getValueType(0));
3975 // Use the LibCall instead, it is very likely faster
3976 // FIXME: Use separate LibCall action.
3977 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3978 break;
3979
3980 if (SDValue Expanded = expandFrexp(Node)) {
3981 Results.push_back(Expanded);
3982 Results.push_back(Expanded.getValue(1));
3983 }
3984 break;
3985 }
3986 case ISD::FMODF: {
3987 RTLIB::Libcall LC = RTLIB::getMODF(Node->getValueType(0));
3988 // Use the LibCall instead, it is very likely faster
3989 // FIXME: Use separate LibCall action.
3990 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported)
3991 break;
3992
3993 if (SDValue Expanded = expandModf(Node)) {
3994 Results.push_back(Expanded);
3995 Results.push_back(Expanded.getValue(1));
3996 }
3997 break;
3998 }
3999 case ISD::FSINCOS: {
4000 if (isSinCosLibcallAvailable(Node, DAG.getLibcalls()))
4001 break;
4002 EVT VT = Node->getValueType(0);
4003 SDValue Op = Node->getOperand(0);
4004 SDNodeFlags Flags = Node->getFlags();
4005 Tmp1 = DAG.getNode(ISD::FSIN, dl, VT, Op, Flags);
4006 Tmp2 = DAG.getNode(ISD::FCOS, dl, VT, Op, Flags);
4007 Results.append({Tmp1, Tmp2});
4008 break;
4009 }
4010 case ISD::FMAD:
4011 llvm_unreachable("Illegal fmad should never be formed");
4012
4013 case ISD::FP16_TO_FP:
4014 if (Node->getValueType(0) != MVT::f32) {
4015 // We can extend to types bigger than f32 in two steps without changing
4016 // the result. Since "f16 -> f32" is much more commonly available, give
4017 // CodeGen the option of emitting that before resorting to a libcall.
4018 SDValue Res =
4019 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
4020 Results.push_back(
4021 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
4022 }
4023 break;
4026 if (Node->getValueType(0) != MVT::f32) {
4027 // We can extend to types bigger than f32 in two steps without changing
4028 // the result. Since "f16 -> f32" is much more commonly available, give
4029 // CodeGen the option of emitting that before resorting to a libcall.
4030 SDValue Res = DAG.getNode(Node->getOpcode(), dl, {MVT::f32, MVT::Other},
4031 {Node->getOperand(0), Node->getOperand(1)});
4032 Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
4033 {Node->getValueType(0), MVT::Other},
4034 {Res.getValue(1), Res});
4035 Results.push_back(Res);
4036 Results.push_back(Res.getValue(1));
4037 }
4038 break;
4039 case ISD::FP_TO_FP16:
4040 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
4041 if (Node->getFlags().hasApproximateFuncs() && !TLI.useSoftFloat()) {
4042 SDValue Op = Node->getOperand(0);
4043 MVT SVT = Op.getSimpleValueType();
4044 if ((SVT == MVT::f64 || SVT == MVT::f80) &&
4046 // Under fastmath, we can expand this node into a fround followed by
4047 // a float-half conversion.
4048 SDValue FloatVal =
4049 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
4050 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
4051 Results.push_back(
4052 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
4053 }
4054 }
4055 break;
4056 case ISD::ConstantFP: {
4057 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
4058 // Check to see if this FP immediate is already legal.
4059 // If this is a legal constant, turn it into a TargetConstantFP node.
4060 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
4061 DAG.shouldOptForSize()))
4062 Results.push_back(ExpandConstantFP(CFP, true));
4063 break;
4064 }
4065 case ISD::Constant: {
4066 ConstantSDNode *CP = cast<ConstantSDNode>(Node);
4067 Results.push_back(ExpandConstant(CP));
4068 break;
4069 }
4070 case ISD::FSUB: {
4071 EVT VT = Node->getValueType(0);
4072 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
4074 const SDNodeFlags Flags = Node->getFlags();
4075 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
4076 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
4077 Results.push_back(Tmp1);
4078 }
4079 break;
4080 }
4081 case ISD::SUB: {
4082 EVT VT = Node->getValueType(0);
4085 "Don't know how to expand this subtraction!");
4086 Tmp1 = DAG.getNOT(dl, Node->getOperand(1), VT);
4087 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
4088 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
4089 break;
4090 }
4091 case ISD::UREM:
4092 case ISD::SREM:
4093 if (TLI.expandREM(Node, Tmp1, DAG))
4094 Results.push_back(Tmp1);
4095 break;
4096 case ISD::UDIV:
4097 case ISD::SDIV: {
4098 bool isSigned = Node->getOpcode() == ISD::SDIV;
4099 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
4100 EVT VT = Node->getValueType(0);
4101 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
4102 SDVTList VTs = DAG.getVTList(VT, VT);
4103 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
4104 Node->getOperand(1));
4105 Results.push_back(Tmp1);
4106 }
4107 break;
4108 }
4109 case ISD::MULHU:
4110 case ISD::MULHS: {
4111 unsigned ExpandOpcode =
4112 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
4113 EVT VT = Node->getValueType(0);
4114 SDVTList VTs = DAG.getVTList(VT, VT);
4115
4116 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
4117 Node->getOperand(1));
4118 Results.push_back(Tmp1.getValue(1));
4119 break;
4120 }
4121 case ISD::UMUL_LOHI:
4122 case ISD::SMUL_LOHI: {
4123 SDValue LHS = Node->getOperand(0);
4124 SDValue RHS = Node->getOperand(1);
4125 EVT VT = LHS.getValueType();
4126 unsigned MULHOpcode =
4127 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS;
4128
4129 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
4130 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
4131 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
4132 break;
4133 }
4134
4136 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
4137 assert(TLI.isTypeLegal(HalfType));
4138 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves,
4139 HalfType, DAG,
4140 TargetLowering::MulExpansionKind::Always)) {
4141 for (unsigned i = 0; i < 2; ++i) {
4142 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
4143 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
4144 SDValue Shift =
4145 DAG.getShiftAmountConstant(HalfType.getScalarSizeInBits(), VT, dl);
4146 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4147 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
4148 }
4149 break;
4150 }
4151 break;
4152 }
4153 case ISD::MUL: {
4154 EVT VT = Node->getValueType(0);
4155 SDVTList VTs = DAG.getVTList(VT, VT);
4156 // See if multiply or divide can be lowered using two-result operations.
4157 // We just need the low half of the multiply; try both the signed
4158 // and unsigned forms. If the target supports both SMUL_LOHI and
4159 // UMUL_LOHI, form a preference by checking which forms of plain
4160 // MULH it supports.
4161 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
4162 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
4163 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
4164 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
4165 unsigned OpToUse = 0;
4166 if (HasSMUL_LOHI && !HasMULHS) {
4167 OpToUse = ISD::SMUL_LOHI;
4168 } else if (HasUMUL_LOHI && !HasMULHU) {
4169 OpToUse = ISD::UMUL_LOHI;
4170 } else if (HasSMUL_LOHI) {
4171 OpToUse = ISD::SMUL_LOHI;
4172 } else if (HasUMUL_LOHI) {
4173 OpToUse = ISD::UMUL_LOHI;
4174 }
4175 if (OpToUse) {
4176 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
4177 Node->getOperand(1)));
4178 break;
4179 }
4180
4181 SDValue Lo, Hi;
4182 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
4187 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
4188 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
4189 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
4190 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
4191 SDValue Shift =
4192 DAG.getShiftAmountConstant(HalfType.getSizeInBits(), VT, dl);
4193 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
4194 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
4195 }
4196 break;
4197 }
4198 case ISD::FSHL:
4199 case ISD::FSHR:
4200 if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG))
4201 Results.push_back(Expanded);
4202 break;
4203 case ISD::ROTL:
4204 case ISD::ROTR:
4205 if (SDValue Expanded = TLI.expandROT(Node, true /*AllowVectorOps*/, DAG))
4206 Results.push_back(Expanded);
4207 break;
4208 case ISD::CLMUL:
4209 case ISD::CLMULR:
4210 case ISD::CLMULH:
4211 if (SDValue Expanded = TLI.expandCLMUL(Node, DAG))
4212 Results.push_back(Expanded);
4213 break;
4214 case ISD::PEXT:
4215 Results.push_back(TLI.expandPEXT(Node, DAG));
4216 break;
4217 case ISD::PDEP:
4218 Results.push_back(TLI.expandPDEP(Node, DAG));
4219 break;
4220 case ISD::SADDSAT:
4221 case ISD::UADDSAT:
4222 case ISD::SSUBSAT:
4223 case ISD::USUBSAT:
4224 Results.push_back(TLI.expandAddSubSat(Node, DAG));
4225 break;
4226 case ISD::SCMP:
4227 case ISD::UCMP:
4228 Results.push_back(TLI.expandCMP(Node, DAG));
4229 break;
4230 case ISD::SSHLSAT:
4231 case ISD::USHLSAT:
4232 Results.push_back(TLI.expandShlSat(Node, DAG));
4233 break;
4234 case ISD::SMULFIX:
4235 case ISD::SMULFIXSAT:
4236 case ISD::UMULFIX:
4237 case ISD::UMULFIXSAT:
4238 Results.push_back(TLI.expandFixedPointMul(Node, DAG));
4239 break;
4240 case ISD::SDIVFIX:
4241 case ISD::SDIVFIXSAT:
4242 case ISD::UDIVFIX:
4243 case ISD::UDIVFIXSAT:
4244 if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node),
4245 Node->getOperand(0),
4246 Node->getOperand(1),
4247 Node->getConstantOperandVal(2),
4248 DAG)) {
4249 Results.push_back(V);
4250 break;
4251 }
4252 // FIXME: We might want to retry here with a wider type if we fail, if that
4253 // type is legal.
4254 // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is
4255 // <= 128 (which is the case for all of the default Embedded-C types),
4256 // we will only get here with types and scales that we could always expand
4257 // if we were allowed to generate libcalls to division functions of illegal
4258 // type. But we cannot do that.
4259 llvm_unreachable("Cannot expand DIVFIX!");
4260 case ISD::UADDO_CARRY:
4261 case ISD::USUBO_CARRY: {
4262 SDValue LHS = Node->getOperand(0);
4263 SDValue RHS = Node->getOperand(1);
4264 SDValue Carry = Node->getOperand(2);
4265
4266 bool IsAdd = Node->getOpcode() == ISD::UADDO_CARRY;
4267
4268 // Initial add of the 2 operands.
4269 unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
4270 EVT VT = LHS.getValueType();
4271 SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
4272
4273 // Initial check for overflow.
4274 EVT CarryType = Node->getValueType(1);
4275 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
4276 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
4277 SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
4278
4279 // Add of the sum and the carry.
4280 SDValue One = DAG.getConstant(1, dl, VT);
4281 SDValue CarryExt =
4282 DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One);
4283 SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
4284
4285 // Second check for overflow. If we are adding, we can only overflow if the
4286 // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
4287 // If we are subtracting, we can only overflow if the initial sum is 0 and
4288 // the carry is set, resulting in a new sum of all 1s.
4289 SDValue Zero = DAG.getConstant(0, dl, VT);
4290 SDValue Overflow2 =
4291 IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
4292 : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
4293 Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
4294 DAG.getZExtOrTrunc(Carry, dl, SetCCType));
4295
4296 SDValue ResultCarry =
4297 DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
4298
4299 Results.push_back(Sum2);
4300 Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
4301 break;
4302 }
4303 case ISD::SADDO:
4304 case ISD::SSUBO: {
4305 SDValue Result, Overflow;
4306 TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
4307 Results.push_back(Result);
4308 Results.push_back(Overflow);
4309 break;
4310 }
4311 case ISD::UADDO:
4312 case ISD::USUBO: {
4313 SDValue Result, Overflow;
4314 TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
4315 Results.push_back(Result);
4316 Results.push_back(Overflow);
4317 break;
4318 }
4319 case ISD::UMULO:
4320 case ISD::SMULO: {
4321 SDValue Result, Overflow;
4322 if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
4323 Results.push_back(Result);
4324 Results.push_back(Overflow);
4325 }
4326 break;
4327 }
4328 case ISD::BUILD_PAIR: {
4329 EVT PairTy = Node->getValueType(0);
4330 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
4331 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
4332 Tmp2 = DAG.getNode(
4333 ISD::SHL, dl, PairTy, Tmp2,
4334 DAG.getShiftAmountConstant(PairTy.getSizeInBits() / 2, PairTy, dl));
4335 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
4336 break;
4337 }
4338 case ISD::SELECT:
4339 Tmp1 = Node->getOperand(0);
4340 Tmp2 = Node->getOperand(1);
4341 Tmp3 = Node->getOperand(2);
4342 if (Tmp1.getOpcode() == ISD::SETCC) {
4343 Tmp1 = DAG.getSelectCC(
4344 dl, Tmp1.getOperand(0), Tmp1.getOperand(1), Tmp2, Tmp3,
4345 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get(), Node->getFlags());
4346 } else {
4347 Tmp1 =
4348 DAG.getSelectCC(dl, Tmp1, DAG.getConstant(0, dl, Tmp1.getValueType()),
4349 Tmp2, Tmp3, ISD::SETNE, Node->getFlags());
4350 }
4351 Results.push_back(Tmp1);
4352 break;
4353 case ISD::BR_JT: {
4354 SDValue Chain = Node->getOperand(0);
4355 SDValue Table = Node->getOperand(1);
4356 SDValue Index = Node->getOperand(2);
4357 int JTI = cast<JumpTableSDNode>(Table.getNode())->getIndex();
4358
4359 const DataLayout &TD = DAG.getDataLayout();
4360 EVT PTy = TLI.getPointerTy(TD);
4361
4362 unsigned EntrySize =
4364
4365 // For power-of-two jumptable entry sizes convert multiplication to a shift.
4366 // This transformation needs to be done here since otherwise the MIPS
4367 // backend will end up emitting a three instruction multiply sequence
4368 // instead of a single shift and MSP430 will call a runtime function.
4369 if (llvm::isPowerOf2_32(EntrySize))
4370 Index = DAG.getNode(
4371 ISD::SHL, dl, Index.getValueType(), Index,
4372 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
4373 else
4374 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
4375 DAG.getConstant(EntrySize, dl, Index.getValueType()));
4376 SDValue Addr = DAG.getMemBasePlusOffset(Table, Index, dl);
4377
4378 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
4379 SDValue LD = DAG.getExtLoad(
4380 ISD::SEXTLOAD, dl, PTy, Chain, Addr,
4382 Addr = LD;
4383 if (TLI.isJumpTableRelative()) {
4384 // For PIC, the sequence is:
4385 // BRIND(RelocBase + load(Jumptable + index))
4386 // RelocBase can be JumpTable, GOT or some sort of global base.
4388 Addr, dl);
4389 }
4390
4391 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, JTI, DAG);
4392 Results.push_back(Tmp1);
4393 break;
4394 }
4395 case ISD::BRCOND:
4396 // Expand brcond's setcc into its constituent parts and create a BR_CC
4397 // Node.
4398 Tmp1 = Node->getOperand(0);
4399 Tmp2 = Node->getOperand(1);
4400 if (Tmp2.getOpcode() == ISD::SETCC &&
4402 Tmp2.getOperand(0).getValueType())) {
4403 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, Tmp2.getOperand(2),
4404 Tmp2.getOperand(0), Tmp2.getOperand(1),
4405 Node->getOperand(2));
4406 } else {
4407 // We test only the i1 bit. Skip the AND if UNDEF or another AND.
4408 if (Tmp2.isUndef() ||
4409 (Tmp2.getOpcode() == ISD::AND && isOneConstant(Tmp2.getOperand(1))))
4410 Tmp3 = Tmp2;
4411 else
4412 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
4413 DAG.getConstant(1, dl, Tmp2.getValueType()));
4414 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
4415 DAG.getCondCode(ISD::SETNE), Tmp3,
4416 DAG.getConstant(0, dl, Tmp3.getValueType()),
4417 Node->getOperand(2));
4418 }
4419 Results.push_back(Tmp1);
4420 break;
4421 case ISD::SETCC:
4422 case ISD::STRICT_FSETCC:
4423 case ISD::STRICT_FSETCCS: {
4424 bool IsStrict = Node->getOpcode() == ISD::STRICT_FSETCC ||
4425 Node->getOpcode() == ISD::STRICT_FSETCCS;
4426 bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS;
4427 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
4428 unsigned Offset = IsStrict ? 1 : 0;
4429 Tmp1 = Node->getOperand(0 + Offset);
4430 Tmp2 = Node->getOperand(1 + Offset);
4431 Tmp3 = Node->getOperand(2 + Offset);
4432 bool Legalized =
4433 TLI.LegalizeSetCCCondCode(DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3,
4434 NeedInvert, dl, Chain, IsSignaling);
4435
4436 if (Legalized) {
4437 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4438 // condition code, create a new SETCC node.
4439 if (Tmp3.getNode()) {
4440 if (IsStrict) {
4441 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getVTList(),
4442 {Chain, Tmp1, Tmp2, Tmp3}, Node->getFlags());
4443 Chain = Tmp1.getValue(1);
4444 } else {
4445 Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1,
4446 Tmp2, Tmp3, Node->getFlags());
4447 }
4448 }
4449
4450 // If we expanded the SETCC by inverting the condition code, then wrap
4451 // the existing SETCC in a NOT to restore the intended condition.
4452 if (NeedInvert) {
4453 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
4454 }
4455
4456 Results.push_back(Tmp1);
4457 if (IsStrict)
4458 Results.push_back(Chain);
4459
4460 break;
4461 }
4462
4463 // FIXME: It seems Legalized is false iff CCCode is Legal. I don't
4464 // understand if this code is useful for strict nodes.
4465 assert(!IsStrict && "Don't know how to expand for strict nodes.");
4466
4467 // Otherwise, SETCC for the given comparison type must be completely
4468 // illegal; expand it into a SELECT_CC.
4469 EVT VT = Node->getValueType(0);
4470 EVT Tmp1VT = Tmp1.getValueType();
4471 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
4472 DAG.getBoolConstant(true, dl, VT, Tmp1VT),
4473 DAG.getBoolConstant(false, dl, VT, Tmp1VT), Tmp3,
4474 Node->getFlags());
4475 Results.push_back(Tmp1);
4476 break;
4477 }
4478 case ISD::SELECT_CC: {
4479 // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS
4480 Tmp1 = Node->getOperand(0); // LHS
4481 Tmp2 = Node->getOperand(1); // RHS
4482 Tmp3 = Node->getOperand(2); // True
4483 Tmp4 = Node->getOperand(3); // False
4484 EVT VT = Node->getValueType(0);
4485 SDValue Chain;
4486 SDValue CC = Node->getOperand(4);
4487 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
4488
4489 if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
4490 // If the condition code is legal, then we need to expand this
4491 // node using SETCC and SELECT.
4492 EVT CmpVT = Tmp1.getValueType();
4494 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
4495 "expanded.");
4496 EVT CCVT = getSetCCResultType(CmpVT);
4497 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
4498 Results.push_back(
4499 DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4, Node->getFlags()));
4500 break;
4501 }
4502
4503 // SELECT_CC is legal, so the condition code must not be.
4504 bool Legalized = false;
4505 // Try to legalize by inverting the condition. This is for targets that
4506 // might support an ordered version of a condition, but not the unordered
4507 // version (or vice versa).
4508 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType());
4509 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
4510 // Use the new condition code and swap true and false
4511 Legalized = true;
4512 Tmp1 =
4513 DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC, Node->getFlags());
4514 } else {
4515 // If The inverse is not legal, then try to swap the arguments using
4516 // the inverse condition code.
4518 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
4519 // The swapped inverse condition is legal, so swap true and false,
4520 // lhs and rhs.
4521 Legalized = true;
4522 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC,
4523 Node->getFlags());
4524 }
4525 }
4526
4527 if (!Legalized) {
4528 Legalized = TLI.LegalizeSetCCCondCode(
4529 DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC,
4530 NeedInvert, dl, Chain);
4531
4532 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
4533
4534 // If we expanded the SETCC by inverting the condition code, then swap
4535 // the True/False operands to match.
4536 if (NeedInvert)
4537 std::swap(Tmp3, Tmp4);
4538
4539 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4540 // condition code, create a new SELECT_CC node.
4541 if (CC.getNode()) {
4542 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4543 Tmp2, Tmp3, Tmp4, CC, Node->getFlags());
4544 } else {
4545 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
4546 CC = DAG.getCondCode(ISD::SETNE);
4547 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4548 Tmp2, Tmp3, Tmp4, CC, Node->getFlags());
4549 }
4550 }
4551 Results.push_back(Tmp1);
4552 break;
4553 }
4554 case ISD::BR_CC: {
4555 // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS
4556 SDValue Chain;
4557 Tmp1 = Node->getOperand(0); // Chain
4558 Tmp2 = Node->getOperand(2); // LHS
4559 Tmp3 = Node->getOperand(3); // RHS
4560 Tmp4 = Node->getOperand(1); // CC
4561
4562 bool Legalized =
4563 TLI.LegalizeSetCCCondCode(DAG, getSetCCResultType(Tmp2.getValueType()),
4564 Tmp2, Tmp3, Tmp4, NeedInvert, dl, Chain);
4565 (void)Legalized;
4566 assert(Legalized && "Can't legalize BR_CC with legal condition!");
4567
4568 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
4569 // node.
4570 if (Tmp4.getNode()) {
4571 assert(!NeedInvert && "Don't know how to invert BR_CC!");
4572
4573 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
4574 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
4575 } else {
4576 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
4577 Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE);
4578 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
4579 Tmp2, Tmp3, Node->getOperand(4));
4580 }
4581 Results.push_back(Tmp1);
4582 break;
4583 }
4584 case ISD::BUILD_VECTOR:
4585 Results.push_back(ExpandBUILD_VECTOR(Node));
4586 break;
4587 case ISD::SPLAT_VECTOR:
4588 Results.push_back(ExpandSPLAT_VECTOR(Node));
4589 break;
4590 case ISD::SRA:
4591 case ISD::SRL:
4592 case ISD::SHL: {
4593 // Scalarize vector SRA/SRL/SHL.
4594 EVT VT = Node->getValueType(0);
4595 assert(VT.isVector() && "Unable to legalize non-vector shift");
4596 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
4597 unsigned NumElem = VT.getVectorNumElements();
4598
4600 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
4601 SDValue Ex =
4603 Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl));
4604 SDValue Sh =
4606 Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl));
4607 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
4608 VT.getScalarType(), Ex, Sh));
4609 }
4610
4611 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
4612 Results.push_back(Result);
4613 break;
4614 }
4617 case ISD::VECREDUCE_ADD:
4618 case ISD::VECREDUCE_MUL:
4619 case ISD::VECREDUCE_AND:
4620 case ISD::VECREDUCE_OR:
4621 case ISD::VECREDUCE_XOR:
4630 Results.push_back(TLI.expandVecReduce(Node, DAG));
4631 break;
4632 case ISD::VP_CTTZ_ELTS:
4633 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
4634 Results.push_back(TLI.expandVPCTTZElements(Node, DAG));
4635 break;
4636 case ISD::CLEAR_CACHE:
4637 // The default expansion of llvm.clear_cache is simply a no-op for those
4638 // targets where it is not needed.
4639 Results.push_back(Node->getOperand(0));
4640 break;
4641 case ISD::LRINT:
4642 case ISD::LLRINT: {
4643 SDValue Arg = Node->getOperand(0);
4644 EVT ArgVT = Arg.getValueType();
4645 EVT ResVT = Node->getValueType(0);
4646 SDLoc DL(Node);
4647 SDValue RoundNode = DAG.getNode(ISD::FRINT, DL, ArgVT, Arg);
4648 SDValue ConvertNode = DAG.getNode(ISD::FP_TO_SINT, DL, ResVT, RoundNode);
4649 // Non-deterministic results are equivalent to freeze poison.
4650 Results.push_back(DAG.getFreeze(ConvertNode));
4651 break;
4652 }
4653 case ISD::ADDRSPACECAST:
4654 Results.push_back(DAG.UnrollVectorOp(Node));
4655 break;
4657 case ISD::GlobalAddress:
4660 case ISD::ConstantPool:
4661 case ISD::JumpTable:
4665 // FIXME: Custom lowering for these operations shouldn't return null!
4666 // Return true so that we don't call ConvertNodeToLibcall which also won't
4667 // do anything.
4668 return true;
4669 }
4670
4671 if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) {
4672 // FIXME: We were asked to expand a strict floating-point operation,
4673 // but there is currently no expansion implemented that would preserve
4674 // the "strict" properties. For now, we just fall back to the non-strict
4675 // version if that is legal on the target. The actual mutation of the
4676 // operation will happen in SelectionDAGISel::DoInstructionSelection.
4677 switch (Node->getOpcode()) {
4678 default:
4679 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
4680 Node->getValueType(0))
4681 == TargetLowering::Legal)
4682 return true;
4683 break;
4684 case ISD::STRICT_FSUB: {
4686 ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal)
4687 return true;
4689 ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal)
4690 break;
4691
4692 EVT VT = Node->getValueType(0);
4693 const SDNodeFlags Flags = Node->getFlags();
4694 SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags);
4695 SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(),
4696 {Node->getOperand(0), Node->getOperand(1), Neg},
4697 Flags);
4698
4699 Results.push_back(Fadd);
4700 Results.push_back(Fadd.getValue(1));
4701 break;
4702 }
4705 case ISD::STRICT_LRINT:
4706 case ISD::STRICT_LLRINT:
4707 case ISD::STRICT_LROUND:
4709 // These are registered by the operand type instead of the value
4710 // type. Reflect that here.
4711 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
4712 Node->getOperand(1).getValueType())
4713 == TargetLowering::Legal)
4714 return true;
4715 break;
4716 }
4717 }
4718
4719 // Replace the original node with the legalized result.
4720 if (Results.empty()) {
4721 LLVM_DEBUG(dbgs() << "Cannot expand node\n");
4722 return false;
4723 }
4724
4725 LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
4726 ReplaceNode(Node, Results.data());
4727 return true;
4728}
4729
4730/// Return if we can use the FAST_* variant of a math libcall for the node.
4731/// FIXME: This is just guessing, we probably should have unique specific sets
4732/// flags required per libcall.
4733static bool canUseFastMathLibcall(const SDNode *Node) {
4734 // FIXME: Probably should define fast to respect nan/inf and only be
4735 // approximate functions.
4736
4737 SDNodeFlags Flags = Node->getFlags();
4738 return Flags.hasApproximateFuncs() && Flags.hasNoNaNs() &&
4739 Flags.hasNoInfs() && Flags.hasNoSignedZeros();
4740}
4741
4742void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
4743 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
4745 SDLoc dl(Node);
4746 TargetLowering::MakeLibCallOptions CallOptions;
4747 CallOptions.IsPostTypeLegalization = true;
4748 // FIXME: Check flags on the node to see if we can use a finite call.
4749 unsigned Opc = Node->getOpcode();
4750 switch (Opc) {
4751 case ISD::ATOMIC_FENCE: {
4752 // If the target didn't lower this, lower it to '__sync_synchronize()' call
4753 // FIXME: handle "fence singlethread" more efficiently.
4754 TargetLowering::ArgListTy Args;
4755
4756 TargetLowering::CallLoweringInfo CLI(DAG);
4757 CLI.setDebugLoc(dl)
4758 .setChain(Node->getOperand(0))
4759 .setLibCallee(
4760 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
4761 DAG.getExternalSymbol("__sync_synchronize",
4762 TLI.getPointerTy(DAG.getDataLayout())),
4763 std::move(Args));
4764
4765 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
4766
4767 Results.push_back(CallResult.second);
4768 break;
4769 }
4770 // By default, atomic intrinsics are marked Legal and lowered. Targets
4771 // which don't support them directly, however, may want libcalls, in which
4772 // case they mark them Expand, and we get here.
4773 case ISD::ATOMIC_SWAP:
4785 case ISD::ATOMIC_CMP_SWAP: {
4786 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
4787 AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering();
4788 RTLIB::Libcall LC = RTLIB::getOUTLINE_ATOMIC(Opc, Order, VT);
4789 EVT RetVT = Node->getValueType(0);
4791 if (DAG.getLibcalls().getLibcallImpl(LC) != RTLIB::Unsupported) {
4792 // If outline atomic available, prepare its arguments and expand.
4793 Ops.append(Node->op_begin() + 2, Node->op_end());
4794 Ops.push_back(Node->getOperand(1));
4795
4796 } else {
4797 LC = RTLIB::getSYNC(Opc, VT);
4798 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
4799 "Unexpected atomic op or value type!");
4800 // Arguments for expansion to sync libcall
4801 Ops.append(Node->op_begin() + 1, Node->op_end());
4802 }
4803 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
4804 Ops, CallOptions,
4805 SDLoc(Node),
4806 Node->getOperand(0));
4807 Results.push_back(Tmp.first);
4808 Results.push_back(Tmp.second);
4809 break;
4810 }
4811 case ISD::TRAP: {
4812 // If this operation is not supported, lower it to 'abort()' call
4813 TargetLowering::ArgListTy Args;
4814 TargetLowering::CallLoweringInfo CLI(DAG);
4815 CLI.setDebugLoc(dl)
4816 .setChain(Node->getOperand(0))
4817 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
4819 "abort", TLI.getPointerTy(DAG.getDataLayout())),
4820 std::move(Args));
4821 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
4822
4823 Results.push_back(CallResult.second);
4824 break;
4825 }
4826 case ISD::CLEAR_CACHE: {
4827 SDValue InputChain = Node->getOperand(0);
4828 SDValue StartVal = Node->getOperand(1);
4829 SDValue EndVal = Node->getOperand(2);
4830 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
4831 DAG, RTLIB::CLEAR_CACHE, MVT::isVoid, {StartVal, EndVal}, CallOptions,
4832 SDLoc(Node), InputChain);
4833 Results.push_back(Tmp.second);
4834 break;
4835 }
4836 case ISD::FMINNUM:
4838 ExpandFPLibCall(Node, RTLIB::getFMIN(Node->getSimpleValueType(0)), Results);
4839 break;
4840 // FIXME: We do not have libcalls for FMAXIMUM and FMINIMUM. So, we cannot use
4841 // libcall legalization for these nodes, but there is no default expasion for
4842 // these nodes either (see PR63267 for example).
4843 case ISD::FMAXNUM:
4845 ExpandFPLibCall(Node, RTLIB::getFMAX(Node->getSimpleValueType(0)), Results);
4846 break;
4847 case ISD::FMINIMUMNUM:
4848 ExpandFPLibCall(Node, RTLIB::getFMINIMUM_NUM(Node->getSimpleValueType(0)),
4849 Results);
4850 break;
4851 case ISD::FMAXIMUMNUM:
4852 ExpandFPLibCall(Node, RTLIB::getFMAXIMUM_NUM(Node->getSimpleValueType(0)),
4853 Results);
4854 break;
4855 case ISD::FSQRT:
4856 case ISD::STRICT_FSQRT: {
4857 // FIXME: Probably should define fast to respect nan/inf and only be
4858 // approximate functions.
4859 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
4860 {RTLIB::FAST_SQRT_F32, RTLIB::SQRT_F32},
4861 {RTLIB::FAST_SQRT_F64, RTLIB::SQRT_F64},
4862 {RTLIB::FAST_SQRT_F80, RTLIB::SQRT_F80},
4863 {RTLIB::FAST_SQRT_F128, RTLIB::SQRT_F128},
4864 {RTLIB::FAST_SQRT_PPCF128, RTLIB::SQRT_PPCF128},
4865 Results);
4866 break;
4867 }
4868 case ISD::FCBRT:
4869 ExpandFPLibCall(Node, RTLIB::getCBRT(Node->getSimpleValueType(0)), Results);
4870 break;
4871 case ISD::FSIN:
4872 case ISD::STRICT_FSIN:
4873 ExpandFPLibCall(Node, RTLIB::getSIN(Node->getSimpleValueType(0)), Results);
4874 break;
4875 case ISD::FCOS:
4876 case ISD::STRICT_FCOS:
4877 ExpandFPLibCall(Node, RTLIB::getCOS(Node->getSimpleValueType(0)), Results);
4878 break;
4879 case ISD::FTAN:
4880 case ISD::STRICT_FTAN:
4881 ExpandFPLibCall(Node, RTLIB::getTAN(Node->getSimpleValueType(0)), Results);
4882 break;
4883 case ISD::FASIN:
4884 case ISD::STRICT_FASIN:
4885 ExpandFPLibCall(Node, RTLIB::getASIN(Node->getSimpleValueType(0)), Results);
4886 break;
4887 case ISD::FACOS:
4888 case ISD::STRICT_FACOS:
4889 ExpandFPLibCall(Node, RTLIB::getACOS(Node->getSimpleValueType(0)), Results);
4890 break;
4891 case ISD::FATAN:
4892 case ISD::STRICT_FATAN:
4893 ExpandFPLibCall(Node, RTLIB::getATAN(Node->getSimpleValueType(0)), Results);
4894 break;
4895 case ISD::FATAN2:
4896 case ISD::STRICT_FATAN2:
4897 ExpandFPLibCall(Node, RTLIB::getATAN2(Node->getSimpleValueType(0)),
4898 Results);
4899 break;
4900 case ISD::FSINH:
4901 case ISD::STRICT_FSINH:
4902 ExpandFPLibCall(Node, RTLIB::getSINH(Node->getSimpleValueType(0)), Results);
4903 break;
4904 case ISD::FCOSH:
4905 case ISD::STRICT_FCOSH:
4906 ExpandFPLibCall(Node, RTLIB::getCOSH(Node->getSimpleValueType(0)), Results);
4907 break;
4908 case ISD::FTANH:
4909 case ISD::STRICT_FTANH:
4910 ExpandFPLibCall(Node, RTLIB::getTANH(Node->getSimpleValueType(0)), Results);
4911 break;
4912 case ISD::FSINCOS:
4913 case ISD::FSINCOSPI: {
4914 EVT VT = Node->getValueType(0);
4915
4916 if (Node->getOpcode() == ISD::FSINCOS) {
4917 RTLIB::Libcall SincosStret = RTLIB::getSINCOS_STRET(VT);
4918 if (SincosStret != RTLIB::UNKNOWN_LIBCALL) {
4919 if (SDValue Expanded = ExpandSincosStretLibCall(Node)) {
4920 Results.push_back(Expanded);
4921 Results.push_back(Expanded.getValue(1));
4922 break;
4923 }
4924 }
4925 }
4926
4927 RTLIB::Libcall LC = Node->getOpcode() == ISD::FSINCOS
4928 ? RTLIB::getSINCOS(VT)
4929 : RTLIB::getSINCOSPI(VT);
4930 bool Expanded = TLI.expandMultipleResultFPLibCall(DAG, LC, Node, Results);
4931 if (!Expanded) {
4932 DAG.getContext()->emitError(Twine("no libcall available for ") +
4933 Node->getOperationName(&DAG));
4934 SDValue Poison = DAG.getPOISON(VT);
4935 Results.push_back(Poison);
4936 Results.push_back(Poison);
4937 }
4938
4939 break;
4940 }
4941 case ISD::FLOG:
4942 case ISD::STRICT_FLOG:
4943 ExpandFPLibCall(Node, RTLIB::getLOG(Node->getSimpleValueType(0)), Results);
4944 break;
4945 case ISD::FLOG2:
4946 case ISD::STRICT_FLOG2:
4947 ExpandFPLibCall(Node, RTLIB::getLOG2(Node->getSimpleValueType(0)), Results);
4948 break;
4949 case ISD::FLOG10:
4950 case ISD::STRICT_FLOG10:
4951 ExpandFPLibCall(Node, RTLIB::getLOG10(Node->getSimpleValueType(0)),
4952 Results);
4953 break;
4954 case ISD::FEXP:
4955 case ISD::STRICT_FEXP:
4956 ExpandFPLibCall(Node, RTLIB::getEXP(Node->getSimpleValueType(0)), Results);
4957 break;
4958 case ISD::FEXP2:
4959 case ISD::STRICT_FEXP2:
4960 ExpandFPLibCall(Node, RTLIB::getEXP2(Node->getSimpleValueType(0)), Results);
4961 break;
4962 case ISD::FEXP10:
4963 ExpandFPLibCall(Node, RTLIB::getEXP10(Node->getSimpleValueType(0)),
4964 Results);
4965 break;
4966 case ISD::FTRUNC:
4967 case ISD::STRICT_FTRUNC:
4968 ExpandFPLibCall(Node, RTLIB::getTRUNC(Node->getSimpleValueType(0)),
4969 Results);
4970 break;
4971 case ISD::FFLOOR:
4972 case ISD::STRICT_FFLOOR:
4973 ExpandFPLibCall(Node, RTLIB::getFLOOR(Node->getSimpleValueType(0)),
4974 Results);
4975 break;
4976 case ISD::FCEIL:
4977 case ISD::STRICT_FCEIL:
4978 ExpandFPLibCall(Node, RTLIB::getCEIL(Node->getSimpleValueType(0)), Results);
4979 break;
4980 case ISD::FRINT:
4981 case ISD::STRICT_FRINT:
4982 ExpandFPLibCall(Node, RTLIB::getRINT(Node->getSimpleValueType(0)), Results);
4983 break;
4984 case ISD::FNEARBYINT:
4986 ExpandFPLibCall(Node, RTLIB::getNEARBYINT(Node->getSimpleValueType(0)),
4987 Results);
4988 break;
4989 case ISD::FROUND:
4990 case ISD::STRICT_FROUND:
4991 ExpandFPLibCall(Node, RTLIB::getROUND(Node->getSimpleValueType(0)),
4992 Results);
4993 break;
4994 case ISD::FROUNDEVEN:
4996 ExpandFPLibCall(Node, RTLIB::getROUNDEVEN(Node->getSimpleValueType(0)),
4997 Results);
4998 break;
4999 case ISD::FLDEXP:
5000 case ISD::STRICT_FLDEXP:
5001 ExpandFPLibCall(Node, RTLIB::getLDEXP(Node->getSimpleValueType(0)),
5002 Results);
5003 break;
5004 case ISD::FMODF:
5005 case ISD::FFREXP: {
5006 EVT VT = Node->getValueType(0);
5007 RTLIB::Libcall LC = Node->getOpcode() == ISD::FMODF ? RTLIB::getMODF(VT)
5008 : RTLIB::getFREXP(VT);
5009 bool Expanded = TLI.expandMultipleResultFPLibCall(DAG, LC, Node, Results,
5010 /*CallRetResNo=*/0);
5011 if (!Expanded) {
5012 DAG.getContext()->emitError(Twine("no libcall available for ") +
5013 Node->getOperationName(&DAG));
5014 for (unsigned I = 0, E = Node->getNumValues(); I != E; ++I)
5015 Results.push_back(DAG.getPOISON(Node->getValueType(I)));
5016 }
5017 break;
5018 }
5019 case ISD::FPOWI:
5020 case ISD::STRICT_FPOWI: {
5021 RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0));
5022 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi.");
5023 if (DAG.getLibcalls().getLibcallImpl(LC) == RTLIB::Unsupported) {
5024 // Some targets don't have a powi libcall; use pow instead.
5025 if (Node->isStrictFPOpcode()) {
5027 DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(Node),
5028 {Node->getValueType(0), Node->getValueType(1)},
5029 {Node->getOperand(0), Node->getOperand(2)});
5030 SDValue FPOW =
5031 DAG.getNode(ISD::STRICT_FPOW, SDLoc(Node),
5032 {Node->getValueType(0), Node->getValueType(1)},
5033 {Exponent.getValue(1), Node->getOperand(1), Exponent});
5034 Results.push_back(FPOW);
5035 Results.push_back(FPOW.getValue(1));
5036 } else {
5038 DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), Node->getValueType(0),
5039 Node->getOperand(1));
5040 Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node),
5041 Node->getValueType(0),
5042 Node->getOperand(0), Exponent));
5043 }
5044 break;
5045 }
5046 unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0;
5047 bool ExponentHasSizeOfInt =
5048 DAG.getLibInfo().getIntSize() ==
5049 Node->getOperand(1 + Offset).getValueType().getSizeInBits();
5050 if (!ExponentHasSizeOfInt) {
5051 // If the exponent does not match with sizeof(int) a libcall to
5052 // RTLIB::POWI would use the wrong type for the argument.
5053 DAG.getContext()->emitError("POWI exponent does not match sizeof(int)");
5054 Results.push_back(DAG.getPOISON(Node->getValueType(0)));
5055 break;
5056 }
5057 ExpandFPLibCall(Node, LC, Results);
5058 break;
5059 }
5060 case ISD::FPOW:
5061 case ISD::STRICT_FPOW:
5062 ExpandFPLibCall(Node, RTLIB::getPOW(Node->getSimpleValueType(0)), Results);
5063 break;
5064 case ISD::LROUND:
5065 case ISD::STRICT_LROUND:
5066 ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
5067 RTLIB::LROUND_F64, RTLIB::LROUND_F80,
5068 RTLIB::LROUND_F128,
5069 RTLIB::LROUND_PPCF128, Results);
5070 break;
5071 case ISD::LLROUND:
5073 ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
5074 RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
5075 RTLIB::LLROUND_F128,
5076 RTLIB::LLROUND_PPCF128, Results);
5077 break;
5078 case ISD::LRINT:
5079 case ISD::STRICT_LRINT:
5080 ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
5081 RTLIB::LRINT_F64, RTLIB::LRINT_F80,
5082 RTLIB::LRINT_F128,
5083 RTLIB::LRINT_PPCF128, Results);
5084 break;
5085 case ISD::LLRINT:
5086 case ISD::STRICT_LLRINT:
5087 ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
5088 RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
5089 RTLIB::LLRINT_F128,
5090 RTLIB::LLRINT_PPCF128, Results);
5091 break;
5092 case ISD::FDIV:
5093 case ISD::STRICT_FDIV: {
5094 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5095 {RTLIB::FAST_DIV_F32, RTLIB::DIV_F32},
5096 {RTLIB::FAST_DIV_F64, RTLIB::DIV_F64},
5097 {RTLIB::FAST_DIV_F80, RTLIB::DIV_F80},
5098 {RTLIB::FAST_DIV_F128, RTLIB::DIV_F128},
5099 {RTLIB::FAST_DIV_PPCF128, RTLIB::DIV_PPCF128}, Results);
5100 break;
5101 }
5102 case ISD::FREM:
5103 case ISD::STRICT_FREM:
5104 ExpandFPLibCall(Node, RTLIB::getREM(Node->getSimpleValueType(0)), Results);
5105 break;
5106 case ISD::FMA:
5107 case ISD::STRICT_FMA:
5108 ExpandFPLibCall(Node, RTLIB::getFMA(Node->getSimpleValueType(0)), Results);
5109 break;
5110 case ISD::FADD:
5111 case ISD::STRICT_FADD: {
5112 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5113 {RTLIB::FAST_ADD_F32, RTLIB::ADD_F32},
5114 {RTLIB::FAST_ADD_F64, RTLIB::ADD_F64},
5115 {RTLIB::FAST_ADD_F80, RTLIB::ADD_F80},
5116 {RTLIB::FAST_ADD_F128, RTLIB::ADD_F128},
5117 {RTLIB::FAST_ADD_PPCF128, RTLIB::ADD_PPCF128}, Results);
5118 break;
5119 }
5120 case ISD::FMUL:
5121 case ISD::STRICT_FMUL: {
5122 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5123 {RTLIB::FAST_MUL_F32, RTLIB::MUL_F32},
5124 {RTLIB::FAST_MUL_F64, RTLIB::MUL_F64},
5125 {RTLIB::FAST_MUL_F80, RTLIB::MUL_F80},
5126 {RTLIB::FAST_MUL_F128, RTLIB::MUL_F128},
5127 {RTLIB::FAST_MUL_PPCF128, RTLIB::MUL_PPCF128}, Results);
5128 break;
5129 }
5130 case ISD::FP16_TO_FP:
5131 if (Node->getValueType(0) == MVT::f32) {
5132 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false).first);
5133 }
5134 break;
5136 if (Node->getValueType(0) == MVT::f32) {
5137 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
5138 DAG, RTLIB::FPEXT_BF16_F32, MVT::f32, Node->getOperand(1),
5139 CallOptions, SDLoc(Node), Node->getOperand(0));
5140 Results.push_back(Tmp.first);
5141 Results.push_back(Tmp.second);
5142 }
5143 break;
5145 if (Node->getValueType(0) == MVT::f32) {
5146 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
5147 DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions,
5148 SDLoc(Node), Node->getOperand(0));
5149 Results.push_back(Tmp.first);
5150 Results.push_back(Tmp.second);
5151 }
5152 break;
5153 }
5154 case ISD::FP_TO_FP16: {
5155 RTLIB::Libcall LC =
5156 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
5157 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
5158 Results.push_back(ExpandLibCall(LC, Node, false).first);
5159 break;
5160 }
5161 case ISD::FP_TO_BF16: {
5162 RTLIB::Libcall LC =
5163 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::bf16);
5164 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_bf16");
5165 Results.push_back(ExpandLibCall(LC, Node, false).first);
5166 break;
5167 }
5170 case ISD::SINT_TO_FP:
5171 case ISD::UINT_TO_FP: {
5172 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP
5173 bool IsStrict = Node->isStrictFPOpcode();
5174 bool Signed = Node->getOpcode() == ISD::SINT_TO_FP ||
5175 Node->getOpcode() == ISD::STRICT_SINT_TO_FP;
5176 EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType();
5177 EVT RVT = Node->getValueType(0);
5178 EVT NVT = EVT();
5179 SDLoc dl(Node);
5180
5181 // Even if the input is legal, no libcall may exactly match, eg. we don't
5182 // have i1 -> fp conversions. So, it needs to be promoted to a larger type,
5183 // eg: i13 -> fp. Then, look for an appropriate libcall.
5184 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5185 for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE;
5186 t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
5187 ++t) {
5188 NVT = (MVT::SimpleValueType)t;
5189 // The source needs to big enough to hold the operand.
5190 if (NVT.bitsGE(SVT))
5191 LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT)
5192 : RTLIB::getUINTTOFP(NVT, RVT);
5193 }
5194 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5195
5196 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5197 // Sign/zero extend the argument if the libcall takes a larger type.
5199 NVT, Node->getOperand(IsStrict ? 1 : 0));
5200 CallOptions.setIsSigned(Signed);
5201 std::pair<SDValue, SDValue> Tmp =
5202 TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain);
5203 Results.push_back(Tmp.first);
5204 if (IsStrict)
5205 Results.push_back(Tmp.second);
5206 break;
5207 }
5208 case ISD::FP_TO_SINT:
5209 case ISD::FP_TO_UINT:
5212 // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT.
5213 bool IsStrict = Node->isStrictFPOpcode();
5214 bool Signed = Node->getOpcode() == ISD::FP_TO_SINT ||
5215 Node->getOpcode() == ISD::STRICT_FP_TO_SINT;
5216
5217 SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
5218 EVT SVT = Op.getValueType();
5219 EVT RVT = Node->getValueType(0);
5220 EVT NVT = EVT();
5221 SDLoc dl(Node);
5222
5223 // Even if the result is legal, no libcall may exactly match, eg. we don't
5224 // have fp -> i1 conversions. So, it needs to be promoted to a larger type,
5225 // eg: fp -> i32. Then, look for an appropriate libcall.
5226 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5227 for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
5228 IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
5229 ++IntVT) {
5230 NVT = (MVT::SimpleValueType)IntVT;
5231 // The type needs to big enough to hold the result.
5232 if (NVT.bitsGE(RVT))
5233 LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT)
5234 : RTLIB::getFPTOUINT(SVT, NVT);
5235 }
5236 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5237
5238 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5239 std::pair<SDValue, SDValue> Tmp =
5240 TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain);
5241
5242 // Truncate the result if the libcall returns a larger type.
5243 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first));
5244 if (IsStrict)
5245 Results.push_back(Tmp.second);
5246 break;
5247 }
5248
5249 case ISD::FP_ROUND:
5250 case ISD::STRICT_FP_ROUND: {
5251 // X = FP_ROUND(Y, TRUNC)
5252 // TRUNC is a flag, which is always an integer that is zero or one.
5253 // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND
5254 // is known to not change the value of Y.
5255 // We can only expand it into libcall if the TRUNC is 0.
5256 bool IsStrict = Node->isStrictFPOpcode();
5257 SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
5258 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
5259 EVT VT = Node->getValueType(0);
5260 assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1))->isZero() &&
5261 "Unable to expand as libcall if it is not normal rounding");
5262
5263 RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT);
5264 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5265
5266 std::pair<SDValue, SDValue> Tmp =
5267 TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain);
5268 Results.push_back(Tmp.first);
5269 if (IsStrict)
5270 Results.push_back(Tmp.second);
5271 break;
5272 }
5273 case ISD::FP_EXTEND: {
5274 Results.push_back(
5275 ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(),
5276 Node->getValueType(0)),
5277 Node, false).first);
5278 break;
5279 }
5283 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5284 if (Node->getOpcode() == ISD::STRICT_FP_TO_FP16)
5285 LC = RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16);
5286 else if (Node->getOpcode() == ISD::STRICT_FP_TO_BF16)
5287 LC = RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::bf16);
5288 else
5289 LC = RTLIB::getFPEXT(Node->getOperand(1).getValueType(),
5290 Node->getValueType(0));
5291
5292 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
5293
5294 std::pair<SDValue, SDValue> Tmp =
5295 TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1),
5296 CallOptions, SDLoc(Node), Node->getOperand(0));
5297 Results.push_back(Tmp.first);
5298 Results.push_back(Tmp.second);
5299 break;
5300 }
5301 case ISD::FSUB:
5302 case ISD::STRICT_FSUB: {
5303 ExpandFastFPLibCall(Node, canUseFastMathLibcall(Node),
5304 {RTLIB::FAST_SUB_F32, RTLIB::SUB_F32},
5305 {RTLIB::FAST_SUB_F64, RTLIB::SUB_F64},
5306 {RTLIB::FAST_SUB_F80, RTLIB::SUB_F80},
5307 {RTLIB::FAST_SUB_F128, RTLIB::SUB_F128},
5308 {RTLIB::FAST_SUB_PPCF128, RTLIB::SUB_PPCF128}, Results);
5309 break;
5310 }
5311 case ISD::SREM:
5312 Results.push_back(ExpandIntLibCall(Node, true,
5313 RTLIB::SREM_I8,
5314 RTLIB::SREM_I16, RTLIB::SREM_I32,
5315 RTLIB::SREM_I64, RTLIB::SREM_I128));
5316 break;
5317 case ISD::UREM:
5318 Results.push_back(ExpandIntLibCall(Node, false,
5319 RTLIB::UREM_I8,
5320 RTLIB::UREM_I16, RTLIB::UREM_I32,
5321 RTLIB::UREM_I64, RTLIB::UREM_I128));
5322 break;
5323 case ISD::SDIV:
5324 Results.push_back(ExpandIntLibCall(Node, true,
5325 RTLIB::SDIV_I8,
5326 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
5327 RTLIB::SDIV_I64, RTLIB::SDIV_I128));
5328 break;
5329 case ISD::UDIV:
5330 Results.push_back(ExpandIntLibCall(Node, false,
5331 RTLIB::UDIV_I8,
5332 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
5333 RTLIB::UDIV_I64, RTLIB::UDIV_I128));
5334 break;
5335 case ISD::SDIVREM:
5336 case ISD::UDIVREM:
5337 // Expand into divrem libcall
5338 ExpandDivRemLibCall(Node, Results);
5339 break;
5340 case ISD::MUL:
5341 Results.push_back(ExpandIntLibCall(Node, false,
5342 RTLIB::MUL_I8,
5343 RTLIB::MUL_I16, RTLIB::MUL_I32,
5344 RTLIB::MUL_I64, RTLIB::MUL_I128));
5345 break;
5347 Results.push_back(ExpandBitCountingLibCall(
5348 Node, RTLIB::CTLZ_I32, RTLIB::CTLZ_I64, RTLIB::CTLZ_I128));
5349 break;
5350 case ISD::CTPOP:
5351 Results.push_back(ExpandBitCountingLibCall(
5352 Node, RTLIB::CTPOP_I32, RTLIB::CTPOP_I64, RTLIB::CTPOP_I128));
5353 break;
5354 case ISD::RESET_FPENV: {
5355 // It is legalized to call 'fesetenv(FE_DFL_ENV)'. On most targets
5356 // FE_DFL_ENV is defined as '((const fenv_t *) -1)' in glibc.
5357 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5358 SDValue Ptr = DAG.getAllOnesConstant(dl, PtrTy);
5359 SDValue Chain = Node->getOperand(0);
5360 Results.push_back(
5361 DAG.makeStateFunctionCall(RTLIB::FESETENV, Ptr, Chain, dl));
5362 break;
5363 }
5364 case ISD::GET_FPENV_MEM: {
5365 SDValue Chain = Node->getOperand(0);
5366 SDValue EnvPtr = Node->getOperand(1);
5367 Results.push_back(
5368 DAG.makeStateFunctionCall(RTLIB::FEGETENV, EnvPtr, Chain, dl));
5369 break;
5370 }
5371 case ISD::SET_FPENV_MEM: {
5372 SDValue Chain = Node->getOperand(0);
5373 SDValue EnvPtr = Node->getOperand(1);
5374 Results.push_back(
5375 DAG.makeStateFunctionCall(RTLIB::FESETENV, EnvPtr, Chain, dl));
5376 break;
5377 }
5378 case ISD::GET_FPMODE: {
5379 // Call fegetmode, which saves control modes into a stack slot. Then load
5380 // the value to return from the stack.
5381 EVT ModeVT = Node->getValueType(0);
5383 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5384 SDValue Chain = DAG.makeStateFunctionCall(RTLIB::FEGETMODE, StackPtr,
5385 Node->getOperand(0), dl);
5386 SDValue LdInst = DAG.getLoad(
5387 ModeVT, dl, Chain, StackPtr,
5389 Results.push_back(LdInst);
5390 Results.push_back(LdInst.getValue(1));
5391 break;
5392 }
5393 case ISD::SET_FPMODE: {
5394 // Move control modes to stack slot and then call fesetmode with the pointer
5395 // to the slot as argument.
5396 SDValue Mode = Node->getOperand(1);
5397 EVT ModeVT = Mode.getValueType();
5399 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5400 SDValue StInst = DAG.getStore(
5401 Node->getOperand(0), dl, Mode, StackPtr,
5403 Results.push_back(
5404 DAG.makeStateFunctionCall(RTLIB::FESETMODE, StackPtr, StInst, dl));
5405 break;
5406 }
5407 case ISD::RESET_FPMODE: {
5408 // It is legalized to a call 'fesetmode(FE_DFL_MODE)'. On most targets
5409 // FE_DFL_MODE is defined as '((const femode_t *) -1)' in glibc. If not, the
5410 // target must provide custom lowering.
5411 const DataLayout &DL = DAG.getDataLayout();
5412 EVT PtrTy = TLI.getPointerTy(DL);
5413 SDValue Mode = DAG.getAllOnesConstant(dl, PtrTy);
5414 Results.push_back(DAG.makeStateFunctionCall(RTLIB::FESETMODE, Mode,
5415 Node->getOperand(0), dl));
5416 break;
5417 }
5418 }
5419
5420 // Replace the original node with the legalized result.
5421 if (!Results.empty()) {
5422 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
5423 ReplaceNode(Node, Results.data());
5424 } else
5425 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
5426}
5427
5428// Determine the vector type to use in place of an original scalar element when
5429// promoting equally sized vectors.
5431 MVT EltVT, MVT NewEltVT) {
5432 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
5433 MVT MidVT = OldEltsPerNewElt == 1
5434 ? NewEltVT
5435 : MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
5436 assert(TLI.isTypeLegal(MidVT) && "unexpected");
5437 return MidVT;
5438}
5439
5440void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
5441 LLVM_DEBUG(dbgs() << "Trying to promote node\n");
5443 MVT OVT = Node->getSimpleValueType(0);
5444 if (Node->getOpcode() == ISD::UINT_TO_FP ||
5445 Node->getOpcode() == ISD::SINT_TO_FP ||
5446 Node->getOpcode() == ISD::SETCC ||
5447 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
5448 Node->getOpcode() == ISD::INSERT_VECTOR_ELT ||
5449 Node->getOpcode() == ISD::VECREDUCE_FMAX ||
5450 Node->getOpcode() == ISD::VECREDUCE_FMIN ||
5451 Node->getOpcode() == ISD::VECREDUCE_FMAXIMUM ||
5452 Node->getOpcode() == ISD::VECREDUCE_FMINIMUM) {
5453 OVT = Node->getOperand(0).getSimpleValueType();
5454 }
5455 if (Node->getOpcode() == ISD::ATOMIC_STORE ||
5456 Node->getOpcode() == ISD::STRICT_UINT_TO_FP ||
5457 Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
5458 Node->getOpcode() == ISD::STRICT_FSETCC ||
5459 Node->getOpcode() == ISD::STRICT_FSETCCS ||
5460 Node->getOpcode() == ISD::STRICT_LRINT ||
5461 Node->getOpcode() == ISD::STRICT_LLRINT ||
5462 Node->getOpcode() == ISD::STRICT_LROUND ||
5463 Node->getOpcode() == ISD::STRICT_LLROUND ||
5464 Node->getOpcode() == ISD::VP_REDUCE_FADD ||
5465 Node->getOpcode() == ISD::VP_REDUCE_FMUL ||
5466 Node->getOpcode() == ISD::VP_REDUCE_FMAX ||
5467 Node->getOpcode() == ISD::VP_REDUCE_FMIN ||
5468 Node->getOpcode() == ISD::VP_REDUCE_FMAXIMUM ||
5469 Node->getOpcode() == ISD::VP_REDUCE_FMINIMUM ||
5470 Node->getOpcode() == ISD::VP_REDUCE_SEQ_FADD)
5471 OVT = Node->getOperand(1).getSimpleValueType();
5472 if (Node->getOpcode() == ISD::BR_CC ||
5473 Node->getOpcode() == ISD::SELECT_CC)
5474 OVT = Node->getOperand(2).getSimpleValueType();
5475 // Preserve fast math flags
5476 SDNodeFlags FastMathFlags = Node->getFlags() & SDNodeFlags::FastMathFlags;
5477 SelectionDAG::FlagInserter FlagsInserter(DAG, FastMathFlags);
5478 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
5479 SDLoc dl(Node);
5480 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
5481 switch (Node->getOpcode()) {
5482 case ISD::CTTZ:
5484 case ISD::CTLZ:
5485 case ISD::CTPOP: {
5486 // Zero extend the argument unless its cttz, then use any_extend.
5487 if (Node->getOpcode() == ISD::CTTZ ||
5488 Node->getOpcode() == ISD::CTTZ_ZERO_POISON)
5489 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5490 else
5491 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
5492
5493 unsigned NewOpc = Node->getOpcode();
5494 if (NewOpc == ISD::CTTZ) {
5495 // The count is the same in the promoted type except if the original
5496 // value was zero. This can be handled by setting the bit just off
5497 // the top of the original type.
5498 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
5499 OVT.getSizeInBits());
5500 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
5501 DAG.getConstant(TopBit, dl, NVT));
5502 NewOpc = ISD::CTTZ_ZERO_POISON;
5503 }
5504 // Perform the larger operation. For CTPOP and CTTZ_ZERO_POISON, this is
5505 // already the correct result.
5506 Tmp1 = DAG.getNode(NewOpc, dl, NVT, Tmp1);
5507 if (NewOpc == ISD::CTLZ) {
5508 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
5509 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
5510 DAG.getConstant(NVT.getSizeInBits() -
5511 OVT.getSizeInBits(), dl, NVT));
5512 }
5513 Results.push_back(
5514 DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1, SDNodeFlags::NoWrap));
5515 break;
5516 }
5517 case ISD::CTLZ_ZERO_POISON: {
5518 // We know that the argument is unlikely to be zero, hence we can take a
5519 // different approach as compared to ISD::CTLZ
5520
5521 // Any Extend the argument
5522 auto AnyExtendedNode =
5523 DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5524
5525 // Tmp1 = Tmp1 << (sizeinbits(NVT) - sizeinbits(Old VT))
5526 auto ShiftConstant = DAG.getShiftAmountConstant(
5527 NVT.getSizeInBits() - OVT.getSizeInBits(), NVT, dl);
5528 auto LeftShiftResult =
5529 DAG.getNode(ISD::SHL, dl, NVT, AnyExtendedNode, ShiftConstant);
5530
5531 // Perform the larger operation
5532 auto CTLZResult = DAG.getNode(Node->getOpcode(), dl, NVT, LeftShiftResult);
5533 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, CTLZResult));
5534 break;
5535 }
5536 case ISD::PEXT: {
5537 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5538 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(1));
5539 Tmp1 = DAG.getNode(ISD::PEXT, dl, NVT, Tmp1, Tmp2);
5540 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5541 break;
5542 }
5543 case ISD::PDEP: {
5544 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5545 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
5546 Tmp1 = DAG.getNode(ISD::PDEP, dl, NVT, Tmp1, Tmp2);
5547 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5548 break;
5549 }
5550 case ISD::BITREVERSE:
5551 case ISD::BSWAP: {
5552 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
5553 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
5554 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
5555 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
5556 DAG.getShiftAmountConstant(DiffBits, NVT, dl));
5557
5558 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5559 break;
5560 }
5561 case ISD::FP_TO_UINT:
5563 case ISD::FP_TO_SINT:
5565 PromoteLegalFP_TO_INT(Node, dl, Results);
5566 break;
5569 Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl));
5570 break;
5571 case ISD::UINT_TO_FP:
5573 case ISD::SINT_TO_FP:
5575 PromoteLegalINT_TO_FP(Node, dl, Results);
5576 break;
5577 case ISD::VAARG: {
5578 SDValue Chain = Node->getOperand(0); // Get the chain.
5579 SDValue Ptr = Node->getOperand(1); // Get the pointer.
5580
5581 unsigned TruncOp;
5582 if (OVT.isVector()) {
5583 TruncOp = ISD::BITCAST;
5584 } else {
5585 assert(OVT.isInteger()
5586 && "VAARG promotion is supported only for vectors or integer types");
5587 TruncOp = ISD::TRUNCATE;
5588 }
5589
5590 // Perform the larger operation, then convert back
5591 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
5592 Node->getConstantOperandVal(3));
5593 Chain = Tmp1.getValue(1);
5594
5595 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
5596
5597 // Modified the chain result - switch anything that used the old chain to
5598 // use the new one.
5599 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
5600 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
5601 if (UpdatedNodes) {
5602 UpdatedNodes->insert(Tmp2.getNode());
5603 UpdatedNodes->insert(Chain.getNode());
5604 }
5605 ReplacedNode(Node);
5606 break;
5607 }
5608 case ISD::MUL:
5609 case ISD::SDIV:
5610 case ISD::SREM:
5611 case ISD::UDIV:
5612 case ISD::UREM:
5613 case ISD::SMIN:
5614 case ISD::SMAX:
5615 case ISD::UMIN:
5616 case ISD::UMAX:
5617 case ISD::AND:
5618 case ISD::OR:
5619 case ISD::XOR: {
5620 unsigned ExtOp, TruncOp;
5621 if (OVT.isVector()) {
5622 ExtOp = ISD::BITCAST;
5623 TruncOp = ISD::BITCAST;
5624 } else {
5625 assert(OVT.isInteger() && "Cannot promote logic operation");
5626
5627 switch (Node->getOpcode()) {
5628 default:
5629 ExtOp = ISD::ANY_EXTEND;
5630 break;
5631 case ISD::SDIV:
5632 case ISD::SREM:
5633 case ISD::SMIN:
5634 case ISD::SMAX:
5635 ExtOp = ISD::SIGN_EXTEND;
5636 break;
5637 case ISD::UDIV:
5638 case ISD::UREM:
5639 ExtOp = ISD::ZERO_EXTEND;
5640 break;
5641 case ISD::UMIN:
5642 case ISD::UMAX:
5643 if (TLI.isSExtCheaperThanZExt(OVT, NVT))
5644 ExtOp = ISD::SIGN_EXTEND;
5645 else
5646 ExtOp = ISD::ZERO_EXTEND;
5647 break;
5648 }
5649 TruncOp = ISD::TRUNCATE;
5650 }
5651 // Promote each of the values to the new type.
5652 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5653 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5654 // Perform the larger operation, then convert back
5655 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5656 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
5657 break;
5658 }
5659 case ISD::UMUL_LOHI:
5660 case ISD::SMUL_LOHI: {
5661 // Promote to a multiply in a wider integer type.
5662 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
5664 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5665 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5666 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
5667
5668 unsigned OriginalSize = OVT.getScalarSizeInBits();
5669 Tmp2 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
5670 DAG.getShiftAmountConstant(OriginalSize, NVT, dl));
5671 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
5672 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
5673 break;
5674 }
5675 case ISD::SELECT: {
5676 unsigned ExtOp, TruncOp;
5677 if (Node->getValueType(0).isVector() ||
5678 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
5679 ExtOp = ISD::BITCAST;
5680 TruncOp = ISD::BITCAST;
5681 } else if (Node->getValueType(0).isInteger()) {
5682 ExtOp = ISD::ANY_EXTEND;
5683 TruncOp = ISD::TRUNCATE;
5684 } else {
5685 ExtOp = ISD::FP_EXTEND;
5686 TruncOp = ISD::FP_ROUND;
5687 }
5688 Tmp1 = Node->getOperand(0);
5689 // Promote each of the values to the new type.
5690 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5691 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5692 // Perform the larger operation, then round down.
5693 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
5694 if (TruncOp != ISD::FP_ROUND)
5695 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
5696 else
5697 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
5698 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5699 Results.push_back(Tmp1);
5700 break;
5701 }
5702 case ISD::VECTOR_SHUFFLE: {
5703 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
5704
5705 // Cast the two input vectors.
5706 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
5707 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
5708
5709 // Convert the shuffle mask to the right # elements.
5710 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
5711 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
5712 Results.push_back(Tmp1);
5713 break;
5714 }
5717 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
5718 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
5719 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
5720 Node->getOperand(2));
5721 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3));
5722 break;
5723 }
5724 case ISD::SELECT_CC: {
5725 SDValue Cond = Node->getOperand(4);
5726 ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get();
5727 // Type of the comparison operands.
5728 MVT CVT = Node->getSimpleValueType(0);
5729 assert(CVT == OVT && "not handled");
5730
5731 unsigned ExtOp = ISD::FP_EXTEND;
5732 if (NVT.isInteger()) {
5734 }
5735
5736 // Promote the comparison operands, if needed.
5737 if (TLI.isCondCodeLegal(CCCode, CVT)) {
5738 Tmp1 = Node->getOperand(0);
5739 Tmp2 = Node->getOperand(1);
5740 } else {
5741 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5742 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5743 }
5744 // Cast the true/false operands.
5745 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5746 Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
5747
5748 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond},
5749 Node->getFlags());
5750
5751 // Cast the result back to the original type.
5752 if (ExtOp != ISD::FP_EXTEND)
5753 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1);
5754 else
5755 Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1,
5756 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5757
5758 Results.push_back(Tmp1);
5759 break;
5760 }
5761 case ISD::SETCC:
5762 case ISD::STRICT_FSETCC:
5763 case ISD::STRICT_FSETCCS: {
5764 unsigned ExtOp = ISD::FP_EXTEND;
5765 if (NVT.isInteger()) {
5766 ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get();
5767 if (isSignedIntSetCC(CCCode) ||
5768 TLI.isSExtCheaperThanZExt(Node->getOperand(0).getValueType(), NVT))
5769 ExtOp = ISD::SIGN_EXTEND;
5770 else
5771 ExtOp = ISD::ZERO_EXTEND;
5772 }
5773 if (Node->isStrictFPOpcode()) {
5774 SDValue InChain = Node->getOperand(0);
5775 std::tie(Tmp1, std::ignore) =
5776 DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT);
5777 std::tie(Tmp2, std::ignore) =
5778 DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT);
5779 SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)};
5780 SDValue OutChain = DAG.getTokenFactor(dl, TmpChains);
5781 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
5782 Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs,
5783 {OutChain, Tmp1, Tmp2, Node->getOperand(3)},
5784 Node->getFlags()));
5785 Results.push_back(Results.back().getValue(1));
5786 break;
5787 }
5788 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
5789 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
5790 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
5791 Tmp2, Node->getOperand(2), Node->getFlags()));
5792 break;
5793 }
5794 case ISD::BR_CC: {
5795 unsigned ExtOp = ISD::FP_EXTEND;
5796 if (NVT.isInteger()) {
5797 ISD::CondCode CCCode =
5798 cast<CondCodeSDNode>(Node->getOperand(1))->get();
5800 }
5801 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
5802 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
5803 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
5804 Node->getOperand(0), Node->getOperand(1),
5805 Tmp1, Tmp2, Node->getOperand(4)));
5806 break;
5807 }
5808 case ISD::FADD:
5809 case ISD::FSUB:
5810 case ISD::FMUL:
5811 case ISD::FDIV:
5812 case ISD::FREM:
5813 case ISD::FMINNUM:
5814 case ISD::FMAXNUM:
5815 case ISD::FMINIMUM:
5816 case ISD::FMAXIMUM:
5817 case ISD::FMINIMUMNUM:
5818 case ISD::FMAXIMUMNUM:
5819 case ISD::FPOW:
5820 case ISD::FATAN2:
5821 // Promote scalar operations to vector using SCALAR_TO_VECTOR
5822 if (!OVT.isVector() && NVT.isVector() &&
5823 NVT.getVectorElementType() == OVT) {
5824 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
5825 Tmp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(1));
5826 Tmp3 =
5827 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Node->getFlags());
5828 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Tmp3,
5829 DAG.getConstant(0, dl, MVT::i32)));
5830 break;
5831 }
5832 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5833 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
5834 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5835 Results.push_back(
5836 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp3,
5837 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5838 break;
5839
5841 case ISD::STRICT_FMAXIMUM: {
5842 SDValue InChain = Node->getOperand(0);
5843 SDVTList VTs = DAG.getVTList(NVT, MVT::Other);
5844 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, VTs, InChain,
5845 Node->getOperand(1));
5846 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, VTs, InChain,
5847 Node->getOperand(2));
5848 SmallVector<SDValue, 4> Ops = {InChain, Tmp1, Tmp2};
5849 Tmp3 = DAG.getNode(Node->getOpcode(), dl, VTs, Ops, Node->getFlags());
5850 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, DAG.getVTList(OVT, MVT::Other),
5851 InChain, Tmp3,
5852 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
5853 Results.push_back(Tmp4);
5854 Results.push_back(Tmp4.getValue(1));
5855 break;
5856 }
5857
5858 case ISD::STRICT_FADD:
5859 case ISD::STRICT_FSUB:
5860 case ISD::STRICT_FMUL:
5861 case ISD::STRICT_FDIV:
5864 case ISD::STRICT_FREM:
5865 case ISD::STRICT_FPOW:
5866 case ISD::STRICT_FATAN2:
5867 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5868 {Node->getOperand(0), Node->getOperand(1)});
5869 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5870 {Node->getOperand(0), Node->getOperand(2)});
5871 Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
5872 Tmp2.getValue(1));
5873 Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5874 {Tmp3, Tmp1, Tmp2});
5875 Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5876 {Tmp1.getValue(1), Tmp1,
5877 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5878 Results.push_back(Tmp1);
5879 Results.push_back(Tmp1.getValue(1));
5880 break;
5881 case ISD::FMA:
5882 // Promote scalar operations to vector using SCALAR_TO_VECTOR
5883 if (!OVT.isVector() && NVT.isVector() &&
5884 NVT.getVectorElementType() == OVT) {
5885 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
5886 Tmp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(1));
5887 Tmp3 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(2));
5888 SDValue Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3,
5889 Node->getFlags());
5890 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Result,
5891 DAG.getConstant(0, dl, MVT::i32)));
5892 break;
5893 }
5894 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5895 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
5896 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
5897 Results.push_back(
5898 DAG.getNode(ISD::FP_ROUND, dl, OVT,
5899 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
5900 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5901 break;
5902 case ISD::STRICT_FMA:
5903 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5904 {Node->getOperand(0), Node->getOperand(1)});
5905 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5906 {Node->getOperand(0), Node->getOperand(2)});
5907 Tmp3 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5908 {Node->getOperand(0), Node->getOperand(3)});
5909 Tmp4 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
5910 Tmp2.getValue(1), Tmp3.getValue(1));
5911 Tmp4 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5912 {Tmp4, Tmp1, Tmp2, Tmp3});
5913 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5914 {Tmp4.getValue(1), Tmp4,
5915 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5916 Results.push_back(Tmp4);
5917 Results.push_back(Tmp4.getValue(1));
5918 break;
5919 case ISD::FCOPYSIGN:
5920 case ISD::FLDEXP:
5921 case ISD::FPOWI: {
5922 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5923 Tmp2 = Node->getOperand(1);
5924 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
5925
5926 // fcopysign doesn't change anything but the sign bit, so
5927 // (fp_round (fcopysign (fpext a), b))
5928 // is as precise as
5929 // (fp_round (fpext a))
5930 // which is a no-op. Mark it as a TRUNCating FP_ROUND.
5931 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
5932 Results.push_back(
5933 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp3,
5934 DAG.getIntPtrConstant(isTrunc, dl, /*isTarget=*/true)));
5935 break;
5936 }
5937 case ISD::STRICT_FLDEXP: {
5938 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5939 {Node->getOperand(0), Node->getOperand(1)});
5940 Tmp2 = Node->getOperand(2);
5941 Tmp3 = DAG.getNode(ISD::STRICT_FLDEXP, dl, {NVT, MVT::Other},
5942 {Tmp1.getValue(1), Tmp1, Tmp2});
5943 Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5944 {Tmp3.getValue(1), Tmp3,
5945 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5946 Results.push_back(Tmp4);
5947 Results.push_back(Tmp4.getValue(1));
5948 break;
5949 }
5950 case ISD::STRICT_FPOWI:
5951 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
5952 {Node->getOperand(0), Node->getOperand(1)});
5953 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
5954 {Tmp1.getValue(1), Tmp1, Node->getOperand(2)});
5955 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
5956 {Tmp2.getValue(1), Tmp2,
5957 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
5958 Results.push_back(Tmp3);
5959 Results.push_back(Tmp3.getValue(1));
5960 break;
5961 case ISD::FFREXP: {
5962 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5963 Tmp2 = DAG.getNode(ISD::FFREXP, dl, {NVT, Node->getValueType(1)}, Tmp1);
5964
5965 Results.push_back(
5966 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
5967 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
5968
5969 Results.push_back(Tmp2.getValue(1));
5970 break;
5971 }
5972 case ISD::FMODF:
5973 case ISD::FSINCOS:
5974 case ISD::FSINCOSPI: {
5975 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
5976 Tmp2 = DAG.getNode(Node->getOpcode(), dl, DAG.getVTList(NVT, NVT), Tmp1);
5977 Tmp3 = DAG.getIntPtrConstant(0, dl, /*isTarget=*/true);
5978 for (unsigned ResNum = 0; ResNum < Node->getNumValues(); ResNum++)
5979 Results.push_back(
5980 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2.getValue(ResNum), Tmp3));
5981 break;
5982 }
5983 case ISD::FFLOOR:
5984 case ISD::FCEIL:
5985 case ISD::FRINT:
5986 case ISD::FNEARBYINT:
5987 case ISD::FROUND:
5988 case ISD::FROUNDEVEN:
5989 case ISD::FTRUNC:
5990 case ISD::FNEG:
5991 case ISD::FSQRT:
5992 case ISD::FSIN:
5993 case ISD::FCOS:
5994 case ISD::FTAN:
5995 case ISD::FASIN:
5996 case ISD::FACOS:
5997 case ISD::FATAN:
5998 case ISD::FSINH:
5999 case ISD::FCOSH:
6000 case ISD::FTANH:
6001 case ISD::FLOG:
6002 case ISD::FLOG2:
6003 case ISD::FLOG10:
6004 case ISD::FABS:
6005 case ISD::FEXP:
6006 case ISD::FEXP2:
6007 case ISD::FEXP10:
6008 case ISD::FCANONICALIZE:
6009 // Promote scalar operations to vector using SCALAR_TO_VECTOR
6010 if (!OVT.isVector() && NVT.isVector() &&
6011 NVT.getVectorElementType() == OVT) {
6012 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Node->getOperand(0));
6013 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Node->getFlags());
6014 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, OVT, Tmp2,
6015 DAG.getConstant(0, dl, MVT::i32)));
6016 break;
6017 }
6018 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
6019 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6020 Results.push_back(
6021 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
6022 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
6023 break;
6024 case ISD::STRICT_FFLOOR:
6025 case ISD::STRICT_FCEIL:
6026 case ISD::STRICT_FRINT:
6028 case ISD::STRICT_FROUND:
6030 case ISD::STRICT_FTRUNC:
6031 case ISD::STRICT_FSQRT:
6032 case ISD::STRICT_FSIN:
6033 case ISD::STRICT_FCOS:
6034 case ISD::STRICT_FTAN:
6035 case ISD::STRICT_FASIN:
6036 case ISD::STRICT_FACOS:
6037 case ISD::STRICT_FATAN:
6038 case ISD::STRICT_FSINH:
6039 case ISD::STRICT_FCOSH:
6040 case ISD::STRICT_FTANH:
6041 case ISD::STRICT_FLOG:
6042 case ISD::STRICT_FLOG2:
6043 case ISD::STRICT_FLOG10:
6044 case ISD::STRICT_FEXP:
6045 case ISD::STRICT_FEXP2:
6046 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
6047 {Node->getOperand(0), Node->getOperand(1)});
6048 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
6049 {Tmp1.getValue(1), Tmp1});
6050 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
6051 {Tmp2.getValue(1), Tmp2,
6052 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)});
6053 Results.push_back(Tmp3);
6054 Results.push_back(Tmp3.getValue(1));
6055 break;
6056 case ISD::LLROUND:
6057 case ISD::LROUND:
6058 case ISD::LRINT:
6059 case ISD::LLRINT:
6060 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
6061 Tmp2 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
6062 Results.push_back(Tmp2);
6063 break;
6065 case ISD::STRICT_LROUND:
6066 case ISD::STRICT_LRINT:
6067 case ISD::STRICT_LLRINT:
6068 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
6069 {Node->getOperand(0), Node->getOperand(1)});
6070 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
6071 {Tmp1.getValue(1), Tmp1});
6072 Results.push_back(Tmp2);
6073 Results.push_back(Tmp2.getValue(1));
6074 break;
6075 case ISD::BUILD_VECTOR: {
6076 MVT EltVT = OVT.getVectorElementType();
6077 MVT NewEltVT = NVT.getVectorElementType();
6078
6079 // Handle bitcasts to a different vector type with the same total bit size
6080 //
6081 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
6082 // =>
6083 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
6084
6085 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6086 "Invalid promote type for build_vector");
6087 assert(NewEltVT.bitsLE(EltVT) && "not handled");
6088
6089 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6090
6092 for (const SDValue &Op : Node->op_values())
6093 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
6094
6095 SDLoc SL(Node);
6096 SDValue Concat =
6097 DAG.getNode(MidVT == NewEltVT ? ISD::BUILD_VECTOR : ISD::CONCAT_VECTORS,
6098 SL, NVT, NewOps);
6099 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
6100 Results.push_back(CvtVec);
6101 break;
6102 }
6104 MVT EltVT = OVT.getVectorElementType();
6105 MVT NewEltVT = NVT.getVectorElementType();
6106
6107 // Handle bitcasts to a different vector type with the same total bit size.
6108 //
6109 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
6110 // =>
6111 // v4i32:castx = bitcast x:v2i64
6112 //
6113 // i64 = bitcast
6114 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
6115 // (i32 (extract_vector_elt castx, (2 * y + 1)))
6116 //
6117
6118 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6119 "Invalid promote type for extract_vector_elt");
6120 assert(NewEltVT.bitsLT(EltVT) && "not handled");
6121
6122 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6123 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
6124
6125 SDValue Idx = Node->getOperand(1);
6126 EVT IdxVT = Idx.getValueType();
6127 SDLoc SL(Node);
6128 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
6129 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
6130
6131 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
6132
6134 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
6135 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
6136 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
6137
6138 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
6139 CastVec, TmpIdx);
6140 NewOps.push_back(Elt);
6141 }
6142
6143 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
6144 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
6145 break;
6146 }
6148 MVT EltVT = OVT.getVectorElementType();
6149 MVT NewEltVT = NVT.getVectorElementType();
6150
6151 // Handle bitcasts to a different vector type with the same total bit size
6152 //
6153 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
6154 // =>
6155 // v4i32:castx = bitcast x:v2i64
6156 // v2i32:casty = bitcast y:i64
6157 //
6158 // v2i64 = bitcast
6159 // (v4i32 insert_vector_elt
6160 // (v4i32 insert_vector_elt v4i32:castx,
6161 // (extract_vector_elt casty, 0), 2 * z),
6162 // (extract_vector_elt casty, 1), (2 * z + 1))
6163
6164 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
6165 "Invalid promote type for insert_vector_elt");
6166 assert(NewEltVT.bitsLT(EltVT) && "not handled");
6167
6168 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6169 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
6170
6171 SDValue Val = Node->getOperand(1);
6172 SDValue Idx = Node->getOperand(2);
6173 EVT IdxVT = Idx.getValueType();
6174 SDLoc SL(Node);
6175
6176 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
6177 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
6178
6179 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
6180 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
6181
6182 SDValue NewVec = CastVec;
6183 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
6184 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
6185 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
6186
6187 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
6188 CastVal, IdxOffset);
6189
6190 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
6191 NewVec, Elt, InEltIdx);
6192 }
6193
6194 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
6195 break;
6196 }
6197 case ISD::SCALAR_TO_VECTOR: {
6198 MVT EltVT = OVT.getVectorElementType();
6199 MVT NewEltVT = NVT.getVectorElementType();
6200
6201 // Handle bitcasts to different vector type with the same total bit size.
6202 //
6203 // e.g. v2i64 = scalar_to_vector x:i64
6204 // =>
6205 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
6206 //
6207
6208 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
6209 SDValue Val = Node->getOperand(0);
6210 SDLoc SL(Node);
6211
6212 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
6213 SDValue Undef = DAG.getUNDEF(MidVT);
6214
6216 NewElts.push_back(CastVal);
6217 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
6218 NewElts.push_back(Undef);
6219
6220 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
6221 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
6222 Results.push_back(CvtVec);
6223 break;
6224 }
6225 case ISD::ATOMIC_SWAP:
6226 case ISD::ATOMIC_STORE: {
6227 AtomicSDNode *AM = cast<AtomicSDNode>(Node);
6228 SDLoc SL(Node);
6229 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
6230 assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
6231 "unexpected promotion type");
6232 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
6233 "unexpected atomic_swap with illegal type");
6234
6235 SDValue Op0 = AM->getBasePtr();
6236 SDValue Op1 = CastVal;
6237
6238 // ATOMIC_STORE uses a swapped operand order from every other AtomicSDNode,
6239 // but really it should merge with ISD::STORE.
6240 if (AM->getOpcode() == ISD::ATOMIC_STORE)
6241 std::swap(Op0, Op1);
6242
6243 SDValue NewAtomic = DAG.getAtomic(AM->getOpcode(), SL, NVT, AM->getChain(),
6244 Op0, Op1, AM->getMemOperand());
6245
6246 if (AM->getOpcode() != ISD::ATOMIC_STORE) {
6247 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
6248 Results.push_back(NewAtomic.getValue(1));
6249 } else
6250 Results.push_back(NewAtomic);
6251 break;
6252 }
6253 case ISD::ATOMIC_LOAD: {
6254 AtomicSDNode *AM = cast<AtomicSDNode>(Node);
6255 SDLoc SL(Node);
6256 assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
6257 "unexpected promotion type");
6258 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
6259 "unexpected atomic_load with illegal type");
6260
6261 SDValue NewAtomic =
6262 DAG.getAtomic(ISD::ATOMIC_LOAD, SL, NVT, DAG.getVTList(NVT, MVT::Other),
6263 {AM->getChain(), AM->getBasePtr()}, AM->getMemOperand());
6264 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
6265 Results.push_back(NewAtomic.getValue(1));
6266 break;
6267 }
6268 case ISD::SPLAT_VECTOR: {
6269 SDValue Scalar = Node->getOperand(0);
6270 MVT ScalarType = Scalar.getSimpleValueType();
6271 MVT NewScalarType = NVT.getVectorElementType();
6272 if (ScalarType.isInteger()) {
6273 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NewScalarType, Scalar);
6274 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6275 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
6276 break;
6277 }
6278 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewScalarType, Scalar);
6279 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
6280 Results.push_back(
6281 DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp2,
6282 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)));
6283 break;
6284 }
6289 case ISD::VP_REDUCE_FMAX:
6290 case ISD::VP_REDUCE_FMIN:
6291 case ISD::VP_REDUCE_FMAXIMUM:
6292 case ISD::VP_REDUCE_FMINIMUM:
6293 Results.push_back(PromoteReduction(Node));
6294 break;
6295 }
6296
6297 // Replace the original node with the legalized result.
6298 if (!Results.empty()) {
6299 LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
6300 ReplaceNode(Node, Results.data());
6301 } else
6302 LLVM_DEBUG(dbgs() << "Could not promote node\n");
6303}
6304
6305/// This is the entry point for the file.
6308
6309 SmallPtrSet<SDNode *, 16> LegalizedNodes;
6310 // Use a delete listener to remove nodes which were deleted during
6311 // legalization from LegalizeNodes. This is needed to handle the situation
6312 // where a new node is allocated by the object pool to the same address of a
6313 // previously deleted node.
6314 DAGNodeDeletedListener DeleteListener(
6315 *this,
6316 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
6317
6318 SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
6319
6320 // Visit all the nodes. We start in topological order, so that we see
6321 // nodes with their original operands intact. Legalization can produce
6322 // new nodes which may themselves need to be legalized. Iterate until all
6323 // nodes have been legalized.
6324 while (true) {
6325 bool AnyLegalized = false;
6326 for (auto NI = allnodes_end(); NI != allnodes_begin();) {
6327 --NI;
6328
6329 SDNode *N = &*NI;
6330 if (N->use_empty() && N != getRoot().getNode()) {
6331 ++NI;
6332 DeleteNode(N);
6333 continue;
6334 }
6335
6336 if (LegalizedNodes.insert(N).second) {
6337 AnyLegalized = true;
6338 Legalizer.LegalizeOp(N);
6339
6340 if (N->use_empty() && N != getRoot().getNode()) {
6341 ++NI;
6342 DeleteNode(N);
6343 }
6344 }
6345 }
6346 if (!AnyLegalized)
6347 break;
6348
6349 }
6350
6351 // Remove dead nodes now.
6353}
6354
6356 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
6357 SmallPtrSet<SDNode *, 16> LegalizedNodes;
6358 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
6359
6360 // Directly insert the node in question, and legalize it. This will recurse
6361 // as needed through operands.
6362 LegalizedNodes.insert(N);
6363 Legalizer.LegalizeOp(N);
6364
6365 return LegalizedNodes.count(N);
6366}
#define Success
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned uint64_t
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Legalizer
static bool isSigned(unsigned Opcode)
Utilities for dealing with flags related to floating point properties and mode controls.
static MaybeAlign getAlign(Value *Ptr)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, const TargetLowering &TLI, SDValue &Res)
static bool isSinCosLibcallAvailable(SDNode *Node, const LibcallLoweringInfo &Libcalls)
Return true if sincos or __sincos_stret libcall is available.
static bool useSinCos(SDNode *Node)
Only issue sincos libcall if both sin and cos are needed.
static bool canUseFastMathLibcall(const SDNode *Node)
Return if we can use the FAST_* variant of a math libcall for the node.
static MachineMemOperand * getStackAlignedMMO(SDValue StackPtr, MachineFunction &MF, bool isObjectScalable)
static MVT getPromotedVectorElementType(const TargetLowering &TLI, MVT EltVT, MVT NewEltVT)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
std::pair< MCSymbol *, MachineModuleInfoImpl::StubValueTy > PairTy
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
PowerPC Reduce CR logical Operation
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
static constexpr int Concat[]
Value * RHS
Value * LHS
BinaryOperator * Mul
bool isSignaling() const
Definition APFloat.h:1577
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1254
APInt bitcastToAPInt() const
Definition APFloat.h:1467
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:226
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:255
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const SDValue & getBasePtr() const
const SDValue & getVal() const
LLVM_ABI Type * getStructRetType() const
static LLVM_ABI bool isValueValidForType(EVT VT, const APFloat &Val)
const APFloat & getValueAPF() const
const ConstantFP * getConstantFPValue() const
const APFloat & getValueAPF() const
Definition Constants.h:463
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const ConstantInt * getConstantIntValue() const
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
bool isBigEndian() const
Definition DataLayout.h:218
unsigned getAllocaAddrSpace() const
Definition DataLayout.h:252
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
bool empty() const
Definition Function.h:843
const BasicBlock & back() const
Definition Function.h:846
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Machine Value Type.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool bitsLE(MVT VT) const
Return true if this has no more bits than VT.
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
LLVM_ABI unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOStore
The memory access writes data.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
bool isStrictFPOpcode()
Test if this node is a strict floating point pseudo-op.
ArrayRef< SDUse > ops() const
LLVM_ABI void dump() const
Dump this node, for debugging.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
const SDValue & getOperand(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI bool shouldOptForSize() const
bool hasSwiftErrorArg() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
allnodes_const_iterator allnodes_end() const
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI void Legalize()
This transforms the SelectionDAG into a SelectionDAG that is compatible with the target instruction s...
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool LegalizeOp(SDNode *N, SmallSetVector< SDNode *, 16 > &UpdatedNodes)
Transforms a SelectionDAG node and any operands to it into a node that is compatible with the target ...
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
const TargetLibraryInfo & getLibInfo() const
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void swap(SmallVectorImpl &RHS)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
unsigned getIntSize() const
Get size of a C-level int or unsigned int, in bits.
bool isOperationExpand(unsigned Op, EVT VT) const
Return true if the specified operation is illegal on this target or unlikely to be made legal with cu...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
bool isOperationLegalOrPromote(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal using promotion.
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
LegalizeAction getCondCodeAction(ISD::CondCode CC, MVT VT) const
Return how the condition code should be treated: either it is legal, needs to be expanded to some oth...
virtual bool isFPImmLegal(const APFloat &, EVT, bool ForCodeSize=false) const
Returns true if the target can instruction select the specified FP immediate natively.
LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return how this store with truncation should be treated: either it is legal, needs to be promoted to ...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
virtual ISD::NodeType getExtendForAtomicOps() const
Returns how the platform's atomic operations are extended (ZERO_EXTEND, SIGN_EXTEND,...
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal for a comparison of the specified types on this ...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
MVT getProgramPointerTy(const DataLayout &DL) const
Return the type for code pointers, which is determined by the program address space specified through...
virtual bool isJumpTableRelative() const
virtual bool ShouldShrinkFPConstant(EVT) const
If true, then instruction selection should seek to shrink the FP constant of the specified type to a ...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
Return true if the target supports a memory access of this type for the given address space and align...
virtual LegalizeAction getCustomOperationAction(SDNode &Op) const
How to legalize this custom operation?
LegalizeAction getLoadAction(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return how this load with extension should be treated: either it is legal, needs to be promoted to a ...
LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const
virtual bool useSoftFloat() const
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
bool allowsMemoryAccessForAlignment(LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const
This function returns true if the memory access is aligned or if the target allows this specific unal...
bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace) const
Return true if the specified store with truncation has solution on this target.
bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const
Return true if the specified condition code is legal or custom for a comparison of the specified type...
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
bool isLoadLegalOrCustom(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal or custom on this target.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
MVT getTypeToPromoteTo(unsigned Op, MVT VT) const
If the action for this operation is to promote, this method returns the ValueType to promote to.
const RTLIB::RuntimeLibcallsInfo & getRuntimeLibcallsInfo() const
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT.
bool expandMultipleResultFPLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, SDNode *Node, SmallVectorImpl< SDValue > &Results, std::optional< unsigned > CallRetResNo={}) const
Expands a node with multiple results to an FP or vector libcall.
bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]MULO.
bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL into two nodes.
bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, bool &NeedInvert, const SDLoc &dl, SDValue &Chain, bool IsSignaling=false) const
Legalize a SETCC with given LHS and RHS and condition code CC on the current target.
SDValue expandFCANONICALIZE(SDNode *Node, SelectionDAG &DAG) const
Expand FCANONICALIZE to FMUL with 1.
SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const
Expand CTLZ/CTLZ_ZERO_POISON nodes.
SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const
Expand BITREVERSE nodes.
SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const
Expand CTTZ/CTTZ_ZERO_POISON nodes.
virtual SDValue expandIndirectJTBranch(const SDLoc &dl, SDValue Value, SDValue Addr, int JTI, SelectionDAG &DAG) const
Expands target specific indirect branch for the case of JumpTable expansion.
SDValue expandABD(SDNode *N, SelectionDAG &DAG) const
Expand ABDS/ABDU nodes.
SDValue expandCLMUL(SDNode *N, SelectionDAG &DAG) const
Expand carryless multiply.
SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]SHLSAT.
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const
Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const
Expands an unaligned store to 2 half-size stores for integer values, and possibly more for vectors.
void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::S(ADD|SUB)O.
SDValue expandABS(SDNode *N, SelectionDAG &DAG, bool IsNegative=false) const
Expand ABS nodes.
SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const
Expand a VECREDUCE_* into an explicit calculation.
SDValue expandVPCTTZElements(SDNode *N, SelectionDAG &DAG) const
Expand VP_CTTZ_ELTS/VP_CTTZ_ELTS_ZERO_POISON nodes.
bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand float to UINT conversion.
bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const
Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
std::pair< SDValue, SDValue > expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const
Expands an unaligned load to 2 half-size loads for an integer, and possibly more for vectors.
SDValue expandFMINIMUMNUM_FMAXIMUMNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimumnum/fmaximumnum into multiple comparison with selects.
SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::VECTOR_SPLICE.
SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, EVT SubVecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to a sub-vector of type SubVecVT at index Idx located in memory for a vector of type Ve...
SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const
Expand CTPOP nodes.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const
Expand BSWAP nodes.
SDValue expandFMINIMUM_FMAXIMUM(SDNode *N, SelectionDAG &DAG) const
Expand fminimum/fmaximum into multiple comparison with selects.
bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const
Expand float(f32) to SINT(i64) conversion.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
SDValue expandCONVERT_TO_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_TO_ARBITRARY_FP using bit manipulation.
SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const
Expand funnel shift.
virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const
This callback is invoked for operations that are unsupported by the target, which are registered to u...
SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl, SDValue LHS, SDValue RHS, unsigned Scale, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]DIVFIX[SAT].
SDValue expandPEXT(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit extract (compress).
SDValue expandFP_ROUND(SDNode *Node, SelectionDAG &DAG) const
Expand round(fp) to fp conversion.
SDValue expandCONVERT_FROM_ARBITRARY_FP(SDNode *Node, SelectionDAG &DAG) const
Expand CONVERT_FROM_ARBITRARY_FP using bit manipulation.
SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const
Expand rotations.
SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT, SDValue Index, const SDNodeFlags PtrArithFlags=SDNodeFlags()) const
Get a pointer to vector element Idx located in memory for a vector of type VecVT starting at a base a...
SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const
Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
SDValue expandCMP(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[US]CMP.
SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT].
void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const
Method for building the DAG expansion of ISD::U(ADD|SUB)O.
SDValue expandPDEP(SDNode *N, SelectionDAG &DAG) const
Expand parallel bit deposit (expand).
bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain, SelectionDAG &DAG) const
Expand UINT(i64) to double(f64) conversion.
bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS, SDValue RHS, SmallVectorImpl< SDValue > &Result, EVT HiLoVT, SelectionDAG &DAG, MulExpansionKind Kind, SDValue LL=SDValue(), SDValue LH=SDValue(), SDValue RL=SDValue(), SDValue RH=SDValue()) const
Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes, respectively,...
SDValue expandAVG(SDNode *N, SelectionDAG &DAG) const
Expand vector/scalar AVGCEILS/AVGCEILU/AVGFLOORS/AVGFLOORU nodes.
SDValue expandCTLS(SDNode *N, SelectionDAG &DAG) const
Expand CTLS (count leading sign bits) nodes.
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
virtual const TargetFrameLowering * getFrameLowering() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Definition Value.h:75
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:513
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ SET_FPENV
Sets the current floating-point environment.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:168
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:127
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:394
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ FRAME_TO_ARGS_OFFSET
FRAME_TO_ARGS_OFFSET - This node represents offset from frame pointer to first (possible) on-stack ar...
Definition ISDOpcodes.h:145
@ RESET_FPENV
Set floating-point environment to default state.
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:524
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:400
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:172
@ GlobalAddress
Definition ISDOpcodes.h:88
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:473
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:407
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:438
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:798
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:156
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:487
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ ADDROFRETURNADDR
ADDROFRETURNADDR - Represents the llvm.addressofreturnaddress intrinsic.
Definition ISDOpcodes.h:117
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:837
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:637
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:802
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:980
@ STRICT_FP_TO_FP16
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ STRICT_FP16_TO_FP
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:472
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:139
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ TargetConstantFP
Definition ISDOpcodes.h:180
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:655
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:413
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ GLOBAL_OFFSET_TABLE
The address of the GOT.
Definition ISDOpcodes.h:103
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:486
@ STRICT_BF16_TO_FP
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:466
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:150
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:480
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:785
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ STRICT_FP_TO_BF16
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:712
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:659
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:427
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:797
@ ExternalSymbol
Definition ISDOpcodes.h:93
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:122
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ EXPERIMENTAL_VECTOR_HISTOGRAM
Experimental vector histogram intrinsic Operands: Input Chain, Inc, Mask, Base, Index,...
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:458
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:955
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:162
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ VECREDUCE_SEQ_FMUL
@ CONVERT_TO_ARBITRARY_FP
CONVERT_TO_ARBITRARY_FP - Converts a native FP value to an arbitrary floating-point format,...
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:626
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getSYNC(unsigned Opc, MVT VT)
Return the SYNC_FETCH_AND_* value for the given opcode and type, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPLibCall(EVT VT, Libcall Call_F32, Libcall Call_F64, Libcall Call_F80, Libcall Call_F128, Libcall Call_PPCF128)
GetFPLibCall - Helper to return the right libcall for the given floating point type,...
LLVM_ABI Libcall getFPTOUINT(EVT OpVT, EVT RetVT)
getFPTOUINT - Return the FPTOUINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getOUTLINE_ATOMIC(unsigned Opc, AtomicOrdering Order, MVT VT)
Return the outline atomics value for the given opcode, atomic ordering and type, or UNKNOWN_LIBCALL i...
LLVM_ABI Libcall getFPEXT(EVT OpVT, EVT RetVT)
getFPEXT - Return the FPEXT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
constexpr double e
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:345
@ Offset
Definition DWP.cpp:578
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1693
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
AtomicOrdering
Atomic ordering for LLVM's memory model.
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Or
Bitwise or logical OR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ Fast
Assign the register banks as fast as possible (default).
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:266
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
EVT getHalfSizedIntegerVT(LLVMContext &Context) const
Finds the smallest simple value type that is greater than or equal to half the width of this EVT.
Definition ValueTypes.h:453
TypeSize getStoreSizeInBits() const
Return the number of bits overwritten by a store of the specified value type.
Definition ValueTypes.h:435
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
LLVM_ABI std::pair< FunctionType *, AttributeList > getFunctionTy(LLVMContext &Ctx, const Triple &TT, const DataLayout &DL, RTLIB::LibcallImpl LibcallImpl) const
These are IR-level optimization flags that may be propagated to SDNodes.
void setNoUnsignedWrap(bool b)
void setNoSignedWrap(bool b)
MakeLibCallOptions & setIsSigned(bool Value=true)