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"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/CodeGen/ISDOpcodes.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/RuntimeLibcalls.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGNodes.h"
28 #include "llvm/CodeGen/TargetFrameLowering.h"
29 #include "llvm/CodeGen/TargetLowering.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MachineValueType.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Transforms/Utils/CheriSetBounds.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <tuple>
53 #include <utility>
54
55 using namespace llvm;
56
57 #define DEBUG_TYPE "legalizedag"
58
59 namespace {
60
61 /// Keeps track of state when getting the sign of a floating-point value as an
62 /// integer.
63 struct FloatSignAsInt {
64 EVT FloatVT;
65 SDValue Chain;
66 SDValue FloatPtr;
67 SDValue IntPtr;
68 MachinePointerInfo IntPointerInfo;
69 MachinePointerInfo FloatPointerInfo;
70 SDValue IntValue;
71 APInt SignMask;
72 uint8_t SignBit;
73 };
74
75 //===----------------------------------------------------------------------===//
76 /// This takes an arbitrary SelectionDAG as input and
77 /// hacks on it until the target machine can handle it. This involves
78 /// eliminating value sizes the machine cannot handle (promoting small sizes to
79 /// large sizes or splitting up large values into small values) as well as
80 /// eliminating operations the machine cannot handle.
81 ///
82 /// This code also does a small amount of optimization and recognition of idioms
83 /// as part of its processing. For example, if a target does not support a
84 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
85 /// will attempt merge setcc and brc instructions into brcc's.
86 class SelectionDAGLegalize {
87 const TargetMachine &TM;
88 const TargetLowering &TLI;
89 SelectionDAG &DAG;
90
91 /// The set of nodes which have already been legalized. We hold a
92 /// reference to it in order to update as necessary on node deletion.
93 SmallPtrSetImpl<SDNode *> &LegalizedNodes;
94
95 /// A set of all the nodes updated during legalization.
96 SmallSetVector<SDNode *, 16> *UpdatedNodes;
97
getSetCCResultType(EVT VT) const98 EVT getSetCCResultType(EVT VT) const {
99 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
100 }
101
102 // Libcall insertion helpers.
103
104 public:
SelectionDAGLegalize(SelectionDAG & DAG,SmallPtrSetImpl<SDNode * > & LegalizedNodes,SmallSetVector<SDNode *,16> * UpdatedNodes=nullptr)105 SelectionDAGLegalize(SelectionDAG &DAG,
106 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
107 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
108 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
109 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
110
111 /// Legalizes the given operation.
112 void LegalizeOp(SDNode *Node);
113
114 private:
115 SDValue OptimizeFloatStore(StoreSDNode *ST);
116
117 void LegalizeLoadOps(SDNode *Node);
118 void LegalizeStoreOps(SDNode *Node);
119
120 /// Some targets cannot handle a variable
121 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
122 /// is necessary to spill the vector being inserted into to memory, perform
123 /// the insert there, and then read the result back.
124 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
125 const SDLoc &dl);
126 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
127 const SDLoc &dl);
128
129 /// Return a vector shuffle operation which
130 /// performs the same shuffe in terms of order or result bytes, but on a type
131 /// whose vector element type is narrower than the original shuffle type.
132 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
133 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
134 SDValue N1, SDValue N2,
135 ArrayRef<int> Mask) const;
136
137 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
138 bool &NeedInvert, const SDLoc &dl, SDValue &Chain,
139 bool IsSignaling = false);
140
141 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
142
143 void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
144 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
145 RTLIB::Libcall Call_F128,
146 RTLIB::Libcall Call_PPCF128,
147 SmallVectorImpl<SDValue> &Results);
148 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
149 RTLIB::Libcall Call_I8,
150 RTLIB::Libcall Call_I16,
151 RTLIB::Libcall Call_I32,
152 RTLIB::Libcall Call_I64,
153 RTLIB::Libcall Call_I128);
154 void ExpandArgFPLibCall(SDNode *Node,
155 RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
156 RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
157 RTLIB::Libcall Call_PPCF128,
158 SmallVectorImpl<SDValue> &Results);
159 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
160 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
161
162 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
163 const SDLoc &dl);
164 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
165 const SDLoc &dl, SDValue ChainIn);
166 SDValue ExpandBUILD_VECTOR(SDNode *Node);
167 SDValue ExpandSPLAT_VECTOR(SDNode *Node);
168 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
169 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
170 SmallVectorImpl<SDValue> &Results);
171 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
172 SDValue Value) const;
173 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
174 SDValue NewIntValue) const;
175 SDValue ExpandFCOPYSIGN(SDNode *Node) const;
176 SDValue ExpandFABS(SDNode *Node) const;
177 SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain);
178 void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl,
179 SmallVectorImpl<SDValue> &Results);
180 void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
181 SmallVectorImpl<SDValue> &Results);
182
183 SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl);
184 SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl);
185
186 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
187 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
188 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
189
190 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
191 SDValue ExpandConstant(ConstantSDNode *CP);
192
193 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
194 bool ExpandNode(SDNode *Node);
195 void ConvertNodeToLibcall(SDNode *Node);
196 void PromoteNode(SDNode *Node);
197
198 public:
199 // Node replacement helpers
200
ReplacedNode(SDNode * N)201 void ReplacedNode(SDNode *N) {
202 LegalizedNodes.erase(N);
203 if (UpdatedNodes)
204 UpdatedNodes->insert(N);
205 }
206
ReplaceNode(SDNode * Old,SDNode * New)207 void ReplaceNode(SDNode *Old, SDNode *New) {
208 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
209 dbgs() << " with: "; New->dump(&DAG));
210
211 assert(Old->getNumValues() == New->getNumValues() &&
212 "Replacing one node with another that produces a different number "
213 "of values!");
214 DAG.ReplaceAllUsesWith(Old, New);
215 if (UpdatedNodes)
216 UpdatedNodes->insert(New);
217 ReplacedNode(Old);
218 }
219
ReplaceNode(SDValue Old,SDValue New)220 void ReplaceNode(SDValue Old, SDValue New) {
221 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
222 dbgs() << " with: "; New->dump(&DAG));
223
224 DAG.ReplaceAllUsesWith(Old, New);
225 if (UpdatedNodes)
226 UpdatedNodes->insert(New.getNode());
227 ReplacedNode(Old.getNode());
228 }
229
ReplaceNode(SDNode * Old,const SDValue * New)230 void ReplaceNode(SDNode *Old, const SDValue *New) {
231 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
232
233 DAG.ReplaceAllUsesWith(Old, New);
234 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
235 LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
236 New[i]->dump(&DAG));
237 if (UpdatedNodes)
238 UpdatedNodes->insert(New[i].getNode());
239 }
240 ReplacedNode(Old);
241 }
242
ReplaceNodeWithValue(SDValue Old,SDValue New)243 void ReplaceNodeWithValue(SDValue Old, SDValue New) {
244 LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
245 dbgs() << " with: "; New->dump(&DAG));
246
247 DAG.ReplaceAllUsesOfValueWith(Old, New);
248 if (UpdatedNodes)
249 UpdatedNodes->insert(New.getNode());
250 ReplacedNode(Old.getNode());
251 }
252 };
253
254 } // end anonymous namespace
255
256 /// Return a vector shuffle operation which
257 /// performs the same shuffle in terms of order or result bytes, but on a type
258 /// whose vector element type is narrower than the original shuffle type.
259 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
ShuffleWithNarrowerEltType(EVT NVT,EVT VT,const SDLoc & dl,SDValue N1,SDValue N2,ArrayRef<int> Mask) const260 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
261 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
262 ArrayRef<int> Mask) const {
263 unsigned NumMaskElts = VT.getVectorNumElements();
264 unsigned NumDestElts = NVT.getVectorNumElements();
265 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
266
267 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
268
269 if (NumEltsGrowth == 1)
270 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
271
272 SmallVector<int, 8> NewMask;
273 for (unsigned i = 0; i != NumMaskElts; ++i) {
274 int Idx = Mask[i];
275 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
276 if (Idx < 0)
277 NewMask.push_back(-1);
278 else
279 NewMask.push_back(Idx * NumEltsGrowth + j);
280 }
281 }
282 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
283 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
284 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
285 }
286
287 /// Expands the ConstantFP node to an integer constant or
288 /// a load from the constant pool.
289 SDValue
ExpandConstantFP(ConstantFPSDNode * CFP,bool UseCP)290 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
291 bool Extend = false;
292 SDLoc dl(CFP);
293
294 // If a FP immediate is precise when represented as a float and if the
295 // target can do an extending load from float to double, we put it into
296 // the constant pool as a float, even if it's is statically typed as a
297 // double. This shrinks FP constants and canonicalizes them for targets where
298 // an FP extending load is the same cost as a normal load (such as on the x87
299 // fp stack or PPC FP unit).
300 EVT VT = CFP->getValueType(0);
301 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
302 if (!UseCP) {
303 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
304 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
305 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
306 }
307
308 APFloat APF = CFP->getValueAPF();
309 EVT OrigVT = VT;
310 EVT SVT = VT;
311
312 // We don't want to shrink SNaNs. Converting the SNaN back to its real type
313 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
314 if (!APF.isSignaling()) {
315 while (SVT != MVT::f32 && SVT != MVT::f16) {
316 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
317 if (ConstantFPSDNode::isValueValidForType(SVT, APF) &&
318 // Only do this if the target has a native EXTLOAD instruction from
319 // smaller type.
320 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
321 TLI.ShouldShrinkFPConstant(OrigVT)) {
322 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
323 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
324 VT = SVT;
325 Extend = true;
326 }
327 }
328 }
329
330 SDValue CPIdx = DAG.getConstantPool(
331 LLVMC, TLI.getPointerTy(DAG.getDataLayout(),
332 DAG.getDataLayout().getGlobalsAddressSpace()));
333 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
334 if (Extend) {
335 SDValue Result = DAG.getExtLoad(
336 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
337 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
338 Alignment);
339 return Result;
340 }
341 SDValue Result = DAG.getLoad(
342 OrigVT, dl, DAG.getEntryNode(), CPIdx,
343 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
344 return Result;
345 }
346
347 /// Expands the Constant node to a load from the constant pool.
ExpandConstant(ConstantSDNode * CP)348 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
349 SDLoc dl(CP);
350 EVT VT = CP->getValueType(0);
351 SDValue CPIdx = DAG.getConstantPool(
352 CP->getConstantIntValue(),
353 TLI.getPointerTy(DAG.getDataLayout(),
354 DAG.getDataLayout().getGlobalsAddressSpace()));
355 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
356 SDValue Result = DAG.getLoad(
357 VT, dl, DAG.getEntryNode(), CPIdx,
358 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
359 return Result;
360 }
361
362 /// Some target cannot handle a variable insertion index for the
363 /// INSERT_VECTOR_ELT instruction. In this case, it
364 /// is necessary to spill the vector being inserted into to memory, perform
365 /// the insert there, and then read the result back.
PerformInsertVectorEltInMemory(SDValue Vec,SDValue Val,SDValue Idx,const SDLoc & dl)366 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
367 SDValue Val,
368 SDValue Idx,
369 const SDLoc &dl) {
370 SDValue Tmp1 = Vec;
371 SDValue Tmp2 = Val;
372 SDValue Tmp3 = Idx;
373
374 // If the target doesn't support this, we have to spill the input vector
375 // to a temporary stack slot, update the element, then reload it. This is
376 // badness. We could also load the value into a vector register (either
377 // with a "move to register" or "extload into register" instruction, then
378 // permute it into place, if the idx is a constant and if the idx is
379 // supported by the target.
380 EVT VT = Tmp1.getValueType();
381 EVT EltVT = VT.getVectorElementType();
382 SDValue StackPtr = DAG.CreateStackTemporary(VT);
383
384 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
385
386 // Store the vector.
387 SDValue Ch = DAG.getStore(
388 DAG.getEntryNode(), dl, Tmp1, StackPtr,
389 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
390
391 SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
392
393 // Store the scalar value.
394 Ch = DAG.getTruncStore(
395 Ch, dl, Tmp2, StackPtr2,
396 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), EltVT);
397 // Load the updated vector.
398 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
399 DAG.getMachineFunction(), SPFI));
400 }
401
ExpandINSERT_VECTOR_ELT(SDValue Vec,SDValue Val,SDValue Idx,const SDLoc & dl)402 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
403 SDValue Idx,
404 const SDLoc &dl) {
405 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
406 // SCALAR_TO_VECTOR requires that the type of the value being inserted
407 // match the element type of the vector being created, except for
408 // integers in which case the inserted value can be over width.
409 EVT EltVT = Vec.getValueType().getVectorElementType();
410 if (Val.getValueType() == EltVT ||
411 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
412 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
413 Vec.getValueType(), Val);
414
415 unsigned NumElts = Vec.getValueType().getVectorNumElements();
416 // We generate a shuffle of InVec and ScVec, so the shuffle mask
417 // should be 0,1,2,3,4,5... with the appropriate element replaced with
418 // elt 0 of the RHS.
419 SmallVector<int, 8> ShufOps;
420 for (unsigned i = 0; i != NumElts; ++i)
421 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
422
423 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
424 }
425 }
426 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
427 }
428
OptimizeFloatStore(StoreSDNode * ST)429 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
430 if (!ISD::isNormalStore(ST))
431 return SDValue();
432
433 LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
434 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
435 // FIXME: We shouldn't do this for TargetConstantFP's.
436 // FIXME: move this to the DAG Combiner! Note that we can't regress due
437 // to phase ordering between legalized code and the dag combiner. This
438 // probably means that we need to integrate dag combiner and legalizer
439 // together.
440 // We generally can't do this one for long doubles.
441 SDValue Chain = ST->getChain();
442 SDValue Ptr = ST->getBasePtr();
443 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
444 AAMDNodes AAInfo = ST->getAAInfo();
445 SDLoc dl(ST);
446 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
447 if (CFP->getValueType(0) == MVT::f32 &&
448 TLI.isTypeLegal(MVT::i32)) {
449 SDValue Con = DAG.getConstant(CFP->getValueAPF().
450 bitcastToAPInt().zextOrTrunc(32),
451 SDLoc(CFP), MVT::i32);
452 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
453 ST->getOriginalAlign(), MMOFlags, AAInfo);
454 }
455
456 if (CFP->getValueType(0) == MVT::f64) {
457 // If this target supports 64-bit registers, do a single 64-bit store.
458 if (TLI.isTypeLegal(MVT::i64)) {
459 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
460 zextOrTrunc(64), SDLoc(CFP), MVT::i64);
461 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
462 ST->getOriginalAlign(), MMOFlags, AAInfo);
463 }
464
465 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
466 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
467 // stores. If the target supports neither 32- nor 64-bits, this
468 // xform is certainly not worth it.
469 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
470 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
471 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
472 if (DAG.getDataLayout().isBigEndian())
473 std::swap(Lo, Hi);
474
475 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(),
476 ST->getOriginalAlign(), MMOFlags, AAInfo);
477 Ptr = DAG.getMemBasePlusOffset(Ptr, 4, dl);
478 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
479 ST->getPointerInfo().getWithOffset(4),
480 ST->getOriginalAlign(), MMOFlags, AAInfo);
481
482 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
483 }
484 }
485 }
486 return SDValue(nullptr, 0);
487 }
488
LegalizeStoreOps(SDNode * Node)489 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
490 StoreSDNode *ST = cast<StoreSDNode>(Node);
491 SDValue Chain = ST->getChain();
492 SDValue Ptr = ST->getBasePtr();
493 SDLoc dl(Node);
494
495 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
496 AAMDNodes AAInfo = ST->getAAInfo();
497
498 if (!ST->isTruncatingStore()) {
499 LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
500 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
501 ReplaceNode(ST, OptStore);
502 return;
503 }
504
505 SDValue Value = ST->getValue();
506 MVT VT = Value.getSimpleValueType();
507 switch (TLI.getOperationAction(ISD::STORE, VT)) {
508 default: llvm_unreachable("This action is not supported yet!");
509 case TargetLowering::Legal: {
510 // If this is an unaligned store and the target doesn't support it,
511 // expand it.
512 EVT MemVT = ST->getMemoryVT();
513 const DataLayout &DL = DAG.getDataLayout();
514 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
515 *ST->getMemOperand())) {
516 LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
517 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
518 ReplaceNode(SDValue(ST, 0), Result);
519 } else
520 LLVM_DEBUG(dbgs() << "Legal store\n");
521 break;
522 }
523 case TargetLowering::Custom: {
524 LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
525 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
526 if (Res && Res != SDValue(Node, 0))
527 ReplaceNode(SDValue(Node, 0), Res);
528 return;
529 }
530 case TargetLowering::Promote: {
531 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
532 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
533 "Can only promote stores to same size type");
534 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
535 SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
536 ST->getOriginalAlign(), MMOFlags, AAInfo);
537 ReplaceNode(SDValue(Node, 0), Result);
538 break;
539 }
540 }
541 return;
542 }
543
544 LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
545 SDValue Value = ST->getValue();
546 EVT StVT = ST->getMemoryVT();
547 unsigned StWidth = StVT.getSizeInBits();
548 auto &DL = DAG.getDataLayout();
549
550 if (StWidth != StVT.getStoreSizeInBits()) {
551 // Promote to a byte-sized store with upper bits zero if not
552 // storing an integral number of bytes. For example, promote
553 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
554 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
555 StVT.getStoreSizeInBits());
556 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
557 SDValue Result =
558 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
559 ST->getOriginalAlign(), MMOFlags, AAInfo);
560 ReplaceNode(SDValue(Node, 0), Result);
561 } else if (StWidth & (StWidth - 1)) {
562 // If not storing a power-of-2 number of bits, expand as two stores.
563 assert(!StVT.isVector() && "Unsupported truncstore!");
564 unsigned LogStWidth = Log2_32(StWidth);
565 assert(LogStWidth < 32);
566 unsigned RoundWidth = 1 << LogStWidth;
567 assert(RoundWidth < StWidth);
568 unsigned ExtraWidth = StWidth - RoundWidth;
569 assert(ExtraWidth < RoundWidth);
570 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
571 "Store size not an integral number of bytes!");
572 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
573 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
574 SDValue Lo, Hi;
575 unsigned IncrementSize;
576
577 if (DL.isLittleEndian()) {
578 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
579 // Store the bottom RoundWidth bits.
580 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
581 RoundVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
582
583 // Store the remaining ExtraWidth bits.
584 IncrementSize = RoundWidth / 8;
585 Ptr = DAG.getMemBasePlusOffset(Ptr, IncrementSize, dl);
586 Hi = DAG.getNode(
587 ISD::SRL, dl, Value.getValueType(), Value,
588 DAG.getConstant(RoundWidth, dl,
589 TLI.getShiftAmountTy(Value.getValueType(), DL)));
590 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
591 ST->getPointerInfo().getWithOffset(IncrementSize),
592 ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
593 } else {
594 // Big endian - avoid unaligned stores.
595 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
596 // Store the top RoundWidth bits.
597 Hi = DAG.getNode(
598 ISD::SRL, dl, Value.getValueType(), Value,
599 DAG.getConstant(ExtraWidth, dl,
600 TLI.getShiftAmountTy(Value.getValueType(), DL)));
601 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT,
602 ST->getOriginalAlign(), MMOFlags, AAInfo);
603
604 // Store the remaining ExtraWidth bits.
605 IncrementSize = RoundWidth / 8;
606 Ptr = DAG.getPointerAdd(dl, Ptr, IncrementSize);
607 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
608 ST->getPointerInfo().getWithOffset(IncrementSize),
609 ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
610
611 }
612
613 // The order of the stores doesn't matter.
614 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
615 ReplaceNode(SDValue(Node, 0), Result);
616 } else {
617 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
618 default: llvm_unreachable("This action is not supported yet!");
619 case TargetLowering::Legal: {
620 EVT MemVT = ST->getMemoryVT();
621 // If this is an unaligned store and the target doesn't support it,
622 // expand it.
623 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
624 *ST->getMemOperand())) {
625 SDValue Result = TLI.expandUnalignedStore(ST, DAG);
626 ReplaceNode(SDValue(ST, 0), Result);
627 }
628 break;
629 }
630 case TargetLowering::Custom: {
631 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
632 if (Res && Res != SDValue(Node, 0))
633 ReplaceNode(SDValue(Node, 0), Res);
634 return;
635 }
636 case TargetLowering::Expand:
637 assert(!StVT.isVector() &&
638 "Vector Stores are handled in LegalizeVectorOps");
639
640 SDValue Result;
641
642 // TRUNCSTORE:i16 i32 -> STORE i16
643 if (TLI.isTypeLegal(StVT)) {
644 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
645 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
646 ST->getOriginalAlign(), MMOFlags, AAInfo);
647 } else {
648 // The in-memory type isn't legal. Truncate to the type it would promote
649 // to, and then do a truncstore.
650 Value = DAG.getNode(ISD::TRUNCATE, dl,
651 TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
652 Value);
653 Result =
654 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), StVT,
655 ST->getOriginalAlign(), MMOFlags, AAInfo);
656 }
657
658 ReplaceNode(SDValue(Node, 0), Result);
659 break;
660 }
661 }
662 }
663
LegalizeLoadOps(SDNode * Node)664 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
665 LoadSDNode *LD = cast<LoadSDNode>(Node);
666 SDValue Chain = LD->getChain(); // The chain.
667 SDValue Ptr = LD->getBasePtr(); // The base pointer.
668 SDValue Value; // The value returned by the load op.
669 SDLoc dl(Node);
670
671 ISD::LoadExtType ExtType = LD->getExtensionType();
672 if (ExtType == ISD::NON_EXTLOAD) {
673 LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
674 MVT VT = Node->getSimpleValueType(0);
675 SDValue RVal = SDValue(Node, 0);
676 SDValue RChain = SDValue(Node, 1);
677
678 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
679 default: llvm_unreachable("This action is not supported yet!");
680 case TargetLowering::Legal: {
681 EVT MemVT = LD->getMemoryVT();
682 const DataLayout &DL = DAG.getDataLayout();
683 // If this is an unaligned load and the target doesn't support it,
684 // expand it.
685 if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
686 *LD->getMemOperand())) {
687 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
688 }
689 break;
690 }
691 case TargetLowering::Custom:
692 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
693 RVal = Res;
694 RChain = Res.getValue(1);
695 }
696 break;
697
698 case TargetLowering::Promote: {
699 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
700 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
701 "Can only promote loads to same size type");
702
703 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
704 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
705 RChain = Res.getValue(1);
706 break;
707 }
708 }
709 if (RChain.getNode() != Node) {
710 assert(RVal.getNode() != Node && "Load must be completely replaced");
711 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
712 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
713 if (UpdatedNodes) {
714 UpdatedNodes->insert(RVal.getNode());
715 UpdatedNodes->insert(RChain.getNode());
716 }
717 ReplacedNode(Node);
718 }
719 return;
720 }
721
722 LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
723 EVT SrcVT = LD->getMemoryVT();
724 unsigned SrcWidth = SrcVT.getSizeInBits();
725 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
726 AAMDNodes AAInfo = LD->getAAInfo();
727
728 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
729 // Some targets pretend to have an i1 loading operation, and actually
730 // load an i8. This trick is correct for ZEXTLOAD because the top 7
731 // bits are guaranteed to be zero; it helps the optimizers understand
732 // that these bits are zero. It is also useful for EXTLOAD, since it
733 // tells the optimizers that those bits are undefined. It would be
734 // nice to have an effective generic way of getting these benefits...
735 // Until such a way is found, don't insist on promoting i1 here.
736 (SrcVT != MVT::i1 ||
737 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
738 TargetLowering::Promote)) {
739 // Promote to a byte-sized load if not loading an integral number of
740 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
741 unsigned NewWidth = SrcVT.getStoreSizeInBits();
742 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
743 SDValue Ch;
744
745 // The extra bits are guaranteed to be zero, since we stored them that
746 // way. A zext load from NVT thus automatically gives zext from SrcVT.
747
748 ISD::LoadExtType NewExtType =
749 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
750
751 SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
752 Chain, Ptr, LD->getPointerInfo(), NVT,
753 LD->getOriginalAlign(), MMOFlags, AAInfo);
754
755 Ch = Result.getValue(1); // The chain.
756
757 if (ExtType == ISD::SEXTLOAD)
758 // Having the top bits zero doesn't help when sign extending.
759 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
760 Result.getValueType(),
761 Result, DAG.getValueType(SrcVT));
762 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
763 // All the top bits are guaranteed to be zero - inform the optimizers.
764 Result = DAG.getNode(ISD::AssertZext, dl,
765 Result.getValueType(), Result,
766 DAG.getValueType(SrcVT));
767
768 Value = Result;
769 Chain = Ch;
770 } else if (SrcWidth & (SrcWidth - 1)) {
771 // If not loading a power-of-2 number of bits, expand as two loads.
772 assert(!SrcVT.isVector() && "Unsupported extload!");
773 unsigned LogSrcWidth = Log2_32(SrcWidth);
774 assert(LogSrcWidth < 32);
775 unsigned RoundWidth = 1 << LogSrcWidth;
776 assert(RoundWidth < SrcWidth);
777 unsigned ExtraWidth = SrcWidth - RoundWidth;
778 assert(ExtraWidth < RoundWidth);
779 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
780 "Load size not an integral number of bytes!");
781 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
782 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
783 SDValue Lo, Hi, Ch;
784 unsigned IncrementSize;
785 auto &DL = DAG.getDataLayout();
786
787 if (DL.isLittleEndian()) {
788 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
789 // Load the bottom RoundWidth bits.
790 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
791 LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
792 MMOFlags, AAInfo);
793
794 // Load the remaining ExtraWidth bits.
795 IncrementSize = RoundWidth / 8;
796 Ptr = DAG.getMemBasePlusOffset(Ptr, IncrementSize, dl);
797 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
798 LD->getPointerInfo().getWithOffset(IncrementSize),
799 ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
800
801 // Build a factor node to remember that this load is independent of
802 // the other one.
803 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
804 Hi.getValue(1));
805
806 // Move the top bits to the right place.
807 Hi = DAG.getNode(
808 ISD::SHL, dl, Hi.getValueType(), Hi,
809 DAG.getConstant(RoundWidth, dl,
810 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
811
812 // Join the hi and lo parts.
813 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
814 } else {
815 // Big endian - avoid unaligned loads.
816 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
817 // Load the top RoundWidth bits.
818 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
819 LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
820 MMOFlags, AAInfo);
821
822 // Load the remaining ExtraWidth bits.
823 IncrementSize = RoundWidth / 8;
824 Ptr = DAG.getMemBasePlusOffset(Ptr, IncrementSize, dl);
825 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
826 LD->getPointerInfo().getWithOffset(IncrementSize),
827 ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
828
829 // Build a factor node to remember that this load is independent of
830 // the other one.
831 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
832 Hi.getValue(1));
833
834 // Move the top bits to the right place.
835 Hi = DAG.getNode(
836 ISD::SHL, dl, Hi.getValueType(), Hi,
837 DAG.getConstant(ExtraWidth, dl,
838 TLI.getShiftAmountTy(Hi.getValueType(), DL)));
839
840 // Join the hi and lo parts.
841 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
842 }
843
844 Chain = Ch;
845 } else {
846 bool isCustom = false;
847 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
848 SrcVT.getSimpleVT())) {
849 default: llvm_unreachable("This action is not supported yet!");
850 case TargetLowering::Custom:
851 isCustom = true;
852 LLVM_FALLTHROUGH;
853 case TargetLowering::Legal:
854 Value = SDValue(Node, 0);
855 Chain = SDValue(Node, 1);
856
857 if (isCustom) {
858 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
859 Value = Res;
860 Chain = Res.getValue(1);
861 }
862 } else {
863 // If this is an unaligned load and the target doesn't support it,
864 // expand it.
865 EVT MemVT = LD->getMemoryVT();
866 const DataLayout &DL = DAG.getDataLayout();
867 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
868 *LD->getMemOperand())) {
869 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
870 }
871 }
872 break;
873
874 case TargetLowering::Expand: {
875 EVT DestVT = Node->getValueType(0);
876 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
877 // If the source type is not legal, see if there is a legal extload to
878 // an intermediate type that we can then extend further.
879 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
880 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
881 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
882 // If we are loading a legal type, this is a non-extload followed by a
883 // full extend.
884 ISD::LoadExtType MidExtType =
885 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
886
887 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
888 SrcVT, LD->getMemOperand());
889 unsigned ExtendOp =
890 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
891 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
892 Chain = Load.getValue(1);
893 break;
894 }
895
896 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
897 // normal undefined upper bits behavior to allow using an in-reg extend
898 // with the illegal FP type, so load as an integer and do the
899 // from-integer conversion.
900 if (SrcVT.getScalarType() == MVT::f16) {
901 EVT ISrcVT = SrcVT.changeTypeToInteger();
902 EVT IDestVT = DestVT.changeTypeToInteger();
903 EVT ILoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
904
905 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
906 Ptr, ISrcVT, LD->getMemOperand());
907 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
908 Chain = Result.getValue(1);
909 break;
910 }
911 }
912
913 assert(!SrcVT.isVector() &&
914 "Vector Loads are handled in LegalizeVectorOps");
915
916 // FIXME: This does not work for vectors on most targets. Sign-
917 // and zero-extend operations are currently folded into extending
918 // loads, whether they are legal or not, and then we end up here
919 // without any support for legalizing them.
920 assert(ExtType != ISD::EXTLOAD &&
921 "EXTLOAD should always be supported!");
922 // Turn the unsupported load into an EXTLOAD followed by an
923 // explicit zero/sign extend inreg.
924 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
925 Node->getValueType(0),
926 Chain, Ptr, SrcVT,
927 LD->getMemOperand());
928 SDValue ValRes;
929 if (ExtType == ISD::SEXTLOAD)
930 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
931 Result.getValueType(),
932 Result, DAG.getValueType(SrcVT));
933 else
934 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
935 Value = ValRes;
936 Chain = Result.getValue(1);
937 break;
938 }
939 }
940 }
941
942 // Since loads produce two values, make sure to remember that we legalized
943 // both of them.
944 if (Chain.getNode() != Node) {
945 assert(Value.getNode() != Node && "Load must be completely replaced");
946 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
947 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
948 if (UpdatedNodes) {
949 UpdatedNodes->insert(Value.getNode());
950 UpdatedNodes->insert(Chain.getNode());
951 }
952 ReplacedNode(Node);
953 }
954 }
955
956 /// Return a legal replacement for the given operation, with all legal operands.
LegalizeOp(SDNode * Node)957 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
958 LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
959
960 // Allow illegal target nodes and illegal registers.
961 if (Node->getOpcode() == ISD::TargetConstant ||
962 Node->getOpcode() == ISD::Register)
963 return;
964
965 #ifndef NDEBUG
966 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
967 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
968 TargetLowering::TypeLegal &&
969 "Unexpected illegal type!");
970
971 for (const SDValue &Op : Node->op_values())
972 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
973 TargetLowering::TypeLegal ||
974 Op.getOpcode() == ISD::TargetConstant ||
975 Op.getOpcode() == ISD::Register) &&
976 "Unexpected illegal type!");
977 #endif
978
979 // Figure out the correct action; the way to query this varies by opcode
980 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
981 bool SimpleFinishLegalizing = true;
982 switch (Node->getOpcode()) {
983 case ISD::INTRINSIC_W_CHAIN:
984 case ISD::INTRINSIC_WO_CHAIN:
985 case ISD::INTRINSIC_VOID:
986 case ISD::STACKSAVE:
987 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
988 break;
989 case ISD::GET_DYNAMIC_AREA_OFFSET:
990 Action = TLI.getOperationAction(Node->getOpcode(),
991 Node->getValueType(0));
992 break;
993 case ISD::VAARG:
994 Action = TLI.getOperationAction(Node->getOpcode(),
995 Node->getValueType(0));
996 if (Action != TargetLowering::Promote)
997 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
998 break;
999 case ISD::FP_TO_FP16:
1000 case ISD::SINT_TO_FP:
1001 case ISD::UINT_TO_FP:
1002 case ISD::EXTRACT_VECTOR_ELT:
1003 case ISD::LROUND:
1004 case ISD::LLROUND:
1005 case ISD::LRINT:
1006 case ISD::LLRINT:
1007 Action = TLI.getOperationAction(Node->getOpcode(),
1008 Node->getOperand(0).getValueType());
1009 break;
1010 case ISD::STRICT_FP_TO_FP16:
1011 case ISD::STRICT_SINT_TO_FP:
1012 case ISD::STRICT_UINT_TO_FP:
1013 case ISD::STRICT_LRINT:
1014 case ISD::STRICT_LLRINT:
1015 case ISD::STRICT_LROUND:
1016 case ISD::STRICT_LLROUND:
1017 // These pseudo-ops are the same as the other STRICT_ ops except
1018 // they are registered with setOperationAction() using the input type
1019 // instead of the output type.
1020 Action = TLI.getOperationAction(Node->getOpcode(),
1021 Node->getOperand(1).getValueType());
1022 break;
1023 case ISD::SIGN_EXTEND_INREG: {
1024 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1025 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1026 break;
1027 }
1028 case ISD::ATOMIC_STORE:
1029 Action = TLI.getOperationAction(Node->getOpcode(),
1030 Node->getOperand(2).getValueType());
1031 break;
1032 case ISD::SELECT_CC:
1033 case ISD::STRICT_FSETCC:
1034 case ISD::STRICT_FSETCCS:
1035 case ISD::SETCC:
1036 case ISD::BR_CC: {
1037 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1038 Node->getOpcode() == ISD::STRICT_FSETCC ? 3 :
1039 Node->getOpcode() == ISD::STRICT_FSETCCS ? 3 :
1040 Node->getOpcode() == ISD::SETCC ? 2 : 1;
1041 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 :
1042 Node->getOpcode() == ISD::STRICT_FSETCC ? 1 :
1043 Node->getOpcode() == ISD::STRICT_FSETCCS ? 1 : 0;
1044 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1045 ISD::CondCode CCCode =
1046 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1047 Action = TLI.getCondCodeAction(CCCode, OpVT);
1048 if (Action == TargetLowering::Legal) {
1049 if (Node->getOpcode() == ISD::SELECT_CC)
1050 Action = TLI.getOperationAction(Node->getOpcode(),
1051 Node->getValueType(0));
1052 else
1053 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1054 }
1055 break;
1056 }
1057 case ISD::LOAD:
1058 case ISD::STORE:
1059 // FIXME: Model these properly. LOAD and STORE are complicated, and
1060 // STORE expects the unlegalized operand in some cases.
1061 SimpleFinishLegalizing = false;
1062 break;
1063 case ISD::CALLSEQ_START:
1064 case ISD::CALLSEQ_END:
1065 // FIXME: This shouldn't be necessary. These nodes have special properties
1066 // dealing with the recursive nature of legalization. Removing this
1067 // special case should be done as part of making LegalizeDAG non-recursive.
1068 SimpleFinishLegalizing = false;
1069 break;
1070 case ISD::EXTRACT_ELEMENT:
1071 case ISD::FLT_ROUNDS_:
1072 case ISD::MERGE_VALUES:
1073 case ISD::EH_RETURN:
1074 case ISD::FRAME_TO_ARGS_OFFSET:
1075 case ISD::EH_DWARF_CFA:
1076 case ISD::EH_SJLJ_SETJMP:
1077 case ISD::EH_SJLJ_LONGJMP:
1078 case ISD::EH_SJLJ_SETUP_DISPATCH:
1079 // These operations lie about being legal: when they claim to be legal,
1080 // they should actually be expanded.
1081 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1082 if (Action == TargetLowering::Legal)
1083 Action = TargetLowering::Expand;
1084 break;
1085 case ISD::INIT_TRAMPOLINE:
1086 case ISD::ADJUST_TRAMPOLINE:
1087 case ISD::FRAMEADDR:
1088 case ISD::RETURNADDR:
1089 case ISD::ADDROFRETURNADDR:
1090 case ISD::SPONENTRY:
1091 // These operations lie about being legal: when they claim to be legal,
1092 // they should actually be custom-lowered.
1093 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1094 if (Action == TargetLowering::Legal)
1095 Action = TargetLowering::Custom;
1096 break;
1097 case ISD::READCYCLECOUNTER:
1098 // READCYCLECOUNTER returns an i64, even if type legalization might have
1099 // expanded that to several smaller types.
1100 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1101 break;
1102 case ISD::READ_REGISTER:
1103 case ISD::WRITE_REGISTER:
1104 // Named register is legal in the DAG, but blocked by register name
1105 // selection if not implemented by target (to chose the correct register)
1106 // They'll be converted to Copy(To/From)Reg.
1107 Action = TargetLowering::Legal;
1108 break;
1109 case ISD::DEBUGTRAP:
1110 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1111 if (Action == TargetLowering::Expand) {
1112 // replace ISD::DEBUGTRAP with ISD::TRAP
1113 SDValue NewVal;
1114 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1115 Node->getOperand(0));
1116 ReplaceNode(Node, NewVal.getNode());
1117 LegalizeOp(NewVal.getNode());
1118 return;
1119 }
1120 break;
1121 case ISD::SADDSAT:
1122 case ISD::UADDSAT:
1123 case ISD::SSUBSAT:
1124 case ISD::USUBSAT: {
1125 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1126 break;
1127 }
1128 case ISD::SMULFIX:
1129 case ISD::SMULFIXSAT:
1130 case ISD::UMULFIX:
1131 case ISD::UMULFIXSAT:
1132 case ISD::SDIVFIX:
1133 case ISD::SDIVFIXSAT:
1134 case ISD::UDIVFIX:
1135 case ISD::UDIVFIXSAT: {
1136 unsigned Scale = Node->getConstantOperandVal(2);
1137 Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1138 Node->getValueType(0), Scale);
1139 break;
1140 }
1141 case ISD::MSCATTER:
1142 Action = TLI.getOperationAction(Node->getOpcode(),
1143 cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1144 break;
1145 case ISD::MSTORE:
1146 Action = TLI.getOperationAction(Node->getOpcode(),
1147 cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1148 break;
1149 case ISD::VECREDUCE_FADD:
1150 case ISD::VECREDUCE_FMUL:
1151 case ISD::VECREDUCE_ADD:
1152 case ISD::VECREDUCE_MUL:
1153 case ISD::VECREDUCE_AND:
1154 case ISD::VECREDUCE_OR:
1155 case ISD::VECREDUCE_XOR:
1156 case ISD::VECREDUCE_SMAX:
1157 case ISD::VECREDUCE_SMIN:
1158 case ISD::VECREDUCE_UMAX:
1159 case ISD::VECREDUCE_UMIN:
1160 case ISD::VECREDUCE_FMAX:
1161 case ISD::VECREDUCE_FMIN:
1162 Action = TLI.getOperationAction(
1163 Node->getOpcode(), Node->getOperand(0).getValueType());
1164 break;
1165 default:
1166 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1167 Action = TargetLowering::Legal;
1168 } else {
1169 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1170 }
1171 break;
1172 }
1173
1174 if (SimpleFinishLegalizing) {
1175 SDNode *NewNode = Node;
1176 switch (Node->getOpcode()) {
1177 default: break;
1178 case ISD::SHL:
1179 case ISD::SRL:
1180 case ISD::SRA:
1181 case ISD::ROTL:
1182 case ISD::ROTR: {
1183 // Legalizing shifts/rotates requires adjusting the shift amount
1184 // to the appropriate width.
1185 SDValue Op0 = Node->getOperand(0);
1186 SDValue Op1 = Node->getOperand(1);
1187 if (!Op1.getValueType().isVector()) {
1188 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1189 // The getShiftAmountOperand() may create a new operand node or
1190 // return the existing one. If new operand is created we need
1191 // to update the parent node.
1192 // Do not try to legalize SAO here! It will be automatically legalized
1193 // in the next round.
1194 if (SAO != Op1)
1195 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1196 }
1197 }
1198 break;
1199 case ISD::FSHL:
1200 case ISD::FSHR:
1201 case ISD::SRL_PARTS:
1202 case ISD::SRA_PARTS:
1203 case ISD::SHL_PARTS: {
1204 // Legalizing shifts/rotates requires adjusting the shift amount
1205 // to the appropriate width.
1206 SDValue Op0 = Node->getOperand(0);
1207 SDValue Op1 = Node->getOperand(1);
1208 SDValue Op2 = Node->getOperand(2);
1209 if (!Op2.getValueType().isVector()) {
1210 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1211 // The getShiftAmountOperand() may create a new operand node or
1212 // return the existing one. If new operand is created we need
1213 // to update the parent node.
1214 if (SAO != Op2)
1215 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1216 }
1217 break;
1218 }
1219 }
1220
1221 if (NewNode != Node) {
1222 ReplaceNode(Node, NewNode);
1223 Node = NewNode;
1224 }
1225 switch (Action) {
1226 case TargetLowering::Legal:
1227 LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1228 return;
1229 case TargetLowering::Custom:
1230 LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1231 // FIXME: The handling for custom lowering with multiple results is
1232 // a complete mess.
1233 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1234 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1235 return;
1236
1237 if (Node->getNumValues() == 1) {
1238 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1239 // We can just directly replace this node with the lowered value.
1240 ReplaceNode(SDValue(Node, 0), Res);
1241 return;
1242 }
1243
1244 SmallVector<SDValue, 8> ResultVals;
1245 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1246 ResultVals.push_back(Res.getValue(i));
1247 LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1248 ReplaceNode(Node, ResultVals.data());
1249 return;
1250 }
1251 LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1252 LLVM_FALLTHROUGH;
1253 case TargetLowering::Expand:
1254 if (ExpandNode(Node))
1255 return;
1256 LLVM_FALLTHROUGH;
1257 case TargetLowering::LibCall:
1258 ConvertNodeToLibcall(Node);
1259 return;
1260 case TargetLowering::Promote:
1261 PromoteNode(Node);
1262 return;
1263 }
1264 }
1265
1266 switch (Node->getOpcode()) {
1267 default:
1268 #ifndef NDEBUG
1269 dbgs() << "NODE: ";
1270 Node->dump( &DAG);
1271 dbgs() << "\n";
1272 #endif
1273 llvm_unreachable("Do not know how to legalize this operator!");
1274
1275 case ISD::CALLSEQ_START:
1276 case ISD::CALLSEQ_END:
1277 break;
1278 case ISD::LOAD:
1279 return LegalizeLoadOps(Node);
1280 case ISD::STORE:
1281 return LegalizeStoreOps(Node);
1282 }
1283 }
1284
ExpandExtractFromVectorThroughStack(SDValue Op)1285 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1286 SDValue Vec = Op.getOperand(0);
1287 SDValue Idx = Op.getOperand(1);
1288 SDLoc dl(Op);
1289
1290 // Before we generate a new store to a temporary stack slot, see if there is
1291 // already one that we can use. There often is because when we scalarize
1292 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1293 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1294 // the vector. If all are expanded here, we don't want one store per vector
1295 // element.
1296
1297 // Caches for hasPredecessorHelper
1298 SmallPtrSet<const SDNode *, 32> Visited;
1299 SmallVector<const SDNode *, 16> Worklist;
1300 Visited.insert(Op.getNode());
1301 Worklist.push_back(Idx.getNode());
1302 SDValue StackPtr, Ch;
1303 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1304 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1305 SDNode *User = *UI;
1306 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1307 if (ST->isIndexed() || ST->isTruncatingStore() ||
1308 ST->getValue() != Vec)
1309 continue;
1310
1311 // Make sure that nothing else could have stored into the destination of
1312 // this store.
1313 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1314 continue;
1315
1316 // If the index is dependent on the store we will introduce a cycle when
1317 // creating the load (the load uses the index, and by replacing the chain
1318 // we will make the index dependent on the load). Also, the store might be
1319 // dependent on the extractelement and introduce a cycle when creating
1320 // the load.
1321 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1322 ST->hasPredecessor(Op.getNode()))
1323 continue;
1324
1325 StackPtr = ST->getBasePtr();
1326 Ch = SDValue(ST, 0);
1327 break;
1328 }
1329 }
1330
1331 EVT VecVT = Vec.getValueType();
1332
1333 if (!Ch.getNode()) {
1334 // Store the value to a temporary stack slot, then LOAD the returned part.
1335 StackPtr = DAG.CreateStackTemporary(VecVT);
1336 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1337 MachinePointerInfo());
1338 }
1339
1340 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1341
1342 SDValue NewLoad;
1343
1344 if (Op.getValueType().isVector())
1345 NewLoad =
1346 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
1347 else
1348 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1349 MachinePointerInfo(),
1350 VecVT.getVectorElementType());
1351
1352 // Replace the chain going out of the store, by the one out of the load.
1353 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1354
1355 // We introduced a cycle though, so update the loads operands, making sure
1356 // to use the original store's chain as an incoming chain.
1357 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1358 NewLoad->op_end());
1359 NewLoadOperands[0] = Ch;
1360 NewLoad =
1361 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1362 return NewLoad;
1363 }
1364
ExpandInsertToVectorThroughStack(SDValue Op)1365 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1366 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1367
1368 SDValue Vec = Op.getOperand(0);
1369 SDValue Part = Op.getOperand(1);
1370 SDValue Idx = Op.getOperand(2);
1371 SDLoc dl(Op);
1372
1373 // Store the value to a temporary stack slot, then LOAD the returned part.
1374 EVT VecVT = Vec.getValueType();
1375 SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1376 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1377 MachinePointerInfo PtrInfo =
1378 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1379
1380 // First store the whole vector.
1381 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1382
1383 // Then store the inserted part.
1384 SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1385
1386 // Store the subvector.
1387 Ch = DAG.getStore(
1388 Ch, dl, Part, SubStackPtr,
1389 MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1390
1391 // Finally, load the updated vector.
1392 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
1393 }
1394
ExpandVectorBuildThroughStack(SDNode * Node)1395 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1396 assert((Node->getOpcode() == ISD::BUILD_VECTOR ||
1397 Node->getOpcode() == ISD::CONCAT_VECTORS) &&
1398 "Unexpected opcode!");
1399
1400 // We can't handle this case efficiently. Allocate a sufficiently
1401 // aligned object on the stack, store each operand into it, then load
1402 // the result as a vector.
1403 // Create the stack frame object.
1404 EVT VT = Node->getValueType(0);
1405 EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType()
1406 : Node->getOperand(0).getValueType();
1407 SDLoc dl(Node);
1408 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1409 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1410 MachinePointerInfo PtrInfo =
1411 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1412
1413 // Emit a store of each element to the stack slot.
1414 SmallVector<SDValue, 8> Stores;
1415 unsigned TypeByteSize = MemVT.getSizeInBits() / 8;
1416 assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1417 // Store (in the right endianness) the elements to memory.
1418 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1419 // Ignore undef elements.
1420 if (Node->getOperand(i).isUndef()) continue;
1421
1422 unsigned Offset = TypeByteSize*i;
1423
1424 SDValue Idx = DAG.getMemBasePlusOffset(FIPtr, Offset, dl);
1425
1426 // If the destination vector element type is narrower than the source
1427 // element type, only store the bits necessary.
1428 if (MemVT.bitsLT(Node->getOperand(i).getValueType()))
1429 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1430 Node->getOperand(i), Idx,
1431 PtrInfo.getWithOffset(Offset), MemVT));
1432 else
1433 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1434 Idx, PtrInfo.getWithOffset(Offset)));
1435 }
1436
1437 SDValue StoreChain;
1438 if (!Stores.empty()) // Not all undef elements?
1439 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1440 else
1441 StoreChain = DAG.getEntryNode();
1442
1443 // Result is a load from the stack slot.
1444 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1445 }
1446
1447 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1448 /// containing the sign bit if the target has no integer value capable of
1449 /// holding all bits of the floating-point value.
getSignAsIntValue(FloatSignAsInt & State,const SDLoc & DL,SDValue Value) const1450 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1451 const SDLoc &DL,
1452 SDValue Value) const {
1453 EVT FloatVT = Value.getValueType();
1454 unsigned NumBits = FloatVT.getSizeInBits();
1455 State.FloatVT = FloatVT;
1456 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1457 // Convert to an integer of the same size.
1458 if (TLI.isTypeLegal(IVT)) {
1459 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1460 State.SignMask = APInt::getSignMask(NumBits);
1461 State.SignBit = NumBits - 1;
1462 return;
1463 }
1464
1465 auto &DataLayout = DAG.getDataLayout();
1466 // Store the float to memory, then load the sign part out as an integer.
1467 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1468 // First create a temporary that is aligned for both the load and store.
1469 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1470 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1471 // Then store the float to it.
1472 State.FloatPtr = StackPtr;
1473 MachineFunction &MF = DAG.getMachineFunction();
1474 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1475 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1476 State.FloatPointerInfo);
1477
1478 SDValue IntPtr;
1479 if (DataLayout.isBigEndian()) {
1480 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1481 // Load out a legal integer with the same sign bit as the float.
1482 IntPtr = StackPtr;
1483 State.IntPointerInfo = State.FloatPointerInfo;
1484 } else {
1485 // Advance the pointer so that the loaded byte will contain the sign bit.
1486 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1;
1487 IntPtr = DAG.getMemBasePlusOffset(StackPtr, ByteOffset, DL);
1488 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1489 ByteOffset);
1490 }
1491
1492 State.IntPtr = IntPtr;
1493 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1494 State.IntPointerInfo, MVT::i8);
1495 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7);
1496 State.SignBit = 7;
1497 }
1498
1499 /// Replace the integer value produced by getSignAsIntValue() with a new value
1500 /// and cast the result back to a floating-point type.
modifySignAsInt(const FloatSignAsInt & State,const SDLoc & DL,SDValue NewIntValue) const1501 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1502 const SDLoc &DL,
1503 SDValue NewIntValue) const {
1504 if (!State.Chain)
1505 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1506
1507 // Override the part containing the sign bit in the value stored on the stack.
1508 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1509 State.IntPointerInfo, MVT::i8);
1510 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1511 State.FloatPointerInfo);
1512 }
1513
ExpandFCOPYSIGN(SDNode * Node) const1514 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1515 SDLoc DL(Node);
1516 SDValue Mag = Node->getOperand(0);
1517 SDValue Sign = Node->getOperand(1);
1518
1519 // Get sign bit into an integer value.
1520 FloatSignAsInt SignAsInt;
1521 getSignAsIntValue(SignAsInt, DL, Sign);
1522
1523 EVT IntVT = SignAsInt.IntValue.getValueType();
1524 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1525 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1526 SignMask);
1527
1528 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1529 EVT FloatVT = Mag.getValueType();
1530 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1531 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1532 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1533 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1534 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1535 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1536 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1537 }
1538
1539 // Transform Mag value to integer, and clear the sign bit.
1540 FloatSignAsInt MagAsInt;
1541 getSignAsIntValue(MagAsInt, DL, Mag);
1542 EVT MagVT = MagAsInt.IntValue.getValueType();
1543 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1544 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1545 ClearSignMask);
1546
1547 // Get the signbit at the right position for MagAsInt.
1548 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1549 EVT ShiftVT = IntVT;
1550 if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) {
1551 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1552 ShiftVT = MagVT;
1553 }
1554 if (ShiftAmount > 0) {
1555 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1556 SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1557 } else if (ShiftAmount < 0) {
1558 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1559 SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1560 }
1561 if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) {
1562 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1563 }
1564
1565 // Store the part with the modified sign and convert back to float.
1566 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
1567 return modifySignAsInt(MagAsInt, DL, CopiedSign);
1568 }
1569
ExpandFABS(SDNode * Node) const1570 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1571 SDLoc DL(Node);
1572 SDValue Value = Node->getOperand(0);
1573
1574 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1575 EVT FloatVT = Value.getValueType();
1576 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1577 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1578 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1579 }
1580
1581 // Transform value to integer, clear the sign bit and transform back.
1582 FloatSignAsInt ValueAsInt;
1583 getSignAsIntValue(ValueAsInt, DL, Value);
1584 EVT IntVT = ValueAsInt.IntValue.getValueType();
1585 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1586 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1587 ClearSignMask);
1588 return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1589 }
1590
ExpandDYNAMIC_STACKALLOC(SDNode * Node,SmallVectorImpl<SDValue> & Results)1591 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1592 SmallVectorImpl<SDValue> &Results) {
1593 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1594 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1595 " not tell us which reg is the stack pointer!");
1596 SDLoc dl(Node);
1597 EVT VT = Node->getValueType(0);
1598 SDValue Tmp1 = SDValue(Node, 0);
1599 SDValue Tmp2 = SDValue(Node, 1);
1600 SDValue Tmp3 = Node->getOperand(2);
1601 SDValue Chain = Tmp1.getOperand(0);
1602
1603 // Chain the dynamic stack allocation so that it doesn't modify the stack
1604 // pointer when other instructions are using the stack.
1605 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1606
1607 SDValue Size = Tmp2.getOperand(1);
1608 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1609 Chain = SP.getValue(1);
1610 Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue();
1611 const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering();
1612 unsigned Opc =
1613 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
1614 ISD::ADD : ISD::SUB;
1615
1616 Align StackAlign = TFL->getStackAlign();
1617 if (VT.isFatPointer()) {
1618 EVT SizeVT = Size.getValueType();
1619 SDValue GetAddr =
1620 DAG.getTargetConstant(Intrinsic::cheri_cap_address_get, dl, SizeVT);
1621 SDValue SetAddr =
1622 DAG.getTargetConstant(Intrinsic::cheri_cap_address_set, dl, SizeVT);
1623 SDValue CRRL =
1624 DAG.getTargetConstant(Intrinsic::cheri_round_representable_length, dl,
1625 SizeVT);
1626 SDValue CRAM =
1627 DAG.getTargetConstant(Intrinsic::cheri_representable_alignment_mask, dl,
1628 SizeVT);
1629
1630 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, SizeVT, GetAddr, SP);
1631
1632 if (TLI.cheriCapabilityTypeHasPreciseBounds()) {
1633 Tmp2 = Size;
1634 Tmp3 = DAG.getConstant(-Alignment.value(), dl, SizeVT);
1635 } else {
1636 Tmp2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, SizeVT, CRRL, Size);
1637 Tmp3 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, SizeVT, CRAM, Size);
1638 }
1639
1640 Tmp1 = DAG.getNode(Opc, dl, SizeVT, Tmp1, Tmp2);
1641 if (Alignment > StackAlign || !TLI.cheriCapabilityTypeHasPreciseBounds())
1642 Tmp1 = DAG.getNode(ISD::AND, dl, SizeVT, Tmp1, Tmp3);
1643
1644 Tmp1 =
1645 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, SetAddr, SP, Tmp1);
1646 // Move the stack pointer *before* setting the bounds!
1647 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1648 Tmp1 = DAG.getCSetBounds(
1649 Tmp1, dl, Tmp2,
1650 Alignment,
1651 "ExpandDYNAMIC_STACKALLOC", cheri::SetBoundsPointerSource::Stack);
1652 } else {
1653 Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size); // Value
1654 if (Alignment > StackAlign)
1655 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1656 DAG.getConstant(-Alignment.value(), dl, VT));
1657 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1658 }
1659
1660 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1661 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1662
1663 Results.push_back(Tmp1);
1664 Results.push_back(Tmp2);
1665 }
1666
1667 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
1668 /// target.
1669 ///
1670 /// If the SETCC has been legalized using AND / OR, then the legalized node
1671 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1672 /// will be set to false.
1673 ///
1674 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1675 /// then the values of LHS and RHS will be swapped, CC will be set to the
1676 /// new condition, and NeedInvert will be set to false.
1677 ///
1678 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1679 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1680 /// will be set to true. The caller must invert the result of the SETCC with
1681 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1682 /// of a true/false result.
1683 ///
1684 /// \returns true if the SetCC has been legalized, false if it hasn't.
LegalizeSetCCCondCode(EVT VT,SDValue & LHS,SDValue & RHS,SDValue & CC,bool & NeedInvert,const SDLoc & dl,SDValue & Chain,bool IsSignaling)1685 bool SelectionDAGLegalize::LegalizeSetCCCondCode(
1686 EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, bool &NeedInvert,
1687 const SDLoc &dl, SDValue &Chain, bool IsSignaling) {
1688 MVT OpVT = LHS.getSimpleValueType();
1689 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1690 NeedInvert = false;
1691 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1692 default: llvm_unreachable("Unknown condition code action!");
1693 case TargetLowering::Legal:
1694 // Nothing to do.
1695 break;
1696 case TargetLowering::Expand: {
1697 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1698 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1699 std::swap(LHS, RHS);
1700 CC = DAG.getCondCode(InvCC);
1701 return true;
1702 }
1703 // Swapping operands didn't work. Try inverting the condition.
1704 bool NeedSwap = false;
1705 InvCC = getSetCCInverse(CCCode, OpVT);
1706 if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1707 // If inverting the condition is not enough, try swapping operands
1708 // on top of it.
1709 InvCC = ISD::getSetCCSwappedOperands(InvCC);
1710 NeedSwap = true;
1711 }
1712 if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1713 CC = DAG.getCondCode(InvCC);
1714 NeedInvert = true;
1715 if (NeedSwap)
1716 std::swap(LHS, RHS);
1717 return true;
1718 }
1719
1720 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1721 unsigned Opc = 0;
1722 switch (CCCode) {
1723 default: llvm_unreachable("Don't know how to expand this condition!");
1724 case ISD::SETO:
1725 assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT)
1726 && "If SETO is expanded, SETOEQ must be legal!");
1727 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1728 case ISD::SETUO:
1729 assert(TLI.isCondCodeLegal(ISD::SETUNE, OpVT)
1730 && "If SETUO is expanded, SETUNE must be legal!");
1731 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1732 case ISD::SETOEQ:
1733 case ISD::SETOGT:
1734 case ISD::SETOGE:
1735 case ISD::SETOLT:
1736 case ISD::SETOLE:
1737 case ISD::SETONE:
1738 case ISD::SETUEQ:
1739 case ISD::SETUNE:
1740 case ISD::SETUGT:
1741 case ISD::SETUGE:
1742 case ISD::SETULT:
1743 case ISD::SETULE:
1744 // If we are floating point, assign and break, otherwise fall through.
1745 if (!OpVT.isInteger()) {
1746 // We can use the 4th bit to tell if we are the unordered
1747 // or ordered version of the opcode.
1748 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1749 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1750 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1751 break;
1752 }
1753 // Fallthrough if we are unsigned integer.
1754 LLVM_FALLTHROUGH;
1755 case ISD::SETLE:
1756 case ISD::SETGT:
1757 case ISD::SETGE:
1758 case ISD::SETLT:
1759 case ISD::SETNE:
1760 case ISD::SETEQ:
1761 // If all combinations of inverting the condition and swapping operands
1762 // didn't work then we have no means to expand the condition.
1763 llvm_unreachable("Don't know how to expand this condition!");
1764 }
1765
1766 SDValue SetCC1, SetCC2;
1767 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1768 // If we aren't the ordered or unorder operation,
1769 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1770 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
1771 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
1772 } else {
1773 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1774 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
1775 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
1776 }
1777 if (Chain)
1778 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
1779 SetCC2.getValue(1));
1780 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1781 RHS = SDValue();
1782 CC = SDValue();
1783 return true;
1784 }
1785 }
1786 return false;
1787 }
1788
1789 /// Emit a store/load combination to the stack. This stores
1790 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1791 /// a load from the stack slot to DestVT, extending it if needed.
1792 /// The resultant code need not be legal.
EmitStackConvert(SDValue SrcOp,EVT SlotVT,EVT DestVT,const SDLoc & dl)1793 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1794 EVT DestVT, const SDLoc &dl) {
1795 return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1796 }
1797
EmitStackConvert(SDValue SrcOp,EVT SlotVT,EVT DestVT,const SDLoc & dl,SDValue Chain)1798 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1799 EVT DestVT, const SDLoc &dl,
1800 SDValue Chain) {
1801 // Create the stack frame object.
1802 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
1803 SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1804 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1805
1806 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1807 int SPFI = StackPtrFI->getIndex();
1808 MachinePointerInfo PtrInfo =
1809 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1810
1811 unsigned SrcSize = SrcOp.getValueSizeInBits();
1812 unsigned SlotSize = SlotVT.getSizeInBits();
1813 unsigned DestSize = DestVT.getSizeInBits();
1814 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1815 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
1816
1817 // Emit a store to the stack slot. Use a truncstore if the input value is
1818 // later than DestVT.
1819 SDValue Store;
1820
1821 if (SrcSize > SlotSize)
1822 Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
1823 SlotVT, SrcAlign);
1824 else {
1825 assert(SrcSize == SlotSize && "Invalid store");
1826 Store =
1827 DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1828 }
1829
1830 // Result is a load from the stack slot.
1831 if (SlotSize == DestSize)
1832 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1833
1834 assert(SlotSize < DestSize && "Unknown extension!");
1835 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1836 DestAlign);
1837 }
1838
ExpandSCALAR_TO_VECTOR(SDNode * Node)1839 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1840 SDLoc dl(Node);
1841 // Create a vector sized/aligned stack slot, store the value to element #0,
1842 // then load the whole vector back out.
1843 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1844
1845 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1846 int SPFI = StackPtrFI->getIndex();
1847
1848 SDValue Ch = DAG.getTruncStore(
1849 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1850 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1851 Node->getValueType(0).getVectorElementType());
1852 return DAG.getLoad(
1853 Node->getValueType(0), dl, Ch, StackPtr,
1854 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
1855 }
1856
1857 static bool
ExpandBVWithShuffles(SDNode * Node,SelectionDAG & DAG,const TargetLowering & TLI,SDValue & Res)1858 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1859 const TargetLowering &TLI, SDValue &Res) {
1860 unsigned NumElems = Node->getNumOperands();
1861 SDLoc dl(Node);
1862 EVT VT = Node->getValueType(0);
1863
1864 // Try to group the scalars into pairs, shuffle the pairs together, then
1865 // shuffle the pairs of pairs together, etc. until the vector has
1866 // been built. This will work only if all of the necessary shuffle masks
1867 // are legal.
1868
1869 // We do this in two phases; first to check the legality of the shuffles,
1870 // and next, assuming that all shuffles are legal, to create the new nodes.
1871 for (int Phase = 0; Phase < 2; ++Phase) {
1872 SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals,
1873 NewIntermedVals;
1874 for (unsigned i = 0; i < NumElems; ++i) {
1875 SDValue V = Node->getOperand(i);
1876 if (V.isUndef())
1877 continue;
1878
1879 SDValue Vec;
1880 if (Phase)
1881 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1882 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1883 }
1884
1885 while (IntermedVals.size() > 2) {
1886 NewIntermedVals.clear();
1887 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1888 // This vector and the next vector are shuffled together (simply to
1889 // append the one to the other).
1890 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1891
1892 SmallVector<int, 16> FinalIndices;
1893 FinalIndices.reserve(IntermedVals[i].second.size() +
1894 IntermedVals[i+1].second.size());
1895
1896 int k = 0;
1897 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1898 ++j, ++k) {
1899 ShuffleVec[k] = j;
1900 FinalIndices.push_back(IntermedVals[i].second[j]);
1901 }
1902 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1903 ++j, ++k) {
1904 ShuffleVec[k] = NumElems + j;
1905 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1906 }
1907
1908 SDValue Shuffle;
1909 if (Phase)
1910 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1911 IntermedVals[i+1].first,
1912 ShuffleVec);
1913 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1914 return false;
1915 NewIntermedVals.push_back(
1916 std::make_pair(Shuffle, std::move(FinalIndices)));
1917 }
1918
1919 // If we had an odd number of defined values, then append the last
1920 // element to the array of new vectors.
1921 if ((IntermedVals.size() & 1) != 0)
1922 NewIntermedVals.push_back(IntermedVals.back());
1923
1924 IntermedVals.swap(NewIntermedVals);
1925 }
1926
1927 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1928 "Invalid number of intermediate vectors");
1929 SDValue Vec1 = IntermedVals[0].first;
1930 SDValue Vec2;
1931 if (IntermedVals.size() > 1)
1932 Vec2 = IntermedVals[1].first;
1933 else if (Phase)
1934 Vec2 = DAG.getUNDEF(VT);
1935
1936 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1937 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1938 ShuffleVec[IntermedVals[0].second[i]] = i;
1939 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1940 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1941
1942 if (Phase)
1943 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1944 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1945 return false;
1946 }
1947
1948 return true;
1949 }
1950
1951 /// Expand a BUILD_VECTOR node on targets that don't
1952 /// support the operation, but do support the resultant vector type.
ExpandBUILD_VECTOR(SDNode * Node)1953 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1954 unsigned NumElems = Node->getNumOperands();
1955 SDValue Value1, Value2;
1956 SDLoc dl(Node);
1957 EVT VT = Node->getValueType(0);
1958 EVT OpVT = Node->getOperand(0).getValueType();
1959 EVT EltVT = VT.getVectorElementType();
1960
1961 // If the only non-undef value is the low element, turn this into a
1962 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1963 bool isOnlyLowElement = true;
1964 bool MoreThanTwoValues = false;
1965 bool isConstant = true;
1966 for (unsigned i = 0; i < NumElems; ++i) {
1967 SDValue V = Node->getOperand(i);
1968 if (V.isUndef())
1969 continue;
1970 if (i > 0)
1971 isOnlyLowElement = false;
1972 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1973 isConstant = false;
1974
1975 if (!Value1.getNode()) {
1976 Value1 = V;
1977 } else if (!Value2.getNode()) {
1978 if (V != Value1)
1979 Value2 = V;
1980 } else if (V != Value1 && V != Value2) {
1981 MoreThanTwoValues = true;
1982 }
1983 }
1984
1985 if (!Value1.getNode())
1986 return DAG.getUNDEF(VT);
1987
1988 if (isOnlyLowElement)
1989 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1990
1991 // If all elements are constants, create a load from the constant pool.
1992 if (isConstant) {
1993 SmallVector<Constant*, 16> CV;
1994 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1995 if (ConstantFPSDNode *V =
1996 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1997 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1998 } else if (ConstantSDNode *V =
1999 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2000 if (OpVT==EltVT)
2001 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2002 else {
2003 // If OpVT and EltVT don't match, EltVT is not legal and the
2004 // element values have been promoted/truncated earlier. Undo this;
2005 // we don't want a v16i8 to become a v16i32 for example.
2006 const ConstantInt *CI = V->getConstantIntValue();
2007 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2008 CI->getZExtValue()));
2009 }
2010 } else {
2011 assert(Node->getOperand(i).isUndef());
2012 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2013 CV.push_back(UndefValue::get(OpNTy));
2014 }
2015 }
2016 Constant *CP = ConstantVector::get(CV);
2017 SDValue CPIdx = DAG.getConstantPool(
2018 CP, TLI.getPointerTy(DAG.getDataLayout(),
2019 DAG.getDataLayout().getGlobalsAddressSpace()));
2020 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
2021 return DAG.getLoad(
2022 VT, dl, DAG.getEntryNode(), CPIdx,
2023 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2024 Alignment);
2025 }
2026
2027 SmallSet<SDValue, 16> DefinedValues;
2028 for (unsigned i = 0; i < NumElems; ++i) {
2029 if (Node->getOperand(i).isUndef())
2030 continue;
2031 DefinedValues.insert(Node->getOperand(i));
2032 }
2033
2034 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
2035 if (!MoreThanTwoValues) {
2036 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2037 for (unsigned i = 0; i < NumElems; ++i) {
2038 SDValue V = Node->getOperand(i);
2039 if (V.isUndef())
2040 continue;
2041 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2042 }
2043 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2044 // Get the splatted value into the low element of a vector register.
2045 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2046 SDValue Vec2;
2047 if (Value2.getNode())
2048 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2049 else
2050 Vec2 = DAG.getUNDEF(VT);
2051
2052 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2053 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
2054 }
2055 } else {
2056 SDValue Res;
2057 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2058 return Res;
2059 }
2060 }
2061
2062 // Otherwise, we can't handle this case efficiently.
2063 return ExpandVectorBuildThroughStack(Node);
2064 }
2065
ExpandSPLAT_VECTOR(SDNode * Node)2066 SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) {
2067 SDLoc DL(Node);
2068 EVT VT = Node->getValueType(0);
2069 SDValue SplatVal = Node->getOperand(0);
2070
2071 return DAG.getSplatBuildVector(VT, DL, SplatVal);
2072 }
2073
2074 // Expand a node into a call to a libcall. If the result value
2075 // does not fit into a register, return the lo part and set the hi part to the
2076 // by-reg argument. If it does fit into a single register, return the result
2077 // and leave the Hi part unset.
ExpandLibCall(RTLIB::Libcall LC,SDNode * Node,bool isSigned)2078 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2079 bool isSigned) {
2080 TargetLowering::ArgListTy Args;
2081 TargetLowering::ArgListEntry Entry;
2082 for (const SDValue &Op : Node->op_values()) {
2083 EVT ArgVT = Op.getValueType();
2084 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2085 Entry.Node = Op;
2086 Entry.Ty = ArgTy;
2087 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2088 Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2089 Args.push_back(Entry);
2090 }
2091 SDValue Callee = DAG.getExternalFunctionSymbol(TLI.getLibcallName(LC));
2092
2093 EVT RetVT = Node->getValueType(0);
2094 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2095
2096 // By default, the input chain to this libcall is the entry node of the
2097 // function. If the libcall is going to be emitted as a tail call then
2098 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2099 // node which is being folded has a non-entry input chain.
2100 SDValue InChain = DAG.getEntryNode();
2101
2102 // isTailCall may be true since the callee does not reference caller stack
2103 // frame. Check if it's in the right position and that the return types match.
2104 SDValue TCChain = InChain;
2105 const Function &F = DAG.getMachineFunction().getFunction();
2106 bool isTailCall =
2107 TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2108 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
2109 if (isTailCall)
2110 InChain = TCChain;
2111
2112 TargetLowering::CallLoweringInfo CLI(DAG);
2113 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
2114 CLI.setDebugLoc(SDLoc(Node))
2115 .setChain(InChain)
2116 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2117 std::move(Args))
2118 .setTailCall(isTailCall)
2119 .setSExtResult(signExtend)
2120 .setZExtResult(!signExtend)
2121 .setIsPostTypeLegalization(true);
2122
2123 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2124
2125 if (!CallInfo.second.getNode()) {
2126 LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
2127 // It's a tailcall, return the chain (which is the DAG root).
2128 return DAG.getRoot();
2129 }
2130
2131 LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
2132 return CallInfo.first;
2133 }
2134
ExpandFPLibCall(SDNode * Node,RTLIB::Libcall Call_F32,RTLIB::Libcall Call_F64,RTLIB::Libcall Call_F80,RTLIB::Libcall Call_F128,RTLIB::Libcall Call_PPCF128,SmallVectorImpl<SDValue> & Results)2135 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2136 RTLIB::Libcall Call_F32,
2137 RTLIB::Libcall Call_F64,
2138 RTLIB::Libcall Call_F80,
2139 RTLIB::Libcall Call_F128,
2140 RTLIB::Libcall Call_PPCF128,
2141 SmallVectorImpl<SDValue> &Results) {
2142 RTLIB::Libcall LC;
2143 switch (Node->getSimpleValueType(0).SimpleTy) {
2144 default: llvm_unreachable("Unexpected request for libcall!");
2145 case MVT::f32: LC = Call_F32; break;
2146 case MVT::f64: LC = Call_F64; break;
2147 case MVT::f80: LC = Call_F80; break;
2148 case MVT::f128: LC = Call_F128; break;
2149 case MVT::ppcf128: LC = Call_PPCF128; break;
2150 }
2151
2152 if (Node->isStrictFPOpcode()) {
2153 EVT RetVT = Node->getValueType(0);
2154 SmallVector<SDValue, 4> Ops(Node->op_begin() + 1, Node->op_end());
2155 TargetLowering::MakeLibCallOptions CallOptions;
2156 // FIXME: This doesn't support tail calls.
2157 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
2158 Ops, CallOptions,
2159 SDLoc(Node),
2160 Node->getOperand(0));
2161 Results.push_back(Tmp.first);
2162 Results.push_back(Tmp.second);
2163 } else {
2164 SDValue Tmp = ExpandLibCall(LC, Node, false);
2165 Results.push_back(Tmp);
2166 }
2167 }
2168
ExpandIntLibCall(SDNode * Node,bool isSigned,RTLIB::Libcall Call_I8,RTLIB::Libcall Call_I16,RTLIB::Libcall Call_I32,RTLIB::Libcall Call_I64,RTLIB::Libcall Call_I128)2169 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2170 RTLIB::Libcall Call_I8,
2171 RTLIB::Libcall Call_I16,
2172 RTLIB::Libcall Call_I32,
2173 RTLIB::Libcall Call_I64,
2174 RTLIB::Libcall Call_I128) {
2175 RTLIB::Libcall LC;
2176 switch (Node->getSimpleValueType(0).SimpleTy) {
2177 default: llvm_unreachable("Unexpected request for libcall!");
2178 case MVT::i8: LC = Call_I8; break;
2179 case MVT::i16: LC = Call_I16; break;
2180 case MVT::i32: LC = Call_I32; break;
2181 case MVT::i64: LC = Call_I64; break;
2182 case MVT::i128: LC = Call_I128; break;
2183 }
2184 return ExpandLibCall(LC, Node, isSigned);
2185 }
2186
2187 /// Expand the node to a libcall based on first argument type (for instance
2188 /// lround and its variant).
ExpandArgFPLibCall(SDNode * Node,RTLIB::Libcall Call_F32,RTLIB::Libcall Call_F64,RTLIB::Libcall Call_F80,RTLIB::Libcall Call_F128,RTLIB::Libcall Call_PPCF128,SmallVectorImpl<SDValue> & Results)2189 void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2190 RTLIB::Libcall Call_F32,
2191 RTLIB::Libcall Call_F64,
2192 RTLIB::Libcall Call_F80,
2193 RTLIB::Libcall Call_F128,
2194 RTLIB::Libcall Call_PPCF128,
2195 SmallVectorImpl<SDValue> &Results) {
2196 EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType();
2197
2198 RTLIB::Libcall LC;
2199 switch (InVT.getSimpleVT().SimpleTy) {
2200 default: llvm_unreachable("Unexpected request for libcall!");
2201 case MVT::f32: LC = Call_F32; break;
2202 case MVT::f64: LC = Call_F64; break;
2203 case MVT::f80: LC = Call_F80; break;
2204 case MVT::f128: LC = Call_F128; break;
2205 case MVT::ppcf128: LC = Call_PPCF128; break;
2206 }
2207
2208 if (Node->isStrictFPOpcode()) {
2209 EVT RetVT = Node->getValueType(0);
2210 SmallVector<SDValue, 4> Ops(Node->op_begin() + 1, Node->op_end());
2211 TargetLowering::MakeLibCallOptions CallOptions;
2212 // FIXME: This doesn't support tail calls.
2213 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
2214 Ops, CallOptions,
2215 SDLoc(Node),
2216 Node->getOperand(0));
2217 Results.push_back(Tmp.first);
2218 Results.push_back(Tmp.second);
2219 } else {
2220 SDValue Tmp = ExpandLibCall(LC, Node, false);
2221 Results.push_back(Tmp);
2222 }
2223 }
2224
2225 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2226 void
ExpandDivRemLibCall(SDNode * Node,SmallVectorImpl<SDValue> & Results)2227 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2228 SmallVectorImpl<SDValue> &Results) {
2229 unsigned Opcode = Node->getOpcode();
2230 bool isSigned = Opcode == ISD::SDIVREM;
2231
2232 RTLIB::Libcall LC;
2233 switch (Node->getSimpleValueType(0).SimpleTy) {
2234 default: llvm_unreachable("Unexpected request for libcall!");
2235 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2236 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2237 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2238 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2239 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2240 }
2241
2242 // The input chain to this libcall is the entry node of the function.
2243 // Legalizing the call will automatically add the previous call to the
2244 // dependence.
2245 SDValue InChain = DAG.getEntryNode();
2246
2247 EVT RetVT = Node->getValueType(0);
2248 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2249
2250 TargetLowering::ArgListTy Args;
2251 TargetLowering::ArgListEntry Entry;
2252 for (const SDValue &Op : Node->op_values()) {
2253 EVT ArgVT = Op.getValueType();
2254 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2255 Entry.Node = Op;
2256 Entry.Ty = ArgTy;
2257 Entry.IsSExt = isSigned;
2258 Entry.IsZExt = !isSigned;
2259 Args.push_back(Entry);
2260 }
2261
2262 // Also pass the return address of the remainder.
2263 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2264 Entry.Node = FIPtr;
2265 Entry.Ty = RetTy->getPointerTo();
2266 Entry.IsSExt = isSigned;
2267 Entry.IsZExt = !isSigned;
2268 Args.push_back(Entry);
2269
2270 SDValue Callee = DAG.getExternalFunctionSymbol(TLI.getLibcallName(LC));
2271
2272 SDLoc dl(Node);
2273 TargetLowering::CallLoweringInfo CLI(DAG);
2274 CLI.setDebugLoc(dl)
2275 .setChain(InChain)
2276 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2277 std::move(Args))
2278 .setSExtResult(isSigned)
2279 .setZExtResult(!isSigned);
2280
2281 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2282
2283 // Remainder is loaded back from the stack frame.
2284 SDValue Rem =
2285 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
2286 Results.push_back(CallInfo.first);
2287 Results.push_back(Rem);
2288 }
2289
2290 /// Return true if sincos libcall is available.
isSinCosLibcallAvailable(SDNode * Node,const TargetLowering & TLI)2291 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2292 RTLIB::Libcall LC;
2293 switch (Node->getSimpleValueType(0).SimpleTy) {
2294 default: llvm_unreachable("Unexpected request for libcall!");
2295 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2296 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2297 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2298 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2299 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2300 }
2301 return TLI.getLibcallName(LC) != nullptr;
2302 }
2303
2304 /// Only issue sincos libcall if both sin and cos are needed.
useSinCos(SDNode * Node)2305 static bool useSinCos(SDNode *Node) {
2306 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2307 ? ISD::FCOS : ISD::FSIN;
2308
2309 SDValue Op0 = Node->getOperand(0);
2310 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2311 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2312 SDNode *User = *UI;
2313 if (User == Node)
2314 continue;
2315 // The other user might have been turned into sincos already.
2316 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2317 return true;
2318 }
2319 return false;
2320 }
2321
2322 /// Issue libcalls to sincos to compute sin / cos pairs.
2323 void
ExpandSinCosLibCall(SDNode * Node,SmallVectorImpl<SDValue> & Results)2324 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2325 SmallVectorImpl<SDValue> &Results) {
2326 RTLIB::Libcall LC;
2327 switch (Node->getSimpleValueType(0).SimpleTy) {
2328 default: llvm_unreachable("Unexpected request for libcall!");
2329 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2330 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2331 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2332 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2333 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2334 }
2335
2336 // The input chain to this libcall is the entry node of the function.
2337 // Legalizing the call will automatically add the previous call to the
2338 // dependence.
2339 SDValue InChain = DAG.getEntryNode();
2340
2341 EVT RetVT = Node->getValueType(0);
2342 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2343
2344 TargetLowering::ArgListTy Args;
2345 TargetLowering::ArgListEntry Entry;
2346
2347 // Pass the argument.
2348 Entry.Node = Node->getOperand(0);
2349 Entry.Ty = RetTy;
2350 Entry.IsSExt = false;
2351 Entry.IsZExt = false;
2352 Args.push_back(Entry);
2353
2354 // Pass the return address of sin.
2355 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2356 Entry.Node = SinPtr;
2357 Entry.Ty = RetTy->getPointerTo();
2358 Entry.IsSExt = false;
2359 Entry.IsZExt = false;
2360 Args.push_back(Entry);
2361
2362 // Also pass the return address of the cos.
2363 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2364 Entry.Node = CosPtr;
2365 Entry.Ty = RetTy->getPointerTo();
2366 Entry.IsSExt = false;
2367 Entry.IsZExt = false;
2368 Args.push_back(Entry);
2369
2370 SDValue Callee = DAG.getExternalFunctionSymbol(TLI.getLibcallName(LC));
2371
2372 SDLoc dl(Node);
2373 TargetLowering::CallLoweringInfo CLI(DAG);
2374 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
2375 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
2376 std::move(Args));
2377
2378 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2379
2380 Results.push_back(
2381 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
2382 Results.push_back(
2383 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
2384 }
2385
2386 /// This function is responsible for legalizing a
2387 /// INT_TO_FP operation of the specified operand when the target requests that
2388 /// we expand it. At this point, we know that the result and operand types are
2389 /// legal for the target.
ExpandLegalINT_TO_FP(SDNode * Node,SDValue & Chain)2390 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node,
2391 SDValue &Chain) {
2392 bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
2393 Node->getOpcode() == ISD::SINT_TO_FP);
2394 EVT DestVT = Node->getValueType(0);
2395 SDLoc dl(Node);
2396 unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
2397 SDValue Op0 = Node->getOperand(OpNo);
2398 EVT SrcVT = Op0.getValueType();
2399
2400 // TODO: Should any fast-math-flags be set for the created nodes?
2401 LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2402 if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2403 LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2404 "expansion\n");
2405
2406 // Get the stack frame index of a 8 byte buffer.
2407 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2408
2409 SDValue Lo = Op0;
2410 // if signed map to unsigned space
2411 if (isSigned) {
2412 // Invert sign bit (signed to unsigned mapping).
2413 Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo,
2414 DAG.getConstant(0x80000000u, dl, MVT::i32));
2415 }
2416 // Initial hi portion of constructed double.
2417 SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2418
2419 // If this a big endian target, swap the lo and high data.
2420 if (DAG.getDataLayout().isBigEndian())
2421 std::swap(Lo, Hi);
2422
2423 SDValue MemChain = DAG.getEntryNode();
2424
2425 // Store the lo of the constructed double.
2426 SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot,
2427 MachinePointerInfo());
2428 // Store the hi of the constructed double.
2429 SDValue HiPtr = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
2430 SDValue Store2 =
2431 DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo());
2432 MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
2433
2434 // load the constructed double
2435 SDValue Load =
2436 DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo());
2437 // FP constant to bias correct the final result
2438 SDValue Bias = DAG.getConstantFP(isSigned ?
2439 BitsToDouble(0x4330000080000000ULL) :
2440 BitsToDouble(0x4330000000000000ULL),
2441 dl, MVT::f64);
2442 // Subtract the bias and get the final result.
2443 SDValue Sub;
2444 SDValue Result;
2445 if (Node->isStrictFPOpcode()) {
2446 Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
2447 {Node->getOperand(0), Load, Bias});
2448 Chain = Sub.getValue(1);
2449 if (DestVT != Sub.getValueType()) {
2450 std::pair<SDValue, SDValue> ResultPair;
2451 ResultPair =
2452 DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT);
2453 Result = ResultPair.first;
2454 Chain = ResultPair.second;
2455 }
2456 else
2457 Result = Sub;
2458 } else {
2459 Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2460 Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2461 }
2462 return Result;
2463 }
2464 // Code below here assumes !isSigned without checking again.
2465 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2466
2467 // TODO: Generalize this for use with other types.
2468 if ((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) {
2469 LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32\n");
2470 // For unsigned conversions, convert them to signed conversions using the
2471 // algorithm from the x86_64 __floatundisf in compiler_rt. That method
2472 // should be valid for i32->f32 as well.
2473
2474 // TODO: This really should be implemented using a branch rather than a
2475 // select. We happen to get lucky and machinesink does the right
2476 // thing most of the time. This would be a good candidate for a
2477 // pseudo-op, or, even better, for whole-function isel.
2478 EVT SetCCVT = getSetCCResultType(SrcVT);
2479
2480 SDValue SignBitTest = DAG.getSetCC(
2481 dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2482
2483 EVT ShiftVT = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
2484 SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
2485 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst);
2486 SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
2487 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst);
2488 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
2489
2490 SDValue Slow, Fast;
2491 if (Node->isStrictFPOpcode()) {
2492 // In strict mode, we must avoid spurious exceptions, and therefore
2493 // must make sure to only emit a single STRICT_SINT_TO_FP.
2494 SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0);
2495 Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2496 { Node->getOperand(0), InCvt });
2497 Slow = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
2498 { Fast.getValue(1), Fast, Fast });
2499 Chain = Slow.getValue(1);
2500 // The STRICT_SINT_TO_FP inherits the exception mode from the
2501 // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can
2502 // never raise any exception.
2503 SDNodeFlags Flags;
2504 Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept());
2505 Fast->setFlags(Flags);
2506 Flags.setNoFPExcept(true);
2507 Slow->setFlags(Flags);
2508 } else {
2509 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or);
2510 Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt);
2511 Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2512 }
2513
2514 return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast);
2515 }
2516
2517 // The following optimization is valid only if every value in SrcVT (when
2518 // treated as signed) is representable in DestVT. Check that the mantissa
2519 // size of DestVT is >= than the number of bits in SrcVT -1.
2520 assert(APFloat::semanticsPrecision(DAG.EVTToAPFloatSemantics(DestVT)) >=
2521 SrcVT.getSizeInBits() - 1 &&
2522 "Cannot perform lossless SINT_TO_FP!");
2523
2524 SDValue Tmp1;
2525 if (Node->isStrictFPOpcode()) {
2526 Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2527 { Node->getOperand(0), Op0 });
2528 } else
2529 Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2530
2531 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2532 DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2533 SDValue Zero = DAG.getIntPtrConstant(0, dl),
2534 Four = DAG.getIntPtrConstant(4, dl);
2535 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2536 SignSet, Four, Zero);
2537
2538 // If the sign bit of the integer is set, the large number will be treated
2539 // as a negative number. To counteract this, the dynamic code adds an
2540 // offset depending on the data type.
2541 uint64_t FF;
2542 switch (SrcVT.getSimpleVT().SimpleTy) {
2543 default: llvm_unreachable("Unsupported integer type!");
2544 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2545 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2546 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2547 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2548 }
2549 if (DAG.getDataLayout().isLittleEndian())
2550 FF <<= 32;
2551 Constant *FudgeFactor = ConstantInt::get(
2552 Type::getInt64Ty(*DAG.getContext()), FF);
2553
2554 SDValue CPIdx = DAG.getConstantPool(
2555 FudgeFactor,
2556 TLI.getPointerTy(DAG.getDataLayout(),
2557 DAG.getDataLayout().getGlobalsAddressSpace()));
2558 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
2559 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2560 Alignment = commonAlignment(Alignment, 4);
2561 SDValue FudgeInReg;
2562 if (DestVT == MVT::f32)
2563 FudgeInReg = DAG.getLoad(
2564 MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2565 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2566 Alignment);
2567 else {
2568 SDValue Load = DAG.getExtLoad(
2569 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2570 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2571 Alignment);
2572 HandleSDNode Handle(Load);
2573 LegalizeOp(Load.getNode());
2574 FudgeInReg = Handle.getValue();
2575 }
2576
2577 if (Node->isStrictFPOpcode()) {
2578 SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
2579 { Tmp1.getValue(1), Tmp1, FudgeInReg });
2580 Chain = Result.getValue(1);
2581 return Result;
2582 }
2583
2584 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2585 }
2586
2587 /// This function is responsible for legalizing a
2588 /// *INT_TO_FP operation of the specified operand when the target requests that
2589 /// we promote it. At this point, we know that the result and operand types are
2590 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2591 /// operation that takes a larger input.
PromoteLegalINT_TO_FP(SDNode * N,const SDLoc & dl,SmallVectorImpl<SDValue> & Results)2592 void SelectionDAGLegalize::PromoteLegalINT_TO_FP(
2593 SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) {
2594 bool IsStrict = N->isStrictFPOpcode();
2595 bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
2596 N->getOpcode() == ISD::STRICT_SINT_TO_FP;
2597 EVT DestVT = N->getValueType(0);
2598 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
2599 unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP;
2600 unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP;
2601
2602 // First step, figure out the appropriate *INT_TO_FP operation to use.
2603 EVT NewInTy = LegalOp.getValueType();
2604
2605 unsigned OpToUse = 0;
2606
2607 // Scan for the appropriate larger type to use.
2608 while (true) {
2609 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2610 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2611
2612 // If the target supports SINT_TO_FP of this type, use it.
2613 if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) {
2614 OpToUse = SIntOp;
2615 break;
2616 }
2617 if (IsSigned)
2618 continue;
2619
2620 // If the target supports UINT_TO_FP of this type, use it.
2621 if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) {
2622 OpToUse = UIntOp;
2623 break;
2624 }
2625
2626 // Otherwise, try a larger type.
2627 }
2628
2629 // Okay, we found the operation and type to use. Zero extend our input to the
2630 // desired type then run the operation on it.
2631 if (IsStrict) {
2632 SDValue Res =
2633 DAG.getNode(OpToUse, dl, {DestVT, MVT::Other},
2634 {N->getOperand(0),
2635 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2636 dl, NewInTy, LegalOp)});
2637 Results.push_back(Res);
2638 Results.push_back(Res.getValue(1));
2639 return;
2640 }
2641
2642 Results.push_back(
2643 DAG.getNode(OpToUse, dl, DestVT,
2644 DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2645 dl, NewInTy, LegalOp)));
2646 }
2647
2648 /// This function is responsible for legalizing a
2649 /// FP_TO_*INT operation of the specified operand when the target requests that
2650 /// we promote it. At this point, we know that the result and operand types are
2651 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2652 /// operation that returns a larger result.
PromoteLegalFP_TO_INT(SDNode * N,const SDLoc & dl,SmallVectorImpl<SDValue> & Results)2653 void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
2654 SmallVectorImpl<SDValue> &Results) {
2655 bool IsStrict = N->isStrictFPOpcode();
2656 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
2657 N->getOpcode() == ISD::STRICT_FP_TO_SINT;
2658 EVT DestVT = N->getValueType(0);
2659 SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
2660 // First step, figure out the appropriate FP_TO*INT operation to use.
2661 EVT NewOutTy = DestVT;
2662
2663 unsigned OpToUse = 0;
2664
2665 // Scan for the appropriate larger type to use.
2666 while (true) {
2667 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2668 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2669
2670 // A larger signed type can hold all unsigned values of the requested type,
2671 // so using FP_TO_SINT is valid
2672 OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT;
2673 if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
2674 break;
2675
2676 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2677 OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT;
2678 if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
2679 break;
2680
2681 // Otherwise, try a larger type.
2682 }
2683
2684 // Okay, we found the operation and type to use.
2685 SDValue Operation;
2686 if (IsStrict) {
2687 SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other);
2688 Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp);
2689 } else
2690 Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2691
2692 // Truncate the result of the extended FP_TO_*INT operation to the desired
2693 // size.
2694 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2695 Results.push_back(Trunc);
2696 if (IsStrict)
2697 Results.push_back(Operation.getValue(1));
2698 }
2699
2700 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts.
ExpandBITREVERSE(SDValue Op,const SDLoc & dl)2701 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) {
2702 EVT VT = Op.getValueType();
2703 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2704 unsigned Sz = VT.getScalarSizeInBits();
2705
2706 SDValue Tmp, Tmp2, Tmp3;
2707
2708 // If we can, perform BSWAP first and then the mask+swap the i4, then i2
2709 // and finally the i1 pairs.
2710 // TODO: We can easily support i4/i2 legal types if any target ever does.
2711 if (Sz >= 8 && isPowerOf2_32(Sz)) {
2712 // Create the masks - repeating the pattern every byte.
2713 APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0));
2714 APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC));
2715 APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA));
2716 APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F));
2717 APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33));
2718 APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55));
2719
2720 // BSWAP if the type is wider than a single byte.
2721 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
2722
2723 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4)
2724 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT));
2725 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT));
2726 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT));
2727 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
2728 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2729
2730 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2)
2731 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT));
2732 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT));
2733 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT));
2734 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
2735 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2736
2737 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1)
2738 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT));
2739 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT));
2740 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT));
2741 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
2742 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2743 return Tmp;
2744 }
2745
2746 Tmp = DAG.getConstant(0, dl, VT);
2747 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
2748 if (I < J)
2749 Tmp2 =
2750 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
2751 else
2752 Tmp2 =
2753 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
2754
2755 APInt Shift(Sz, 1);
2756 Shift <<= J;
2757 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
2758 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
2759 }
2760
2761 return Tmp;
2762 }
2763
2764 /// Open code the operations for BSWAP of the specified operation.
ExpandBSWAP(SDValue Op,const SDLoc & dl)2765 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) {
2766 EVT VT = Op.getValueType();
2767 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2768 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2769 switch (VT.getSimpleVT().getScalarType().SimpleTy) {
2770 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2771 case MVT::i16:
2772 // Use a rotate by 8. This can be further expanded if necessary.
2773 return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2774 case MVT::i32:
2775 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2776 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2777 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2778 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2779 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2780 DAG.getConstant(0xFF0000, dl, VT));
2781 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
2782 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2783 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2784 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2785 case MVT::i64:
2786 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2787 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2788 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2789 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2790 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2791 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2792 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2793 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2794 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
2795 DAG.getConstant(255ULL<<48, dl, VT));
2796 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
2797 DAG.getConstant(255ULL<<40, dl, VT));
2798 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
2799 DAG.getConstant(255ULL<<32, dl, VT));
2800 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
2801 DAG.getConstant(255ULL<<24, dl, VT));
2802 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2803 DAG.getConstant(255ULL<<16, dl, VT));
2804 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
2805 DAG.getConstant(255ULL<<8 , dl, VT));
2806 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2807 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2808 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2809 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2810 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2811 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2812 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2813 }
2814 }
2815
ExpandNode(SDNode * Node)2816 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2817 LLVM_DEBUG(dbgs() << "Trying to expand node\n");
2818 SmallVector<SDValue, 8> Results;
2819 SDLoc dl(Node);
2820 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2821 bool NeedInvert;
2822 switch (Node->getOpcode()) {
2823 case ISD::ABS:
2824 if (TLI.expandABS(Node, Tmp1, DAG))
2825 Results.push_back(Tmp1);
2826 break;
2827 case ISD::CTPOP:
2828 if (TLI.expandCTPOP(Node, Tmp1, DAG))
2829 Results.push_back(Tmp1);
2830 break;
2831 case ISD::CTLZ:
2832 case ISD::CTLZ_ZERO_UNDEF:
2833 if (TLI.expandCTLZ(Node, Tmp1, DAG))
2834 Results.push_back(Tmp1);
2835 break;
2836 case ISD::CTTZ:
2837 case ISD::CTTZ_ZERO_UNDEF:
2838 if (TLI.expandCTTZ(Node, Tmp1, DAG))
2839 Results.push_back(Tmp1);
2840 break;
2841 case ISD::BITREVERSE:
2842 Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl));
2843 break;
2844 case ISD::BSWAP:
2845 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2846 break;
2847 case ISD::FRAMEADDR:
2848 case ISD::RETURNADDR:
2849 case ISD::FRAME_TO_ARGS_OFFSET:
2850 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2851 break;
2852 case ISD::EH_DWARF_CFA: {
2853 unsigned DwarfAS = 0; // FIXME: is this correct?
2854 SDValue CfaArg =
2855 DAG.getSExtOrTrunc(Node->getOperand(0), dl,
2856 TLI.getPointerTy(DAG.getDataLayout(), DwarfAS));
2857 SDValue Offset = DAG.getNode(ISD::ADD, dl,
2858 CfaArg.getValueType(),
2859 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
2860 CfaArg.getValueType()),
2861 CfaArg);
2862 SDValue FA = DAG.getNode(
2863 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout(), DwarfAS),
2864 DAG.getConstant(0, dl, TLI.getPointerRangeTy(DAG.getDataLayout())));
2865 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
2866 FA, Offset));
2867 break;
2868 }
2869 case ISD::FLT_ROUNDS_:
2870 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2871 Results.push_back(Node->getOperand(0));
2872 break;
2873 case ISD::EH_RETURN:
2874 case ISD::EH_LABEL:
2875 case ISD::PREFETCH:
2876 case ISD::VAEND:
2877 case ISD::EH_SJLJ_LONGJMP:
2878 // If the target didn't expand these, there's nothing to do, so just
2879 // preserve the chain and be done.
2880 Results.push_back(Node->getOperand(0));
2881 break;
2882 case ISD::READCYCLECOUNTER:
2883 // If the target didn't expand this, just return 'zero' and preserve the
2884 // chain.
2885 Results.append(Node->getNumValues() - 1,
2886 DAG.getConstant(0, dl, Node->getValueType(0)));
2887 Results.push_back(Node->getOperand(0));
2888 break;
2889 case ISD::EH_SJLJ_SETJMP:
2890 // If the target didn't expand this, just return 'zero' and preserve the
2891 // chain.
2892 Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2893 Results.push_back(Node->getOperand(0));
2894 break;
2895 case ISD::ATOMIC_LOAD: {
2896 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2897 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2898 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2899 SDValue Swap = DAG.getAtomicCmpSwap(
2900 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2901 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2902 cast<AtomicSDNode>(Node)->getMemOperand());
2903 Results.push_back(Swap.getValue(0));
2904 Results.push_back(Swap.getValue(1));
2905 break;
2906 }
2907 case ISD::ATOMIC_STORE: {
2908 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2909 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2910 cast<AtomicSDNode>(Node)->getMemoryVT(),
2911 Node->getOperand(0),
2912 Node->getOperand(1), Node->getOperand(2),
2913 cast<AtomicSDNode>(Node)->getMemOperand());
2914 Results.push_back(Swap.getValue(1));
2915 break;
2916 }
2917 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
2918 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
2919 // splits out the success value as a comparison. Expanding the resulting
2920 // ATOMIC_CMP_SWAP will produce a libcall.
2921 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2922 SDValue Res = DAG.getAtomicCmpSwap(
2923 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2924 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
2925 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
2926
2927 SDValue ExtRes = Res;
2928 SDValue LHS = Res;
2929 SDValue RHS = Node->getOperand(2);
2930
2931 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2932 EVT OuterType = Node->getValueType(0);
2933 // XXXAR: Sign/Zero extending fat pointers doesn't make sense -> skip this
2934 if (!OuterType.isFatPointer()) {
2935 // XXXAR: not indented correctly to avoid merge conflicts
2936 switch (TLI.getExtendForAtomicOps()) {
2937 case ISD::SIGN_EXTEND:
2938 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2939 DAG.getValueType(AtomicType));
2940 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2941 Node->getOperand(2), DAG.getValueType(AtomicType));
2942 ExtRes = LHS;
2943 break;
2944 case ISD::ZERO_EXTEND:
2945 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2946 DAG.getValueType(AtomicType));
2947 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2948 ExtRes = LHS;
2949 break;
2950 case ISD::ANY_EXTEND:
2951 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2952 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2953 break;
2954 default:
2955 llvm_unreachable("Invalid atomic op extension");
2956 }
2957 }
2958
2959 SDValue Success =
2960 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2961
2962 Results.push_back(ExtRes.getValue(0));
2963 Results.push_back(Success);
2964 Results.push_back(Res.getValue(1));
2965 break;
2966 }
2967 case ISD::DYNAMIC_STACKALLOC:
2968 ExpandDYNAMIC_STACKALLOC(Node, Results);
2969 break;
2970 case ISD::MERGE_VALUES:
2971 for (unsigned i = 0; i < Node->getNumValues(); i++)
2972 Results.push_back(Node->getOperand(i));
2973 break;
2974 case ISD::UNDEF: {
2975 EVT VT = Node->getValueType(0);
2976 if (VT.isInteger())
2977 Results.push_back(DAG.getConstant(0, dl, VT));
2978 else {
2979 assert(VT.isFloatingPoint() && "Unknown value type!");
2980 Results.push_back(DAG.getConstantFP(0, dl, VT));
2981 }
2982 break;
2983 }
2984 case ISD::STRICT_FP_ROUND:
2985 // When strict mode is enforced we can't do expansion because it
2986 // does not honor the "strict" properties. Only libcall is allowed.
2987 if (TLI.isStrictFPEnabled())
2988 break;
2989 // We might as well mutate to FP_ROUND when FP_ROUND operation is legal
2990 // since this operation is more efficient than stack operation.
2991 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2992 Node->getValueType(0))
2993 == TargetLowering::Legal)
2994 break;
2995 // We fall back to use stack operation when the FP_ROUND operation
2996 // isn't available.
2997 Tmp1 = EmitStackConvert(Node->getOperand(1),
2998 Node->getValueType(0),
2999 Node->getValueType(0), dl, Node->getOperand(0));
3000 ReplaceNode(Node, Tmp1.getNode());
3001 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
3002 return true;
3003 case ISD::FP_ROUND:
3004 case ISD::BITCAST:
3005 Tmp1 = EmitStackConvert(Node->getOperand(0),
3006 Node->getValueType(0),
3007 Node->getValueType(0), dl);
3008 Results.push_back(Tmp1);
3009 break;
3010 case ISD::STRICT_FP_EXTEND:
3011 // When strict mode is enforced we can't do expansion because it
3012 // does not honor the "strict" properties. Only libcall is allowed.
3013 if (TLI.isStrictFPEnabled())
3014 break;
3015 // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal
3016 // since this operation is more efficient than stack operation.
3017 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3018 Node->getValueType(0))
3019 == TargetLowering::Legal)
3020 break;
3021 // We fall back to use stack operation when the FP_EXTEND operation
3022 // isn't available.
3023 Tmp1 = EmitStackConvert(Node->getOperand(1),
3024 Node->getOperand(1).getValueType(),
3025 Node->getValueType(0), dl, Node->getOperand(0));
3026 ReplaceNode(Node, Tmp1.getNode());
3027 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
3028 return true;
3029 case ISD::FP_EXTEND:
3030 Tmp1 = EmitStackConvert(Node->getOperand(0),
3031 Node->getOperand(0).getValueType(),
3032 Node->getValueType(0), dl);
3033 Results.push_back(Tmp1);
3034 break;
3035 case ISD::SIGN_EXTEND_INREG: {
3036 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3037 EVT VT = Node->getValueType(0);
3038
3039 // An in-register sign-extend of a boolean is a negation:
3040 // 'true' (1) sign-extended is -1.
3041 // 'false' (0) sign-extended is 0.
3042 // However, we must mask the high bits of the source operand because the
3043 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
3044
3045 // TODO: Do this for vectors too?
3046 if (ExtraVT.getSizeInBits() == 1) {
3047 SDValue One = DAG.getConstant(1, dl, VT);
3048 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
3049 SDValue Zero = DAG.getConstant(0, dl, VT);
3050 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
3051 Results.push_back(Neg);
3052 break;
3053 }
3054
3055 // NOTE: we could fall back on load/store here too for targets without
3056 // SRA. However, it is doubtful that any exist.
3057 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3058 unsigned BitsDiff = VT.getScalarSizeInBits() -
3059 ExtraVT.getScalarSizeInBits();
3060 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
3061 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3062 Node->getOperand(0), ShiftCst);
3063 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3064 Results.push_back(Tmp1);
3065 break;
3066 }
3067 case ISD::UINT_TO_FP:
3068 case ISD::STRICT_UINT_TO_FP:
3069 if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) {
3070 Results.push_back(Tmp1);
3071 if (Node->isStrictFPOpcode())
3072 Results.push_back(Tmp2);
3073 break;
3074 }
3075 LLVM_FALLTHROUGH;
3076 case ISD::SINT_TO_FP:
3077 case ISD::STRICT_SINT_TO_FP:
3078 Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2);
3079 Results.push_back(Tmp1);
3080 if (Node->isStrictFPOpcode())
3081 Results.push_back(Tmp2);
3082 break;
3083 case ISD::FP_TO_SINT:
3084 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3085 Results.push_back(Tmp1);
3086 break;
3087 case ISD::STRICT_FP_TO_SINT:
3088 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
3089 ReplaceNode(Node, Tmp1.getNode());
3090 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
3091 return true;
3092 }
3093 break;
3094 case ISD::FP_TO_UINT:
3095 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
3096 Results.push_back(Tmp1);
3097 break;
3098 case ISD::STRICT_FP_TO_UINT:
3099 if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
3100 // Relink the chain.
3101 DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
3102 // Replace the new UINT result.
3103 ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
3104 LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
3105 return true;
3106 }
3107 break;
3108 case ISD::VAARG:
3109 Results.push_back(DAG.expandVAArg(Node));
3110 Results.push_back(Results[0].getValue(1));
3111 break;
3112 case ISD::VACOPY:
3113 Results.push_back(DAG.expandVACopy(Node));
3114 break;
3115 case ISD::EXTRACT_VECTOR_ELT:
3116 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3117 // This must be an access of the only element. Return it.
3118 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3119 Node->getOperand(0));
3120 else
3121 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3122 Results.push_back(Tmp1);
3123 break;
3124 case ISD::EXTRACT_SUBVECTOR:
3125 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3126 break;
3127 case ISD::INSERT_SUBVECTOR:
3128 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3129 break;
3130 case ISD::CONCAT_VECTORS:
3131 Results.push_back(ExpandVectorBuildThroughStack(Node));
3132 break;
3133 case ISD::SCALAR_TO_VECTOR:
3134 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3135 break;
3136 case ISD::INSERT_VECTOR_ELT:
3137 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3138 Node->getOperand(1),
3139 Node->getOperand(2), dl));
3140 break;
3141 case ISD::VECTOR_SHUFFLE: {
3142 SmallVector<int, 32> NewMask;
3143 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3144
3145 EVT VT = Node->getValueType(0);
3146 EVT EltVT = VT.getVectorElementType();
3147 SDValue Op0 = Node->getOperand(0);
3148 SDValue Op1 = Node->getOperand(1);
3149 if (!TLI.isTypeLegal(EltVT)) {
3150 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3151
3152 // BUILD_VECTOR operands are allowed to be wider than the element type.
3153 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3154 // it.
3155 if (NewEltVT.bitsLT(EltVT)) {
3156 // Convert shuffle node.
3157 // If original node was v4i64 and the new EltVT is i32,
3158 // cast operands to v8i32 and re-build the mask.
3159
3160 // Calculate new VT, the size of the new VT should be equal to original.
3161 EVT NewVT =
3162 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3163 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3164 assert(NewVT.bitsEq(VT));
3165
3166 // cast operands to new VT
3167 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3168 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3169
3170 // Convert the shuffle mask
3171 unsigned int factor =
3172 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3173
3174 // EltVT gets smaller
3175 assert(factor > 0);
3176
3177 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3178 if (Mask[i] < 0) {
3179 for (unsigned fi = 0; fi < factor; ++fi)
3180 NewMask.push_back(Mask[i]);
3181 }
3182 else {
3183 for (unsigned fi = 0; fi < factor; ++fi)
3184 NewMask.push_back(Mask[i]*factor+fi);
3185 }
3186 }
3187 Mask = NewMask;
3188 VT = NewVT;
3189 }
3190 EltVT = NewEltVT;
3191 }
3192 unsigned NumElems = VT.getVectorNumElements();
3193 SmallVector<SDValue, 16> Ops;
3194 for (unsigned i = 0; i != NumElems; ++i) {
3195 if (Mask[i] < 0) {
3196 Ops.push_back(DAG.getUNDEF(EltVT));
3197 continue;
3198 }
3199 unsigned Idx = Mask[i];
3200 if (Idx < NumElems)
3201 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3202 DAG.getVectorIdxConstant(Idx, dl)));
3203 else
3204 Ops.push_back(
3205 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3206 DAG.getVectorIdxConstant(Idx - NumElems, dl)));
3207 }
3208
3209 Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3210 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3211 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3212 Results.push_back(Tmp1);
3213 break;
3214 }
3215 case ISD::EXTRACT_ELEMENT: {
3216 EVT OpTy = Node->getOperand(0).getValueType();
3217 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3218 // 1 -> Hi
3219 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3220 DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3221 TLI.getShiftAmountTy(
3222 Node->getOperand(0).getValueType(),
3223 DAG.getDataLayout())));
3224 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3225 } else {
3226 // 0 -> Lo
3227 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3228 Node->getOperand(0));
3229 }
3230 Results.push_back(Tmp1);
3231 break;
3232 }
3233 case ISD::STACKSAVE:
3234 // Expand to CopyFromReg if the target set
3235 // StackPointerRegisterToSaveRestore.
3236 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3237 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3238 Node->getValueType(0)));
3239 Results.push_back(Results[0].getValue(1));
3240 } else {
3241 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3242 Results.push_back(Node->getOperand(0));
3243 }
3244 break;
3245 case ISD::STACKRESTORE:
3246 // Expand to CopyToReg if the target set
3247 // StackPointerRegisterToSaveRestore.
3248 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3249 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3250 Node->getOperand(1)));
3251 } else {
3252 Results.push_back(Node->getOperand(0));
3253 }
3254 break;
3255 case ISD::GET_DYNAMIC_AREA_OFFSET:
3256 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3257 Results.push_back(Results[0].getValue(0));
3258 break;
3259 case ISD::FCOPYSIGN:
3260 Results.push_back(ExpandFCOPYSIGN(Node));
3261 break;
3262 case ISD::FNEG:
3263 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3264 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3265 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3266 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3267 Node->getOperand(0));
3268 Results.push_back(Tmp1);
3269 break;
3270 case ISD::FABS:
3271 Results.push_back(ExpandFABS(Node));
3272 break;
3273 case ISD::SMIN:
3274 case ISD::SMAX:
3275 case ISD::UMIN:
3276 case ISD::UMAX: {
3277 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3278 ISD::CondCode Pred;
3279 switch (Node->getOpcode()) {
3280 default: llvm_unreachable("How did we get here?");
3281 case ISD::SMAX: Pred = ISD::SETGT; break;
3282 case ISD::SMIN: Pred = ISD::SETLT; break;
3283 case ISD::UMAX: Pred = ISD::SETUGT; break;
3284 case ISD::UMIN: Pred = ISD::SETULT; break;
3285 }
3286 Tmp1 = Node->getOperand(0);
3287 Tmp2 = Node->getOperand(1);
3288 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3289 Results.push_back(Tmp1);
3290 break;
3291 }
3292 case ISD::FMINNUM:
3293 case ISD::FMAXNUM: {
3294 if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3295 Results.push_back(Expanded);
3296 break;
3297 }
3298 case ISD::FSIN:
3299 case ISD::FCOS: {
3300 EVT VT = Node->getValueType(0);
3301 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3302 // fcos which share the same operand and both are used.
3303 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3304 isSinCosLibcallAvailable(Node, TLI))
3305 && useSinCos(Node)) {
3306 SDVTList VTs = DAG.getVTList(VT, VT);
3307 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3308 if (Node->getOpcode() == ISD::FCOS)
3309 Tmp1 = Tmp1.getValue(1);
3310 Results.push_back(Tmp1);
3311 }
3312 break;
3313 }
3314 case ISD::FMAD:
3315 llvm_unreachable("Illegal fmad should never be formed");
3316
3317 case ISD::FP16_TO_FP:
3318 if (Node->getValueType(0) != MVT::f32) {
3319 // We can extend to types bigger than f32 in two steps without changing
3320 // the result. Since "f16 -> f32" is much more commonly available, give
3321 // CodeGen the option of emitting that before resorting to a libcall.
3322 SDValue Res =
3323 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3324 Results.push_back(
3325 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3326 }
3327 break;
3328 case ISD::STRICT_FP16_TO_FP:
3329 if (Node->getValueType(0) != MVT::f32) {
3330 // We can extend to types bigger than f32 in two steps without changing
3331 // the result. Since "f16 -> f32" is much more commonly available, give
3332 // CodeGen the option of emitting that before resorting to a libcall.
3333 SDValue Res =
3334 DAG.getNode(ISD::STRICT_FP16_TO_FP, dl, {MVT::f32, MVT::Other},
3335 {Node->getOperand(0), Node->getOperand(1)});
3336 Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
3337 {Node->getValueType(0), MVT::Other},
3338 {Res.getValue(1), Res});
3339 Results.push_back(Res);
3340 Results.push_back(Res.getValue(1));
3341 }
3342 break;
3343 case ISD::FP_TO_FP16:
3344 LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
3345 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3346 SDValue Op = Node->getOperand(0);
3347 MVT SVT = Op.getSimpleValueType();
3348 if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3349 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3350 // Under fastmath, we can expand this node into a fround followed by
3351 // a float-half conversion.
3352 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3353 DAG.getIntPtrConstant(0, dl));
3354 Results.push_back(
3355 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3356 }
3357 }
3358 break;
3359 case ISD::ConstantFP: {
3360 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3361 // Check to see if this FP immediate is already legal.
3362 // If this is a legal constant, turn it into a TargetConstantFP node.
3363 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
3364 DAG.getMachineFunction().getFunction().hasOptSize()))
3365 Results.push_back(ExpandConstantFP(CFP, true));
3366 break;
3367 }
3368 case ISD::Constant: {
3369 ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3370 Results.push_back(ExpandConstant(CP));
3371 break;
3372 }
3373 case ISD::FSUB: {
3374 EVT VT = Node->getValueType(0);
3375 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3376 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3377 const SDNodeFlags Flags = Node->getFlags();
3378 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3379 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3380 Results.push_back(Tmp1);
3381 }
3382 break;
3383 }
3384 case ISD::SUB: {
3385 EVT VT = Node->getValueType(0);
3386 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3387 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3388 "Don't know how to expand this subtraction!");
3389 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3390 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3391 VT));
3392 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3393 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3394 break;
3395 }
3396 case ISD::UREM:
3397 case ISD::SREM:
3398 if (TLI.expandREM(Node, Tmp1, DAG))
3399 Results.push_back(Tmp1);
3400 break;
3401 case ISD::UDIV:
3402 case ISD::SDIV: {
3403 bool isSigned = Node->getOpcode() == ISD::SDIV;
3404 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3405 EVT VT = Node->getValueType(0);
3406 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3407 SDVTList VTs = DAG.getVTList(VT, VT);
3408 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3409 Node->getOperand(1));
3410 Results.push_back(Tmp1);
3411 }
3412 break;
3413 }
3414 case ISD::MULHU:
3415 case ISD::MULHS: {
3416 unsigned ExpandOpcode =
3417 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
3418 EVT VT = Node->getValueType(0);
3419 SDVTList VTs = DAG.getVTList(VT, VT);
3420
3421 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3422 Node->getOperand(1));
3423 Results.push_back(Tmp1.getValue(1));
3424 break;
3425 }
3426 case ISD::UMUL_LOHI:
3427 case ISD::SMUL_LOHI: {
3428 SDValue LHS = Node->getOperand(0);
3429 SDValue RHS = Node->getOperand(1);
3430 MVT VT = LHS.getSimpleValueType();
3431 unsigned MULHOpcode =
3432 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS;
3433
3434 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
3435 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
3436 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
3437 break;
3438 }
3439
3440 SmallVector<SDValue, 4> Halves;
3441 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
3442 assert(TLI.isTypeLegal(HalfType));
3443 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves,
3444 HalfType, DAG,
3445 TargetLowering::MulExpansionKind::Always)) {
3446 for (unsigned i = 0; i < 2; ++i) {
3447 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
3448 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
3449 SDValue Shift = DAG.getConstant(
3450 HalfType.getScalarSizeInBits(), dl,
3451 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3452 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3453 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3454 }
3455 break;
3456 }
3457 break;
3458 }
3459 case ISD::MUL: {
3460 EVT VT = Node->getValueType(0);
3461 SDVTList VTs = DAG.getVTList(VT, VT);
3462 // See if multiply or divide can be lowered using two-result operations.
3463 // We just need the low half of the multiply; try both the signed
3464 // and unsigned forms. If the target supports both SMUL_LOHI and
3465 // UMUL_LOHI, form a preference by checking which forms of plain
3466 // MULH it supports.
3467 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3468 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3469 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3470 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3471 unsigned OpToUse = 0;
3472 if (HasSMUL_LOHI && !HasMULHS) {
3473 OpToUse = ISD::SMUL_LOHI;
3474 } else if (HasUMUL_LOHI && !HasMULHU) {
3475 OpToUse = ISD::UMUL_LOHI;
3476 } else if (HasSMUL_LOHI) {
3477 OpToUse = ISD::SMUL_LOHI;
3478 } else if (HasUMUL_LOHI) {
3479 OpToUse = ISD::UMUL_LOHI;
3480 }
3481 if (OpToUse) {
3482 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3483 Node->getOperand(1)));
3484 break;
3485 }
3486
3487 SDValue Lo, Hi;
3488 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3489 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3490 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3491 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3492 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3493 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
3494 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
3495 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3496 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3497 SDValue Shift =
3498 DAG.getConstant(HalfType.getSizeInBits(), dl,
3499 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3500 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3501 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3502 }
3503 break;
3504 }
3505 case ISD::FSHL:
3506 case ISD::FSHR:
3507 if (TLI.expandFunnelShift(Node, Tmp1, DAG))
3508 Results.push_back(Tmp1);
3509 break;
3510 case ISD::ROTL:
3511 case ISD::ROTR:
3512 if (TLI.expandROT(Node, Tmp1, DAG))
3513 Results.push_back(Tmp1);
3514 break;
3515 case ISD::SADDSAT:
3516 case ISD::UADDSAT:
3517 case ISD::SSUBSAT:
3518 case ISD::USUBSAT:
3519 Results.push_back(TLI.expandAddSubSat(Node, DAG));
3520 break;
3521 case ISD::SMULFIX:
3522 case ISD::SMULFIXSAT:
3523 case ISD::UMULFIX:
3524 case ISD::UMULFIXSAT:
3525 Results.push_back(TLI.expandFixedPointMul(Node, DAG));
3526 break;
3527 case ISD::SDIVFIX:
3528 case ISD::SDIVFIXSAT:
3529 case ISD::UDIVFIX:
3530 case ISD::UDIVFIXSAT:
3531 if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node),
3532 Node->getOperand(0),
3533 Node->getOperand(1),
3534 Node->getConstantOperandVal(2),
3535 DAG)) {
3536 Results.push_back(V);
3537 break;
3538 }
3539 // FIXME: We might want to retry here with a wider type if we fail, if that
3540 // type is legal.
3541 // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is
3542 // <= 128 (which is the case for all of the default Embedded-C types),
3543 // we will only get here with types and scales that we could always expand
3544 // if we were allowed to generate libcalls to division functions of illegal
3545 // type. But we cannot do that.
3546 llvm_unreachable("Cannot expand DIVFIX!");
3547 case ISD::ADDCARRY:
3548 case ISD::SUBCARRY: {
3549 SDValue LHS = Node->getOperand(0);
3550 SDValue RHS = Node->getOperand(1);
3551 SDValue Carry = Node->getOperand(2);
3552
3553 bool IsAdd = Node->getOpcode() == ISD::ADDCARRY;
3554
3555 // Initial add of the 2 operands.
3556 unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
3557 EVT VT = LHS.getValueType();
3558 SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
3559
3560 // Initial check for overflow.
3561 EVT CarryType = Node->getValueType(1);
3562 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3563 ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
3564 SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3565
3566 // Add of the sum and the carry.
3567 SDValue One = DAG.getConstant(1, dl, VT);
3568 SDValue CarryExt =
3569 DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One);
3570 SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
3571
3572 // Second check for overflow. If we are adding, we can only overflow if the
3573 // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
3574 // If we are subtracting, we can only overflow if the initial sum is 0 and
3575 // the carry is set, resulting in a new sum of all 1s.
3576 SDValue Zero = DAG.getConstant(0, dl, VT);
3577 SDValue Overflow2 =
3578 IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
3579 : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
3580 Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
3581 DAG.getZExtOrTrunc(Carry, dl, SetCCType));
3582
3583 SDValue ResultCarry =
3584 DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
3585
3586 Results.push_back(Sum2);
3587 Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
3588 break;
3589 }
3590 case ISD::SADDO:
3591 case ISD::SSUBO: {
3592 SDValue Result, Overflow;
3593 TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
3594 Results.push_back(Result);
3595 Results.push_back(Overflow);
3596 break;
3597 }
3598 case ISD::UADDO:
3599 case ISD::USUBO: {
3600 SDValue Result, Overflow;
3601 TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
3602 Results.push_back(Result);
3603 Results.push_back(Overflow);
3604 break;
3605 }
3606 case ISD::UMULO:
3607 case ISD::SMULO: {
3608 SDValue Result, Overflow;
3609 if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
3610 Results.push_back(Result);
3611 Results.push_back(Overflow);
3612 }
3613 break;
3614 }
3615 case ISD::BUILD_PAIR: {
3616 EVT PairTy = Node->getValueType(0);
3617 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3618 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3619 Tmp2 = DAG.getNode(
3620 ISD::SHL, dl, PairTy, Tmp2,
3621 DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3622 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3623 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3624 break;
3625 }
3626 case ISD::SELECT:
3627 Tmp1 = Node->getOperand(0);
3628 Tmp2 = Node->getOperand(1);
3629 Tmp3 = Node->getOperand(2);
3630 if (Tmp1.getOpcode() == ISD::SETCC) {
3631 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3632 Tmp2, Tmp3,
3633 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3634 } else {
3635 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3636 DAG.getConstant(0, dl, Tmp1.getValueType()),
3637 Tmp2, Tmp3, ISD::SETNE);
3638 }
3639 Tmp1->setFlags(Node->getFlags());
3640 Results.push_back(Tmp1);
3641 break;
3642 case ISD::BR_JT: {
3643 SDValue Chain = Node->getOperand(0);
3644 SDValue Table = Node->getOperand(1);
3645 SDValue Index = Node->getOperand(2);
3646 assert(Index.getValueType().isInteger());
3647
3648 const DataLayout &TD = DAG.getDataLayout();
3649 EVT PTy = TLI.getPointerRangeTy(TD);
3650
3651 unsigned EntrySize =
3652 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3653
3654 // For power-of-two jumptable entry sizes convert multiplication to a shift.
3655 // This transformation needs to be done here since otherwise the MIPS
3656 // backend will end up emitting a three instruction multiply sequence
3657 // instead of a single shift and MSP430 will call a runtime function.
3658 if (llvm::isPowerOf2_32(EntrySize))
3659 Index = DAG.getNode(
3660 ISD::SHL, dl, Index.getValueType(), Index,
3661 DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
3662 else
3663 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3664 DAG.getConstant(EntrySize, dl, Index.getValueType()));
3665 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3666 Index, Table);
3667
3668 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3669 SDValue LD = DAG.getExtLoad(
3670 ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3671 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
3672 Addr = LD;
3673 if (TLI.isJumpTableRelative()) {
3674 // For PIC, the sequence is:
3675 // BRIND(load(Jumptable + index) + RelocBase)
3676 // RelocBase can be JumpTable, GOT or some sort of global base.
3677 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3678 TLI.getPICJumpTableRelocBase(Table, DAG));
3679 }
3680
3681 Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG);
3682 Results.push_back(Tmp1);
3683 break;
3684 }
3685 case ISD::BRCOND:
3686 // Expand brcond's setcc into its constituent parts and create a BR_CC
3687 // Node.
3688 Tmp1 = Node->getOperand(0);
3689 Tmp2 = Node->getOperand(1);
3690 if (Tmp2.getOpcode() == ISD::SETCC) {
3691 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3692 Tmp1, Tmp2.getOperand(2),
3693 Tmp2.getOperand(0), Tmp2.getOperand(1),
3694 Node->getOperand(2));
3695 } else {
3696 // We test only the i1 bit. Skip the AND if UNDEF or another AND.
3697 if (Tmp2.isUndef() ||
3698 (Tmp2.getOpcode() == ISD::AND &&
3699 isa<ConstantSDNode>(Tmp2.getOperand(1)) &&
3700 cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1))
3701 Tmp3 = Tmp2;
3702 else
3703 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3704 DAG.getConstant(1, dl, Tmp2.getValueType()));
3705 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3706 DAG.getCondCode(ISD::SETNE), Tmp3,
3707 DAG.getConstant(0, dl, Tmp3.getValueType()),
3708 Node->getOperand(2));
3709 }
3710 Results.push_back(Tmp1);
3711 break;
3712 case ISD::SETCC:
3713 case ISD::STRICT_FSETCC:
3714 case ISD::STRICT_FSETCCS: {
3715 bool IsStrict = Node->getOpcode() != ISD::SETCC;
3716 bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS;
3717 SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
3718 unsigned Offset = IsStrict ? 1 : 0;
3719 Tmp1 = Node->getOperand(0 + Offset);
3720 Tmp2 = Node->getOperand(1 + Offset);
3721 Tmp3 = Node->getOperand(2 + Offset);
3722 bool Legalized =
3723 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3,
3724 NeedInvert, dl, Chain, IsSignaling);
3725
3726 if (Legalized) {
3727 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3728 // condition code, create a new SETCC node.
3729 if (Tmp3.getNode())
3730 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3731 Tmp1, Tmp2, Tmp3, Node->getFlags());
3732
3733 // If we expanded the SETCC by inverting the condition code, then wrap
3734 // the existing SETCC in a NOT to restore the intended condition.
3735 if (NeedInvert)
3736 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3737
3738 Results.push_back(Tmp1);
3739 if (IsStrict)
3740 Results.push_back(Chain);
3741
3742 break;
3743 }
3744
3745 // FIXME: It seems Legalized is false iff CCCode is Legal. I don't
3746 // understand if this code is useful for strict nodes.
3747 assert(!IsStrict && "Don't know how to expand for strict nodes.");
3748
3749 // Otherwise, SETCC for the given comparison type must be completely
3750 // illegal; expand it into a SELECT_CC.
3751 EVT VT = Node->getValueType(0);
3752 int TrueValue;
3753 switch (TLI.getBooleanContents(Tmp1.getValueType())) {
3754 case TargetLowering::ZeroOrOneBooleanContent:
3755 case TargetLowering::UndefinedBooleanContent:
3756 TrueValue = 1;
3757 break;
3758 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3759 TrueValue = -1;
3760 break;
3761 }
3762 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3763 DAG.getConstant(TrueValue, dl, VT),
3764 DAG.getConstant(0, dl, VT),
3765 Tmp3);
3766 Tmp1->setFlags(Node->getFlags());
3767 Results.push_back(Tmp1);
3768 break;
3769 }
3770 case ISD::SELECT_CC: {
3771 // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS
3772 Tmp1 = Node->getOperand(0); // LHS
3773 Tmp2 = Node->getOperand(1); // RHS
3774 Tmp3 = Node->getOperand(2); // True
3775 Tmp4 = Node->getOperand(3); // False
3776 EVT VT = Node->getValueType(0);
3777 SDValue Chain;
3778 SDValue CC = Node->getOperand(4);
3779 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3780
3781 if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
3782 // If the condition code is legal, then we need to expand this
3783 // node using SETCC and SELECT.
3784 EVT CmpVT = Tmp1.getValueType();
3785 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3786 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3787 "expanded.");
3788 EVT CCVT = getSetCCResultType(CmpVT);
3789 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
3790 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3791 break;
3792 }
3793
3794 // SELECT_CC is legal, so the condition code must not be.
3795 bool Legalized = false;
3796 // Try to legalize by inverting the condition. This is for targets that
3797 // might support an ordered version of a condition, but not the unordered
3798 // version (or vice versa).
3799 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType());
3800 if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
3801 // Use the new condition code and swap true and false
3802 Legalized = true;
3803 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3804 Tmp1->setFlags(Node->getFlags());
3805 } else {
3806 // If The inverse is not legal, then try to swap the arguments using
3807 // the inverse condition code.
3808 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3809 if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
3810 // The swapped inverse condition is legal, so swap true and false,
3811 // lhs and rhs.
3812 Legalized = true;
3813 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3814 Tmp1->setFlags(Node->getFlags());
3815 }
3816 }
3817
3818 if (!Legalized) {
3819 Legalized = LegalizeSetCCCondCode(getSetCCResultType(Tmp1.getValueType()),
3820 Tmp1, Tmp2, CC, NeedInvert, dl, Chain);
3821
3822 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3823
3824 // If we expanded the SETCC by inverting the condition code, then swap
3825 // the True/False operands to match.
3826 if (NeedInvert)
3827 std::swap(Tmp3, Tmp4);
3828
3829 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3830 // condition code, create a new SELECT_CC node.
3831 if (CC.getNode()) {
3832 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3833 Tmp1, Tmp2, Tmp3, Tmp4, CC);
3834 } else {
3835 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3836 CC = DAG.getCondCode(ISD::SETNE);
3837 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3838 Tmp2, Tmp3, Tmp4, CC);
3839 }
3840 Tmp1->setFlags(Node->getFlags());
3841 }
3842 Results.push_back(Tmp1);
3843 break;
3844 }
3845 case ISD::BR_CC: {
3846 // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS
3847 SDValue Chain;
3848 Tmp1 = Node->getOperand(0); // Chain
3849 Tmp2 = Node->getOperand(2); // LHS
3850 Tmp3 = Node->getOperand(3); // RHS
3851 Tmp4 = Node->getOperand(1); // CC
3852
3853 bool Legalized =
3854 LegalizeSetCCCondCode(getSetCCResultType(Tmp2.getValueType()), Tmp2,
3855 Tmp3, Tmp4, NeedInvert, dl, Chain);
3856 (void)Legalized;
3857 assert(Legalized && "Can't legalize BR_CC with legal condition!");
3858
3859 assert(!NeedInvert && "Don't know how to invert BR_CC!");
3860
3861 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3862 // node.
3863 if (Tmp4.getNode()) {
3864 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3865 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3866 } else {
3867 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3868 Tmp4 = DAG.getCondCode(ISD::SETNE);
3869 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3870 Tmp2, Tmp3, Node->getOperand(4));
3871 }
3872 Results.push_back(Tmp1);
3873 break;
3874 }
3875 case ISD::BUILD_VECTOR:
3876 Results.push_back(ExpandBUILD_VECTOR(Node));
3877 break;
3878 case ISD::SPLAT_VECTOR:
3879 Results.push_back(ExpandSPLAT_VECTOR(Node));
3880 break;
3881 case ISD::SRA:
3882 case ISD::SRL:
3883 case ISD::SHL: {
3884 // Scalarize vector SRA/SRL/SHL.
3885 EVT VT = Node->getValueType(0);
3886 assert(VT.isVector() && "Unable to legalize non-vector shift");
3887 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3888 unsigned NumElem = VT.getVectorNumElements();
3889
3890 SmallVector<SDValue, 8> Scalars;
3891 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3892 SDValue Ex =
3893 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
3894 Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl));
3895 SDValue Sh =
3896 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
3897 Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl));
3898 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3899 VT.getScalarType(), Ex, Sh));
3900 }
3901
3902 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
3903 Results.push_back(Result);
3904 break;
3905 }
3906 case ISD::VECREDUCE_FADD:
3907 case ISD::VECREDUCE_FMUL:
3908 case ISD::VECREDUCE_ADD:
3909 case ISD::VECREDUCE_MUL:
3910 case ISD::VECREDUCE_AND:
3911 case ISD::VECREDUCE_OR:
3912 case ISD::VECREDUCE_XOR:
3913 case ISD::VECREDUCE_SMAX:
3914 case ISD::VECREDUCE_SMIN:
3915 case ISD::VECREDUCE_UMAX:
3916 case ISD::VECREDUCE_UMIN:
3917 case ISD::VECREDUCE_FMAX:
3918 case ISD::VECREDUCE_FMIN:
3919 Results.push_back(TLI.expandVecReduce(Node, DAG));
3920 break;
3921 case ISD::GLOBAL_OFFSET_TABLE:
3922 case ISD::GlobalAddress:
3923 case ISD::GlobalTLSAddress:
3924 case ISD::ExternalSymbol:
3925 case ISD::ConstantPool:
3926 case ISD::JumpTable:
3927 case ISD::INTRINSIC_W_CHAIN:
3928 case ISD::INTRINSIC_WO_CHAIN:
3929 case ISD::INTRINSIC_VOID:
3930 // FIXME: Custom lowering for these operations shouldn't return null!
3931 // Return true so that we don't call ConvertNodeToLibcall which also won't
3932 // do anything.
3933 return true;
3934 }
3935
3936 if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) {
3937 // FIXME: We were asked to expand a strict floating-point operation,
3938 // but there is currently no expansion implemented that would preserve
3939 // the "strict" properties. For now, we just fall back to the non-strict
3940 // version if that is legal on the target. The actual mutation of the
3941 // operation will happen in SelectionDAGISel::DoInstructionSelection.
3942 switch (Node->getOpcode()) {
3943 default:
3944 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3945 Node->getValueType(0))
3946 == TargetLowering::Legal)
3947 return true;
3948 break;
3949 case ISD::STRICT_LRINT:
3950 case ISD::STRICT_LLRINT:
3951 case ISD::STRICT_LROUND:
3952 case ISD::STRICT_LLROUND:
3953 // These are registered by the operand type instead of the value
3954 // type. Reflect that here.
3955 if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3956 Node->getOperand(1).getValueType())
3957 == TargetLowering::Legal)
3958 return true;
3959 break;
3960 }
3961 }
3962
3963 // Replace the original node with the legalized result.
3964 if (Results.empty()) {
3965 LLVM_DEBUG(dbgs() << "Cannot expand node\n");
3966 return false;
3967 }
3968
3969 LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
3970 ReplaceNode(Node, Results.data());
3971 return true;
3972 }
3973
ConvertNodeToLibcall(SDNode * Node)3974 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3975 LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
3976 SmallVector<SDValue, 8> Results;
3977 SDLoc dl(Node);
3978 // FIXME: Check flags on the node to see if we can use a finite call.
3979 unsigned Opc = Node->getOpcode();
3980 switch (Opc) {
3981 case ISD::ATOMIC_FENCE: {
3982 // If the target didn't lower this, lower it to '__sync_synchronize()' call
3983 // FIXME: handle "fence singlethread" more efficiently.
3984 TargetLowering::ArgListTy Args;
3985
3986 TargetLowering::CallLoweringInfo CLI(DAG);
3987 CLI.setDebugLoc(dl)
3988 .setChain(Node->getOperand(0))
3989 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3990 DAG.getExternalFunctionSymbol("__sync_synchronize"),
3991 std::move(Args));
3992
3993 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3994
3995 Results.push_back(CallResult.second);
3996 break;
3997 }
3998 // By default, atomic intrinsics are marked Legal and lowered. Targets
3999 // which don't support them directly, however, may want libcalls, in which
4000 // case they mark them Expand, and we get here.
4001 case ISD::ATOMIC_SWAP:
4002 case ISD::ATOMIC_LOAD_ADD:
4003 case ISD::ATOMIC_LOAD_SUB:
4004 case ISD::ATOMIC_LOAD_AND:
4005 case ISD::ATOMIC_LOAD_CLR:
4006 case ISD::ATOMIC_LOAD_OR:
4007 case ISD::ATOMIC_LOAD_XOR:
4008 case ISD::ATOMIC_LOAD_NAND:
4009 case ISD::ATOMIC_LOAD_MIN:
4010 case ISD::ATOMIC_LOAD_MAX:
4011 case ISD::ATOMIC_LOAD_UMIN:
4012 case ISD::ATOMIC_LOAD_UMAX:
4013 case ISD::ATOMIC_CMP_SWAP: {
4014 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
4015 RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
4016 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
4017
4018 EVT RetVT = Node->getValueType(0);
4019 SmallVector<SDValue, 4> Ops(Node->op_begin() + 1, Node->op_end());
4020 TargetLowering::MakeLibCallOptions CallOptions;
4021 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
4022 Ops, CallOptions,
4023 SDLoc(Node),
4024 Node->getOperand(0));
4025 Results.push_back(Tmp.first);
4026 Results.push_back(Tmp.second);
4027 break;
4028 }
4029 case ISD::TRAP: {
4030 // If this operation is not supported, lower it to 'abort()' call
4031 TargetLowering::ArgListTy Args;
4032 TargetLowering::CallLoweringInfo CLI(DAG);
4033 CLI.setDebugLoc(dl)
4034 .setChain(Node->getOperand(0))
4035 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
4036 DAG.getExternalFunctionSymbol("abort"), std::move(Args));
4037 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
4038
4039 Results.push_back(CallResult.second);
4040 break;
4041 }
4042 case ISD::FMINNUM:
4043 case ISD::STRICT_FMINNUM:
4044 ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
4045 RTLIB::FMIN_F80, RTLIB::FMIN_F128,
4046 RTLIB::FMIN_PPCF128, Results);
4047 break;
4048 case ISD::FMAXNUM:
4049 case ISD::STRICT_FMAXNUM:
4050 ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
4051 RTLIB::FMAX_F80, RTLIB::FMAX_F128,
4052 RTLIB::FMAX_PPCF128, Results);
4053 break;
4054 case ISD::FSQRT:
4055 case ISD::STRICT_FSQRT:
4056 ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
4057 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
4058 RTLIB::SQRT_PPCF128, Results);
4059 break;
4060 case ISD::FCBRT:
4061 ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64,
4062 RTLIB::CBRT_F80, RTLIB::CBRT_F128,
4063 RTLIB::CBRT_PPCF128, Results);
4064 break;
4065 case ISD::FSIN:
4066 case ISD::STRICT_FSIN:
4067 ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
4068 RTLIB::SIN_F80, RTLIB::SIN_F128,
4069 RTLIB::SIN_PPCF128, Results);
4070 break;
4071 case ISD::FCOS:
4072 case ISD::STRICT_FCOS:
4073 ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
4074 RTLIB::COS_F80, RTLIB::COS_F128,
4075 RTLIB::COS_PPCF128, Results);
4076 break;
4077 case ISD::FSINCOS:
4078 // Expand into sincos libcall.
4079 ExpandSinCosLibCall(Node, Results);
4080 break;
4081 case ISD::FLOG:
4082 case ISD::STRICT_FLOG:
4083 ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, RTLIB::LOG_F80,
4084 RTLIB::LOG_F128, RTLIB::LOG_PPCF128, Results);
4085 break;
4086 case ISD::FLOG2:
4087 case ISD::STRICT_FLOG2:
4088 ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, RTLIB::LOG2_F80,
4089 RTLIB::LOG2_F128, RTLIB::LOG2_PPCF128, Results);
4090 break;
4091 case ISD::FLOG10:
4092 case ISD::STRICT_FLOG10:
4093 ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, RTLIB::LOG10_F80,
4094 RTLIB::LOG10_F128, RTLIB::LOG10_PPCF128, Results);
4095 break;
4096 case ISD::FEXP:
4097 case ISD::STRICT_FEXP:
4098 ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, RTLIB::EXP_F80,
4099 RTLIB::EXP_F128, RTLIB::EXP_PPCF128, Results);
4100 break;
4101 case ISD::FEXP2:
4102 case ISD::STRICT_FEXP2:
4103 ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, RTLIB::EXP2_F80,
4104 RTLIB::EXP2_F128, RTLIB::EXP2_PPCF128, Results);
4105 break;
4106 case ISD::FTRUNC:
4107 case ISD::STRICT_FTRUNC:
4108 ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
4109 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
4110 RTLIB::TRUNC_PPCF128, Results);
4111 break;
4112 case ISD::FFLOOR:
4113 case ISD::STRICT_FFLOOR:
4114 ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
4115 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
4116 RTLIB::FLOOR_PPCF128, Results);
4117 break;
4118 case ISD::FCEIL:
4119 case ISD::STRICT_FCEIL:
4120 ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
4121 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
4122 RTLIB::CEIL_PPCF128, Results);
4123 break;
4124 case ISD::FRINT:
4125 case ISD::STRICT_FRINT:
4126 ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
4127 RTLIB::RINT_F80, RTLIB::RINT_F128,
4128 RTLIB::RINT_PPCF128, Results);
4129 break;
4130 case ISD::FNEARBYINT:
4131 case ISD::STRICT_FNEARBYINT:
4132 ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
4133 RTLIB::NEARBYINT_F64,
4134 RTLIB::NEARBYINT_F80,
4135 RTLIB::NEARBYINT_F128,
4136 RTLIB::NEARBYINT_PPCF128, Results);
4137 break;
4138 case ISD::FROUND:
4139 case ISD::STRICT_FROUND:
4140 ExpandFPLibCall(Node, RTLIB::ROUND_F32,
4141 RTLIB::ROUND_F64,
4142 RTLIB::ROUND_F80,
4143 RTLIB::ROUND_F128,
4144 RTLIB::ROUND_PPCF128, Results);
4145 break;
4146 case ISD::FROUNDEVEN:
4147 case ISD::STRICT_FROUNDEVEN:
4148 ExpandFPLibCall(Node, RTLIB::ROUNDEVEN_F32,
4149 RTLIB::ROUNDEVEN_F64,
4150 RTLIB::ROUNDEVEN_F80,
4151 RTLIB::ROUNDEVEN_F128,
4152 RTLIB::ROUNDEVEN_PPCF128, Results);
4153 break;
4154 case ISD::FPOWI:
4155 case ISD::STRICT_FPOWI: {
4156 RTLIB::Libcall LC;
4157 switch (Node->getSimpleValueType(0).SimpleTy) {
4158 default: llvm_unreachable("Unexpected request for libcall!");
4159 case MVT::f32: LC = RTLIB::POWI_F32; break;
4160 case MVT::f64: LC = RTLIB::POWI_F64; break;
4161 case MVT::f80: LC = RTLIB::POWI_F80; break;
4162 case MVT::f128: LC = RTLIB::POWI_F128; break;
4163 case MVT::ppcf128: LC = RTLIB::POWI_PPCF128; break;
4164 }
4165 if (!TLI.getLibcallName(LC)) {
4166 // Some targets don't have a powi libcall; use pow instead.
4167 SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node),
4168 Node->getValueType(0),
4169 Node->getOperand(1));
4170 Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node),
4171 Node->getValueType(0), Node->getOperand(0),
4172 Exponent));
4173 break;
4174 }
4175 ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
4176 RTLIB::POWI_F80, RTLIB::POWI_F128,
4177 RTLIB::POWI_PPCF128, Results);
4178 break;
4179 }
4180 case ISD::FPOW:
4181 case ISD::STRICT_FPOW:
4182 ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
4183 RTLIB::POW_F128, RTLIB::POW_PPCF128, Results);
4184 break;
4185 case ISD::LROUND:
4186 case ISD::STRICT_LROUND:
4187 ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
4188 RTLIB::LROUND_F64, RTLIB::LROUND_F80,
4189 RTLIB::LROUND_F128,
4190 RTLIB::LROUND_PPCF128, Results);
4191 break;
4192 case ISD::LLROUND:
4193 case ISD::STRICT_LLROUND:
4194 ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
4195 RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
4196 RTLIB::LLROUND_F128,
4197 RTLIB::LLROUND_PPCF128, Results);
4198 break;
4199 case ISD::LRINT:
4200 case ISD::STRICT_LRINT:
4201 ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
4202 RTLIB::LRINT_F64, RTLIB::LRINT_F80,
4203 RTLIB::LRINT_F128,
4204 RTLIB::LRINT_PPCF128, Results);
4205 break;
4206 case ISD::LLRINT:
4207 case ISD::STRICT_LLRINT:
4208 ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
4209 RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
4210 RTLIB::LLRINT_F128,
4211 RTLIB::LLRINT_PPCF128, Results);
4212 break;
4213 case ISD::FDIV:
4214 case ISD::STRICT_FDIV:
4215 ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
4216 RTLIB::DIV_F80, RTLIB::DIV_F128,
4217 RTLIB::DIV_PPCF128, Results);
4218 break;
4219 case ISD::FREM:
4220 case ISD::STRICT_FREM:
4221 ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
4222 RTLIB::REM_F80, RTLIB::REM_F128,
4223 RTLIB::REM_PPCF128, Results);
4224 break;
4225 case ISD::FMA:
4226 case ISD::STRICT_FMA:
4227 ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
4228 RTLIB::FMA_F80, RTLIB::FMA_F128,
4229 RTLIB::FMA_PPCF128, Results);
4230 break;
4231 case ISD::FADD:
4232 case ISD::STRICT_FADD:
4233 ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
4234 RTLIB::ADD_F80, RTLIB::ADD_F128,
4235 RTLIB::ADD_PPCF128, Results);
4236 break;
4237 case ISD::FMUL:
4238 case ISD::STRICT_FMUL:
4239 ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
4240 RTLIB::MUL_F80, RTLIB::MUL_F128,
4241 RTLIB::MUL_PPCF128, Results);
4242 break;
4243 case ISD::FP16_TO_FP:
4244 if (Node->getValueType(0) == MVT::f32) {
4245 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
4246 }
4247 break;
4248 case ISD::STRICT_FP16_TO_FP: {
4249 if (Node->getValueType(0) == MVT::f32) {
4250 TargetLowering::MakeLibCallOptions CallOptions;
4251 std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
4252 DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions,
4253 SDLoc(Node), Node->getOperand(0));
4254 Results.push_back(Tmp.first);
4255 Results.push_back(Tmp.second);
4256 }
4257 break;
4258 }
4259 case ISD::FP_TO_FP16: {
4260 RTLIB::Libcall LC =
4261 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
4262 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
4263 Results.push_back(ExpandLibCall(LC, Node, false));
4264 break;
4265 }
4266 case ISD::STRICT_FP_TO_FP16: {
4267 RTLIB::Libcall LC =
4268 RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16);
4269 assert(LC != RTLIB::UNKNOWN_LIBCALL &&
4270 "Unable to expand strict_fp_to_fp16");
4271 TargetLowering::MakeLibCallOptions CallOptions;
4272 std::pair<SDValue, SDValue> Tmp =
4273 TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1),
4274 CallOptions, SDLoc(Node), Node->getOperand(0));
4275 Results.push_back(Tmp.first);
4276 Results.push_back(Tmp.second);
4277 break;
4278 }
4279 case ISD::FSUB:
4280 case ISD::STRICT_FSUB:
4281 ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
4282 RTLIB::SUB_F80, RTLIB::SUB_F128,
4283 RTLIB::SUB_PPCF128, Results);
4284 break;
4285 case ISD::SREM:
4286 Results.push_back(ExpandIntLibCall(Node, true,
4287 RTLIB::SREM_I8,
4288 RTLIB::SREM_I16, RTLIB::SREM_I32,
4289 RTLIB::SREM_I64, RTLIB::SREM_I128));
4290 break;
4291 case ISD::UREM:
4292 Results.push_back(ExpandIntLibCall(Node, false,
4293 RTLIB::UREM_I8,
4294 RTLIB::UREM_I16, RTLIB::UREM_I32,
4295 RTLIB::UREM_I64, RTLIB::UREM_I128));
4296 break;
4297 case ISD::SDIV:
4298 Results.push_back(ExpandIntLibCall(Node, true,
4299 RTLIB::SDIV_I8,
4300 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4301 RTLIB::SDIV_I64, RTLIB::SDIV_I128));
4302 break;
4303 case ISD::UDIV:
4304 Results.push_back(ExpandIntLibCall(Node, false,
4305 RTLIB::UDIV_I8,
4306 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4307 RTLIB::UDIV_I64, RTLIB::UDIV_I128));
4308 break;
4309 case ISD::SDIVREM:
4310 case ISD::UDIVREM:
4311 // Expand into divrem libcall
4312 ExpandDivRemLibCall(Node, Results);
4313 break;
4314 case ISD::MUL:
4315 Results.push_back(ExpandIntLibCall(Node, false,
4316 RTLIB::MUL_I8,
4317 RTLIB::MUL_I16, RTLIB::MUL_I32,
4318 RTLIB::MUL_I64, RTLIB::MUL_I128));
4319 break;
4320 case ISD::CTLZ_ZERO_UNDEF:
4321 switch (Node->getSimpleValueType(0).SimpleTy) {
4322 default:
4323 llvm_unreachable("LibCall explicitly requested, but not available");
4324 case MVT::i32:
4325 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false));
4326 break;
4327 case MVT::i64:
4328 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false));
4329 break;
4330 case MVT::i128:
4331 Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false));
4332 break;
4333 }
4334 break;
4335 }
4336
4337 // Replace the original node with the legalized result.
4338 if (!Results.empty()) {
4339 LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
4340 ReplaceNode(Node, Results.data());
4341 } else
4342 LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
4343 }
4344
4345 // Determine the vector type to use in place of an original scalar element when
4346 // promoting equally sized vectors.
getPromotedVectorElementType(const TargetLowering & TLI,MVT EltVT,MVT NewEltVT)4347 static MVT getPromotedVectorElementType(const TargetLowering &TLI,
4348 MVT EltVT, MVT NewEltVT) {
4349 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4350 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4351 assert(TLI.isTypeLegal(MidVT) && "unexpected");
4352 return MidVT;
4353 }
4354
PromoteNode(SDNode * Node)4355 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4356 LLVM_DEBUG(dbgs() << "Trying to promote node\n");
4357 SmallVector<SDValue, 8> Results;
4358 MVT OVT = Node->getSimpleValueType(0);
4359 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4360 Node->getOpcode() == ISD::SINT_TO_FP ||
4361 Node->getOpcode() == ISD::SETCC ||
4362 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4363 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4364 OVT = Node->getOperand(0).getSimpleValueType();
4365 }
4366 if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP ||
4367 Node->getOpcode() == ISD::STRICT_SINT_TO_FP)
4368 OVT = Node->getOperand(1).getSimpleValueType();
4369 if (Node->getOpcode() == ISD::BR_CC)
4370 OVT = Node->getOperand(2).getSimpleValueType();
4371 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4372 SDLoc dl(Node);
4373 SDValue Tmp1, Tmp2, Tmp3;
4374 switch (Node->getOpcode()) {
4375 case ISD::CTTZ:
4376 case ISD::CTTZ_ZERO_UNDEF:
4377 case ISD::CTLZ:
4378 case ISD::CTLZ_ZERO_UNDEF:
4379 case ISD::CTPOP:
4380 // Zero extend the argument unless its cttz, then use any_extend.
4381 if (Node->getOpcode() == ISD::CTTZ ||
4382 Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF)
4383 Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
4384 else
4385 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4386
4387 if (Node->getOpcode() == ISD::CTTZ) {
4388 // The count is the same in the promoted type except if the original
4389 // value was zero. This can be handled by setting the bit just off
4390 // the top of the original type.
4391 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4392 OVT.getSizeInBits());
4393 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4394 DAG.getConstant(TopBit, dl, NVT));
4395 }
4396 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4397 // already the correct result.
4398 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4399 if (Node->getOpcode() == ISD::CTLZ ||
4400 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4401 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4402 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4403 DAG.getConstant(NVT.getSizeInBits() -
4404 OVT.getSizeInBits(), dl, NVT));
4405 }
4406 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4407 break;
4408 case ISD::BITREVERSE:
4409 case ISD::BSWAP: {
4410 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4411 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4412 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4413 Tmp1 = DAG.getNode(
4414 ISD::SRL, dl, NVT, Tmp1,
4415 DAG.getConstant(DiffBits, dl,
4416 TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4417
4418 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4419 break;
4420 }
4421 case ISD::FP_TO_UINT:
4422 case ISD::STRICT_FP_TO_UINT:
4423 case ISD::FP_TO_SINT:
4424 case ISD::STRICT_FP_TO_SINT:
4425 PromoteLegalFP_TO_INT(Node, dl, Results);
4426 break;
4427 case ISD::UINT_TO_FP:
4428 case ISD::STRICT_UINT_TO_FP:
4429 case ISD::SINT_TO_FP:
4430 case ISD::STRICT_SINT_TO_FP:
4431 PromoteLegalINT_TO_FP(Node, dl, Results);
4432 break;
4433 case ISD::VAARG: {
4434 SDValue Chain = Node->getOperand(0); // Get the chain.
4435 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4436
4437 unsigned TruncOp;
4438 if (OVT.isVector()) {
4439 TruncOp = ISD::BITCAST;
4440 } else {
4441 assert(OVT.isInteger()
4442 && "VAARG promotion is supported only for vectors or integer types");
4443 TruncOp = ISD::TRUNCATE;
4444 }
4445
4446 // Perform the larger operation, then convert back
4447 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4448 Node->getConstantOperandVal(3));
4449 Chain = Tmp1.getValue(1);
4450
4451 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4452
4453 // Modified the chain result - switch anything that used the old chain to
4454 // use the new one.
4455 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4456 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4457 if (UpdatedNodes) {
4458 UpdatedNodes->insert(Tmp2.getNode());
4459 UpdatedNodes->insert(Chain.getNode());
4460 }
4461 ReplacedNode(Node);
4462 break;
4463 }
4464 case ISD::MUL:
4465 case ISD::SDIV:
4466 case ISD::SREM:
4467 case ISD::UDIV:
4468 case ISD::UREM:
4469 case ISD::AND:
4470 case ISD::OR:
4471 case ISD::XOR: {
4472 unsigned ExtOp, TruncOp;
4473 if (OVT.isVector()) {
4474 ExtOp = ISD::BITCAST;
4475 TruncOp = ISD::BITCAST;
4476 } else {
4477 assert(OVT.isInteger() && "Cannot promote logic operation");
4478
4479 switch (Node->getOpcode()) {
4480 default:
4481 ExtOp = ISD::ANY_EXTEND;
4482 break;
4483 case ISD::SDIV:
4484 case ISD::SREM:
4485 ExtOp = ISD::SIGN_EXTEND;
4486 break;
4487 case ISD::UDIV:
4488 case ISD::UREM:
4489 ExtOp = ISD::ZERO_EXTEND;
4490 break;
4491 }
4492 TruncOp = ISD::TRUNCATE;
4493 }
4494 // Promote each of the values to the new type.
4495 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4496 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4497 // Perform the larger operation, then convert back
4498 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4499 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4500 break;
4501 }
4502 case ISD::UMUL_LOHI:
4503 case ISD::SMUL_LOHI: {
4504 // Promote to a multiply in a wider integer type.
4505 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
4506 : ISD::SIGN_EXTEND;
4507 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4508 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4509 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
4510
4511 auto &DL = DAG.getDataLayout();
4512 unsigned OriginalSize = OVT.getScalarSizeInBits();
4513 Tmp2 = DAG.getNode(
4514 ISD::SRL, dl, NVT, Tmp1,
4515 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
4516 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4517 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
4518 break;
4519 }
4520 case ISD::SELECT: {
4521 unsigned ExtOp, TruncOp;
4522 if (Node->getValueType(0).isVector() ||
4523 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4524 ExtOp = ISD::BITCAST;
4525 TruncOp = ISD::BITCAST;
4526 } else if (Node->getValueType(0).isInteger()) {
4527 ExtOp = ISD::ANY_EXTEND;
4528 TruncOp = ISD::TRUNCATE;
4529 } else {
4530 ExtOp = ISD::FP_EXTEND;
4531 TruncOp = ISD::FP_ROUND;
4532 }
4533 Tmp1 = Node->getOperand(0);
4534 // Promote each of the values to the new type.
4535 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4536 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4537 // Perform the larger operation, then round down.
4538 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4539 Tmp1->setFlags(Node->getFlags());
4540 if (TruncOp != ISD::FP_ROUND)
4541 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4542 else
4543 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4544 DAG.getIntPtrConstant(0, dl));
4545 Results.push_back(Tmp1);
4546 break;
4547 }
4548 case ISD::VECTOR_SHUFFLE: {
4549 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4550
4551 // Cast the two input vectors.
4552 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4553 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4554
4555 // Convert the shuffle mask to the right # elements.
4556 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4557 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4558 Results.push_back(Tmp1);
4559 break;
4560 }
4561 case ISD::SETCC: {
4562 unsigned ExtOp = ISD::FP_EXTEND;
4563 if (NVT.isInteger()) {
4564 ISD::CondCode CCCode =
4565 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4566 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4567 }
4568 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4569 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4570 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
4571 Tmp2, Node->getOperand(2), Node->getFlags()));
4572 break;
4573 }
4574 case ISD::BR_CC: {
4575 unsigned ExtOp = ISD::FP_EXTEND;
4576 if (NVT.isInteger()) {
4577 ISD::CondCode CCCode =
4578 cast<CondCodeSDNode>(Node->getOperand(1))->get();
4579 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4580 }
4581 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4582 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4583 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4584 Node->getOperand(0), Node->getOperand(1),
4585 Tmp1, Tmp2, Node->getOperand(4)));
4586 break;
4587 }
4588 case ISD::FADD:
4589 case ISD::FSUB:
4590 case ISD::FMUL:
4591 case ISD::FDIV:
4592 case ISD::FREM:
4593 case ISD::FMINNUM:
4594 case ISD::FMAXNUM:
4595 case ISD::FPOW:
4596 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4597 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4598 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4599 Node->getFlags());
4600 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4601 Tmp3, DAG.getIntPtrConstant(0, dl)));
4602 break;
4603 case ISD::STRICT_FREM:
4604 case ISD::STRICT_FPOW:
4605 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4606 {Node->getOperand(0), Node->getOperand(1)});
4607 Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4608 {Node->getOperand(0), Node->getOperand(2)});
4609 Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
4610 Tmp2.getValue(1));
4611 Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4612 {Tmp3, Tmp1, Tmp2});
4613 Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4614 {Tmp1.getValue(1), Tmp1, DAG.getIntPtrConstant(0, dl)});
4615 Results.push_back(Tmp1);
4616 Results.push_back(Tmp1.getValue(1));
4617 break;
4618 case ISD::FMA:
4619 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4620 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4621 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4622 Results.push_back(
4623 DAG.getNode(ISD::FP_ROUND, dl, OVT,
4624 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4625 DAG.getIntPtrConstant(0, dl)));
4626 break;
4627 case ISD::FCOPYSIGN:
4628 case ISD::FPOWI: {
4629 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4630 Tmp2 = Node->getOperand(1);
4631 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4632
4633 // fcopysign doesn't change anything but the sign bit, so
4634 // (fp_round (fcopysign (fpext a), b))
4635 // is as precise as
4636 // (fp_round (fpext a))
4637 // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4638 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4639 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4640 Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4641 break;
4642 }
4643 case ISD::FFLOOR:
4644 case ISD::FCEIL:
4645 case ISD::FRINT:
4646 case ISD::FNEARBYINT:
4647 case ISD::FROUND:
4648 case ISD::FROUNDEVEN:
4649 case ISD::FTRUNC:
4650 case ISD::FNEG:
4651 case ISD::FSQRT:
4652 case ISD::FSIN:
4653 case ISD::FCOS:
4654 case ISD::FLOG:
4655 case ISD::FLOG2:
4656 case ISD::FLOG10:
4657 case ISD::FABS:
4658 case ISD::FEXP:
4659 case ISD::FEXP2:
4660 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4661 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4662 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4663 Tmp2, DAG.getIntPtrConstant(0, dl)));
4664 break;
4665 case ISD::STRICT_FFLOOR:
4666 case ISD::STRICT_FCEIL:
4667 case ISD::STRICT_FSIN:
4668 case ISD::STRICT_FCOS:
4669 case ISD::STRICT_FLOG:
4670 case ISD::STRICT_FLOG10:
4671 case ISD::STRICT_FEXP:
4672 Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4673 {Node->getOperand(0), Node->getOperand(1)});
4674 Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4675 {Tmp1.getValue(1), Tmp1});
4676 Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4677 {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)});
4678 Results.push_back(Tmp3);
4679 Results.push_back(Tmp3.getValue(1));
4680 break;
4681 case ISD::BUILD_VECTOR: {
4682 MVT EltVT = OVT.getVectorElementType();
4683 MVT NewEltVT = NVT.getVectorElementType();
4684
4685 // Handle bitcasts to a different vector type with the same total bit size
4686 //
4687 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4688 // =>
4689 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4690
4691 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4692 "Invalid promote type for build_vector");
4693 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4694
4695 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4696
4697 SmallVector<SDValue, 8> NewOps;
4698 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4699 SDValue Op = Node->getOperand(I);
4700 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4701 }
4702
4703 SDLoc SL(Node);
4704 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4705 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4706 Results.push_back(CvtVec);
4707 break;
4708 }
4709 case ISD::EXTRACT_VECTOR_ELT: {
4710 MVT EltVT = OVT.getVectorElementType();
4711 MVT NewEltVT = NVT.getVectorElementType();
4712
4713 // Handle bitcasts to a different vector type with the same total bit size.
4714 //
4715 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4716 // =>
4717 // v4i32:castx = bitcast x:v2i64
4718 //
4719 // i64 = bitcast
4720 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4721 // (i32 (extract_vector_elt castx, (2 * y + 1)))
4722 //
4723
4724 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4725 "Invalid promote type for extract_vector_elt");
4726 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4727
4728 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4729 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4730
4731 SDValue Idx = Node->getOperand(1);
4732 EVT IdxVT = Idx.getValueType();
4733 SDLoc SL(Node);
4734 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4735 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4736
4737 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4738
4739 SmallVector<SDValue, 8> NewOps;
4740 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4741 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4742 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4743
4744 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4745 CastVec, TmpIdx);
4746 NewOps.push_back(Elt);
4747 }
4748
4749 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
4750 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4751 break;
4752 }
4753 case ISD::INSERT_VECTOR_ELT: {
4754 MVT EltVT = OVT.getVectorElementType();
4755 MVT NewEltVT = NVT.getVectorElementType();
4756
4757 // Handle bitcasts to a different vector type with the same total bit size
4758 //
4759 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4760 // =>
4761 // v4i32:castx = bitcast x:v2i64
4762 // v2i32:casty = bitcast y:i64
4763 //
4764 // v2i64 = bitcast
4765 // (v4i32 insert_vector_elt
4766 // (v4i32 insert_vector_elt v4i32:castx,
4767 // (extract_vector_elt casty, 0), 2 * z),
4768 // (extract_vector_elt casty, 1), (2 * z + 1))
4769
4770 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4771 "Invalid promote type for insert_vector_elt");
4772 assert(NewEltVT.bitsLT(EltVT) && "not handled");
4773
4774 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4775 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4776
4777 SDValue Val = Node->getOperand(1);
4778 SDValue Idx = Node->getOperand(2);
4779 EVT IdxVT = Idx.getValueType();
4780 SDLoc SL(Node);
4781
4782 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4783 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4784
4785 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4786 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4787
4788 SDValue NewVec = CastVec;
4789 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4790 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4791 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4792
4793 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4794 CastVal, IdxOffset);
4795
4796 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4797 NewVec, Elt, InEltIdx);
4798 }
4799
4800 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4801 break;
4802 }
4803 case ISD::SCALAR_TO_VECTOR: {
4804 MVT EltVT = OVT.getVectorElementType();
4805 MVT NewEltVT = NVT.getVectorElementType();
4806
4807 // Handle bitcasts to different vector type with the same total bit size.
4808 //
4809 // e.g. v2i64 = scalar_to_vector x:i64
4810 // =>
4811 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4812 //
4813
4814 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4815 SDValue Val = Node->getOperand(0);
4816 SDLoc SL(Node);
4817
4818 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4819 SDValue Undef = DAG.getUNDEF(MidVT);
4820
4821 SmallVector<SDValue, 8> NewElts;
4822 NewElts.push_back(CastVal);
4823 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4824 NewElts.push_back(Undef);
4825
4826 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4827 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4828 Results.push_back(CvtVec);
4829 break;
4830 }
4831 case ISD::ATOMIC_SWAP: {
4832 AtomicSDNode *AM = cast<AtomicSDNode>(Node);
4833 SDLoc SL(Node);
4834 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
4835 assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
4836 "unexpected promotion type");
4837 assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
4838 "unexpected atomic_swap with illegal type");
4839
4840 SDValue NewAtomic
4841 = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT,
4842 DAG.getVTList(NVT, MVT::Other),
4843 { AM->getChain(), AM->getBasePtr(), CastVal },
4844 AM->getMemOperand());
4845 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
4846 Results.push_back(NewAtomic.getValue(1));
4847 break;
4848 }
4849 }
4850
4851 // Replace the original node with the legalized result.
4852 if (!Results.empty()) {
4853 LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
4854 ReplaceNode(Node, Results.data());
4855 } else
4856 LLVM_DEBUG(dbgs() << "Could not promote node\n");
4857 }
4858
4859 /// This is the entry point for the file.
Legalize()4860 void SelectionDAG::Legalize() {
4861 AssignTopologicalOrder();
4862
4863 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4864 // Use a delete listener to remove nodes which were deleted during
4865 // legalization from LegalizeNodes. This is needed to handle the situation
4866 // where a new node is allocated by the object pool to the same address of a
4867 // previously deleted node.
4868 DAGNodeDeletedListener DeleteListener(
4869 *this,
4870 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
4871
4872 SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4873
4874 // Visit all the nodes. We start in topological order, so that we see
4875 // nodes with their original operands intact. Legalization can produce
4876 // new nodes which may themselves need to be legalized. Iterate until all
4877 // nodes have been legalized.
4878 while (true) {
4879 bool AnyLegalized = false;
4880 for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4881 --NI;
4882
4883 SDNode *N = &*NI;
4884 if (N->use_empty() && N != getRoot().getNode()) {
4885 ++NI;
4886 DeleteNode(N);
4887 continue;
4888 }
4889
4890 if (LegalizedNodes.insert(N).second) {
4891 AnyLegalized = true;
4892 Legalizer.LegalizeOp(N);
4893
4894 if (N->use_empty() && N != getRoot().getNode()) {
4895 ++NI;
4896 DeleteNode(N);
4897 }
4898 }
4899 }
4900 if (!AnyLegalized)
4901 break;
4902
4903 }
4904
4905 // Remove dead nodes now.
4906 RemoveDeadNodes();
4907 }
4908
LegalizeOp(SDNode * N,SmallSetVector<SDNode *,16> & UpdatedNodes)4909 bool SelectionDAG::LegalizeOp(SDNode *N,
4910 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4911 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4912 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4913
4914 // Directly insert the node in question, and legalize it. This will recurse
4915 // as needed through operands.
4916 LegalizedNodes.insert(N);
4917 Legalizer.LegalizeOp(N);
4918
4919 return LegalizedNodes.count(N);
4920 }
4921