1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
39 //===----------------------------------------------------------------------===//
40 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
41 /// hacks on it until the target machine can handle it. This involves
42 /// eliminating value sizes the machine cannot handle (promoting small sizes to
43 /// large sizes or splitting up large values into small values) as well as
44 /// eliminating operations the machine cannot handle.
46 /// This code also does a small amount of optimization and recognition of idioms
47 /// as part of its processing. For example, if a target does not support a
48 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
49 /// will attempt merge setcc and brc instructions into brcc's.
52 class SelectionDAGLegalize : public SelectionDAG::DAGUpdateListener {
53 const TargetMachine &TM;
54 const TargetLowering &TLI;
57 /// \brief The iterator being used to walk the DAG. We hold a reference to it
58 /// in order to update it as necessary on node deletion.
59 SelectionDAG::allnodes_iterator &LegalizePosition;
61 /// \brief The set of nodes which have already been legalized. We hold a
62 /// reference to it in order to update as necessary on node deletion.
63 SmallPtrSetImpl<SDNode *> &LegalizedNodes;
65 /// \brief A set of all the nodes updated during legalization.
66 SmallSetVector<SDNode *, 16> *UpdatedNodes;
68 EVT getSetCCResultType(EVT VT) const {
69 return TLI.getSetCCResultType(*DAG.getContext(), VT);
72 // Libcall insertion helpers.
75 SelectionDAGLegalize(SelectionDAG &DAG,
76 SelectionDAG::allnodes_iterator &LegalizePosition,
77 SmallPtrSetImpl<SDNode *> &LegalizedNodes,
78 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
79 : SelectionDAG::DAGUpdateListener(DAG), TM(DAG.getTarget()),
80 TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
81 LegalizePosition(LegalizePosition), LegalizedNodes(LegalizedNodes),
82 UpdatedNodes(UpdatedNodes) {}
84 /// \brief Legalizes the given operation.
85 void LegalizeOp(SDNode *Node);
88 SDValue OptimizeFloatStore(StoreSDNode *ST);
90 void LegalizeLoadOps(SDNode *Node);
91 void LegalizeStoreOps(SDNode *Node);
93 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
94 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
95 /// is necessary to spill the vector being inserted into to memory, perform
96 /// the insert there, and then read the result back.
97 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
98 SDValue Idx, SDLoc dl);
99 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
100 SDValue Idx, SDLoc dl);
102 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
103 /// performs the same shuffe in terms of order or result bytes, but on a type
104 /// whose vector element type is narrower than the original shuffle type.
105 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
106 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
107 SDValue N1, SDValue N2,
108 ArrayRef<int> Mask) const;
110 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
111 bool &NeedInvert, SDLoc dl);
113 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
114 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
115 unsigned NumOps, bool isSigned, SDLoc dl);
117 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
118 SDNode *Node, bool isSigned);
119 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
120 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
121 RTLIB::Libcall Call_F128,
122 RTLIB::Libcall Call_PPCF128);
123 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
124 RTLIB::Libcall Call_I8,
125 RTLIB::Libcall Call_I16,
126 RTLIB::Libcall Call_I32,
127 RTLIB::Libcall Call_I64,
128 RTLIB::Libcall Call_I128);
129 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
130 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
132 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, SDLoc dl);
133 SDValue ExpandBUILD_VECTOR(SDNode *Node);
134 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
135 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
136 SmallVectorImpl<SDValue> &Results);
137 SDValue ExpandFCOPYSIGN(SDNode *Node);
138 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
140 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
142 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
145 SDValue ExpandBSWAP(SDValue Op, SDLoc dl);
146 SDValue ExpandBitCount(unsigned Opc, SDValue Op, SDLoc dl);
148 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
149 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
150 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
152 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
154 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
156 void ExpandNode(SDNode *Node);
157 void PromoteNode(SDNode *Node);
159 void ForgetNode(SDNode *N) {
160 LegalizedNodes.erase(N);
161 if (LegalizePosition == SelectionDAG::allnodes_iterator(N))
164 UpdatedNodes->remove(N);
168 // DAGUpdateListener implementation.
169 void NodeDeleted(SDNode *N, SDNode *E) override {
172 void NodeUpdated(SDNode *N) override {}
174 // Node replacement helpers
175 void ReplacedNode(SDNode *N) {
176 if (N->use_empty()) {
177 DAG.RemoveDeadNode(N);
182 void ReplaceNode(SDNode *Old, SDNode *New) {
183 assert(Old->getNumValues() == New->getNumValues() &&
184 "Replacing one node with another that produces a different number "
186 DAG.ReplaceAllUsesWith(Old, New);
187 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i)
188 DAG.TransferDbgValues(SDValue(Old, i), SDValue(New, i));
190 UpdatedNodes->insert(New);
193 void ReplaceNode(SDValue Old, SDValue New) {
194 DAG.ReplaceAllUsesWith(Old, New);
195 DAG.TransferDbgValues(Old, New);
197 UpdatedNodes->insert(New.getNode());
198 ReplacedNode(Old.getNode());
200 void ReplaceNode(SDNode *Old, const SDValue *New) {
201 DAG.ReplaceAllUsesWith(Old, New);
202 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i)
203 DAG.TransferDbgValues(SDValue(Old, i), New[i]);
205 UpdatedNodes->insert(New->getNode());
211 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
212 /// performs the same shuffe in terms of order or result bytes, but on a type
213 /// whose vector element type is narrower than the original shuffle type.
214 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
216 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
217 SDValue N1, SDValue N2,
218 ArrayRef<int> Mask) const {
219 unsigned NumMaskElts = VT.getVectorNumElements();
220 unsigned NumDestElts = NVT.getVectorNumElements();
221 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
223 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
225 if (NumEltsGrowth == 1)
226 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
228 SmallVector<int, 8> NewMask;
229 for (unsigned i = 0; i != NumMaskElts; ++i) {
231 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
233 NewMask.push_back(-1);
235 NewMask.push_back(Idx * NumEltsGrowth + j);
238 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
239 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
240 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
243 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
244 /// a load from the constant pool.
246 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
250 // If a FP immediate is precise when represented as a float and if the
251 // target can do an extending load from float to double, we put it into
252 // the constant pool as a float, even if it's is statically typed as a
253 // double. This shrinks FP constants and canonicalizes them for targets where
254 // an FP extending load is the same cost as a normal load (such as on the x87
255 // fp stack or PPC FP unit).
256 EVT VT = CFP->getValueType(0);
257 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
259 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
260 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
261 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
266 while (SVT != MVT::f32 && SVT != MVT::f16) {
267 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
268 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
269 // Only do this if the target has a native EXTLOAD instruction from
271 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
272 TLI.ShouldShrinkFPConstant(OrigVT)) {
273 Type *SType = SVT.getTypeForEVT(*DAG.getContext());
274 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
280 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
281 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
284 DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
286 CPIdx, MachinePointerInfo::getConstantPool(),
287 VT, false, false, Alignment);
291 DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
292 MachinePointerInfo::getConstantPool(), false, false, false,
297 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
298 static void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
299 const TargetLowering &TLI,
300 SelectionDAGLegalize *DAGLegalize) {
301 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
302 "unaligned indexed stores not implemented!");
303 SDValue Chain = ST->getChain();
304 SDValue Ptr = ST->getBasePtr();
305 SDValue Val = ST->getValue();
306 EVT VT = Val.getValueType();
307 int Alignment = ST->getAlignment();
308 unsigned AS = ST->getAddressSpace();
311 if (ST->getMemoryVT().isFloatingPoint() ||
312 ST->getMemoryVT().isVector()) {
313 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
314 if (TLI.isTypeLegal(intVT)) {
315 // Expand to a bitconvert of the value to the integer type of the
316 // same size, then a (misaligned) int store.
317 // FIXME: Does not handle truncating floating point stores!
318 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
319 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
320 ST->isVolatile(), ST->isNonTemporal(), Alignment);
321 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
324 // Do a (aligned) store to a stack slot, then copy from the stack slot
325 // to the final destination using (unaligned) integer loads and stores.
326 EVT StoredVT = ST->getMemoryVT();
328 TLI.getRegisterType(*DAG.getContext(),
329 EVT::getIntegerVT(*DAG.getContext(),
330 StoredVT.getSizeInBits()));
331 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
332 unsigned RegBytes = RegVT.getSizeInBits() / 8;
333 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
335 // Make sure the stack slot is also aligned for the register type.
336 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
338 // Perform the original store, only redirected to the stack slot.
339 SDValue Store = DAG.getTruncStore(Chain, dl,
340 Val, StackPtr, MachinePointerInfo(),
341 StoredVT, false, false, 0);
342 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy(AS));
343 SmallVector<SDValue, 8> Stores;
346 // Do all but one copies using the full register width.
347 for (unsigned i = 1; i < NumRegs; i++) {
348 // Load one integer register's worth from the stack slot.
349 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
350 MachinePointerInfo(),
351 false, false, false, 0);
352 // Store it to the final location. Remember the store.
353 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
354 ST->getPointerInfo().getWithOffset(Offset),
355 ST->isVolatile(), ST->isNonTemporal(),
356 MinAlign(ST->getAlignment(), Offset)));
357 // Increment the pointers.
359 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
361 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
364 // The last store may be partial. Do a truncating store. On big-endian
365 // machines this requires an extending load from the stack slot to ensure
366 // that the bits are in the right place.
367 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
368 8 * (StoredBytes - Offset));
370 // Load from the stack slot.
371 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
372 MachinePointerInfo(),
373 MemVT, false, false, 0);
375 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
377 .getWithOffset(Offset),
378 MemVT, ST->isVolatile(),
380 MinAlign(ST->getAlignment(), Offset),
382 // The order of the stores doesn't matter - say it with a TokenFactor.
383 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
384 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
387 assert(ST->getMemoryVT().isInteger() &&
388 !ST->getMemoryVT().isVector() &&
389 "Unaligned store of unknown type.");
390 // Get the half-size VT
391 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
392 int NumBits = NewStoredVT.getSizeInBits();
393 int IncrementSize = NumBits / 8;
395 // Divide the stored value in two parts.
396 SDValue ShiftAmount = DAG.getConstant(NumBits,
397 TLI.getShiftAmountTy(Val.getValueType()));
399 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
401 // Store the two parts
402 SDValue Store1, Store2;
403 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
404 ST->getPointerInfo(), NewStoredVT,
405 ST->isVolatile(), ST->isNonTemporal(), Alignment);
407 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
408 DAG.getConstant(IncrementSize, TLI.getPointerTy(AS)));
409 Alignment = MinAlign(Alignment, IncrementSize);
410 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
411 ST->getPointerInfo().getWithOffset(IncrementSize),
412 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
413 Alignment, ST->getAAInfo());
416 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
417 DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
420 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
422 ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
423 const TargetLowering &TLI,
424 SDValue &ValResult, SDValue &ChainResult) {
425 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
426 "unaligned indexed loads not implemented!");
427 SDValue Chain = LD->getChain();
428 SDValue Ptr = LD->getBasePtr();
429 EVT VT = LD->getValueType(0);
430 EVT LoadedVT = LD->getMemoryVT();
432 if (VT.isFloatingPoint() || VT.isVector()) {
433 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
434 if (TLI.isTypeLegal(intVT) && TLI.isTypeLegal(LoadedVT)) {
435 // Expand to a (misaligned) integer load of the same size,
436 // then bitconvert to floating point or vector.
437 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
438 LD->getMemOperand());
439 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
441 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
442 ISD::ANY_EXTEND, dl, VT, Result);
449 // Copy the value to a (aligned) stack slot using (unaligned) integer
450 // loads and stores, then do a (aligned) load from the stack slot.
451 MVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
452 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
453 unsigned RegBytes = RegVT.getSizeInBits() / 8;
454 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
456 // Make sure the stack slot is also aligned for the register type.
457 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
459 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
460 SmallVector<SDValue, 8> Stores;
461 SDValue StackPtr = StackBase;
464 // Do all but one copies using the full register width.
465 for (unsigned i = 1; i < NumRegs; i++) {
466 // Load one integer register's worth from the original location.
467 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
468 LD->getPointerInfo().getWithOffset(Offset),
469 LD->isVolatile(), LD->isNonTemporal(),
471 MinAlign(LD->getAlignment(), Offset),
473 // Follow the load with a store to the stack slot. Remember the store.
474 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
475 MachinePointerInfo(), false, false, 0));
476 // Increment the pointers.
478 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
479 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
483 // The last copy may be partial. Do an extending load.
484 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
485 8 * (LoadedBytes - Offset));
486 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
487 LD->getPointerInfo().getWithOffset(Offset),
488 MemVT, LD->isVolatile(),
490 MinAlign(LD->getAlignment(), Offset),
492 // Follow the load with a store to the stack slot. Remember the store.
493 // On big-endian machines this requires a truncating store to ensure
494 // that the bits end up in the right place.
495 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
496 MachinePointerInfo(), MemVT,
499 // The order of the stores doesn't matter - say it with a TokenFactor.
500 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
502 // Finally, perform the original load only redirected to the stack slot.
503 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
504 MachinePointerInfo(), LoadedVT, false, false, 0);
506 // Callers expect a MERGE_VALUES node.
511 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
512 "Unaligned load of unsupported type.");
514 // Compute the new VT that is half the size of the old one. This is an
516 unsigned NumBits = LoadedVT.getSizeInBits();
518 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
521 unsigned Alignment = LD->getAlignment();
522 unsigned IncrementSize = NumBits / 8;
523 ISD::LoadExtType HiExtType = LD->getExtensionType();
525 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
526 if (HiExtType == ISD::NON_EXTLOAD)
527 HiExtType = ISD::ZEXTLOAD;
529 // Load the value in two parts
531 if (TLI.isLittleEndian()) {
532 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
533 NewLoadedVT, LD->isVolatile(),
534 LD->isNonTemporal(), Alignment, LD->getAAInfo());
535 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
536 DAG.getConstant(IncrementSize, Ptr.getValueType()));
537 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
538 LD->getPointerInfo().getWithOffset(IncrementSize),
539 NewLoadedVT, LD->isVolatile(),
540 LD->isNonTemporal(), MinAlign(Alignment, IncrementSize),
543 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
544 NewLoadedVT, LD->isVolatile(),
545 LD->isNonTemporal(), Alignment, LD->getAAInfo());
546 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
547 DAG.getConstant(IncrementSize, Ptr.getValueType()));
548 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
549 LD->getPointerInfo().getWithOffset(IncrementSize),
550 NewLoadedVT, LD->isVolatile(),
551 LD->isNonTemporal(), MinAlign(Alignment, IncrementSize),
555 // aggregate the two parts
556 SDValue ShiftAmount = DAG.getConstant(NumBits,
557 TLI.getShiftAmountTy(Hi.getValueType()));
558 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
559 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
561 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
568 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
569 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
570 /// is necessary to spill the vector being inserted into to memory, perform
571 /// the insert there, and then read the result back.
572 SDValue SelectionDAGLegalize::
573 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
579 // If the target doesn't support this, we have to spill the input vector
580 // to a temporary stack slot, update the element, then reload it. This is
581 // badness. We could also load the value into a vector register (either
582 // with a "move to register" or "extload into register" instruction, then
583 // permute it into place, if the idx is a constant and if the idx is
584 // supported by the target.
585 EVT VT = Tmp1.getValueType();
586 EVT EltVT = VT.getVectorElementType();
587 EVT IdxVT = Tmp3.getValueType();
588 EVT PtrVT = TLI.getPointerTy();
589 SDValue StackPtr = DAG.CreateStackTemporary(VT);
591 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
594 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
595 MachinePointerInfo::getFixedStack(SPFI),
598 // Truncate or zero extend offset to target pointer type.
599 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
600 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
601 // Add the offset to the index.
602 unsigned EltSize = EltVT.getSizeInBits()/8;
603 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
604 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
605 // Store the scalar value.
606 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
608 // Load the updated vector.
609 return DAG.getLoad(VT, dl, Ch, StackPtr,
610 MachinePointerInfo::getFixedStack(SPFI), false, false,
615 SDValue SelectionDAGLegalize::
616 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, SDLoc dl) {
617 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
618 // SCALAR_TO_VECTOR requires that the type of the value being inserted
619 // match the element type of the vector being created, except for
620 // integers in which case the inserted value can be over width.
621 EVT EltVT = Vec.getValueType().getVectorElementType();
622 if (Val.getValueType() == EltVT ||
623 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
624 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
625 Vec.getValueType(), Val);
627 unsigned NumElts = Vec.getValueType().getVectorNumElements();
628 // We generate a shuffle of InVec and ScVec, so the shuffle mask
629 // should be 0,1,2,3,4,5... with the appropriate element replaced with
631 SmallVector<int, 8> ShufOps;
632 for (unsigned i = 0; i != NumElts; ++i)
633 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
635 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
639 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
642 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
643 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
644 // FIXME: We shouldn't do this for TargetConstantFP's.
645 // FIXME: move this to the DAG Combiner! Note that we can't regress due
646 // to phase ordering between legalized code and the dag combiner. This
647 // probably means that we need to integrate dag combiner and legalizer
649 // We generally can't do this one for long doubles.
650 SDValue Chain = ST->getChain();
651 SDValue Ptr = ST->getBasePtr();
652 unsigned Alignment = ST->getAlignment();
653 bool isVolatile = ST->isVolatile();
654 bool isNonTemporal = ST->isNonTemporal();
655 AAMDNodes AAInfo = ST->getAAInfo();
657 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
658 if (CFP->getValueType(0) == MVT::f32 &&
659 TLI.isTypeLegal(MVT::i32)) {
660 SDValue Con = DAG.getConstant(CFP->getValueAPF().
661 bitcastToAPInt().zextOrTrunc(32),
663 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
664 isVolatile, isNonTemporal, Alignment, AAInfo);
667 if (CFP->getValueType(0) == MVT::f64) {
668 // If this target supports 64-bit registers, do a single 64-bit store.
669 if (TLI.isTypeLegal(MVT::i64)) {
670 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
671 zextOrTrunc(64), MVT::i64);
672 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
673 isVolatile, isNonTemporal, Alignment, AAInfo);
676 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
677 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
678 // stores. If the target supports neither 32- nor 64-bits, this
679 // xform is certainly not worth it.
680 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
681 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
682 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
683 if (TLI.isBigEndian()) std::swap(Lo, Hi);
685 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), isVolatile,
686 isNonTemporal, Alignment, AAInfo);
687 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
688 DAG.getConstant(4, Ptr.getValueType()));
689 Hi = DAG.getStore(Chain, dl, Hi, Ptr,
690 ST->getPointerInfo().getWithOffset(4),
691 isVolatile, isNonTemporal, MinAlign(Alignment, 4U),
694 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
698 return SDValue(nullptr, 0);
701 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
702 StoreSDNode *ST = cast<StoreSDNode>(Node);
703 SDValue Chain = ST->getChain();
704 SDValue Ptr = ST->getBasePtr();
707 unsigned Alignment = ST->getAlignment();
708 bool isVolatile = ST->isVolatile();
709 bool isNonTemporal = ST->isNonTemporal();
710 AAMDNodes AAInfo = ST->getAAInfo();
712 if (!ST->isTruncatingStore()) {
713 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
714 ReplaceNode(ST, OptStore);
719 SDValue Value = ST->getValue();
720 MVT VT = Value.getSimpleValueType();
721 switch (TLI.getOperationAction(ISD::STORE, VT)) {
722 default: llvm_unreachable("This action is not supported yet!");
723 case TargetLowering::Legal: {
724 // If this is an unaligned store and the target doesn't support it,
726 unsigned AS = ST->getAddressSpace();
727 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT(), AS)) {
728 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
729 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
730 if (ST->getAlignment() < ABIAlignment)
731 ExpandUnalignedStore(cast<StoreSDNode>(Node),
736 case TargetLowering::Custom: {
737 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
739 ReplaceNode(SDValue(Node, 0), Res);
742 case TargetLowering::Promote: {
743 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
744 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
745 "Can only promote stores to same size type");
746 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
748 DAG.getStore(Chain, dl, Value, Ptr,
749 ST->getPointerInfo(), isVolatile,
750 isNonTemporal, Alignment, AAInfo);
751 ReplaceNode(SDValue(Node, 0), Result);
758 SDValue Value = ST->getValue();
760 EVT StVT = ST->getMemoryVT();
761 unsigned StWidth = StVT.getSizeInBits();
763 if (StWidth != StVT.getStoreSizeInBits()) {
764 // Promote to a byte-sized store with upper bits zero if not
765 // storing an integral number of bytes. For example, promote
766 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
767 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
768 StVT.getStoreSizeInBits());
769 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
771 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
772 NVT, isVolatile, isNonTemporal, Alignment,
774 ReplaceNode(SDValue(Node, 0), Result);
775 } else if (StWidth & (StWidth - 1)) {
776 // If not storing a power-of-2 number of bits, expand as two stores.
777 assert(!StVT.isVector() && "Unsupported truncstore!");
778 unsigned RoundWidth = 1 << Log2_32(StWidth);
779 assert(RoundWidth < StWidth);
780 unsigned ExtraWidth = StWidth - RoundWidth;
781 assert(ExtraWidth < RoundWidth);
782 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
783 "Store size not an integral number of bytes!");
784 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
785 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
787 unsigned IncrementSize;
789 if (TLI.isLittleEndian()) {
790 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
791 // Store the bottom RoundWidth bits.
792 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
794 isVolatile, isNonTemporal, Alignment,
797 // Store the remaining ExtraWidth bits.
798 IncrementSize = RoundWidth / 8;
799 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
800 DAG.getConstant(IncrementSize, Ptr.getValueType()));
801 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
802 DAG.getConstant(RoundWidth,
803 TLI.getShiftAmountTy(Value.getValueType())));
804 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
805 ST->getPointerInfo().getWithOffset(IncrementSize),
806 ExtraVT, isVolatile, isNonTemporal,
807 MinAlign(Alignment, IncrementSize), AAInfo);
809 // Big endian - avoid unaligned stores.
810 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
811 // Store the top RoundWidth bits.
812 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
813 DAG.getConstant(ExtraWidth,
814 TLI.getShiftAmountTy(Value.getValueType())));
815 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
816 RoundVT, isVolatile, isNonTemporal, Alignment,
819 // Store the remaining ExtraWidth bits.
820 IncrementSize = RoundWidth / 8;
821 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
822 DAG.getConstant(IncrementSize, Ptr.getValueType()));
823 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
824 ST->getPointerInfo().getWithOffset(IncrementSize),
825 ExtraVT, isVolatile, isNonTemporal,
826 MinAlign(Alignment, IncrementSize), AAInfo);
829 // The order of the stores doesn't matter.
830 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
831 ReplaceNode(SDValue(Node, 0), Result);
833 switch (TLI.getTruncStoreAction(ST->getValue().getSimpleValueType(),
834 StVT.getSimpleVT())) {
835 default: llvm_unreachable("This action is not supported yet!");
836 case TargetLowering::Legal: {
837 unsigned AS = ST->getAddressSpace();
838 // If this is an unaligned store and the target doesn't support it,
840 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT(), AS)) {
841 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
842 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
843 if (ST->getAlignment() < ABIAlignment)
844 ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
848 case TargetLowering::Custom: {
849 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
851 ReplaceNode(SDValue(Node, 0), Res);
854 case TargetLowering::Expand:
855 assert(!StVT.isVector() &&
856 "Vector Stores are handled in LegalizeVectorOps");
858 // TRUNCSTORE:i16 i32 -> STORE i16
859 assert(TLI.isTypeLegal(StVT) &&
860 "Do not know how to expand this store!");
861 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
863 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
864 isVolatile, isNonTemporal, Alignment, AAInfo);
865 ReplaceNode(SDValue(Node, 0), Result);
872 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
873 LoadSDNode *LD = cast<LoadSDNode>(Node);
874 SDValue Chain = LD->getChain(); // The chain.
875 SDValue Ptr = LD->getBasePtr(); // The base pointer.
876 SDValue Value; // The value returned by the load op.
879 ISD::LoadExtType ExtType = LD->getExtensionType();
880 if (ExtType == ISD::NON_EXTLOAD) {
881 MVT VT = Node->getSimpleValueType(0);
882 SDValue RVal = SDValue(Node, 0);
883 SDValue RChain = SDValue(Node, 1);
885 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
886 default: llvm_unreachable("This action is not supported yet!");
887 case TargetLowering::Legal: {
888 unsigned AS = LD->getAddressSpace();
889 // If this is an unaligned load and the target doesn't support it,
891 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT(), AS)) {
892 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
893 unsigned ABIAlignment =
894 TLI.getDataLayout()->getABITypeAlignment(Ty);
895 if (LD->getAlignment() < ABIAlignment){
896 ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, RVal, RChain);
901 case TargetLowering::Custom: {
902 SDValue Res = TLI.LowerOperation(RVal, DAG);
905 RChain = Res.getValue(1);
909 case TargetLowering::Promote: {
910 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
911 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
912 "Can only promote loads to same size type");
914 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
915 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
916 RChain = Res.getValue(1);
920 if (RChain.getNode() != Node) {
921 assert(RVal.getNode() != Node && "Load must be completely replaced");
922 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
923 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
925 UpdatedNodes->insert(RVal.getNode());
926 UpdatedNodes->insert(RChain.getNode());
933 EVT SrcVT = LD->getMemoryVT();
934 unsigned SrcWidth = SrcVT.getSizeInBits();
935 unsigned Alignment = LD->getAlignment();
936 bool isVolatile = LD->isVolatile();
937 bool isNonTemporal = LD->isNonTemporal();
938 AAMDNodes AAInfo = LD->getAAInfo();
940 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
941 // Some targets pretend to have an i1 loading operation, and actually
942 // load an i8. This trick is correct for ZEXTLOAD because the top 7
943 // bits are guaranteed to be zero; it helps the optimizers understand
944 // that these bits are zero. It is also useful for EXTLOAD, since it
945 // tells the optimizers that those bits are undefined. It would be
946 // nice to have an effective generic way of getting these benefits...
947 // Until such a way is found, don't insist on promoting i1 here.
949 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
950 // Promote to a byte-sized load if not loading an integral number of
951 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
952 unsigned NewWidth = SrcVT.getStoreSizeInBits();
953 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
956 // The extra bits are guaranteed to be zero, since we stored them that
957 // way. A zext load from NVT thus automatically gives zext from SrcVT.
959 ISD::LoadExtType NewExtType =
960 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
963 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
964 Chain, Ptr, LD->getPointerInfo(),
965 NVT, isVolatile, isNonTemporal, Alignment, AAInfo);
967 Ch = Result.getValue(1); // The chain.
969 if (ExtType == ISD::SEXTLOAD)
970 // Having the top bits zero doesn't help when sign extending.
971 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
972 Result.getValueType(),
973 Result, DAG.getValueType(SrcVT));
974 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
975 // All the top bits are guaranteed to be zero - inform the optimizers.
976 Result = DAG.getNode(ISD::AssertZext, dl,
977 Result.getValueType(), Result,
978 DAG.getValueType(SrcVT));
982 } else if (SrcWidth & (SrcWidth - 1)) {
983 // If not loading a power-of-2 number of bits, expand as two loads.
984 assert(!SrcVT.isVector() && "Unsupported extload!");
985 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
986 assert(RoundWidth < SrcWidth);
987 unsigned ExtraWidth = SrcWidth - RoundWidth;
988 assert(ExtraWidth < RoundWidth);
989 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
990 "Load size not an integral number of bytes!");
991 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
992 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
994 unsigned IncrementSize;
996 if (TLI.isLittleEndian()) {
997 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
998 // Load the bottom RoundWidth bits.
999 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1001 LD->getPointerInfo(), RoundVT, isVolatile,
1002 isNonTemporal, Alignment, AAInfo);
1004 // Load the remaining ExtraWidth bits.
1005 IncrementSize = RoundWidth / 8;
1006 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1007 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1008 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1009 LD->getPointerInfo().getWithOffset(IncrementSize),
1010 ExtraVT, isVolatile, isNonTemporal,
1011 MinAlign(Alignment, IncrementSize), AAInfo);
1013 // Build a factor node to remember that this load is independent of
1015 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1018 // Move the top bits to the right place.
1019 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1020 DAG.getConstant(RoundWidth,
1021 TLI.getShiftAmountTy(Hi.getValueType())));
1023 // Join the hi and lo parts.
1024 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1026 // Big endian - avoid unaligned loads.
1027 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1028 // Load the top RoundWidth bits.
1029 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1030 LD->getPointerInfo(), RoundVT, isVolatile,
1031 isNonTemporal, Alignment, AAInfo);
1033 // Load the remaining ExtraWidth bits.
1034 IncrementSize = RoundWidth / 8;
1035 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1036 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1037 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1038 dl, Node->getValueType(0), Chain, Ptr,
1039 LD->getPointerInfo().getWithOffset(IncrementSize),
1040 ExtraVT, isVolatile, isNonTemporal,
1041 MinAlign(Alignment, IncrementSize), AAInfo);
1043 // Build a factor node to remember that this load is independent of
1045 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1048 // Move the top bits to the right place.
1049 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1050 DAG.getConstant(ExtraWidth,
1051 TLI.getShiftAmountTy(Hi.getValueType())));
1053 // Join the hi and lo parts.
1054 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1059 bool isCustom = false;
1060 switch (TLI.getLoadExtAction(ExtType, SrcVT.getSimpleVT())) {
1061 default: llvm_unreachable("This action is not supported yet!");
1062 case TargetLowering::Custom:
1065 case TargetLowering::Legal: {
1066 Value = SDValue(Node, 0);
1067 Chain = SDValue(Node, 1);
1070 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1071 if (Res.getNode()) {
1073 Chain = Res.getValue(1);
1076 // If this is an unaligned load and the target doesn't support
1078 EVT MemVT = LD->getMemoryVT();
1079 unsigned AS = LD->getAddressSpace();
1080 if (!TLI.allowsUnalignedMemoryAccesses(MemVT, AS)) {
1082 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1083 unsigned ABIAlignment =
1084 TLI.getDataLayout()->getABITypeAlignment(Ty);
1085 if (LD->getAlignment() < ABIAlignment){
1086 ExpandUnalignedLoad(cast<LoadSDNode>(Node),
1087 DAG, TLI, Value, Chain);
1093 case TargetLowering::Expand:
1094 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) &&
1095 TLI.isTypeLegal(SrcVT)) {
1096 SDValue Load = DAG.getLoad(SrcVT, dl, Chain, Ptr,
1097 LD->getMemOperand());
1101 ExtendOp = (SrcVT.isFloatingPoint() ?
1102 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1104 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1105 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1106 default: llvm_unreachable("Unexpected extend load type!");
1108 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1109 Chain = Load.getValue(1);
1113 assert(!SrcVT.isVector() &&
1114 "Vector Loads are handled in LegalizeVectorOps");
1116 // FIXME: This does not work for vectors on most targets. Sign-
1117 // and zero-extend operations are currently folded into extending
1118 // loads, whether they are legal or not, and then we end up here
1119 // without any support for legalizing them.
1120 assert(ExtType != ISD::EXTLOAD &&
1121 "EXTLOAD should always be supported!");
1122 // Turn the unsupported load into an EXTLOAD followed by an
1123 // explicit zero/sign extend inreg.
1124 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
1125 Node->getValueType(0),
1127 LD->getMemOperand());
1129 if (ExtType == ISD::SEXTLOAD)
1130 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1131 Result.getValueType(),
1132 Result, DAG.getValueType(SrcVT));
1134 ValRes = DAG.getZeroExtendInReg(Result, dl,
1135 SrcVT.getScalarType());
1137 Chain = Result.getValue(1);
1142 // Since loads produce two values, make sure to remember that we legalized
1144 if (Chain.getNode() != Node) {
1145 assert(Value.getNode() != Node && "Load must be completely replaced");
1146 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
1147 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
1149 UpdatedNodes->insert(Value.getNode());
1150 UpdatedNodes->insert(Chain.getNode());
1156 /// LegalizeOp - Return a legal replacement for the given operation, with
1157 /// all legal operands.
1158 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
1159 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
1162 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1163 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
1164 TargetLowering::TypeLegal &&
1165 "Unexpected illegal type!");
1167 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1168 assert((TLI.getTypeAction(*DAG.getContext(),
1169 Node->getOperand(i).getValueType()) ==
1170 TargetLowering::TypeLegal ||
1171 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
1172 "Unexpected illegal type!");
1174 // Figure out the correct action; the way to query this varies by opcode
1175 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1176 bool SimpleFinishLegalizing = true;
1177 switch (Node->getOpcode()) {
1178 case ISD::INTRINSIC_W_CHAIN:
1179 case ISD::INTRINSIC_WO_CHAIN:
1180 case ISD::INTRINSIC_VOID:
1181 case ISD::STACKSAVE:
1182 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1185 Action = TLI.getOperationAction(Node->getOpcode(),
1186 Node->getValueType(0));
1187 if (Action != TargetLowering::Promote)
1188 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1190 case ISD::FP_TO_FP16:
1191 case ISD::SINT_TO_FP:
1192 case ISD::UINT_TO_FP:
1193 case ISD::EXTRACT_VECTOR_ELT:
1194 Action = TLI.getOperationAction(Node->getOpcode(),
1195 Node->getOperand(0).getValueType());
1197 case ISD::FP_ROUND_INREG:
1198 case ISD::SIGN_EXTEND_INREG: {
1199 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1200 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1203 case ISD::ATOMIC_STORE: {
1204 Action = TLI.getOperationAction(Node->getOpcode(),
1205 Node->getOperand(2).getValueType());
1208 case ISD::SELECT_CC:
1211 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1212 Node->getOpcode() == ISD::SETCC ? 2 : 1;
1213 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1214 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1215 ISD::CondCode CCCode =
1216 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1217 Action = TLI.getCondCodeAction(CCCode, OpVT);
1218 if (Action == TargetLowering::Legal) {
1219 if (Node->getOpcode() == ISD::SELECT_CC)
1220 Action = TLI.getOperationAction(Node->getOpcode(),
1221 Node->getValueType(0));
1223 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1229 // FIXME: Model these properly. LOAD and STORE are complicated, and
1230 // STORE expects the unlegalized operand in some cases.
1231 SimpleFinishLegalizing = false;
1233 case ISD::CALLSEQ_START:
1234 case ISD::CALLSEQ_END:
1235 // FIXME: This shouldn't be necessary. These nodes have special properties
1236 // dealing with the recursive nature of legalization. Removing this
1237 // special case should be done as part of making LegalizeDAG non-recursive.
1238 SimpleFinishLegalizing = false;
1240 case ISD::EXTRACT_ELEMENT:
1241 case ISD::FLT_ROUNDS_:
1249 case ISD::MERGE_VALUES:
1250 case ISD::EH_RETURN:
1251 case ISD::FRAME_TO_ARGS_OFFSET:
1252 case ISD::EH_SJLJ_SETJMP:
1253 case ISD::EH_SJLJ_LONGJMP:
1254 // These operations lie about being legal: when they claim to be legal,
1255 // they should actually be expanded.
1256 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1257 if (Action == TargetLowering::Legal)
1258 Action = TargetLowering::Expand;
1260 case ISD::INIT_TRAMPOLINE:
1261 case ISD::ADJUST_TRAMPOLINE:
1262 case ISD::FRAMEADDR:
1263 case ISD::RETURNADDR:
1264 // These operations lie about being legal: when they claim to be legal,
1265 // they should actually be custom-lowered.
1266 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1267 if (Action == TargetLowering::Legal)
1268 Action = TargetLowering::Custom;
1270 case ISD::READ_REGISTER:
1271 case ISD::WRITE_REGISTER:
1272 // Named register is legal in the DAG, but blocked by register name
1273 // selection if not implemented by target (to chose the correct register)
1274 // They'll be converted to Copy(To/From)Reg.
1275 Action = TargetLowering::Legal;
1277 case ISD::DEBUGTRAP:
1278 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1279 if (Action == TargetLowering::Expand) {
1280 // replace ISD::DEBUGTRAP with ISD::TRAP
1282 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1283 Node->getOperand(0));
1284 ReplaceNode(Node, NewVal.getNode());
1285 LegalizeOp(NewVal.getNode());
1291 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1292 Action = TargetLowering::Legal;
1294 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1299 if (SimpleFinishLegalizing) {
1300 SDNode *NewNode = Node;
1301 switch (Node->getOpcode()) {
1308 // Legalizing shifts/rotates requires adjusting the shift amount
1309 // to the appropriate width.
1310 if (!Node->getOperand(1).getValueType().isVector()) {
1312 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1313 Node->getOperand(1));
1314 HandleSDNode Handle(SAO);
1315 LegalizeOp(SAO.getNode());
1316 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1320 case ISD::SRL_PARTS:
1321 case ISD::SRA_PARTS:
1322 case ISD::SHL_PARTS:
1323 // Legalizing shifts/rotates requires adjusting the shift amount
1324 // to the appropriate width.
1325 if (!Node->getOperand(2).getValueType().isVector()) {
1327 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1328 Node->getOperand(2));
1329 HandleSDNode Handle(SAO);
1330 LegalizeOp(SAO.getNode());
1331 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1332 Node->getOperand(1),
1338 if (NewNode != Node) {
1339 ReplaceNode(Node, NewNode);
1343 case TargetLowering::Legal:
1345 case TargetLowering::Custom: {
1346 // FIXME: The handling for custom lowering with multiple results is
1348 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1349 if (Res.getNode()) {
1350 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1353 if (Node->getNumValues() == 1) {
1354 // We can just directly replace this node with the lowered value.
1355 ReplaceNode(SDValue(Node, 0), Res);
1359 SmallVector<SDValue, 8> ResultVals;
1360 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1361 ResultVals.push_back(Res.getValue(i));
1362 ReplaceNode(Node, ResultVals.data());
1367 case TargetLowering::Expand:
1370 case TargetLowering::Promote:
1376 switch (Node->getOpcode()) {
1383 llvm_unreachable("Do not know how to legalize this operator!");
1385 case ISD::CALLSEQ_START:
1386 case ISD::CALLSEQ_END:
1389 return LegalizeLoadOps(Node);
1392 return LegalizeStoreOps(Node);
1397 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1398 SDValue Vec = Op.getOperand(0);
1399 SDValue Idx = Op.getOperand(1);
1402 // Before we generate a new store to a temporary stack slot, see if there is
1403 // already one that we can use. There often is because when we scalarize
1404 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1405 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1406 // the vector. If all are expanded here, we don't want one store per vector
1408 SDValue StackPtr, Ch;
1409 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1410 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1412 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1413 if (ST->isIndexed() || ST->isTruncatingStore() ||
1414 ST->getValue() != Vec)
1417 // Make sure that nothing else could have stored into the destination of
1419 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1422 StackPtr = ST->getBasePtr();
1423 Ch = SDValue(ST, 0);
1428 if (!Ch.getNode()) {
1429 // Store the value to a temporary stack slot, then LOAD the returned part.
1430 StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1431 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1432 MachinePointerInfo(), false, false, 0);
1435 // Add the offset to the index.
1437 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1438 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1439 DAG.getConstant(EltSize, Idx.getValueType()));
1441 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1442 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1444 if (Op.getValueType().isVector())
1445 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1446 false, false, false, 0);
1447 return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1448 MachinePointerInfo(),
1449 Vec.getValueType().getVectorElementType(),
1453 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1454 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1456 SDValue Vec = Op.getOperand(0);
1457 SDValue Part = Op.getOperand(1);
1458 SDValue Idx = Op.getOperand(2);
1461 // Store the value to a temporary stack slot, then LOAD the returned part.
1463 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1464 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1465 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1467 // First store the whole vector.
1468 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1471 // Then store the inserted part.
1473 // Add the offset to the index.
1475 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1477 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1478 DAG.getConstant(EltSize, Idx.getValueType()));
1479 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1481 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1484 // Store the subvector.
1485 Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1486 MachinePointerInfo(), false, false, 0);
1488 // Finally, load the updated vector.
1489 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1490 false, false, false, 0);
1493 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1494 // We can't handle this case efficiently. Allocate a sufficiently
1495 // aligned object on the stack, store each element into it, then load
1496 // the result as a vector.
1497 // Create the stack frame object.
1498 EVT VT = Node->getValueType(0);
1499 EVT EltVT = VT.getVectorElementType();
1501 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1502 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1503 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1505 // Emit a store of each element to the stack slot.
1506 SmallVector<SDValue, 8> Stores;
1507 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1508 // Store (in the right endianness) the elements to memory.
1509 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1510 // Ignore undef elements.
1511 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1513 unsigned Offset = TypeByteSize*i;
1515 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1516 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1518 // If the destination vector element type is narrower than the source
1519 // element type, only store the bits necessary.
1520 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1521 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1522 Node->getOperand(i), Idx,
1523 PtrInfo.getWithOffset(Offset),
1524 EltVT, false, false, 0));
1526 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1527 Node->getOperand(i), Idx,
1528 PtrInfo.getWithOffset(Offset),
1533 if (!Stores.empty()) // Not all undef elements?
1534 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1536 StoreChain = DAG.getEntryNode();
1538 // Result is a load from the stack slot.
1539 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
1540 false, false, false, 0);
1543 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1545 SDValue Tmp1 = Node->getOperand(0);
1546 SDValue Tmp2 = Node->getOperand(1);
1548 // Get the sign bit of the RHS. First obtain a value that has the same
1549 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1551 EVT FloatVT = Tmp2.getValueType();
1552 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1553 if (TLI.isTypeLegal(IVT)) {
1554 // Convert to an integer with the same sign bit.
1555 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1557 // Store the float to memory, then load the sign part out as an integer.
1558 MVT LoadTy = TLI.getPointerTy();
1559 // First create a temporary that is aligned for both the load and store.
1560 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1561 // Then store the float to it.
1563 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1565 if (TLI.isBigEndian()) {
1566 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1567 // Load out a legal integer with the same sign bit as the float.
1568 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1569 false, false, false, 0);
1570 } else { // Little endian
1571 SDValue LoadPtr = StackPtr;
1572 // The float may be wider than the integer we are going to load. Advance
1573 // the pointer so that the loaded integer will contain the sign bit.
1574 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1575 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1576 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(), LoadPtr,
1577 DAG.getConstant(ByteOffset, LoadPtr.getValueType()));
1578 // Load a legal integer containing the sign bit.
1579 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1580 false, false, false, 0);
1581 // Move the sign bit to the top bit of the loaded integer.
1582 unsigned BitShift = LoadTy.getSizeInBits() -
1583 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1584 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1586 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1587 DAG.getConstant(BitShift,
1588 TLI.getShiftAmountTy(SignBit.getValueType())));
1591 // Now get the sign bit proper, by seeing whether the value is negative.
1592 SignBit = DAG.getSetCC(dl, getSetCCResultType(SignBit.getValueType()),
1593 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1595 // Get the absolute value of the result.
1596 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1597 // Select between the nabs and abs value based on the sign bit of
1599 return DAG.getSelect(dl, AbsVal.getValueType(), SignBit,
1600 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1604 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1605 SmallVectorImpl<SDValue> &Results) {
1606 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1607 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1608 " not tell us which reg is the stack pointer!");
1610 EVT VT = Node->getValueType(0);
1611 SDValue Tmp1 = SDValue(Node, 0);
1612 SDValue Tmp2 = SDValue(Node, 1);
1613 SDValue Tmp3 = Node->getOperand(2);
1614 SDValue Chain = Tmp1.getOperand(0);
1616 // Chain the dynamic stack allocation so that it doesn't modify the stack
1617 // pointer when other instructions are using the stack.
1618 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
1621 SDValue Size = Tmp2.getOperand(1);
1622 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1623 Chain = SP.getValue(1);
1624 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1625 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1626 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1627 if (Align > StackAlign)
1628 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1629 DAG.getConstant(-(uint64_t)Align, VT));
1630 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1632 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1633 DAG.getIntPtrConstant(0, true), SDValue(),
1636 Results.push_back(Tmp1);
1637 Results.push_back(Tmp2);
1640 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1641 /// condition code CC on the current target.
1643 /// If the SETCC has been legalized using AND / OR, then the legalized node
1644 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1645 /// will be set to false.
1647 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1648 /// then the values of LHS and RHS will be swapped, CC will be set to the
1649 /// new condition, and NeedInvert will be set to false.
1651 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1652 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1653 /// will be set to true. The caller must invert the result of the SETCC with
1654 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1655 /// of a true/false result.
1657 /// \returns true if the SetCC has been legalized, false if it hasn't.
1658 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1659 SDValue &LHS, SDValue &RHS,
1663 MVT OpVT = LHS.getSimpleValueType();
1664 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1666 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1667 default: llvm_unreachable("Unknown condition code action!");
1668 case TargetLowering::Legal:
1671 case TargetLowering::Expand: {
1672 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1673 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1674 std::swap(LHS, RHS);
1675 CC = DAG.getCondCode(InvCC);
1678 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1681 default: llvm_unreachable("Don't know how to expand this condition!");
1683 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
1684 == TargetLowering::Legal
1685 && "If SETO is expanded, SETOEQ must be legal!");
1686 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1688 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
1689 == TargetLowering::Legal
1690 && "If SETUO is expanded, SETUNE must be legal!");
1691 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1704 // If we are floating point, assign and break, otherwise fall through.
1705 if (!OpVT.isInteger()) {
1706 // We can use the 4th bit to tell if we are the unordered
1707 // or ordered version of the opcode.
1708 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1709 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1710 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1713 // Fallthrough if we are unsigned integer.
1718 // We only support using the inverted operation, which is computed above
1719 // and not a different manner of supporting expanding these cases.
1720 llvm_unreachable("Don't know how to expand this condition!");
1723 // Try inverting the result of the inverse condition.
1724 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
1725 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1726 CC = DAG.getCondCode(InvCC);
1730 // If inverting the condition didn't work then we have no means to expand
1732 llvm_unreachable("Don't know how to expand this condition!");
1735 SDValue SetCC1, SetCC2;
1736 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1737 // If we aren't the ordered or unorder operation,
1738 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1739 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1740 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1742 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1743 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1744 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1746 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1755 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1756 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1757 /// a load from the stack slot to DestVT, extending it if needed.
1758 /// The resultant code need not be legal.
1759 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1763 // Create the stack frame object.
1765 TLI.getDataLayout()->getPrefTypeAlignment(SrcOp.getValueType().
1766 getTypeForEVT(*DAG.getContext()));
1767 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1769 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1770 int SPFI = StackPtrFI->getIndex();
1771 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1773 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1774 unsigned SlotSize = SlotVT.getSizeInBits();
1775 unsigned DestSize = DestVT.getSizeInBits();
1776 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1777 unsigned DestAlign = TLI.getDataLayout()->getPrefTypeAlignment(DestType);
1779 // Emit a store to the stack slot. Use a truncstore if the input value is
1780 // later than DestVT.
1783 if (SrcSize > SlotSize)
1784 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1785 PtrInfo, SlotVT, false, false, SrcAlign);
1787 assert(SrcSize == SlotSize && "Invalid store");
1788 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1789 PtrInfo, false, false, SrcAlign);
1792 // Result is a load from the stack slot.
1793 if (SlotSize == DestSize)
1794 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1795 false, false, false, DestAlign);
1797 assert(SlotSize < DestSize && "Unknown extension!");
1798 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
1799 PtrInfo, SlotVT, false, false, DestAlign);
1802 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1804 // Create a vector sized/aligned stack slot, store the value to element #0,
1805 // then load the whole vector back out.
1806 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1808 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1809 int SPFI = StackPtrFI->getIndex();
1811 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1813 MachinePointerInfo::getFixedStack(SPFI),
1814 Node->getValueType(0).getVectorElementType(),
1816 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1817 MachinePointerInfo::getFixedStack(SPFI),
1818 false, false, false, 0);
1822 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1823 const TargetLowering &TLI, SDValue &Res) {
1824 unsigned NumElems = Node->getNumOperands();
1826 EVT VT = Node->getValueType(0);
1828 // Try to group the scalars into pairs, shuffle the pairs together, then
1829 // shuffle the pairs of pairs together, etc. until the vector has
1830 // been built. This will work only if all of the necessary shuffle masks
1833 // We do this in two phases; first to check the legality of the shuffles,
1834 // and next, assuming that all shuffles are legal, to create the new nodes.
1835 for (int Phase = 0; Phase < 2; ++Phase) {
1836 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
1838 for (unsigned i = 0; i < NumElems; ++i) {
1839 SDValue V = Node->getOperand(i);
1840 if (V.getOpcode() == ISD::UNDEF)
1845 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1846 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1849 while (IntermedVals.size() > 2) {
1850 NewIntermedVals.clear();
1851 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1852 // This vector and the next vector are shuffled together (simply to
1853 // append the one to the other).
1854 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1856 SmallVector<int, 16> FinalIndices;
1857 FinalIndices.reserve(IntermedVals[i].second.size() +
1858 IntermedVals[i+1].second.size());
1861 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1864 FinalIndices.push_back(IntermedVals[i].second[j]);
1866 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1868 ShuffleVec[k] = NumElems + j;
1869 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1874 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1875 IntermedVals[i+1].first,
1877 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1879 NewIntermedVals.push_back(std::make_pair(Shuffle, FinalIndices));
1882 // If we had an odd number of defined values, then append the last
1883 // element to the array of new vectors.
1884 if ((IntermedVals.size() & 1) != 0)
1885 NewIntermedVals.push_back(IntermedVals.back());
1887 IntermedVals.swap(NewIntermedVals);
1890 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1891 "Invalid number of intermediate vectors");
1892 SDValue Vec1 = IntermedVals[0].first;
1894 if (IntermedVals.size() > 1)
1895 Vec2 = IntermedVals[1].first;
1897 Vec2 = DAG.getUNDEF(VT);
1899 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1900 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1901 ShuffleVec[IntermedVals[0].second[i]] = i;
1902 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1903 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1906 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1907 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1914 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1915 /// support the operation, but do support the resultant vector type.
1916 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1917 unsigned NumElems = Node->getNumOperands();
1918 SDValue Value1, Value2;
1920 EVT VT = Node->getValueType(0);
1921 EVT OpVT = Node->getOperand(0).getValueType();
1922 EVT EltVT = VT.getVectorElementType();
1924 // If the only non-undef value is the low element, turn this into a
1925 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1926 bool isOnlyLowElement = true;
1927 bool MoreThanTwoValues = false;
1928 bool isConstant = true;
1929 for (unsigned i = 0; i < NumElems; ++i) {
1930 SDValue V = Node->getOperand(i);
1931 if (V.getOpcode() == ISD::UNDEF)
1934 isOnlyLowElement = false;
1935 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1938 if (!Value1.getNode()) {
1940 } else if (!Value2.getNode()) {
1943 } else if (V != Value1 && V != Value2) {
1944 MoreThanTwoValues = true;
1948 if (!Value1.getNode())
1949 return DAG.getUNDEF(VT);
1951 if (isOnlyLowElement)
1952 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1954 // If all elements are constants, create a load from the constant pool.
1956 SmallVector<Constant*, 16> CV;
1957 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1958 if (ConstantFPSDNode *V =
1959 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1960 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1961 } else if (ConstantSDNode *V =
1962 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1964 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1966 // If OpVT and EltVT don't match, EltVT is not legal and the
1967 // element values have been promoted/truncated earlier. Undo this;
1968 // we don't want a v16i8 to become a v16i32 for example.
1969 const ConstantInt *CI = V->getConstantIntValue();
1970 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1971 CI->getZExtValue()));
1974 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1975 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1976 CV.push_back(UndefValue::get(OpNTy));
1979 Constant *CP = ConstantVector::get(CV);
1980 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1981 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1982 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1983 MachinePointerInfo::getConstantPool(),
1984 false, false, false, Alignment);
1987 SmallSet<SDValue, 16> DefinedValues;
1988 for (unsigned i = 0; i < NumElems; ++i) {
1989 if (Node->getOperand(i).getOpcode() == ISD::UNDEF)
1991 DefinedValues.insert(Node->getOperand(i));
1994 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1995 if (!MoreThanTwoValues) {
1996 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1997 for (unsigned i = 0; i < NumElems; ++i) {
1998 SDValue V = Node->getOperand(i);
1999 if (V.getOpcode() == ISD::UNDEF)
2001 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2003 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2004 // Get the splatted value into the low element of a vector register.
2005 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2007 if (Value2.getNode())
2008 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2010 Vec2 = DAG.getUNDEF(VT);
2012 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2013 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2017 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2022 // Otherwise, we can't handle this case efficiently.
2023 return ExpandVectorBuildThroughStack(Node);
2026 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
2027 // does not fit into a register, return the lo part and set the hi part to the
2028 // by-reg argument. If it does fit into a single register, return the result
2029 // and leave the Hi part unset.
2030 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2032 TargetLowering::ArgListTy Args;
2033 TargetLowering::ArgListEntry Entry;
2034 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2035 EVT ArgVT = Node->getOperand(i).getValueType();
2036 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2037 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2038 Entry.isSExt = isSigned;
2039 Entry.isZExt = !isSigned;
2040 Args.push_back(Entry);
2042 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2043 TLI.getPointerTy());
2045 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2047 // By default, the input chain to this libcall is the entry node of the
2048 // function. If the libcall is going to be emitted as a tail call then
2049 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2050 // node which is being folded has a non-entry input chain.
2051 SDValue InChain = DAG.getEntryNode();
2053 // isTailCall may be true since the callee does not reference caller stack
2054 // frame. Check if it's in the right position.
2055 SDValue TCChain = InChain;
2056 bool isTailCall = TLI.isInTailCallPosition(DAG, Node, TCChain);
2060 TargetLowering::CallLoweringInfo CLI(DAG);
2061 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2062 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2063 .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned);
2065 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2067 if (!CallInfo.second.getNode())
2068 // It's a tailcall, return the chain (which is the DAG root).
2069 return DAG.getRoot();
2071 return CallInfo.first;
2074 /// ExpandLibCall - Generate a libcall taking the given operands as arguments
2075 /// and returning a result of type RetVT.
2076 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2077 const SDValue *Ops, unsigned NumOps,
2078 bool isSigned, SDLoc dl) {
2079 TargetLowering::ArgListTy Args;
2080 Args.reserve(NumOps);
2082 TargetLowering::ArgListEntry Entry;
2083 for (unsigned i = 0; i != NumOps; ++i) {
2084 Entry.Node = Ops[i];
2085 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2086 Entry.isSExt = isSigned;
2087 Entry.isZExt = !isSigned;
2088 Args.push_back(Entry);
2090 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2091 TLI.getPointerTy());
2093 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2095 TargetLowering::CallLoweringInfo CLI(DAG);
2096 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2097 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2098 .setSExtResult(isSigned).setZExtResult(!isSigned);
2100 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
2102 return CallInfo.first;
2105 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
2106 // ExpandLibCall except that the first operand is the in-chain.
2107 std::pair<SDValue, SDValue>
2108 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2111 SDValue InChain = Node->getOperand(0);
2113 TargetLowering::ArgListTy Args;
2114 TargetLowering::ArgListEntry Entry;
2115 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2116 EVT ArgVT = Node->getOperand(i).getValueType();
2117 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2118 Entry.Node = Node->getOperand(i);
2120 Entry.isSExt = isSigned;
2121 Entry.isZExt = !isSigned;
2122 Args.push_back(Entry);
2124 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2125 TLI.getPointerTy());
2127 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2129 TargetLowering::CallLoweringInfo CLI(DAG);
2130 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2131 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2132 .setSExtResult(isSigned).setZExtResult(!isSigned);
2134 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2139 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2140 RTLIB::Libcall Call_F32,
2141 RTLIB::Libcall Call_F64,
2142 RTLIB::Libcall Call_F80,
2143 RTLIB::Libcall Call_F128,
2144 RTLIB::Libcall Call_PPCF128) {
2146 switch (Node->getSimpleValueType(0).SimpleTy) {
2147 default: llvm_unreachable("Unexpected request for libcall!");
2148 case MVT::f32: LC = Call_F32; break;
2149 case MVT::f64: LC = Call_F64; break;
2150 case MVT::f80: LC = Call_F80; break;
2151 case MVT::f128: LC = Call_F128; break;
2152 case MVT::ppcf128: LC = Call_PPCF128; break;
2154 return ExpandLibCall(LC, Node, false);
2157 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2158 RTLIB::Libcall Call_I8,
2159 RTLIB::Libcall Call_I16,
2160 RTLIB::Libcall Call_I32,
2161 RTLIB::Libcall Call_I64,
2162 RTLIB::Libcall Call_I128) {
2164 switch (Node->getSimpleValueType(0).SimpleTy) {
2165 default: llvm_unreachable("Unexpected request for libcall!");
2166 case MVT::i8: LC = Call_I8; break;
2167 case MVT::i16: LC = Call_I16; break;
2168 case MVT::i32: LC = Call_I32; break;
2169 case MVT::i64: LC = Call_I64; break;
2170 case MVT::i128: LC = Call_I128; break;
2172 return ExpandLibCall(LC, Node, isSigned);
2175 /// isDivRemLibcallAvailable - Return true if divmod libcall is available.
2176 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2177 const TargetLowering &TLI) {
2179 switch (Node->getSimpleValueType(0).SimpleTy) {
2180 default: llvm_unreachable("Unexpected request for libcall!");
2181 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2182 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2183 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2184 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2185 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2188 return TLI.getLibcallName(LC) != nullptr;
2191 /// useDivRem - Only issue divrem libcall if both quotient and remainder are
2193 static bool useDivRem(SDNode *Node, bool isSigned, bool isDIV) {
2194 // The other use might have been replaced with a divrem already.
2195 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2196 unsigned OtherOpcode = 0;
2198 OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
2200 OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
2202 SDValue Op0 = Node->getOperand(0);
2203 SDValue Op1 = Node->getOperand(1);
2204 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2205 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2209 if ((User->getOpcode() == OtherOpcode || User->getOpcode() == DivRemOpc) &&
2210 User->getOperand(0) == Op0 &&
2211 User->getOperand(1) == Op1)
2217 /// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
2220 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2221 SmallVectorImpl<SDValue> &Results) {
2222 unsigned Opcode = Node->getOpcode();
2223 bool isSigned = Opcode == ISD::SDIVREM;
2226 switch (Node->getSimpleValueType(0).SimpleTy) {
2227 default: llvm_unreachable("Unexpected request for libcall!");
2228 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2229 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2230 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2231 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2232 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2235 // The input chain to this libcall is the entry node of the function.
2236 // Legalizing the call will automatically add the previous call to the
2238 SDValue InChain = DAG.getEntryNode();
2240 EVT RetVT = Node->getValueType(0);
2241 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2243 TargetLowering::ArgListTy Args;
2244 TargetLowering::ArgListEntry Entry;
2245 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2246 EVT ArgVT = Node->getOperand(i).getValueType();
2247 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2248 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2249 Entry.isSExt = isSigned;
2250 Entry.isZExt = !isSigned;
2251 Args.push_back(Entry);
2254 // Also pass the return address of the remainder.
2255 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2257 Entry.Ty = RetTy->getPointerTo();
2258 Entry.isSExt = isSigned;
2259 Entry.isZExt = !isSigned;
2260 Args.push_back(Entry);
2262 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2263 TLI.getPointerTy());
2266 TargetLowering::CallLoweringInfo CLI(DAG);
2267 CLI.setDebugLoc(dl).setChain(InChain)
2268 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2269 .setSExtResult(isSigned).setZExtResult(!isSigned);
2271 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2273 // Remainder is loaded back from the stack frame.
2274 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
2275 MachinePointerInfo(), false, false, false, 0);
2276 Results.push_back(CallInfo.first);
2277 Results.push_back(Rem);
2280 /// isSinCosLibcallAvailable - Return true if sincos libcall is available.
2281 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2283 switch (Node->getSimpleValueType(0).SimpleTy) {
2284 default: llvm_unreachable("Unexpected request for libcall!");
2285 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2286 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2287 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2288 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2289 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2291 return TLI.getLibcallName(LC) != nullptr;
2294 /// canCombineSinCosLibcall - Return true if sincos libcall is available and
2295 /// can be used to combine sin and cos.
2296 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
2297 const TargetMachine &TM) {
2298 if (!isSinCosLibcallAvailable(Node, TLI))
2300 // GNU sin/cos functions set errno while sincos does not. Therefore
2301 // combining sin and cos is only safe if unsafe-fpmath is enabled.
2302 bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU;
2303 if (isGNU && !TM.Options.UnsafeFPMath)
2308 /// useSinCos - Only issue sincos libcall if both sin and cos are
2310 static bool useSinCos(SDNode *Node) {
2311 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2312 ? ISD::FCOS : ISD::FSIN;
2314 SDValue Op0 = Node->getOperand(0);
2315 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2316 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2320 // The other user might have been turned into sincos already.
2321 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2327 /// ExpandSinCosLibCall - Issue libcalls to sincos to compute sin / cos
2330 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2331 SmallVectorImpl<SDValue> &Results) {
2333 switch (Node->getSimpleValueType(0).SimpleTy) {
2334 default: llvm_unreachable("Unexpected request for libcall!");
2335 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2336 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2337 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2338 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2339 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2342 // The input chain to this libcall is the entry node of the function.
2343 // Legalizing the call will automatically add the previous call to the
2345 SDValue InChain = DAG.getEntryNode();
2347 EVT RetVT = Node->getValueType(0);
2348 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2350 TargetLowering::ArgListTy Args;
2351 TargetLowering::ArgListEntry Entry;
2353 // Pass the argument.
2354 Entry.Node = Node->getOperand(0);
2356 Entry.isSExt = false;
2357 Entry.isZExt = false;
2358 Args.push_back(Entry);
2360 // Pass the return address of sin.
2361 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2362 Entry.Node = SinPtr;
2363 Entry.Ty = RetTy->getPointerTo();
2364 Entry.isSExt = false;
2365 Entry.isZExt = false;
2366 Args.push_back(Entry);
2368 // Also pass the return address of the cos.
2369 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2370 Entry.Node = CosPtr;
2371 Entry.Ty = RetTy->getPointerTo();
2372 Entry.isSExt = false;
2373 Entry.isZExt = false;
2374 Args.push_back(Entry);
2376 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2377 TLI.getPointerTy());
2380 TargetLowering::CallLoweringInfo CLI(DAG);
2381 CLI.setDebugLoc(dl).setChain(InChain)
2382 .setCallee(TLI.getLibcallCallingConv(LC),
2383 Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0);
2385 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2387 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr,
2388 MachinePointerInfo(), false, false, false, 0));
2389 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr,
2390 MachinePointerInfo(), false, false, false, 0));
2393 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2394 /// INT_TO_FP operation of the specified operand when the target requests that
2395 /// we expand it. At this point, we know that the result and operand types are
2396 /// legal for the target.
2397 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2401 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2402 // simple 32-bit [signed|unsigned] integer to float/double expansion
2404 // Get the stack frame index of a 8 byte buffer.
2405 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2407 // word offset constant for Hi/Lo address computation
2408 SDValue WordOff = DAG.getConstant(sizeof(int), StackSlot.getValueType());
2409 // set up Hi and Lo (into buffer) address based on endian
2410 SDValue Hi = StackSlot;
2411 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2412 StackSlot, WordOff);
2413 if (TLI.isLittleEndian())
2416 // if signed map to unsigned space
2419 // constant used to invert sign bit (signed to unsigned mapping)
2420 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2421 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2425 // store the lo of the constructed double - based on integer input
2426 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2427 Op0Mapped, Lo, MachinePointerInfo(),
2429 // initial hi portion of constructed double
2430 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2431 // store the hi of the constructed double - biased exponent
2432 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2433 MachinePointerInfo(),
2435 // load the constructed double
2436 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2437 MachinePointerInfo(), false, false, false, 0);
2438 // FP constant to bias correct the final result
2439 SDValue Bias = DAG.getConstantFP(isSigned ?
2440 BitsToDouble(0x4330000080000000ULL) :
2441 BitsToDouble(0x4330000000000000ULL),
2443 // subtract the bias
2444 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2447 // handle final rounding
2448 if (DestVT == MVT::f64) {
2451 } else if (DestVT.bitsLT(MVT::f64)) {
2452 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2453 DAG.getIntPtrConstant(0));
2454 } else if (DestVT.bitsGT(MVT::f64)) {
2455 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2459 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2460 // Code below here assumes !isSigned without checking again.
2462 // Implementation of unsigned i64 to f64 following the algorithm in
2463 // __floatundidf in compiler_rt. This implementation has the advantage
2464 // of performing rounding correctly, both in the default rounding mode
2465 // and in all alternate rounding modes.
2466 // TODO: Generalize this for use with other types.
2467 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2469 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2470 SDValue TwoP84PlusTwoP52 =
2471 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2473 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2475 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2476 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2477 DAG.getConstant(32, MVT::i64));
2478 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2479 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2480 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2481 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2482 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2484 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2487 // Implementation of unsigned i64 to f32.
2488 // TODO: Generalize this for use with other types.
2489 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2490 // For unsigned conversions, convert them to signed conversions using the
2491 // algorithm from the x86_64 __floatundidf in compiler_rt.
2493 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2495 SDValue ShiftConst =
2496 DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2497 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2498 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2499 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2500 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2502 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2503 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2505 // TODO: This really should be implemented using a branch rather than a
2506 // select. We happen to get lucky and machinesink does the right
2507 // thing most of the time. This would be a good candidate for a
2508 //pseudo-op, or, even better, for whole-function isel.
2509 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2510 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2511 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
2514 // Otherwise, implement the fully general conversion.
2516 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2517 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2518 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2519 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2520 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2521 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2522 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2523 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2524 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
2525 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2526 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2528 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
2529 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2531 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2532 DAG.getConstant(32, SHVT));
2533 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2534 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2536 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2537 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2538 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2539 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2540 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2541 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2542 DAG.getIntPtrConstant(0));
2545 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2547 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
2548 Op0, DAG.getConstant(0, Op0.getValueType()),
2550 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2551 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2552 SignSet, Four, Zero);
2554 // If the sign bit of the integer is set, the large number will be treated
2555 // as a negative number. To counteract this, the dynamic code adds an
2556 // offset depending on the data type.
2558 switch (Op0.getSimpleValueType().SimpleTy) {
2559 default: llvm_unreachable("Unsupported integer type!");
2560 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2561 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2562 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2563 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2565 if (TLI.isLittleEndian()) FF <<= 32;
2566 Constant *FudgeFactor = ConstantInt::get(
2567 Type::getInt64Ty(*DAG.getContext()), FF);
2569 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2570 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2571 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2572 Alignment = std::min(Alignment, 4u);
2574 if (DestVT == MVT::f32)
2575 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2576 MachinePointerInfo::getConstantPool(),
2577 false, false, false, Alignment);
2579 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2580 DAG.getEntryNode(), CPIdx,
2581 MachinePointerInfo::getConstantPool(),
2582 MVT::f32, false, false, Alignment);
2583 HandleSDNode Handle(Load);
2584 LegalizeOp(Load.getNode());
2585 FudgeInReg = Handle.getValue();
2588 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2591 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2592 /// *INT_TO_FP operation of the specified operand when the target requests that
2593 /// we promote it. At this point, we know that the result and operand types are
2594 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2595 /// operation that takes a larger input.
2596 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2600 // First step, figure out the appropriate *INT_TO_FP operation to use.
2601 EVT NewInTy = LegalOp.getValueType();
2603 unsigned OpToUse = 0;
2605 // Scan for the appropriate larger type to use.
2607 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2608 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2610 // If the target supports SINT_TO_FP of this type, use it.
2611 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2612 OpToUse = ISD::SINT_TO_FP;
2615 if (isSigned) continue;
2617 // If the target supports UINT_TO_FP of this type, use it.
2618 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2619 OpToUse = ISD::UINT_TO_FP;
2623 // Otherwise, try a larger type.
2626 // Okay, we found the operation and type to use. Zero extend our input to the
2627 // desired type then run the operation on it.
2628 return DAG.getNode(OpToUse, dl, DestVT,
2629 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2630 dl, NewInTy, LegalOp));
2633 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2634 /// FP_TO_*INT operation of the specified operand when the target requests that
2635 /// we promote it. At this point, we know that the result and operand types are
2636 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2637 /// operation that returns a larger result.
2638 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2642 // First step, figure out the appropriate FP_TO*INT operation to use.
2643 EVT NewOutTy = DestVT;
2645 unsigned OpToUse = 0;
2647 // Scan for the appropriate larger type to use.
2649 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2650 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2652 // A larger signed type can hold all unsigned values of the requested type,
2653 // so using FP_TO_SINT is valid
2654 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2655 OpToUse = ISD::FP_TO_SINT;
2659 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2660 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2661 OpToUse = ISD::FP_TO_UINT;
2665 // Otherwise, try a larger type.
2669 // Okay, we found the operation and type to use.
2670 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2672 // Truncate the result of the extended FP_TO_*INT operation to the desired
2674 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2677 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2679 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, SDLoc dl) {
2680 EVT VT = Op.getValueType();
2681 EVT SHVT = TLI.getShiftAmountTy(VT);
2682 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2683 switch (VT.getSimpleVT().SimpleTy) {
2684 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2686 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2687 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2688 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2690 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2691 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2692 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2693 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2694 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2695 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2696 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2697 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2698 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2700 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2701 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2702 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2703 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2704 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2705 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2706 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2707 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2708 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2709 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2710 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2711 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2712 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2713 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2714 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2715 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2716 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2717 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2718 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2719 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2720 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2724 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2726 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2729 default: llvm_unreachable("Cannot expand this yet!");
2731 EVT VT = Op.getValueType();
2732 EVT ShVT = TLI.getShiftAmountTy(VT);
2733 unsigned Len = VT.getSizeInBits();
2735 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2736 "CTPOP not implemented for this type.");
2738 // This is the "best" algorithm from
2739 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2741 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), VT);
2742 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), VT);
2743 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), VT);
2744 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), VT);
2746 // v = v - ((v >> 1) & 0x55555555...)
2747 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2748 DAG.getNode(ISD::AND, dl, VT,
2749 DAG.getNode(ISD::SRL, dl, VT, Op,
2750 DAG.getConstant(1, ShVT)),
2752 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2753 Op = DAG.getNode(ISD::ADD, dl, VT,
2754 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2755 DAG.getNode(ISD::AND, dl, VT,
2756 DAG.getNode(ISD::SRL, dl, VT, Op,
2757 DAG.getConstant(2, ShVT)),
2759 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2760 Op = DAG.getNode(ISD::AND, dl, VT,
2761 DAG.getNode(ISD::ADD, dl, VT, Op,
2762 DAG.getNode(ISD::SRL, dl, VT, Op,
2763 DAG.getConstant(4, ShVT))),
2765 // v = (v * 0x01010101...) >> (Len - 8)
2766 Op = DAG.getNode(ISD::SRL, dl, VT,
2767 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2768 DAG.getConstant(Len - 8, ShVT));
2772 case ISD::CTLZ_ZERO_UNDEF:
2773 // This trivially expands to CTLZ.
2774 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2776 // for now, we do this:
2777 // x = x | (x >> 1);
2778 // x = x | (x >> 2);
2780 // x = x | (x >>16);
2781 // x = x | (x >>32); // for 64-bit input
2782 // return popcount(~x);
2784 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2785 EVT VT = Op.getValueType();
2786 EVT ShVT = TLI.getShiftAmountTy(VT);
2787 unsigned len = VT.getSizeInBits();
2788 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2789 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2790 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2791 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2793 Op = DAG.getNOT(dl, Op, VT);
2794 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2796 case ISD::CTTZ_ZERO_UNDEF:
2797 // This trivially expands to CTTZ.
2798 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2800 // for now, we use: { return popcount(~x & (x - 1)); }
2801 // unless the target has ctlz but not ctpop, in which case we use:
2802 // { return 32 - nlz(~x & (x-1)); }
2803 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2804 EVT VT = Op.getValueType();
2805 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2806 DAG.getNOT(dl, Op, VT),
2807 DAG.getNode(ISD::SUB, dl, VT, Op,
2808 DAG.getConstant(1, VT)));
2809 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2810 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2811 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2812 return DAG.getNode(ISD::SUB, dl, VT,
2813 DAG.getConstant(VT.getSizeInBits(), VT),
2814 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2815 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2820 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2821 unsigned Opc = Node->getOpcode();
2822 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2827 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2828 case ISD::ATOMIC_SWAP:
2829 switch (VT.SimpleTy) {
2830 default: llvm_unreachable("Unexpected value type for atomic!");
2831 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2832 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2833 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2834 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2835 case MVT::i128:LC = RTLIB::SYNC_LOCK_TEST_AND_SET_16;break;
2838 case ISD::ATOMIC_CMP_SWAP:
2839 switch (VT.SimpleTy) {
2840 default: llvm_unreachable("Unexpected value type for atomic!");
2841 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2842 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2843 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2844 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2845 case MVT::i128:LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16;break;
2848 case ISD::ATOMIC_LOAD_ADD:
2849 switch (VT.SimpleTy) {
2850 default: llvm_unreachable("Unexpected value type for atomic!");
2851 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2852 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2853 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2854 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2855 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_ADD_16;break;
2858 case ISD::ATOMIC_LOAD_SUB:
2859 switch (VT.SimpleTy) {
2860 default: llvm_unreachable("Unexpected value type for atomic!");
2861 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2862 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2863 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2864 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2865 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_SUB_16;break;
2868 case ISD::ATOMIC_LOAD_AND:
2869 switch (VT.SimpleTy) {
2870 default: llvm_unreachable("Unexpected value type for atomic!");
2871 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2872 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2873 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2874 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2875 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_AND_16;break;
2878 case ISD::ATOMIC_LOAD_OR:
2879 switch (VT.SimpleTy) {
2880 default: llvm_unreachable("Unexpected value type for atomic!");
2881 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2882 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2883 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2884 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2885 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_OR_16;break;
2888 case ISD::ATOMIC_LOAD_XOR:
2889 switch (VT.SimpleTy) {
2890 default: llvm_unreachable("Unexpected value type for atomic!");
2891 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2892 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2893 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2894 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2895 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_XOR_16;break;
2898 case ISD::ATOMIC_LOAD_NAND:
2899 switch (VT.SimpleTy) {
2900 default: llvm_unreachable("Unexpected value type for atomic!");
2901 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2902 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2903 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2904 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2905 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_NAND_16;break;
2908 case ISD::ATOMIC_LOAD_MAX:
2909 switch (VT.SimpleTy) {
2910 default: llvm_unreachable("Unexpected value type for atomic!");
2911 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MAX_1; break;
2912 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MAX_2; break;
2913 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MAX_4; break;
2914 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MAX_8; break;
2915 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MAX_16;break;
2918 case ISD::ATOMIC_LOAD_UMAX:
2919 switch (VT.SimpleTy) {
2920 default: llvm_unreachable("Unexpected value type for atomic!");
2921 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMAX_1; break;
2922 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMAX_2; break;
2923 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMAX_4; break;
2924 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMAX_8; break;
2925 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMAX_16;break;
2928 case ISD::ATOMIC_LOAD_MIN:
2929 switch (VT.SimpleTy) {
2930 default: llvm_unreachable("Unexpected value type for atomic!");
2931 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MIN_1; break;
2932 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MIN_2; break;
2933 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MIN_4; break;
2934 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MIN_8; break;
2935 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MIN_16;break;
2938 case ISD::ATOMIC_LOAD_UMIN:
2939 switch (VT.SimpleTy) {
2940 default: llvm_unreachable("Unexpected value type for atomic!");
2941 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMIN_1; break;
2942 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMIN_2; break;
2943 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMIN_4; break;
2944 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMIN_8; break;
2945 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMIN_16;break;
2950 return ExpandChainLibCall(LC, Node, false);
2953 void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2954 SmallVector<SDValue, 8> Results;
2956 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2958 switch (Node->getOpcode()) {
2961 case ISD::CTLZ_ZERO_UNDEF:
2963 case ISD::CTTZ_ZERO_UNDEF:
2964 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2965 Results.push_back(Tmp1);
2968 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2970 case ISD::FRAMEADDR:
2971 case ISD::RETURNADDR:
2972 case ISD::FRAME_TO_ARGS_OFFSET:
2973 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2975 case ISD::FLT_ROUNDS_:
2976 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2978 case ISD::EH_RETURN:
2982 case ISD::EH_SJLJ_LONGJMP:
2983 // If the target didn't expand these, there's nothing to do, so just
2984 // preserve the chain and be done.
2985 Results.push_back(Node->getOperand(0));
2987 case ISD::EH_SJLJ_SETJMP:
2988 // If the target didn't expand this, just return 'zero' and preserve the
2990 Results.push_back(DAG.getConstant(0, MVT::i32));
2991 Results.push_back(Node->getOperand(0));
2993 case ISD::ATOMIC_FENCE: {
2994 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2995 // FIXME: handle "fence singlethread" more efficiently.
2996 TargetLowering::ArgListTy Args;
2998 TargetLowering::CallLoweringInfo CLI(DAG);
2999 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3000 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3001 DAG.getExternalSymbol("__sync_synchronize",
3002 TLI.getPointerTy()), std::move(Args), 0);
3004 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3006 Results.push_back(CallResult.second);
3009 case ISD::ATOMIC_LOAD: {
3010 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
3011 SDValue Zero = DAG.getConstant(0, Node->getValueType(0));
3012 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3013 SDValue Swap = DAG.getAtomicCmpSwap(
3014 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3015 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
3016 cast<AtomicSDNode>(Node)->getMemOperand(),
3017 cast<AtomicSDNode>(Node)->getOrdering(),
3018 cast<AtomicSDNode>(Node)->getOrdering(),
3019 cast<AtomicSDNode>(Node)->getSynchScope());
3020 Results.push_back(Swap.getValue(0));
3021 Results.push_back(Swap.getValue(1));
3024 case ISD::ATOMIC_STORE: {
3025 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
3026 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
3027 cast<AtomicSDNode>(Node)->getMemoryVT(),
3028 Node->getOperand(0),
3029 Node->getOperand(1), Node->getOperand(2),
3030 cast<AtomicSDNode>(Node)->getMemOperand(),
3031 cast<AtomicSDNode>(Node)->getOrdering(),
3032 cast<AtomicSDNode>(Node)->getSynchScope());
3033 Results.push_back(Swap.getValue(1));
3036 // By default, atomic intrinsics are marked Legal and lowered. Targets
3037 // which don't support them directly, however, may want libcalls, in which
3038 // case they mark them Expand, and we get here.
3039 case ISD::ATOMIC_SWAP:
3040 case ISD::ATOMIC_LOAD_ADD:
3041 case ISD::ATOMIC_LOAD_SUB:
3042 case ISD::ATOMIC_LOAD_AND:
3043 case ISD::ATOMIC_LOAD_OR:
3044 case ISD::ATOMIC_LOAD_XOR:
3045 case ISD::ATOMIC_LOAD_NAND:
3046 case ISD::ATOMIC_LOAD_MIN:
3047 case ISD::ATOMIC_LOAD_MAX:
3048 case ISD::ATOMIC_LOAD_UMIN:
3049 case ISD::ATOMIC_LOAD_UMAX:
3050 case ISD::ATOMIC_CMP_SWAP: {
3051 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
3052 Results.push_back(Tmp.first);
3053 Results.push_back(Tmp.second);
3056 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
3057 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3058 // splits out the success value as a comparison. Expanding the resulting
3059 // ATOMIC_CMP_SWAP will produce a libcall.
3060 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3061 SDValue Res = DAG.getAtomicCmpSwap(
3062 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3063 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3064 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(),
3065 cast<AtomicSDNode>(Node)->getSuccessOrdering(),
3066 cast<AtomicSDNode>(Node)->getFailureOrdering(),
3067 cast<AtomicSDNode>(Node)->getSynchScope());
3069 SDValue Success = DAG.getSetCC(SDLoc(Node), Node->getValueType(1),
3070 Res, Node->getOperand(2), ISD::SETEQ);
3072 Results.push_back(Res.getValue(0));
3073 Results.push_back(Success);
3074 Results.push_back(Res.getValue(1));
3077 case ISD::DYNAMIC_STACKALLOC:
3078 ExpandDYNAMIC_STACKALLOC(Node, Results);
3080 case ISD::MERGE_VALUES:
3081 for (unsigned i = 0; i < Node->getNumValues(); i++)
3082 Results.push_back(Node->getOperand(i));
3085 EVT VT = Node->getValueType(0);
3087 Results.push_back(DAG.getConstant(0, VT));
3089 assert(VT.isFloatingPoint() && "Unknown value type!");
3090 Results.push_back(DAG.getConstantFP(0, VT));
3095 // If this operation is not supported, lower it to 'abort()' call
3096 TargetLowering::ArgListTy Args;
3097 TargetLowering::CallLoweringInfo CLI(DAG);
3098 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3099 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3100 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3101 std::move(Args), 0);
3102 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3104 Results.push_back(CallResult.second);
3109 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3110 Node->getValueType(0), dl);
3111 Results.push_back(Tmp1);
3113 case ISD::FP_EXTEND:
3114 Tmp1 = EmitStackConvert(Node->getOperand(0),
3115 Node->getOperand(0).getValueType(),
3116 Node->getValueType(0), dl);
3117 Results.push_back(Tmp1);
3119 case ISD::SIGN_EXTEND_INREG: {
3120 // NOTE: we could fall back on load/store here too for targets without
3121 // SAR. However, it is doubtful that any exist.
3122 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3123 EVT VT = Node->getValueType(0);
3124 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
3127 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3128 ExtraVT.getScalarType().getSizeInBits();
3129 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
3130 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3131 Node->getOperand(0), ShiftCst);
3132 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3133 Results.push_back(Tmp1);
3136 case ISD::FP_ROUND_INREG: {
3137 // The only way we can lower this is to turn it into a TRUNCSTORE,
3138 // EXTLOAD pair, targeting a temporary location (a stack slot).
3140 // NOTE: there is a choice here between constantly creating new stack
3141 // slots and always reusing the same one. We currently always create
3142 // new ones, as reuse may inhibit scheduling.
3143 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3144 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3145 Node->getValueType(0), dl);
3146 Results.push_back(Tmp1);
3149 case ISD::SINT_TO_FP:
3150 case ISD::UINT_TO_FP:
3151 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3152 Node->getOperand(0), Node->getValueType(0), dl);
3153 Results.push_back(Tmp1);
3155 case ISD::FP_TO_SINT:
3156 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3157 Results.push_back(Tmp1);
3159 case ISD::FP_TO_UINT: {
3160 SDValue True, False;
3161 EVT VT = Node->getOperand(0).getValueType();
3162 EVT NVT = Node->getValueType(0);
3163 APFloat apf(DAG.EVTToAPFloatSemantics(VT),
3164 APInt::getNullValue(VT.getSizeInBits()));
3165 APInt x = APInt::getSignBit(NVT.getSizeInBits());
3166 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3167 Tmp1 = DAG.getConstantFP(apf, VT);
3168 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
3169 Node->getOperand(0),
3171 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3172 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3173 DAG.getNode(ISD::FSUB, dl, VT,
3174 Node->getOperand(0), Tmp1));
3175 False = DAG.getNode(ISD::XOR, dl, NVT, False,
3176 DAG.getConstant(x, NVT));
3177 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
3178 Results.push_back(Tmp1);
3182 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3183 EVT VT = Node->getValueType(0);
3184 Tmp1 = Node->getOperand(0);
3185 Tmp2 = Node->getOperand(1);
3186 unsigned Align = Node->getConstantOperandVal(3);
3188 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
3189 MachinePointerInfo(V),
3190 false, false, false, 0);
3191 SDValue VAList = VAListLoad;
3193 if (Align > TLI.getMinStackArgumentAlignment()) {
3194 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
3196 VAList = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3197 DAG.getConstant(Align - 1,
3198 VAList.getValueType()));
3200 VAList = DAG.getNode(ISD::AND, dl, VAList.getValueType(), VAList,
3201 DAG.getConstant(-(int64_t)Align,
3202 VAList.getValueType()));
3205 // Increment the pointer, VAList, to the next vaarg
3206 Tmp3 = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3207 DAG.getConstant(TLI.getDataLayout()->
3208 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
3209 VAList.getValueType()));
3210 // Store the incremented VAList to the legalized pointer
3211 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
3212 MachinePointerInfo(V), false, false, 0);
3213 // Load the actual argument out of the pointer VAList
3214 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
3215 false, false, false, 0));
3216 Results.push_back(Results[0].getValue(1));
3220 // This defaults to loading a pointer from the input and storing it to the
3221 // output, returning the chain.
3222 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3223 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3224 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
3225 Node->getOperand(2), MachinePointerInfo(VS),
3226 false, false, false, 0);
3227 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
3228 MachinePointerInfo(VD), false, false, 0);
3229 Results.push_back(Tmp1);
3232 case ISD::EXTRACT_VECTOR_ELT:
3233 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3234 // This must be an access of the only element. Return it.
3235 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3236 Node->getOperand(0));
3238 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3239 Results.push_back(Tmp1);
3241 case ISD::EXTRACT_SUBVECTOR:
3242 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3244 case ISD::INSERT_SUBVECTOR:
3245 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3247 case ISD::CONCAT_VECTORS: {
3248 Results.push_back(ExpandVectorBuildThroughStack(Node));
3251 case ISD::SCALAR_TO_VECTOR:
3252 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3254 case ISD::INSERT_VECTOR_ELT:
3255 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3256 Node->getOperand(1),
3257 Node->getOperand(2), dl));
3259 case ISD::VECTOR_SHUFFLE: {
3260 SmallVector<int, 32> NewMask;
3261 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3263 EVT VT = Node->getValueType(0);
3264 EVT EltVT = VT.getVectorElementType();
3265 SDValue Op0 = Node->getOperand(0);
3266 SDValue Op1 = Node->getOperand(1);
3267 if (!TLI.isTypeLegal(EltVT)) {
3269 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3271 // BUILD_VECTOR operands are allowed to be wider than the element type.
3272 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3274 if (NewEltVT.bitsLT(EltVT)) {
3276 // Convert shuffle node.
3277 // If original node was v4i64 and the new EltVT is i32,
3278 // cast operands to v8i32 and re-build the mask.
3280 // Calculate new VT, the size of the new VT should be equal to original.
3282 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3283 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3284 assert(NewVT.bitsEq(VT));
3286 // cast operands to new VT
3287 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3288 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3290 // Convert the shuffle mask
3291 unsigned int factor =
3292 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3294 // EltVT gets smaller
3297 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3299 for (unsigned fi = 0; fi < factor; ++fi)
3300 NewMask.push_back(Mask[i]);
3303 for (unsigned fi = 0; fi < factor; ++fi)
3304 NewMask.push_back(Mask[i]*factor+fi);
3312 unsigned NumElems = VT.getVectorNumElements();
3313 SmallVector<SDValue, 16> Ops;
3314 for (unsigned i = 0; i != NumElems; ++i) {
3316 Ops.push_back(DAG.getUNDEF(EltVT));
3319 unsigned Idx = Mask[i];
3321 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3323 DAG.getConstant(Idx, TLI.getVectorIdxTy())));
3325 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3327 DAG.getConstant(Idx - NumElems,
3328 TLI.getVectorIdxTy())));
3331 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3332 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3333 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3334 Results.push_back(Tmp1);
3337 case ISD::EXTRACT_ELEMENT: {
3338 EVT OpTy = Node->getOperand(0).getValueType();
3339 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3341 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3342 DAG.getConstant(OpTy.getSizeInBits()/2,
3343 TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
3344 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3347 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3348 Node->getOperand(0));
3350 Results.push_back(Tmp1);
3353 case ISD::STACKSAVE:
3354 // Expand to CopyFromReg if the target set
3355 // StackPointerRegisterToSaveRestore.
3356 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3357 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3358 Node->getValueType(0)));
3359 Results.push_back(Results[0].getValue(1));
3361 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3362 Results.push_back(Node->getOperand(0));
3365 case ISD::STACKRESTORE:
3366 // Expand to CopyToReg if the target set
3367 // StackPointerRegisterToSaveRestore.
3368 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3369 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3370 Node->getOperand(1)));
3372 Results.push_back(Node->getOperand(0));
3375 case ISD::FCOPYSIGN:
3376 Results.push_back(ExpandFCOPYSIGN(Node));
3379 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3380 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3381 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3382 Node->getOperand(0));
3383 Results.push_back(Tmp1);
3386 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3387 EVT VT = Node->getValueType(0);
3388 Tmp1 = Node->getOperand(0);
3389 Tmp2 = DAG.getConstantFP(0.0, VT);
3390 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(Tmp1.getValueType()),
3391 Tmp1, Tmp2, ISD::SETUGT);
3392 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3393 Tmp1 = DAG.getSelect(dl, VT, Tmp2, Tmp1, Tmp3);
3394 Results.push_back(Tmp1);
3398 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3399 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3400 RTLIB::SQRT_PPCF128));
3404 EVT VT = Node->getValueType(0);
3405 bool isSIN = Node->getOpcode() == ISD::FSIN;
3406 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3407 // fcos which share the same operand and both are used.
3408 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3409 canCombineSinCosLibcall(Node, TLI, TM))
3410 && useSinCos(Node)) {
3411 SDVTList VTs = DAG.getVTList(VT, VT);
3412 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3414 Tmp1 = Tmp1.getValue(1);
3415 Results.push_back(Tmp1);
3417 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3418 RTLIB::SIN_F80, RTLIB::SIN_F128,
3419 RTLIB::SIN_PPCF128));
3421 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3422 RTLIB::COS_F80, RTLIB::COS_F128,
3423 RTLIB::COS_PPCF128));
3428 // Expand into sincos libcall.
3429 ExpandSinCosLibCall(Node, Results);
3432 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3433 RTLIB::LOG_F80, RTLIB::LOG_F128,
3434 RTLIB::LOG_PPCF128));
3437 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3438 RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3439 RTLIB::LOG2_PPCF128));
3442 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3443 RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3444 RTLIB::LOG10_PPCF128));
3447 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3448 RTLIB::EXP_F80, RTLIB::EXP_F128,
3449 RTLIB::EXP_PPCF128));
3452 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3453 RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3454 RTLIB::EXP2_PPCF128));
3457 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3458 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3459 RTLIB::TRUNC_PPCF128));
3462 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3463 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3464 RTLIB::FLOOR_PPCF128));
3467 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3468 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3469 RTLIB::CEIL_PPCF128));
3472 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3473 RTLIB::RINT_F80, RTLIB::RINT_F128,
3474 RTLIB::RINT_PPCF128));
3476 case ISD::FNEARBYINT:
3477 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3478 RTLIB::NEARBYINT_F64,
3479 RTLIB::NEARBYINT_F80,
3480 RTLIB::NEARBYINT_F128,
3481 RTLIB::NEARBYINT_PPCF128));
3484 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3488 RTLIB::ROUND_PPCF128));
3491 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3492 RTLIB::POWI_F80, RTLIB::POWI_F128,
3493 RTLIB::POWI_PPCF128));
3496 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3497 RTLIB::POW_F80, RTLIB::POW_F128,
3498 RTLIB::POW_PPCF128));
3501 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3502 RTLIB::DIV_F80, RTLIB::DIV_F128,
3503 RTLIB::DIV_PPCF128));
3506 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3507 RTLIB::REM_F80, RTLIB::REM_F128,
3508 RTLIB::REM_PPCF128));
3511 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3512 RTLIB::FMA_F80, RTLIB::FMA_F128,
3513 RTLIB::FMA_PPCF128));
3515 case ISD::FP16_TO_FP: {
3516 if (Node->getValueType(0) == MVT::f32) {
3517 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3521 // We can extend to types bigger than f32 in two steps without changing the
3522 // result. Since "f16 -> f32" is much more commonly available, give CodeGen
3523 // the option of emitting that before resorting to a libcall.
3525 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3527 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3530 case ISD::FP_TO_FP16: {
3532 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
3533 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
3534 Results.push_back(ExpandLibCall(LC, Node, false));
3537 case ISD::ConstantFP: {
3538 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3539 // Check to see if this FP immediate is already legal.
3540 // If this is a legal constant, turn it into a TargetConstantFP node.
3541 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3542 Results.push_back(ExpandConstantFP(CFP, true));
3546 EVT VT = Node->getValueType(0);
3547 assert(TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3548 TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
3549 "Don't know how to expand this FP subtraction!");
3550 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3551 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
3552 Results.push_back(Tmp1);
3556 EVT VT = Node->getValueType(0);
3557 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3558 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3559 "Don't know how to expand this subtraction!");
3560 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3561 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3562 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, VT));
3563 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3568 EVT VT = Node->getValueType(0);
3569 bool isSigned = Node->getOpcode() == ISD::SREM;
3570 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3571 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3572 Tmp2 = Node->getOperand(0);
3573 Tmp3 = Node->getOperand(1);
3574 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3575 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3576 // If div is legal, it's better to do the normal expansion
3577 !TLI.isOperationLegalOrCustom(DivOpc, Node->getValueType(0)) &&
3578 useDivRem(Node, isSigned, false))) {
3579 SDVTList VTs = DAG.getVTList(VT, VT);
3580 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3581 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3583 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3584 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3585 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3586 } else if (isSigned)
3587 Tmp1 = ExpandIntLibCall(Node, true,
3589 RTLIB::SREM_I16, RTLIB::SREM_I32,
3590 RTLIB::SREM_I64, RTLIB::SREM_I128);
3592 Tmp1 = ExpandIntLibCall(Node, false,
3594 RTLIB::UREM_I16, RTLIB::UREM_I32,
3595 RTLIB::UREM_I64, RTLIB::UREM_I128);
3596 Results.push_back(Tmp1);
3601 bool isSigned = Node->getOpcode() == ISD::SDIV;
3602 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3603 EVT VT = Node->getValueType(0);
3604 SDVTList VTs = DAG.getVTList(VT, VT);
3605 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3606 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3607 useDivRem(Node, isSigned, true)))
3608 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3609 Node->getOperand(1));
3611 Tmp1 = ExpandIntLibCall(Node, true,
3613 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3614 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3616 Tmp1 = ExpandIntLibCall(Node, false,
3618 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3619 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3620 Results.push_back(Tmp1);
3625 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3627 EVT VT = Node->getValueType(0);
3628 SDVTList VTs = DAG.getVTList(VT, VT);
3629 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3630 "If this wasn't legal, it shouldn't have been created!");
3631 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3632 Node->getOperand(1));
3633 Results.push_back(Tmp1.getValue(1));
3638 // Expand into divrem libcall
3639 ExpandDivRemLibCall(Node, Results);
3642 EVT VT = Node->getValueType(0);
3643 SDVTList VTs = DAG.getVTList(VT, VT);
3644 // See if multiply or divide can be lowered using two-result operations.
3645 // We just need the low half of the multiply; try both the signed
3646 // and unsigned forms. If the target supports both SMUL_LOHI and
3647 // UMUL_LOHI, form a preference by checking which forms of plain
3648 // MULH it supports.
3649 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3650 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3651 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3652 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3653 unsigned OpToUse = 0;
3654 if (HasSMUL_LOHI && !HasMULHS) {
3655 OpToUse = ISD::SMUL_LOHI;
3656 } else if (HasUMUL_LOHI && !HasMULHU) {
3657 OpToUse = ISD::UMUL_LOHI;
3658 } else if (HasSMUL_LOHI) {
3659 OpToUse = ISD::SMUL_LOHI;
3660 } else if (HasUMUL_LOHI) {
3661 OpToUse = ISD::UMUL_LOHI;
3664 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3665 Node->getOperand(1)));
3670 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3671 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3672 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3673 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3674 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3675 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
3676 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3677 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3678 SDValue Shift = DAG.getConstant(HalfType.getSizeInBits(),
3679 TLI.getShiftAmountTy(HalfType));
3680 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3681 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3685 Tmp1 = ExpandIntLibCall(Node, false,
3687 RTLIB::MUL_I16, RTLIB::MUL_I32,
3688 RTLIB::MUL_I64, RTLIB::MUL_I128);
3689 Results.push_back(Tmp1);
3694 SDValue LHS = Node->getOperand(0);
3695 SDValue RHS = Node->getOperand(1);
3696 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3697 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3699 Results.push_back(Sum);
3700 EVT ResultType = Node->getValueType(1);
3701 EVT OType = getSetCCResultType(Node->getValueType(0));
3703 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3705 // LHSSign -> LHS >= 0
3706 // RHSSign -> RHS >= 0
3707 // SumSign -> Sum >= 0
3710 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3712 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3714 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3715 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3716 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3717 Node->getOpcode() == ISD::SADDO ?
3718 ISD::SETEQ : ISD::SETNE);
3720 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3721 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3723 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3724 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3729 SDValue LHS = Node->getOperand(0);
3730 SDValue RHS = Node->getOperand(1);
3731 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3732 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3734 Results.push_back(Sum);
3736 EVT ResultType = Node->getValueType(1);
3737 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3739 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3740 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3742 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3747 EVT VT = Node->getValueType(0);
3748 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3749 SDValue LHS = Node->getOperand(0);
3750 SDValue RHS = Node->getOperand(1);
3753 static const unsigned Ops[2][3] =
3754 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3755 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3756 bool isSigned = Node->getOpcode() == ISD::SMULO;
3757 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3758 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3759 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3760 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3761 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3763 TopHalf = BottomHalf.getValue(1);
3764 } else if (TLI.isTypeLegal(WideVT)) {
3765 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3766 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3767 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3768 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3769 DAG.getIntPtrConstant(0));
3770 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3771 DAG.getIntPtrConstant(1));
3773 // We can fall back to a libcall with an illegal type for the MUL if we
3774 // have a libcall big enough.
3775 // Also, we can fall back to a division in some cases, but that's a big
3776 // performance hit in the general case.
3777 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3778 if (WideVT == MVT::i16)
3779 LC = RTLIB::MUL_I16;
3780 else if (WideVT == MVT::i32)
3781 LC = RTLIB::MUL_I32;
3782 else if (WideVT == MVT::i64)
3783 LC = RTLIB::MUL_I64;
3784 else if (WideVT == MVT::i128)
3785 LC = RTLIB::MUL_I128;
3786 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3788 // The high part is obtained by SRA'ing all but one of the bits of low
3790 unsigned LoSize = VT.getSizeInBits();
3791 SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3792 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3793 SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3794 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3796 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3797 // pre-lowered to the correct types. This all depends upon WideVT not
3798 // being a legal type for the architecture and thus has to be split to
3800 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3801 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3802 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3803 DAG.getIntPtrConstant(0));
3804 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3805 DAG.getIntPtrConstant(1));
3806 // Ret is a node with an illegal type. Because such things are not
3807 // generally permitted during this phase of legalization, delete the
3808 // node. The above EXTRACT_ELEMENT nodes should have been folded.
3809 DAG.DeleteNode(Ret.getNode());
3813 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3814 TLI.getShiftAmountTy(BottomHalf.getValueType()));
3815 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3816 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3819 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3820 DAG.getConstant(0, VT), ISD::SETNE);
3822 Results.push_back(BottomHalf);
3823 Results.push_back(TopHalf);
3826 case ISD::BUILD_PAIR: {
3827 EVT PairTy = Node->getValueType(0);
3828 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3829 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3830 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3831 DAG.getConstant(PairTy.getSizeInBits()/2,
3832 TLI.getShiftAmountTy(PairTy)));
3833 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3837 Tmp1 = Node->getOperand(0);
3838 Tmp2 = Node->getOperand(1);
3839 Tmp3 = Node->getOperand(2);
3840 if (Tmp1.getOpcode() == ISD::SETCC) {
3841 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3843 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3845 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3846 DAG.getConstant(0, Tmp1.getValueType()),
3847 Tmp2, Tmp3, ISD::SETNE);
3849 Results.push_back(Tmp1);
3852 SDValue Chain = Node->getOperand(0);
3853 SDValue Table = Node->getOperand(1);
3854 SDValue Index = Node->getOperand(2);
3856 EVT PTy = TLI.getPointerTy();
3858 const DataLayout &TD = *TLI.getDataLayout();
3859 unsigned EntrySize =
3860 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3862 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(),
3863 Index, DAG.getConstant(EntrySize, Index.getValueType()));
3864 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3867 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3868 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3869 MachinePointerInfo::getJumpTable(), MemVT,
3872 if (TM.getRelocationModel() == Reloc::PIC_) {
3873 // For PIC, the sequence is:
3874 // BRIND(load(Jumptable + index) + RelocBase)
3875 // RelocBase can be JumpTable, GOT or some sort of global base.
3876 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3877 TLI.getPICJumpTableRelocBase(Table, DAG));
3879 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3880 Results.push_back(Tmp1);
3884 // Expand brcond's setcc into its constituent parts and create a BR_CC
3886 Tmp1 = Node->getOperand(0);
3887 Tmp2 = Node->getOperand(1);
3888 if (Tmp2.getOpcode() == ISD::SETCC) {
3889 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3890 Tmp1, Tmp2.getOperand(2),
3891 Tmp2.getOperand(0), Tmp2.getOperand(1),
3892 Node->getOperand(2));
3894 // We test only the i1 bit. Skip the AND if UNDEF.
3895 Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3896 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3897 DAG.getConstant(1, Tmp2.getValueType()));
3898 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3899 DAG.getCondCode(ISD::SETNE), Tmp3,
3900 DAG.getConstant(0, Tmp3.getValueType()),
3901 Node->getOperand(2));
3903 Results.push_back(Tmp1);
3906 Tmp1 = Node->getOperand(0);
3907 Tmp2 = Node->getOperand(1);
3908 Tmp3 = Node->getOperand(2);
3909 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3910 Tmp3, NeedInvert, dl);
3913 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3914 // condition code, create a new SETCC node.
3916 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3919 // If we expanded the SETCC by inverting the condition code, then wrap
3920 // the existing SETCC in a NOT to restore the intended condition.
3922 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3924 Results.push_back(Tmp1);
3928 // Otherwise, SETCC for the given comparison type must be completely
3929 // illegal; expand it into a SELECT_CC.
3930 EVT VT = Node->getValueType(0);
3932 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3933 case TargetLowering::ZeroOrOneBooleanContent:
3934 case TargetLowering::UndefinedBooleanContent:
3937 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3941 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3942 DAG.getConstant(TrueValue, VT), DAG.getConstant(0, VT),
3944 Results.push_back(Tmp1);
3947 case ISD::SELECT_CC: {
3948 Tmp1 = Node->getOperand(0); // LHS
3949 Tmp2 = Node->getOperand(1); // RHS
3950 Tmp3 = Node->getOperand(2); // True
3951 Tmp4 = Node->getOperand(3); // False
3952 EVT VT = Node->getValueType(0);
3953 SDValue CC = Node->getOperand(4);
3954 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3956 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3957 // If the condition code is legal, then we need to expand this
3958 // node using SETCC and SELECT.
3959 EVT CmpVT = Tmp1.getValueType();
3960 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3961 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3963 EVT CCVT = TLI.getSetCCResultType(*DAG.getContext(), CmpVT);
3964 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3965 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3969 // SELECT_CC is legal, so the condition code must not be.
3970 bool Legalized = false;
3971 // Try to legalize by inverting the condition. This is for targets that
3972 // might support an ordered version of a condition, but not the unordered
3973 // version (or vice versa).
3974 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3975 Tmp1.getValueType().isInteger());
3976 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
3977 // Use the new condition code and swap true and false
3979 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3981 // If The inverse is not legal, then try to swap the arguments using
3982 // the inverse condition code.
3983 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3984 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
3985 // The swapped inverse condition is legal, so swap true and false,
3988 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3993 Legalized = LegalizeSetCCCondCode(
3994 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3997 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3999 // If we expanded the SETCC by inverting the condition code, then swap
4000 // the True/False operands to match.
4002 std::swap(Tmp3, Tmp4);
4004 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4005 // condition code, create a new SELECT_CC node.
4007 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
4008 Tmp1, Tmp2, Tmp3, Tmp4, CC);
4010 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4011 CC = DAG.getCondCode(ISD::SETNE);
4012 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4013 Tmp2, Tmp3, Tmp4, CC);
4016 Results.push_back(Tmp1);
4020 Tmp1 = Node->getOperand(0); // Chain
4021 Tmp2 = Node->getOperand(2); // LHS
4022 Tmp3 = Node->getOperand(3); // RHS
4023 Tmp4 = Node->getOperand(1); // CC
4025 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
4026 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
4028 assert(Legalized && "Can't legalize BR_CC with legal condition!");
4030 // If we expanded the SETCC by inverting the condition code, then wrap
4031 // the existing SETCC in a NOT to restore the intended condition.
4033 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
4035 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
4037 if (Tmp4.getNode()) {
4038 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
4039 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
4041 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
4042 Tmp4 = DAG.getCondCode(ISD::SETNE);
4043 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
4044 Tmp2, Tmp3, Node->getOperand(4));
4046 Results.push_back(Tmp1);
4049 case ISD::BUILD_VECTOR:
4050 Results.push_back(ExpandBUILD_VECTOR(Node));
4055 // Scalarize vector SRA/SRL/SHL.
4056 EVT VT = Node->getValueType(0);
4057 assert(VT.isVector() && "Unable to legalize non-vector shift");
4058 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
4059 unsigned NumElem = VT.getVectorNumElements();
4061 SmallVector<SDValue, 8> Scalars;
4062 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
4063 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4065 Node->getOperand(0), DAG.getConstant(Idx,
4066 TLI.getVectorIdxTy()));
4067 SDValue Sh = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4069 Node->getOperand(1), DAG.getConstant(Idx,
4070 TLI.getVectorIdxTy()));
4071 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
4072 VT.getScalarType(), Ex, Sh));
4075 DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
4076 ReplaceNode(SDValue(Node, 0), Result);
4079 case ISD::GLOBAL_OFFSET_TABLE:
4080 case ISD::GlobalAddress:
4081 case ISD::GlobalTLSAddress:
4082 case ISD::ExternalSymbol:
4083 case ISD::ConstantPool:
4084 case ISD::JumpTable:
4085 case ISD::INTRINSIC_W_CHAIN:
4086 case ISD::INTRINSIC_WO_CHAIN:
4087 case ISD::INTRINSIC_VOID:
4088 // FIXME: Custom lowering for these operations shouldn't return null!
4092 // Replace the original node with the legalized result.
4093 if (!Results.empty())
4094 ReplaceNode(Node, Results.data());
4097 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4098 SmallVector<SDValue, 8> Results;
4099 MVT OVT = Node->getSimpleValueType(0);
4100 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4101 Node->getOpcode() == ISD::SINT_TO_FP ||
4102 Node->getOpcode() == ISD::SETCC) {
4103 OVT = Node->getOperand(0).getSimpleValueType();
4105 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4107 SDValue Tmp1, Tmp2, Tmp3;
4108 switch (Node->getOpcode()) {
4110 case ISD::CTTZ_ZERO_UNDEF:
4112 case ISD::CTLZ_ZERO_UNDEF:
4114 // Zero extend the argument.
4115 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4116 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4117 // already the correct result.
4118 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4119 if (Node->getOpcode() == ISD::CTTZ) {
4120 // FIXME: This should set a bit in the zero extended value instead.
4121 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT),
4122 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
4124 Tmp1 = DAG.getSelect(dl, NVT, Tmp2,
4125 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
4126 } else if (Node->getOpcode() == ISD::CTLZ ||
4127 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4128 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4129 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4130 DAG.getConstant(NVT.getSizeInBits() -
4131 OVT.getSizeInBits(), NVT));
4133 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4136 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4137 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4138 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4139 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
4140 DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
4141 Results.push_back(Tmp1);
4144 case ISD::FP_TO_UINT:
4145 case ISD::FP_TO_SINT:
4146 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4147 Node->getOpcode() == ISD::FP_TO_SINT, dl);
4148 Results.push_back(Tmp1);
4150 case ISD::UINT_TO_FP:
4151 case ISD::SINT_TO_FP:
4152 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4153 Node->getOpcode() == ISD::SINT_TO_FP, dl);
4154 Results.push_back(Tmp1);
4157 SDValue Chain = Node->getOperand(0); // Get the chain.
4158 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4161 if (OVT.isVector()) {
4162 TruncOp = ISD::BITCAST;
4164 assert(OVT.isInteger()
4165 && "VAARG promotion is supported only for vectors or integer types");
4166 TruncOp = ISD::TRUNCATE;
4169 // Perform the larger operation, then convert back
4170 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4171 Node->getConstantOperandVal(3));
4172 Chain = Tmp1.getValue(1);
4174 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4176 // Modified the chain result - switch anything that used the old chain to
4178 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4179 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4181 UpdatedNodes->insert(Tmp2.getNode());
4182 UpdatedNodes->insert(Chain.getNode());
4190 unsigned ExtOp, TruncOp;
4191 if (OVT.isVector()) {
4192 ExtOp = ISD::BITCAST;
4193 TruncOp = ISD::BITCAST;
4195 assert(OVT.isInteger() && "Cannot promote logic operation");
4196 ExtOp = ISD::ANY_EXTEND;
4197 TruncOp = ISD::TRUNCATE;
4199 // Promote each of the values to the new type.
4200 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4201 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4202 // Perform the larger operation, then convert back
4203 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4204 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4208 unsigned ExtOp, TruncOp;
4209 if (Node->getValueType(0).isVector() ||
4210 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4211 ExtOp = ISD::BITCAST;
4212 TruncOp = ISD::BITCAST;
4213 } else if (Node->getValueType(0).isInteger()) {
4214 ExtOp = ISD::ANY_EXTEND;
4215 TruncOp = ISD::TRUNCATE;
4217 ExtOp = ISD::FP_EXTEND;
4218 TruncOp = ISD::FP_ROUND;
4220 Tmp1 = Node->getOperand(0);
4221 // Promote each of the values to the new type.
4222 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4223 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4224 // Perform the larger operation, then round down.
4225 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4226 if (TruncOp != ISD::FP_ROUND)
4227 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4229 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4230 DAG.getIntPtrConstant(0));
4231 Results.push_back(Tmp1);
4234 case ISD::VECTOR_SHUFFLE: {
4235 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4237 // Cast the two input vectors.
4238 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4239 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4241 // Convert the shuffle mask to the right # elements.
4242 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4243 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4244 Results.push_back(Tmp1);
4248 unsigned ExtOp = ISD::FP_EXTEND;
4249 if (NVT.isInteger()) {
4250 ISD::CondCode CCCode =
4251 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4252 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4254 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4255 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4256 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4257 Tmp1, Tmp2, Node->getOperand(2)));
4263 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4264 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4265 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4266 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4267 Tmp3, DAG.getIntPtrConstant(0)));
4274 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4275 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4276 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4277 Tmp2, DAG.getIntPtrConstant(0)));
4282 // Replace the original node with the legalized result.
4283 if (!Results.empty())
4284 ReplaceNode(Node, Results.data());
4287 // SelectionDAG::Legalize - This is the entry point for the file.
4289 void SelectionDAG::Legalize() {
4290 AssignTopologicalOrder();
4292 allnodes_iterator LegalizePosition;
4293 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4294 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes);
4296 // Visit all the nodes. We start in topological order, so that we see
4297 // nodes with their original operands intact. Legalization can produce
4298 // new nodes which may themselves need to be legalized. Iterate until all
4299 // nodes have been legalized.
4301 bool AnyLegalized = false;
4302 for (LegalizePosition = allnodes_end();
4303 LegalizePosition != allnodes_begin(); ) {
4306 SDNode *N = LegalizePosition;
4307 if (LegalizedNodes.insert(N)) {
4308 AnyLegalized = true;
4309 Legalizer.LegalizeOp(N);
4317 // Remove dead nodes now.
4321 bool SelectionDAG::LegalizeOp(SDNode *N,
4322 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4323 allnodes_iterator LegalizePosition(N);
4324 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4325 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes,
4328 // Directly insert the node in question, and legalize it. This will recurse
4329 // as needed through operands.
4330 LegalizedNodes.insert(N);
4331 Legalizer.LegalizeOp(N);
4333 return LegalizedNodes.count(N);