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