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 unsigned Align = ST->getAlignment();
728 if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
729 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
730 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
731 if (Align < ABIAlignment)
732 ExpandUnalignedStore(cast<StoreSDNode>(Node),
737 case TargetLowering::Custom: {
738 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
740 ReplaceNode(SDValue(Node, 0), Res);
743 case TargetLowering::Promote: {
744 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
745 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
746 "Can only promote stores to same size type");
747 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
749 DAG.getStore(Chain, dl, Value, Ptr,
750 ST->getPointerInfo(), isVolatile,
751 isNonTemporal, Alignment, AAInfo);
752 ReplaceNode(SDValue(Node, 0), Result);
759 SDValue Value = ST->getValue();
761 EVT StVT = ST->getMemoryVT();
762 unsigned StWidth = StVT.getSizeInBits();
764 if (StWidth != StVT.getStoreSizeInBits()) {
765 // Promote to a byte-sized store with upper bits zero if not
766 // storing an integral number of bytes. For example, promote
767 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
768 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
769 StVT.getStoreSizeInBits());
770 Value = DAG.getZeroExtendInReg(Value, dl, StVT);
772 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
773 NVT, isVolatile, isNonTemporal, Alignment,
775 ReplaceNode(SDValue(Node, 0), Result);
776 } else if (StWidth & (StWidth - 1)) {
777 // If not storing a power-of-2 number of bits, expand as two stores.
778 assert(!StVT.isVector() && "Unsupported truncstore!");
779 unsigned RoundWidth = 1 << Log2_32(StWidth);
780 assert(RoundWidth < StWidth);
781 unsigned ExtraWidth = StWidth - RoundWidth;
782 assert(ExtraWidth < RoundWidth);
783 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
784 "Store size not an integral number of bytes!");
785 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
786 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
788 unsigned IncrementSize;
790 if (TLI.isLittleEndian()) {
791 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
792 // Store the bottom RoundWidth bits.
793 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
795 isVolatile, isNonTemporal, Alignment,
798 // Store the remaining ExtraWidth bits.
799 IncrementSize = RoundWidth / 8;
800 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
801 DAG.getConstant(IncrementSize, Ptr.getValueType()));
802 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
803 DAG.getConstant(RoundWidth,
804 TLI.getShiftAmountTy(Value.getValueType())));
805 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
806 ST->getPointerInfo().getWithOffset(IncrementSize),
807 ExtraVT, isVolatile, isNonTemporal,
808 MinAlign(Alignment, IncrementSize), AAInfo);
810 // Big endian - avoid unaligned stores.
811 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
812 // Store the top RoundWidth bits.
813 Hi = DAG.getNode(ISD::SRL, dl, Value.getValueType(), Value,
814 DAG.getConstant(ExtraWidth,
815 TLI.getShiftAmountTy(Value.getValueType())));
816 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
817 RoundVT, isVolatile, isNonTemporal, Alignment,
820 // Store the remaining ExtraWidth bits.
821 IncrementSize = RoundWidth / 8;
822 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
823 DAG.getConstant(IncrementSize, Ptr.getValueType()));
824 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
825 ST->getPointerInfo().getWithOffset(IncrementSize),
826 ExtraVT, isVolatile, isNonTemporal,
827 MinAlign(Alignment, IncrementSize), AAInfo);
830 // The order of the stores doesn't matter.
831 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
832 ReplaceNode(SDValue(Node, 0), Result);
834 switch (TLI.getTruncStoreAction(ST->getValue().getSimpleValueType(),
835 StVT.getSimpleVT())) {
836 default: llvm_unreachable("This action is not supported yet!");
837 case TargetLowering::Legal: {
838 unsigned AS = ST->getAddressSpace();
839 unsigned Align = ST->getAlignment();
840 // If this is an unaligned store and the target doesn't support it,
842 if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
843 Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
844 unsigned ABIAlignment= TLI.getDataLayout()->getABITypeAlignment(Ty);
845 if (Align < ABIAlignment)
846 ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
850 case TargetLowering::Custom: {
851 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
853 ReplaceNode(SDValue(Node, 0), Res);
856 case TargetLowering::Expand:
857 assert(!StVT.isVector() &&
858 "Vector Stores are handled in LegalizeVectorOps");
860 // TRUNCSTORE:i16 i32 -> STORE i16
861 assert(TLI.isTypeLegal(StVT) &&
862 "Do not know how to expand this store!");
863 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
865 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
866 isVolatile, isNonTemporal, Alignment, AAInfo);
867 ReplaceNode(SDValue(Node, 0), Result);
874 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
875 LoadSDNode *LD = cast<LoadSDNode>(Node);
876 SDValue Chain = LD->getChain(); // The chain.
877 SDValue Ptr = LD->getBasePtr(); // The base pointer.
878 SDValue Value; // The value returned by the load op.
881 ISD::LoadExtType ExtType = LD->getExtensionType();
882 if (ExtType == ISD::NON_EXTLOAD) {
883 MVT VT = Node->getSimpleValueType(0);
884 SDValue RVal = SDValue(Node, 0);
885 SDValue RChain = SDValue(Node, 1);
887 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
888 default: llvm_unreachable("This action is not supported yet!");
889 case TargetLowering::Legal: {
890 unsigned AS = LD->getAddressSpace();
891 unsigned Align = LD->getAlignment();
892 // If this is an unaligned load and the target doesn't support it,
894 if (!TLI.allowsMisalignedMemoryAccesses(LD->getMemoryVT(), AS, Align)) {
895 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
896 unsigned ABIAlignment =
897 TLI.getDataLayout()->getABITypeAlignment(Ty);
898 if (Align < ABIAlignment){
899 ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, RVal, RChain);
904 case TargetLowering::Custom: {
905 SDValue Res = TLI.LowerOperation(RVal, DAG);
908 RChain = Res.getValue(1);
912 case TargetLowering::Promote: {
913 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
914 assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
915 "Can only promote loads to same size type");
917 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
918 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
919 RChain = Res.getValue(1);
923 if (RChain.getNode() != Node) {
924 assert(RVal.getNode() != Node && "Load must be completely replaced");
925 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
926 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
928 UpdatedNodes->insert(RVal.getNode());
929 UpdatedNodes->insert(RChain.getNode());
936 EVT SrcVT = LD->getMemoryVT();
937 unsigned SrcWidth = SrcVT.getSizeInBits();
938 unsigned Alignment = LD->getAlignment();
939 bool isVolatile = LD->isVolatile();
940 bool isNonTemporal = LD->isNonTemporal();
941 AAMDNodes AAInfo = LD->getAAInfo();
943 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
944 // Some targets pretend to have an i1 loading operation, and actually
945 // load an i8. This trick is correct for ZEXTLOAD because the top 7
946 // bits are guaranteed to be zero; it helps the optimizers understand
947 // that these bits are zero. It is also useful for EXTLOAD, since it
948 // tells the optimizers that those bits are undefined. It would be
949 // nice to have an effective generic way of getting these benefits...
950 // Until such a way is found, don't insist on promoting i1 here.
952 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
953 // Promote to a byte-sized load if not loading an integral number of
954 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
955 unsigned NewWidth = SrcVT.getStoreSizeInBits();
956 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
959 // The extra bits are guaranteed to be zero, since we stored them that
960 // way. A zext load from NVT thus automatically gives zext from SrcVT.
962 ISD::LoadExtType NewExtType =
963 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
966 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
967 Chain, Ptr, LD->getPointerInfo(),
968 NVT, isVolatile, isNonTemporal, Alignment, AAInfo);
970 Ch = Result.getValue(1); // The chain.
972 if (ExtType == ISD::SEXTLOAD)
973 // Having the top bits zero doesn't help when sign extending.
974 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
975 Result.getValueType(),
976 Result, DAG.getValueType(SrcVT));
977 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
978 // All the top bits are guaranteed to be zero - inform the optimizers.
979 Result = DAG.getNode(ISD::AssertZext, dl,
980 Result.getValueType(), Result,
981 DAG.getValueType(SrcVT));
985 } else if (SrcWidth & (SrcWidth - 1)) {
986 // If not loading a power-of-2 number of bits, expand as two loads.
987 assert(!SrcVT.isVector() && "Unsupported extload!");
988 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
989 assert(RoundWidth < SrcWidth);
990 unsigned ExtraWidth = SrcWidth - RoundWidth;
991 assert(ExtraWidth < RoundWidth);
992 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
993 "Load size not an integral number of bytes!");
994 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
995 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
997 unsigned IncrementSize;
999 if (TLI.isLittleEndian()) {
1000 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1001 // Load the bottom RoundWidth bits.
1002 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1004 LD->getPointerInfo(), RoundVT, isVolatile,
1005 isNonTemporal, Alignment, AAInfo);
1007 // Load the remaining ExtraWidth bits.
1008 IncrementSize = RoundWidth / 8;
1009 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1010 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1011 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1012 LD->getPointerInfo().getWithOffset(IncrementSize),
1013 ExtraVT, isVolatile, isNonTemporal,
1014 MinAlign(Alignment, IncrementSize), AAInfo);
1016 // Build a factor node to remember that this load is independent of
1018 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1021 // Move the top bits to the right place.
1022 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1023 DAG.getConstant(RoundWidth,
1024 TLI.getShiftAmountTy(Hi.getValueType())));
1026 // Join the hi and lo parts.
1027 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1029 // Big endian - avoid unaligned loads.
1030 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1031 // Load the top RoundWidth bits.
1032 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
1033 LD->getPointerInfo(), RoundVT, isVolatile,
1034 isNonTemporal, Alignment, AAInfo);
1036 // Load the remaining ExtraWidth bits.
1037 IncrementSize = RoundWidth / 8;
1038 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1039 DAG.getConstant(IncrementSize, Ptr.getValueType()));
1040 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1041 dl, Node->getValueType(0), Chain, Ptr,
1042 LD->getPointerInfo().getWithOffset(IncrementSize),
1043 ExtraVT, isVolatile, isNonTemporal,
1044 MinAlign(Alignment, IncrementSize), AAInfo);
1046 // Build a factor node to remember that this load is independent of
1048 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1051 // Move the top bits to the right place.
1052 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1053 DAG.getConstant(ExtraWidth,
1054 TLI.getShiftAmountTy(Hi.getValueType())));
1056 // Join the hi and lo parts.
1057 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1062 bool isCustom = false;
1063 switch (TLI.getLoadExtAction(ExtType, SrcVT.getSimpleVT())) {
1064 default: llvm_unreachable("This action is not supported yet!");
1065 case TargetLowering::Custom:
1068 case TargetLowering::Legal: {
1069 Value = SDValue(Node, 0);
1070 Chain = SDValue(Node, 1);
1073 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1074 if (Res.getNode()) {
1076 Chain = Res.getValue(1);
1079 // If this is an unaligned load and the target doesn't support
1081 EVT MemVT = LD->getMemoryVT();
1082 unsigned AS = LD->getAddressSpace();
1083 unsigned Align = LD->getAlignment();
1084 if (!TLI.allowsMisalignedMemoryAccesses(MemVT, AS, Align)) {
1086 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1087 unsigned ABIAlignment =
1088 TLI.getDataLayout()->getABITypeAlignment(Ty);
1089 if (Align < ABIAlignment){
1090 ExpandUnalignedLoad(cast<LoadSDNode>(Node),
1091 DAG, TLI, Value, Chain);
1097 case TargetLowering::Expand:
1098 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) &&
1099 TLI.isTypeLegal(SrcVT)) {
1100 SDValue Load = DAG.getLoad(SrcVT, dl, Chain, Ptr,
1101 LD->getMemOperand());
1105 ExtendOp = (SrcVT.isFloatingPoint() ?
1106 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1108 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1109 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1110 default: llvm_unreachable("Unexpected extend load type!");
1112 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1113 Chain = Load.getValue(1);
1117 assert(!SrcVT.isVector() &&
1118 "Vector Loads are handled in LegalizeVectorOps");
1120 // FIXME: This does not work for vectors on most targets. Sign-
1121 // and zero-extend operations are currently folded into extending
1122 // loads, whether they are legal or not, and then we end up here
1123 // without any support for legalizing them.
1124 assert(ExtType != ISD::EXTLOAD &&
1125 "EXTLOAD should always be supported!");
1126 // Turn the unsupported load into an EXTLOAD followed by an
1127 // explicit zero/sign extend inreg.
1128 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
1129 Node->getValueType(0),
1131 LD->getMemOperand());
1133 if (ExtType == ISD::SEXTLOAD)
1134 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1135 Result.getValueType(),
1136 Result, DAG.getValueType(SrcVT));
1138 ValRes = DAG.getZeroExtendInReg(Result, dl,
1139 SrcVT.getScalarType());
1141 Chain = Result.getValue(1);
1146 // Since loads produce two values, make sure to remember that we legalized
1148 if (Chain.getNode() != Node) {
1149 assert(Value.getNode() != Node && "Load must be completely replaced");
1150 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
1151 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
1153 UpdatedNodes->insert(Value.getNode());
1154 UpdatedNodes->insert(Chain.getNode());
1160 /// LegalizeOp - Return a legal replacement for the given operation, with
1161 /// all legal operands.
1162 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
1163 if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
1166 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1167 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
1168 TargetLowering::TypeLegal &&
1169 "Unexpected illegal type!");
1171 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1172 assert((TLI.getTypeAction(*DAG.getContext(),
1173 Node->getOperand(i).getValueType()) ==
1174 TargetLowering::TypeLegal ||
1175 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
1176 "Unexpected illegal type!");
1178 // Figure out the correct action; the way to query this varies by opcode
1179 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
1180 bool SimpleFinishLegalizing = true;
1181 switch (Node->getOpcode()) {
1182 case ISD::INTRINSIC_W_CHAIN:
1183 case ISD::INTRINSIC_WO_CHAIN:
1184 case ISD::INTRINSIC_VOID:
1185 case ISD::STACKSAVE:
1186 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1189 Action = TLI.getOperationAction(Node->getOpcode(),
1190 Node->getValueType(0));
1191 if (Action != TargetLowering::Promote)
1192 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1194 case ISD::FP_TO_FP16:
1195 case ISD::SINT_TO_FP:
1196 case ISD::UINT_TO_FP:
1197 case ISD::EXTRACT_VECTOR_ELT:
1198 Action = TLI.getOperationAction(Node->getOpcode(),
1199 Node->getOperand(0).getValueType());
1201 case ISD::FP_ROUND_INREG:
1202 case ISD::SIGN_EXTEND_INREG: {
1203 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1204 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1207 case ISD::ATOMIC_STORE: {
1208 Action = TLI.getOperationAction(Node->getOpcode(),
1209 Node->getOperand(2).getValueType());
1212 case ISD::SELECT_CC:
1215 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1216 Node->getOpcode() == ISD::SETCC ? 2 : 1;
1217 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1218 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1219 ISD::CondCode CCCode =
1220 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1221 Action = TLI.getCondCodeAction(CCCode, OpVT);
1222 if (Action == TargetLowering::Legal) {
1223 if (Node->getOpcode() == ISD::SELECT_CC)
1224 Action = TLI.getOperationAction(Node->getOpcode(),
1225 Node->getValueType(0));
1227 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1233 // FIXME: Model these properly. LOAD and STORE are complicated, and
1234 // STORE expects the unlegalized operand in some cases.
1235 SimpleFinishLegalizing = false;
1237 case ISD::CALLSEQ_START:
1238 case ISD::CALLSEQ_END:
1239 // FIXME: This shouldn't be necessary. These nodes have special properties
1240 // dealing with the recursive nature of legalization. Removing this
1241 // special case should be done as part of making LegalizeDAG non-recursive.
1242 SimpleFinishLegalizing = false;
1244 case ISD::EXTRACT_ELEMENT:
1245 case ISD::FLT_ROUNDS_:
1253 case ISD::MERGE_VALUES:
1254 case ISD::EH_RETURN:
1255 case ISD::FRAME_TO_ARGS_OFFSET:
1256 case ISD::EH_SJLJ_SETJMP:
1257 case ISD::EH_SJLJ_LONGJMP:
1258 // These operations lie about being legal: when they claim to be legal,
1259 // they should actually be expanded.
1260 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1261 if (Action == TargetLowering::Legal)
1262 Action = TargetLowering::Expand;
1264 case ISD::INIT_TRAMPOLINE:
1265 case ISD::ADJUST_TRAMPOLINE:
1266 case ISD::FRAMEADDR:
1267 case ISD::RETURNADDR:
1268 // These operations lie about being legal: when they claim to be legal,
1269 // they should actually be custom-lowered.
1270 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1271 if (Action == TargetLowering::Legal)
1272 Action = TargetLowering::Custom;
1274 case ISD::READ_REGISTER:
1275 case ISD::WRITE_REGISTER:
1276 // Named register is legal in the DAG, but blocked by register name
1277 // selection if not implemented by target (to chose the correct register)
1278 // They'll be converted to Copy(To/From)Reg.
1279 Action = TargetLowering::Legal;
1281 case ISD::DEBUGTRAP:
1282 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1283 if (Action == TargetLowering::Expand) {
1284 // replace ISD::DEBUGTRAP with ISD::TRAP
1286 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1287 Node->getOperand(0));
1288 ReplaceNode(Node, NewVal.getNode());
1289 LegalizeOp(NewVal.getNode());
1295 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1296 Action = TargetLowering::Legal;
1298 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1303 if (SimpleFinishLegalizing) {
1304 SDNode *NewNode = Node;
1305 switch (Node->getOpcode()) {
1312 // Legalizing shifts/rotates requires adjusting the shift amount
1313 // to the appropriate width.
1314 if (!Node->getOperand(1).getValueType().isVector()) {
1316 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1317 Node->getOperand(1));
1318 HandleSDNode Handle(SAO);
1319 LegalizeOp(SAO.getNode());
1320 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1324 case ISD::SRL_PARTS:
1325 case ISD::SRA_PARTS:
1326 case ISD::SHL_PARTS:
1327 // Legalizing shifts/rotates requires adjusting the shift amount
1328 // to the appropriate width.
1329 if (!Node->getOperand(2).getValueType().isVector()) {
1331 DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
1332 Node->getOperand(2));
1333 HandleSDNode Handle(SAO);
1334 LegalizeOp(SAO.getNode());
1335 NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
1336 Node->getOperand(1),
1342 if (NewNode != Node) {
1343 ReplaceNode(Node, NewNode);
1347 case TargetLowering::Legal:
1349 case TargetLowering::Custom: {
1350 // FIXME: The handling for custom lowering with multiple results is
1352 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
1353 if (Res.getNode()) {
1354 if (!(Res.getNode() != Node || Res.getResNo() != 0))
1357 if (Node->getNumValues() == 1) {
1358 // We can just directly replace this node with the lowered value.
1359 ReplaceNode(SDValue(Node, 0), Res);
1363 SmallVector<SDValue, 8> ResultVals;
1364 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1365 ResultVals.push_back(Res.getValue(i));
1366 ReplaceNode(Node, ResultVals.data());
1371 case TargetLowering::Expand:
1374 case TargetLowering::Promote:
1380 switch (Node->getOpcode()) {
1387 llvm_unreachable("Do not know how to legalize this operator!");
1389 case ISD::CALLSEQ_START:
1390 case ISD::CALLSEQ_END:
1393 return LegalizeLoadOps(Node);
1396 return LegalizeStoreOps(Node);
1401 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1402 SDValue Vec = Op.getOperand(0);
1403 SDValue Idx = Op.getOperand(1);
1406 // Before we generate a new store to a temporary stack slot, see if there is
1407 // already one that we can use. There often is because when we scalarize
1408 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1409 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1410 // the vector. If all are expanded here, we don't want one store per vector
1412 SDValue StackPtr, Ch;
1413 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1414 UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1416 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1417 if (ST->isIndexed() || ST->isTruncatingStore() ||
1418 ST->getValue() != Vec)
1421 // Make sure that nothing else could have stored into the destination of
1423 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1426 StackPtr = ST->getBasePtr();
1427 Ch = SDValue(ST, 0);
1432 if (!Ch.getNode()) {
1433 // Store the value to a temporary stack slot, then LOAD the returned part.
1434 StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1435 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1436 MachinePointerInfo(), false, false, 0);
1439 // Add the offset to the index.
1441 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1442 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1443 DAG.getConstant(EltSize, Idx.getValueType()));
1445 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1446 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1448 if (Op.getValueType().isVector())
1449 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1450 false, false, false, 0);
1451 return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1452 MachinePointerInfo(),
1453 Vec.getValueType().getVectorElementType(),
1457 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1458 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1460 SDValue Vec = Op.getOperand(0);
1461 SDValue Part = Op.getOperand(1);
1462 SDValue Idx = Op.getOperand(2);
1465 // Store the value to a temporary stack slot, then LOAD the returned part.
1467 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1468 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1469 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1471 // First store the whole vector.
1472 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1475 // Then store the inserted part.
1477 // Add the offset to the index.
1479 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1481 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1482 DAG.getConstant(EltSize, Idx.getValueType()));
1483 Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy());
1485 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1488 // Store the subvector.
1489 Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1490 MachinePointerInfo(), false, false, 0);
1492 // Finally, load the updated vector.
1493 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1494 false, false, false, 0);
1497 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1498 // We can't handle this case efficiently. Allocate a sufficiently
1499 // aligned object on the stack, store each element into it, then load
1500 // the result as a vector.
1501 // Create the stack frame object.
1502 EVT VT = Node->getValueType(0);
1503 EVT EltVT = VT.getVectorElementType();
1505 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1506 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1507 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1509 // Emit a store of each element to the stack slot.
1510 SmallVector<SDValue, 8> Stores;
1511 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1512 // Store (in the right endianness) the elements to memory.
1513 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1514 // Ignore undef elements.
1515 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1517 unsigned Offset = TypeByteSize*i;
1519 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1520 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1522 // If the destination vector element type is narrower than the source
1523 // element type, only store the bits necessary.
1524 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1525 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1526 Node->getOperand(i), Idx,
1527 PtrInfo.getWithOffset(Offset),
1528 EltVT, false, false, 0));
1530 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1531 Node->getOperand(i), Idx,
1532 PtrInfo.getWithOffset(Offset),
1537 if (!Stores.empty()) // Not all undef elements?
1538 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1540 StoreChain = DAG.getEntryNode();
1542 // Result is a load from the stack slot.
1543 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
1544 false, false, false, 0);
1547 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1549 SDValue Tmp1 = Node->getOperand(0);
1550 SDValue Tmp2 = Node->getOperand(1);
1552 // Get the sign bit of the RHS. First obtain a value that has the same
1553 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1555 EVT FloatVT = Tmp2.getValueType();
1556 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1557 if (TLI.isTypeLegal(IVT)) {
1558 // Convert to an integer with the same sign bit.
1559 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1561 // Store the float to memory, then load the sign part out as an integer.
1562 MVT LoadTy = TLI.getPointerTy();
1563 // First create a temporary that is aligned for both the load and store.
1564 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1565 // Then store the float to it.
1567 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1569 if (TLI.isBigEndian()) {
1570 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1571 // Load out a legal integer with the same sign bit as the float.
1572 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1573 false, false, false, 0);
1574 } else { // Little endian
1575 SDValue LoadPtr = StackPtr;
1576 // The float may be wider than the integer we are going to load. Advance
1577 // the pointer so that the loaded integer will contain the sign bit.
1578 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1579 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1580 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(), LoadPtr,
1581 DAG.getConstant(ByteOffset, LoadPtr.getValueType()));
1582 // Load a legal integer containing the sign bit.
1583 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1584 false, false, false, 0);
1585 // Move the sign bit to the top bit of the loaded integer.
1586 unsigned BitShift = LoadTy.getSizeInBits() -
1587 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1588 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1590 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1591 DAG.getConstant(BitShift,
1592 TLI.getShiftAmountTy(SignBit.getValueType())));
1595 // Now get the sign bit proper, by seeing whether the value is negative.
1596 SignBit = DAG.getSetCC(dl, getSetCCResultType(SignBit.getValueType()),
1597 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1599 // Get the absolute value of the result.
1600 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1601 // Select between the nabs and abs value based on the sign bit of
1603 return DAG.getSelect(dl, AbsVal.getValueType(), SignBit,
1604 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1608 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1609 SmallVectorImpl<SDValue> &Results) {
1610 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1611 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1612 " not tell us which reg is the stack pointer!");
1614 EVT VT = Node->getValueType(0);
1615 SDValue Tmp1 = SDValue(Node, 0);
1616 SDValue Tmp2 = SDValue(Node, 1);
1617 SDValue Tmp3 = Node->getOperand(2);
1618 SDValue Chain = Tmp1.getOperand(0);
1620 // Chain the dynamic stack allocation so that it doesn't modify the stack
1621 // pointer when other instructions are using the stack.
1622 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
1625 SDValue Size = Tmp2.getOperand(1);
1626 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1627 Chain = SP.getValue(1);
1628 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1629 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1630 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1631 if (Align > StackAlign)
1632 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1633 DAG.getConstant(-(uint64_t)Align, VT));
1634 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1636 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1637 DAG.getIntPtrConstant(0, true), SDValue(),
1640 Results.push_back(Tmp1);
1641 Results.push_back(Tmp2);
1644 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1645 /// condition code CC on the current target.
1647 /// If the SETCC has been legalized using AND / OR, then the legalized node
1648 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1649 /// will be set to false.
1651 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1652 /// then the values of LHS and RHS will be swapped, CC will be set to the
1653 /// new condition, and NeedInvert will be set to false.
1655 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1656 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1657 /// will be set to true. The caller must invert the result of the SETCC with
1658 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1659 /// of a true/false result.
1661 /// \returns true if the SetCC has been legalized, false if it hasn't.
1662 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1663 SDValue &LHS, SDValue &RHS,
1667 MVT OpVT = LHS.getSimpleValueType();
1668 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1670 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1671 default: llvm_unreachable("Unknown condition code action!");
1672 case TargetLowering::Legal:
1675 case TargetLowering::Expand: {
1676 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
1677 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1678 std::swap(LHS, RHS);
1679 CC = DAG.getCondCode(InvCC);
1682 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1685 default: llvm_unreachable("Don't know how to expand this condition!");
1687 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
1688 == TargetLowering::Legal
1689 && "If SETO is expanded, SETOEQ must be legal!");
1690 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1692 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
1693 == TargetLowering::Legal
1694 && "If SETUO is expanded, SETUNE must be legal!");
1695 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1708 // If we are floating point, assign and break, otherwise fall through.
1709 if (!OpVT.isInteger()) {
1710 // We can use the 4th bit to tell if we are the unordered
1711 // or ordered version of the opcode.
1712 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1713 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1714 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1717 // Fallthrough if we are unsigned integer.
1722 // We only support using the inverted operation, which is computed above
1723 // and not a different manner of supporting expanding these cases.
1724 llvm_unreachable("Don't know how to expand this condition!");
1727 // Try inverting the result of the inverse condition.
1728 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
1729 if (TLI.isCondCodeLegal(InvCC, OpVT)) {
1730 CC = DAG.getCondCode(InvCC);
1734 // If inverting the condition didn't work then we have no means to expand
1736 llvm_unreachable("Don't know how to expand this condition!");
1739 SDValue SetCC1, SetCC2;
1740 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1741 // If we aren't the ordered or unorder operation,
1742 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1743 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1744 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1746 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1747 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1748 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1750 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1759 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1760 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1761 /// a load from the stack slot to DestVT, extending it if needed.
1762 /// The resultant code need not be legal.
1763 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1767 // Create the stack frame object.
1769 TLI.getDataLayout()->getPrefTypeAlignment(SrcOp.getValueType().
1770 getTypeForEVT(*DAG.getContext()));
1771 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1773 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1774 int SPFI = StackPtrFI->getIndex();
1775 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1777 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1778 unsigned SlotSize = SlotVT.getSizeInBits();
1779 unsigned DestSize = DestVT.getSizeInBits();
1780 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1781 unsigned DestAlign = TLI.getDataLayout()->getPrefTypeAlignment(DestType);
1783 // Emit a store to the stack slot. Use a truncstore if the input value is
1784 // later than DestVT.
1787 if (SrcSize > SlotSize)
1788 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1789 PtrInfo, SlotVT, false, false, SrcAlign);
1791 assert(SrcSize == SlotSize && "Invalid store");
1792 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1793 PtrInfo, false, false, SrcAlign);
1796 // Result is a load from the stack slot.
1797 if (SlotSize == DestSize)
1798 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1799 false, false, false, DestAlign);
1801 assert(SlotSize < DestSize && "Unknown extension!");
1802 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
1803 PtrInfo, SlotVT, false, false, DestAlign);
1806 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1808 // Create a vector sized/aligned stack slot, store the value to element #0,
1809 // then load the whole vector back out.
1810 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1812 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1813 int SPFI = StackPtrFI->getIndex();
1815 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1817 MachinePointerInfo::getFixedStack(SPFI),
1818 Node->getValueType(0).getVectorElementType(),
1820 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1821 MachinePointerInfo::getFixedStack(SPFI),
1822 false, false, false, 0);
1826 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1827 const TargetLowering &TLI, SDValue &Res) {
1828 unsigned NumElems = Node->getNumOperands();
1830 EVT VT = Node->getValueType(0);
1832 // Try to group the scalars into pairs, shuffle the pairs together, then
1833 // shuffle the pairs of pairs together, etc. until the vector has
1834 // been built. This will work only if all of the necessary shuffle masks
1837 // We do this in two phases; first to check the legality of the shuffles,
1838 // and next, assuming that all shuffles are legal, to create the new nodes.
1839 for (int Phase = 0; Phase < 2; ++Phase) {
1840 SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
1842 for (unsigned i = 0; i < NumElems; ++i) {
1843 SDValue V = Node->getOperand(i);
1844 if (V.getOpcode() == ISD::UNDEF)
1849 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1850 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1853 while (IntermedVals.size() > 2) {
1854 NewIntermedVals.clear();
1855 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1856 // This vector and the next vector are shuffled together (simply to
1857 // append the one to the other).
1858 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1860 SmallVector<int, 16> FinalIndices;
1861 FinalIndices.reserve(IntermedVals[i].second.size() +
1862 IntermedVals[i+1].second.size());
1865 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1868 FinalIndices.push_back(IntermedVals[i].second[j]);
1870 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1872 ShuffleVec[k] = NumElems + j;
1873 FinalIndices.push_back(IntermedVals[i+1].second[j]);
1878 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1879 IntermedVals[i+1].first,
1881 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1883 NewIntermedVals.push_back(std::make_pair(Shuffle, FinalIndices));
1886 // If we had an odd number of defined values, then append the last
1887 // element to the array of new vectors.
1888 if ((IntermedVals.size() & 1) != 0)
1889 NewIntermedVals.push_back(IntermedVals.back());
1891 IntermedVals.swap(NewIntermedVals);
1894 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1895 "Invalid number of intermediate vectors");
1896 SDValue Vec1 = IntermedVals[0].first;
1898 if (IntermedVals.size() > 1)
1899 Vec2 = IntermedVals[1].first;
1901 Vec2 = DAG.getUNDEF(VT);
1903 SmallVector<int, 16> ShuffleVec(NumElems, -1);
1904 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1905 ShuffleVec[IntermedVals[0].second[i]] = i;
1906 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1907 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1910 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1911 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1918 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1919 /// support the operation, but do support the resultant vector type.
1920 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1921 unsigned NumElems = Node->getNumOperands();
1922 SDValue Value1, Value2;
1924 EVT VT = Node->getValueType(0);
1925 EVT OpVT = Node->getOperand(0).getValueType();
1926 EVT EltVT = VT.getVectorElementType();
1928 // If the only non-undef value is the low element, turn this into a
1929 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1930 bool isOnlyLowElement = true;
1931 bool MoreThanTwoValues = false;
1932 bool isConstant = true;
1933 for (unsigned i = 0; i < NumElems; ++i) {
1934 SDValue V = Node->getOperand(i);
1935 if (V.getOpcode() == ISD::UNDEF)
1938 isOnlyLowElement = false;
1939 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1942 if (!Value1.getNode()) {
1944 } else if (!Value2.getNode()) {
1947 } else if (V != Value1 && V != Value2) {
1948 MoreThanTwoValues = true;
1952 if (!Value1.getNode())
1953 return DAG.getUNDEF(VT);
1955 if (isOnlyLowElement)
1956 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1958 // If all elements are constants, create a load from the constant pool.
1960 SmallVector<Constant*, 16> CV;
1961 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1962 if (ConstantFPSDNode *V =
1963 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1964 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1965 } else if (ConstantSDNode *V =
1966 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1968 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1970 // If OpVT and EltVT don't match, EltVT is not legal and the
1971 // element values have been promoted/truncated earlier. Undo this;
1972 // we don't want a v16i8 to become a v16i32 for example.
1973 const ConstantInt *CI = V->getConstantIntValue();
1974 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1975 CI->getZExtValue()));
1978 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1979 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1980 CV.push_back(UndefValue::get(OpNTy));
1983 Constant *CP = ConstantVector::get(CV);
1984 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1985 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1986 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1987 MachinePointerInfo::getConstantPool(),
1988 false, false, false, Alignment);
1991 SmallSet<SDValue, 16> DefinedValues;
1992 for (unsigned i = 0; i < NumElems; ++i) {
1993 if (Node->getOperand(i).getOpcode() == ISD::UNDEF)
1995 DefinedValues.insert(Node->getOperand(i));
1998 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1999 if (!MoreThanTwoValues) {
2000 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2001 for (unsigned i = 0; i < NumElems; ++i) {
2002 SDValue V = Node->getOperand(i);
2003 if (V.getOpcode() == ISD::UNDEF)
2005 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2007 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2008 // Get the splatted value into the low element of a vector register.
2009 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2011 if (Value2.getNode())
2012 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2014 Vec2 = DAG.getUNDEF(VT);
2016 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2017 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2021 if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2026 // Otherwise, we can't handle this case efficiently.
2027 return ExpandVectorBuildThroughStack(Node);
2030 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
2031 // does not fit into a register, return the lo part and set the hi part to the
2032 // by-reg argument. If it does fit into a single register, return the result
2033 // and leave the Hi part unset.
2034 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2036 TargetLowering::ArgListTy Args;
2037 TargetLowering::ArgListEntry Entry;
2038 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2039 EVT ArgVT = Node->getOperand(i).getValueType();
2040 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2041 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2042 Entry.isSExt = isSigned;
2043 Entry.isZExt = !isSigned;
2044 Args.push_back(Entry);
2046 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2047 TLI.getPointerTy());
2049 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2051 // By default, the input chain to this libcall is the entry node of the
2052 // function. If the libcall is going to be emitted as a tail call then
2053 // TLI.isUsedByReturnOnly will change it to the right chain if the return
2054 // node which is being folded has a non-entry input chain.
2055 SDValue InChain = DAG.getEntryNode();
2057 // isTailCall may be true since the callee does not reference caller stack
2058 // frame. Check if it's in the right position.
2059 SDValue TCChain = InChain;
2060 bool isTailCall = TLI.isInTailCallPosition(DAG, Node, TCChain);
2064 TargetLowering::CallLoweringInfo CLI(DAG);
2065 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2066 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2067 .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned);
2069 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2071 if (!CallInfo.second.getNode())
2072 // It's a tailcall, return the chain (which is the DAG root).
2073 return DAG.getRoot();
2075 return CallInfo.first;
2078 /// ExpandLibCall - Generate a libcall taking the given operands as arguments
2079 /// and returning a result of type RetVT.
2080 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2081 const SDValue *Ops, unsigned NumOps,
2082 bool isSigned, SDLoc dl) {
2083 TargetLowering::ArgListTy Args;
2084 Args.reserve(NumOps);
2086 TargetLowering::ArgListEntry Entry;
2087 for (unsigned i = 0; i != NumOps; ++i) {
2088 Entry.Node = Ops[i];
2089 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2090 Entry.isSExt = isSigned;
2091 Entry.isZExt = !isSigned;
2092 Args.push_back(Entry);
2094 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2095 TLI.getPointerTy());
2097 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2099 TargetLowering::CallLoweringInfo CLI(DAG);
2100 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
2101 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2102 .setSExtResult(isSigned).setZExtResult(!isSigned);
2104 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
2106 return CallInfo.first;
2109 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
2110 // ExpandLibCall except that the first operand is the in-chain.
2111 std::pair<SDValue, SDValue>
2112 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2115 SDValue InChain = Node->getOperand(0);
2117 TargetLowering::ArgListTy Args;
2118 TargetLowering::ArgListEntry Entry;
2119 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2120 EVT ArgVT = Node->getOperand(i).getValueType();
2121 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2122 Entry.Node = Node->getOperand(i);
2124 Entry.isSExt = isSigned;
2125 Entry.isZExt = !isSigned;
2126 Args.push_back(Entry);
2128 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2129 TLI.getPointerTy());
2131 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2133 TargetLowering::CallLoweringInfo CLI(DAG);
2134 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
2135 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2136 .setSExtResult(isSigned).setZExtResult(!isSigned);
2138 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2143 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2144 RTLIB::Libcall Call_F32,
2145 RTLIB::Libcall Call_F64,
2146 RTLIB::Libcall Call_F80,
2147 RTLIB::Libcall Call_F128,
2148 RTLIB::Libcall Call_PPCF128) {
2150 switch (Node->getSimpleValueType(0).SimpleTy) {
2151 default: llvm_unreachable("Unexpected request for libcall!");
2152 case MVT::f32: LC = Call_F32; break;
2153 case MVT::f64: LC = Call_F64; break;
2154 case MVT::f80: LC = Call_F80; break;
2155 case MVT::f128: LC = Call_F128; break;
2156 case MVT::ppcf128: LC = Call_PPCF128; break;
2158 return ExpandLibCall(LC, Node, false);
2161 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2162 RTLIB::Libcall Call_I8,
2163 RTLIB::Libcall Call_I16,
2164 RTLIB::Libcall Call_I32,
2165 RTLIB::Libcall Call_I64,
2166 RTLIB::Libcall Call_I128) {
2168 switch (Node->getSimpleValueType(0).SimpleTy) {
2169 default: llvm_unreachable("Unexpected request for libcall!");
2170 case MVT::i8: LC = Call_I8; break;
2171 case MVT::i16: LC = Call_I16; break;
2172 case MVT::i32: LC = Call_I32; break;
2173 case MVT::i64: LC = Call_I64; break;
2174 case MVT::i128: LC = Call_I128; break;
2176 return ExpandLibCall(LC, Node, isSigned);
2179 /// isDivRemLibcallAvailable - Return true if divmod libcall is available.
2180 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2181 const TargetLowering &TLI) {
2183 switch (Node->getSimpleValueType(0).SimpleTy) {
2184 default: llvm_unreachable("Unexpected request for libcall!");
2185 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2186 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2187 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2188 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2189 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2192 return TLI.getLibcallName(LC) != nullptr;
2195 /// useDivRem - Only issue divrem libcall if both quotient and remainder are
2197 static bool useDivRem(SDNode *Node, bool isSigned, bool isDIV) {
2198 // The other use might have been replaced with a divrem already.
2199 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2200 unsigned OtherOpcode = 0;
2202 OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
2204 OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
2206 SDValue Op0 = Node->getOperand(0);
2207 SDValue Op1 = Node->getOperand(1);
2208 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2209 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2213 if ((User->getOpcode() == OtherOpcode || User->getOpcode() == DivRemOpc) &&
2214 User->getOperand(0) == Op0 &&
2215 User->getOperand(1) == Op1)
2221 /// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
2224 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2225 SmallVectorImpl<SDValue> &Results) {
2226 unsigned Opcode = Node->getOpcode();
2227 bool isSigned = Opcode == ISD::SDIVREM;
2230 switch (Node->getSimpleValueType(0).SimpleTy) {
2231 default: llvm_unreachable("Unexpected request for libcall!");
2232 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2233 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2234 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2235 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2236 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2239 // The input chain to this libcall is the entry node of the function.
2240 // Legalizing the call will automatically add the previous call to the
2242 SDValue InChain = DAG.getEntryNode();
2244 EVT RetVT = Node->getValueType(0);
2245 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2247 TargetLowering::ArgListTy Args;
2248 TargetLowering::ArgListEntry Entry;
2249 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2250 EVT ArgVT = Node->getOperand(i).getValueType();
2251 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2252 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2253 Entry.isSExt = isSigned;
2254 Entry.isZExt = !isSigned;
2255 Args.push_back(Entry);
2258 // Also pass the return address of the remainder.
2259 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2261 Entry.Ty = RetTy->getPointerTo();
2262 Entry.isSExt = isSigned;
2263 Entry.isZExt = !isSigned;
2264 Args.push_back(Entry);
2266 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2267 TLI.getPointerTy());
2270 TargetLowering::CallLoweringInfo CLI(DAG);
2271 CLI.setDebugLoc(dl).setChain(InChain)
2272 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
2273 .setSExtResult(isSigned).setZExtResult(!isSigned);
2275 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2277 // Remainder is loaded back from the stack frame.
2278 SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
2279 MachinePointerInfo(), false, false, false, 0);
2280 Results.push_back(CallInfo.first);
2281 Results.push_back(Rem);
2284 /// isSinCosLibcallAvailable - Return true if sincos libcall is available.
2285 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2287 switch (Node->getSimpleValueType(0).SimpleTy) {
2288 default: llvm_unreachable("Unexpected request for libcall!");
2289 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2290 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2291 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2292 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2293 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2295 return TLI.getLibcallName(LC) != nullptr;
2298 /// canCombineSinCosLibcall - Return true if sincos libcall is available and
2299 /// can be used to combine sin and cos.
2300 static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
2301 const TargetMachine &TM) {
2302 if (!isSinCosLibcallAvailable(Node, TLI))
2304 // GNU sin/cos functions set errno while sincos does not. Therefore
2305 // combining sin and cos is only safe if unsafe-fpmath is enabled.
2306 bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU;
2307 if (isGNU && !TM.Options.UnsafeFPMath)
2312 /// useSinCos - Only issue sincos libcall if both sin and cos are
2314 static bool useSinCos(SDNode *Node) {
2315 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2316 ? ISD::FCOS : ISD::FSIN;
2318 SDValue Op0 = Node->getOperand(0);
2319 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2320 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2324 // The other user might have been turned into sincos already.
2325 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2331 /// ExpandSinCosLibCall - Issue libcalls to sincos to compute sin / cos
2334 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2335 SmallVectorImpl<SDValue> &Results) {
2337 switch (Node->getSimpleValueType(0).SimpleTy) {
2338 default: llvm_unreachable("Unexpected request for libcall!");
2339 case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2340 case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2341 case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2342 case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2343 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2346 // The input chain to this libcall is the entry node of the function.
2347 // Legalizing the call will automatically add the previous call to the
2349 SDValue InChain = DAG.getEntryNode();
2351 EVT RetVT = Node->getValueType(0);
2352 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2354 TargetLowering::ArgListTy Args;
2355 TargetLowering::ArgListEntry Entry;
2357 // Pass the argument.
2358 Entry.Node = Node->getOperand(0);
2360 Entry.isSExt = false;
2361 Entry.isZExt = false;
2362 Args.push_back(Entry);
2364 // Pass the return address of sin.
2365 SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2366 Entry.Node = SinPtr;
2367 Entry.Ty = RetTy->getPointerTo();
2368 Entry.isSExt = false;
2369 Entry.isZExt = false;
2370 Args.push_back(Entry);
2372 // Also pass the return address of the cos.
2373 SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2374 Entry.Node = CosPtr;
2375 Entry.Ty = RetTy->getPointerTo();
2376 Entry.isSExt = false;
2377 Entry.isZExt = false;
2378 Args.push_back(Entry);
2380 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2381 TLI.getPointerTy());
2384 TargetLowering::CallLoweringInfo CLI(DAG);
2385 CLI.setDebugLoc(dl).setChain(InChain)
2386 .setCallee(TLI.getLibcallCallingConv(LC),
2387 Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0);
2389 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2391 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr,
2392 MachinePointerInfo(), false, false, false, 0));
2393 Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr,
2394 MachinePointerInfo(), false, false, false, 0));
2397 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2398 /// INT_TO_FP operation of the specified operand when the target requests that
2399 /// we expand it. At this point, we know that the result and operand types are
2400 /// legal for the target.
2401 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2405 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2406 // simple 32-bit [signed|unsigned] integer to float/double expansion
2408 // Get the stack frame index of a 8 byte buffer.
2409 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2411 // word offset constant for Hi/Lo address computation
2412 SDValue WordOff = DAG.getConstant(sizeof(int), StackSlot.getValueType());
2413 // set up Hi and Lo (into buffer) address based on endian
2414 SDValue Hi = StackSlot;
2415 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2416 StackSlot, WordOff);
2417 if (TLI.isLittleEndian())
2420 // if signed map to unsigned space
2423 // constant used to invert sign bit (signed to unsigned mapping)
2424 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2425 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2429 // store the lo of the constructed double - based on integer input
2430 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2431 Op0Mapped, Lo, MachinePointerInfo(),
2433 // initial hi portion of constructed double
2434 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2435 // store the hi of the constructed double - biased exponent
2436 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2437 MachinePointerInfo(),
2439 // load the constructed double
2440 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2441 MachinePointerInfo(), false, false, false, 0);
2442 // FP constant to bias correct the final result
2443 SDValue Bias = DAG.getConstantFP(isSigned ?
2444 BitsToDouble(0x4330000080000000ULL) :
2445 BitsToDouble(0x4330000000000000ULL),
2447 // subtract the bias
2448 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2451 // handle final rounding
2452 if (DestVT == MVT::f64) {
2455 } else if (DestVT.bitsLT(MVT::f64)) {
2456 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2457 DAG.getIntPtrConstant(0));
2458 } else if (DestVT.bitsGT(MVT::f64)) {
2459 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2463 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2464 // Code below here assumes !isSigned without checking again.
2466 // Implementation of unsigned i64 to f64 following the algorithm in
2467 // __floatundidf in compiler_rt. This implementation has the advantage
2468 // of performing rounding correctly, both in the default rounding mode
2469 // and in all alternate rounding modes.
2470 // TODO: Generalize this for use with other types.
2471 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2473 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2474 SDValue TwoP84PlusTwoP52 =
2475 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2477 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2479 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2480 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2481 DAG.getConstant(32, MVT::i64));
2482 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2483 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2484 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2485 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2486 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2488 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2491 // Implementation of unsigned i64 to f32.
2492 // TODO: Generalize this for use with other types.
2493 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2494 // For unsigned conversions, convert them to signed conversions using the
2495 // algorithm from the x86_64 __floatundidf in compiler_rt.
2497 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2499 SDValue ShiftConst =
2500 DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2501 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2502 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2503 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2504 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2506 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2507 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2509 // TODO: This really should be implemented using a branch rather than a
2510 // select. We happen to get lucky and machinesink does the right
2511 // thing most of the time. This would be a good candidate for a
2512 //pseudo-op, or, even better, for whole-function isel.
2513 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2514 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2515 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
2518 // Otherwise, implement the fully general conversion.
2520 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2521 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2522 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2523 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2524 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2525 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2526 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2527 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2528 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
2529 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
2530 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2532 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
2533 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2535 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2536 DAG.getConstant(32, SHVT));
2537 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2538 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2540 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2541 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2542 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2543 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2544 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2545 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2546 DAG.getIntPtrConstant(0));
2549 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2551 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
2552 Op0, DAG.getConstant(0, Op0.getValueType()),
2554 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2555 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2556 SignSet, Four, Zero);
2558 // If the sign bit of the integer is set, the large number will be treated
2559 // as a negative number. To counteract this, the dynamic code adds an
2560 // offset depending on the data type.
2562 switch (Op0.getSimpleValueType().SimpleTy) {
2563 default: llvm_unreachable("Unsupported integer type!");
2564 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2565 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2566 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2567 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2569 if (TLI.isLittleEndian()) FF <<= 32;
2570 Constant *FudgeFactor = ConstantInt::get(
2571 Type::getInt64Ty(*DAG.getContext()), FF);
2573 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2574 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2575 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2576 Alignment = std::min(Alignment, 4u);
2578 if (DestVT == MVT::f32)
2579 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2580 MachinePointerInfo::getConstantPool(),
2581 false, false, false, Alignment);
2583 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2584 DAG.getEntryNode(), CPIdx,
2585 MachinePointerInfo::getConstantPool(),
2586 MVT::f32, false, false, Alignment);
2587 HandleSDNode Handle(Load);
2588 LegalizeOp(Load.getNode());
2589 FudgeInReg = Handle.getValue();
2592 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2595 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2596 /// *INT_TO_FP operation of the specified operand when the target requests that
2597 /// we promote it. At this point, we know that the result and operand types are
2598 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2599 /// operation that takes a larger input.
2600 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2604 // First step, figure out the appropriate *INT_TO_FP operation to use.
2605 EVT NewInTy = LegalOp.getValueType();
2607 unsigned OpToUse = 0;
2609 // Scan for the appropriate larger type to use.
2611 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2612 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2614 // If the target supports SINT_TO_FP of this type, use it.
2615 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2616 OpToUse = ISD::SINT_TO_FP;
2619 if (isSigned) continue;
2621 // If the target supports UINT_TO_FP of this type, use it.
2622 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2623 OpToUse = ISD::UINT_TO_FP;
2627 // Otherwise, try a larger type.
2630 // Okay, we found the operation and type to use. Zero extend our input to the
2631 // desired type then run the operation on it.
2632 return DAG.getNode(OpToUse, dl, DestVT,
2633 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2634 dl, NewInTy, LegalOp));
2637 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2638 /// FP_TO_*INT operation of the specified operand when the target requests that
2639 /// we promote it. At this point, we know that the result and operand types are
2640 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2641 /// operation that returns a larger result.
2642 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2646 // First step, figure out the appropriate FP_TO*INT operation to use.
2647 EVT NewOutTy = DestVT;
2649 unsigned OpToUse = 0;
2651 // Scan for the appropriate larger type to use.
2653 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2654 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2656 // A larger signed type can hold all unsigned values of the requested type,
2657 // so using FP_TO_SINT is valid
2658 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2659 OpToUse = ISD::FP_TO_SINT;
2663 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2664 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2665 OpToUse = ISD::FP_TO_UINT;
2669 // Otherwise, try a larger type.
2673 // Okay, we found the operation and type to use.
2674 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2676 // Truncate the result of the extended FP_TO_*INT operation to the desired
2678 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2681 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2683 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, SDLoc dl) {
2684 EVT VT = Op.getValueType();
2685 EVT SHVT = TLI.getShiftAmountTy(VT);
2686 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2687 switch (VT.getSimpleVT().SimpleTy) {
2688 default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2690 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2691 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2692 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2694 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2695 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2696 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2697 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2698 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2699 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2700 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2701 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2702 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2704 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2705 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2706 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2707 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2708 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2709 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2710 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2711 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2712 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2713 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2714 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2715 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2716 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2717 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2718 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2719 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2720 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2721 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2722 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2723 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2724 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2728 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2730 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2733 default: llvm_unreachable("Cannot expand this yet!");
2735 EVT VT = Op.getValueType();
2736 EVT ShVT = TLI.getShiftAmountTy(VT);
2737 unsigned Len = VT.getSizeInBits();
2739 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2740 "CTPOP not implemented for this type.");
2742 // This is the "best" algorithm from
2743 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2745 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), VT);
2746 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), VT);
2747 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), VT);
2748 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), VT);
2750 // v = v - ((v >> 1) & 0x55555555...)
2751 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2752 DAG.getNode(ISD::AND, dl, VT,
2753 DAG.getNode(ISD::SRL, dl, VT, Op,
2754 DAG.getConstant(1, ShVT)),
2756 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2757 Op = DAG.getNode(ISD::ADD, dl, VT,
2758 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2759 DAG.getNode(ISD::AND, dl, VT,
2760 DAG.getNode(ISD::SRL, dl, VT, Op,
2761 DAG.getConstant(2, ShVT)),
2763 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2764 Op = DAG.getNode(ISD::AND, dl, VT,
2765 DAG.getNode(ISD::ADD, dl, VT, Op,
2766 DAG.getNode(ISD::SRL, dl, VT, Op,
2767 DAG.getConstant(4, ShVT))),
2769 // v = (v * 0x01010101...) >> (Len - 8)
2770 Op = DAG.getNode(ISD::SRL, dl, VT,
2771 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2772 DAG.getConstant(Len - 8, ShVT));
2776 case ISD::CTLZ_ZERO_UNDEF:
2777 // This trivially expands to CTLZ.
2778 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2780 // for now, we do this:
2781 // x = x | (x >> 1);
2782 // x = x | (x >> 2);
2784 // x = x | (x >>16);
2785 // x = x | (x >>32); // for 64-bit input
2786 // return popcount(~x);
2788 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2789 EVT VT = Op.getValueType();
2790 EVT ShVT = TLI.getShiftAmountTy(VT);
2791 unsigned len = VT.getSizeInBits();
2792 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2793 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2794 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2795 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2797 Op = DAG.getNOT(dl, Op, VT);
2798 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2800 case ISD::CTTZ_ZERO_UNDEF:
2801 // This trivially expands to CTTZ.
2802 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2804 // for now, we use: { return popcount(~x & (x - 1)); }
2805 // unless the target has ctlz but not ctpop, in which case we use:
2806 // { return 32 - nlz(~x & (x-1)); }
2807 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2808 EVT VT = Op.getValueType();
2809 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2810 DAG.getNOT(dl, Op, VT),
2811 DAG.getNode(ISD::SUB, dl, VT, Op,
2812 DAG.getConstant(1, VT)));
2813 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2814 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2815 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2816 return DAG.getNode(ISD::SUB, dl, VT,
2817 DAG.getConstant(VT.getSizeInBits(), VT),
2818 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2819 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2824 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2825 unsigned Opc = Node->getOpcode();
2826 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2831 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2832 case ISD::ATOMIC_SWAP:
2833 switch (VT.SimpleTy) {
2834 default: llvm_unreachable("Unexpected value type for atomic!");
2835 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2836 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2837 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2838 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2839 case MVT::i128:LC = RTLIB::SYNC_LOCK_TEST_AND_SET_16;break;
2842 case ISD::ATOMIC_CMP_SWAP:
2843 switch (VT.SimpleTy) {
2844 default: llvm_unreachable("Unexpected value type for atomic!");
2845 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2846 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2847 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2848 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2849 case MVT::i128:LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16;break;
2852 case ISD::ATOMIC_LOAD_ADD:
2853 switch (VT.SimpleTy) {
2854 default: llvm_unreachable("Unexpected value type for atomic!");
2855 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2856 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2857 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2858 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2859 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_ADD_16;break;
2862 case ISD::ATOMIC_LOAD_SUB:
2863 switch (VT.SimpleTy) {
2864 default: llvm_unreachable("Unexpected value type for atomic!");
2865 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2866 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2867 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2868 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2869 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_SUB_16;break;
2872 case ISD::ATOMIC_LOAD_AND:
2873 switch (VT.SimpleTy) {
2874 default: llvm_unreachable("Unexpected value type for atomic!");
2875 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2876 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2877 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2878 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2879 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_AND_16;break;
2882 case ISD::ATOMIC_LOAD_OR:
2883 switch (VT.SimpleTy) {
2884 default: llvm_unreachable("Unexpected value type for atomic!");
2885 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2886 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2887 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2888 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2889 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_OR_16;break;
2892 case ISD::ATOMIC_LOAD_XOR:
2893 switch (VT.SimpleTy) {
2894 default: llvm_unreachable("Unexpected value type for atomic!");
2895 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2896 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2897 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2898 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2899 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_XOR_16;break;
2902 case ISD::ATOMIC_LOAD_NAND:
2903 switch (VT.SimpleTy) {
2904 default: llvm_unreachable("Unexpected value type for atomic!");
2905 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2906 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2907 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2908 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2909 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_NAND_16;break;
2912 case ISD::ATOMIC_LOAD_MAX:
2913 switch (VT.SimpleTy) {
2914 default: llvm_unreachable("Unexpected value type for atomic!");
2915 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MAX_1; break;
2916 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MAX_2; break;
2917 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MAX_4; break;
2918 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MAX_8; break;
2919 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MAX_16;break;
2922 case ISD::ATOMIC_LOAD_UMAX:
2923 switch (VT.SimpleTy) {
2924 default: llvm_unreachable("Unexpected value type for atomic!");
2925 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMAX_1; break;
2926 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMAX_2; break;
2927 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMAX_4; break;
2928 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMAX_8; break;
2929 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMAX_16;break;
2932 case ISD::ATOMIC_LOAD_MIN:
2933 switch (VT.SimpleTy) {
2934 default: llvm_unreachable("Unexpected value type for atomic!");
2935 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_MIN_1; break;
2936 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_MIN_2; break;
2937 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_MIN_4; break;
2938 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_MIN_8; break;
2939 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_MIN_16;break;
2942 case ISD::ATOMIC_LOAD_UMIN:
2943 switch (VT.SimpleTy) {
2944 default: llvm_unreachable("Unexpected value type for atomic!");
2945 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_UMIN_1; break;
2946 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_UMIN_2; break;
2947 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_UMIN_4; break;
2948 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_UMIN_8; break;
2949 case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_UMIN_16;break;
2954 return ExpandChainLibCall(LC, Node, false);
2957 void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2958 SmallVector<SDValue, 8> Results;
2960 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2962 switch (Node->getOpcode()) {
2965 case ISD::CTLZ_ZERO_UNDEF:
2967 case ISD::CTTZ_ZERO_UNDEF:
2968 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2969 Results.push_back(Tmp1);
2972 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2974 case ISD::FRAMEADDR:
2975 case ISD::RETURNADDR:
2976 case ISD::FRAME_TO_ARGS_OFFSET:
2977 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2979 case ISD::FLT_ROUNDS_:
2980 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2982 case ISD::EH_RETURN:
2986 case ISD::EH_SJLJ_LONGJMP:
2987 // If the target didn't expand these, there's nothing to do, so just
2988 // preserve the chain and be done.
2989 Results.push_back(Node->getOperand(0));
2991 case ISD::EH_SJLJ_SETJMP:
2992 // If the target didn't expand this, just return 'zero' and preserve the
2994 Results.push_back(DAG.getConstant(0, MVT::i32));
2995 Results.push_back(Node->getOperand(0));
2997 case ISD::ATOMIC_FENCE: {
2998 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2999 // FIXME: handle "fence singlethread" more efficiently.
3000 TargetLowering::ArgListTy Args;
3002 TargetLowering::CallLoweringInfo CLI(DAG);
3003 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3004 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3005 DAG.getExternalSymbol("__sync_synchronize",
3006 TLI.getPointerTy()), std::move(Args), 0);
3008 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3010 Results.push_back(CallResult.second);
3013 case ISD::ATOMIC_LOAD: {
3014 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
3015 SDValue Zero = DAG.getConstant(0, Node->getValueType(0));
3016 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3017 SDValue Swap = DAG.getAtomicCmpSwap(
3018 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3019 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
3020 cast<AtomicSDNode>(Node)->getMemOperand(),
3021 cast<AtomicSDNode>(Node)->getOrdering(),
3022 cast<AtomicSDNode>(Node)->getOrdering(),
3023 cast<AtomicSDNode>(Node)->getSynchScope());
3024 Results.push_back(Swap.getValue(0));
3025 Results.push_back(Swap.getValue(1));
3028 case ISD::ATOMIC_STORE: {
3029 // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
3030 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
3031 cast<AtomicSDNode>(Node)->getMemoryVT(),
3032 Node->getOperand(0),
3033 Node->getOperand(1), Node->getOperand(2),
3034 cast<AtomicSDNode>(Node)->getMemOperand(),
3035 cast<AtomicSDNode>(Node)->getOrdering(),
3036 cast<AtomicSDNode>(Node)->getSynchScope());
3037 Results.push_back(Swap.getValue(1));
3040 // By default, atomic intrinsics are marked Legal and lowered. Targets
3041 // which don't support them directly, however, may want libcalls, in which
3042 // case they mark them Expand, and we get here.
3043 case ISD::ATOMIC_SWAP:
3044 case ISD::ATOMIC_LOAD_ADD:
3045 case ISD::ATOMIC_LOAD_SUB:
3046 case ISD::ATOMIC_LOAD_AND:
3047 case ISD::ATOMIC_LOAD_OR:
3048 case ISD::ATOMIC_LOAD_XOR:
3049 case ISD::ATOMIC_LOAD_NAND:
3050 case ISD::ATOMIC_LOAD_MIN:
3051 case ISD::ATOMIC_LOAD_MAX:
3052 case ISD::ATOMIC_LOAD_UMIN:
3053 case ISD::ATOMIC_LOAD_UMAX:
3054 case ISD::ATOMIC_CMP_SWAP: {
3055 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
3056 Results.push_back(Tmp.first);
3057 Results.push_back(Tmp.second);
3060 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
3061 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
3062 // splits out the success value as a comparison. Expanding the resulting
3063 // ATOMIC_CMP_SWAP will produce a libcall.
3064 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
3065 SDValue Res = DAG.getAtomicCmpSwap(
3066 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
3067 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
3068 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(),
3069 cast<AtomicSDNode>(Node)->getSuccessOrdering(),
3070 cast<AtomicSDNode>(Node)->getFailureOrdering(),
3071 cast<AtomicSDNode>(Node)->getSynchScope());
3073 SDValue Success = DAG.getSetCC(SDLoc(Node), Node->getValueType(1),
3074 Res, Node->getOperand(2), ISD::SETEQ);
3076 Results.push_back(Res.getValue(0));
3077 Results.push_back(Success);
3078 Results.push_back(Res.getValue(1));
3081 case ISD::DYNAMIC_STACKALLOC:
3082 ExpandDYNAMIC_STACKALLOC(Node, Results);
3084 case ISD::MERGE_VALUES:
3085 for (unsigned i = 0; i < Node->getNumValues(); i++)
3086 Results.push_back(Node->getOperand(i));
3089 EVT VT = Node->getValueType(0);
3091 Results.push_back(DAG.getConstant(0, VT));
3093 assert(VT.isFloatingPoint() && "Unknown value type!");
3094 Results.push_back(DAG.getConstantFP(0, VT));
3099 // If this operation is not supported, lower it to 'abort()' call
3100 TargetLowering::ArgListTy Args;
3101 TargetLowering::CallLoweringInfo CLI(DAG);
3102 CLI.setDebugLoc(dl).setChain(Node->getOperand(0))
3103 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3104 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3105 std::move(Args), 0);
3106 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3108 Results.push_back(CallResult.second);
3113 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3114 Node->getValueType(0), dl);
3115 Results.push_back(Tmp1);
3117 case ISD::FP_EXTEND:
3118 Tmp1 = EmitStackConvert(Node->getOperand(0),
3119 Node->getOperand(0).getValueType(),
3120 Node->getValueType(0), dl);
3121 Results.push_back(Tmp1);
3123 case ISD::SIGN_EXTEND_INREG: {
3124 // NOTE: we could fall back on load/store here too for targets without
3125 // SAR. However, it is doubtful that any exist.
3126 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3127 EVT VT = Node->getValueType(0);
3128 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
3131 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3132 ExtraVT.getScalarType().getSizeInBits();
3133 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
3134 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3135 Node->getOperand(0), ShiftCst);
3136 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3137 Results.push_back(Tmp1);
3140 case ISD::FP_ROUND_INREG: {
3141 // The only way we can lower this is to turn it into a TRUNCSTORE,
3142 // EXTLOAD pair, targeting a temporary location (a stack slot).
3144 // NOTE: there is a choice here between constantly creating new stack
3145 // slots and always reusing the same one. We currently always create
3146 // new ones, as reuse may inhibit scheduling.
3147 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3148 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3149 Node->getValueType(0), dl);
3150 Results.push_back(Tmp1);
3153 case ISD::SINT_TO_FP:
3154 case ISD::UINT_TO_FP:
3155 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3156 Node->getOperand(0), Node->getValueType(0), dl);
3157 Results.push_back(Tmp1);
3159 case ISD::FP_TO_SINT:
3160 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
3161 Results.push_back(Tmp1);
3163 case ISD::FP_TO_UINT: {
3164 SDValue True, False;
3165 EVT VT = Node->getOperand(0).getValueType();
3166 EVT NVT = Node->getValueType(0);
3167 APFloat apf(DAG.EVTToAPFloatSemantics(VT),
3168 APInt::getNullValue(VT.getSizeInBits()));
3169 APInt x = APInt::getSignBit(NVT.getSizeInBits());
3170 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3171 Tmp1 = DAG.getConstantFP(apf, VT);
3172 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
3173 Node->getOperand(0),
3175 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3176 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3177 DAG.getNode(ISD::FSUB, dl, VT,
3178 Node->getOperand(0), Tmp1));
3179 False = DAG.getNode(ISD::XOR, dl, NVT, False,
3180 DAG.getConstant(x, NVT));
3181 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
3182 Results.push_back(Tmp1);
3186 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3187 EVT VT = Node->getValueType(0);
3188 Tmp1 = Node->getOperand(0);
3189 Tmp2 = Node->getOperand(1);
3190 unsigned Align = Node->getConstantOperandVal(3);
3192 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
3193 MachinePointerInfo(V),
3194 false, false, false, 0);
3195 SDValue VAList = VAListLoad;
3197 if (Align > TLI.getMinStackArgumentAlignment()) {
3198 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
3200 VAList = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3201 DAG.getConstant(Align - 1,
3202 VAList.getValueType()));
3204 VAList = DAG.getNode(ISD::AND, dl, VAList.getValueType(), VAList,
3205 DAG.getConstant(-(int64_t)Align,
3206 VAList.getValueType()));
3209 // Increment the pointer, VAList, to the next vaarg
3210 Tmp3 = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
3211 DAG.getConstant(TLI.getDataLayout()->
3212 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
3213 VAList.getValueType()));
3214 // Store the incremented VAList to the legalized pointer
3215 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
3216 MachinePointerInfo(V), false, false, 0);
3217 // Load the actual argument out of the pointer VAList
3218 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
3219 false, false, false, 0));
3220 Results.push_back(Results[0].getValue(1));
3224 // This defaults to loading a pointer from the input and storing it to the
3225 // output, returning the chain.
3226 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3227 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3228 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
3229 Node->getOperand(2), MachinePointerInfo(VS),
3230 false, false, false, 0);
3231 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
3232 MachinePointerInfo(VD), false, false, 0);
3233 Results.push_back(Tmp1);
3236 case ISD::EXTRACT_VECTOR_ELT:
3237 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3238 // This must be an access of the only element. Return it.
3239 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3240 Node->getOperand(0));
3242 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3243 Results.push_back(Tmp1);
3245 case ISD::EXTRACT_SUBVECTOR:
3246 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3248 case ISD::INSERT_SUBVECTOR:
3249 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3251 case ISD::CONCAT_VECTORS: {
3252 Results.push_back(ExpandVectorBuildThroughStack(Node));
3255 case ISD::SCALAR_TO_VECTOR:
3256 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3258 case ISD::INSERT_VECTOR_ELT:
3259 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3260 Node->getOperand(1),
3261 Node->getOperand(2), dl));
3263 case ISD::VECTOR_SHUFFLE: {
3264 SmallVector<int, 32> NewMask;
3265 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3267 EVT VT = Node->getValueType(0);
3268 EVT EltVT = VT.getVectorElementType();
3269 SDValue Op0 = Node->getOperand(0);
3270 SDValue Op1 = Node->getOperand(1);
3271 if (!TLI.isTypeLegal(EltVT)) {
3273 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3275 // BUILD_VECTOR operands are allowed to be wider than the element type.
3276 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3278 if (NewEltVT.bitsLT(EltVT)) {
3280 // Convert shuffle node.
3281 // If original node was v4i64 and the new EltVT is i32,
3282 // cast operands to v8i32 and re-build the mask.
3284 // Calculate new VT, the size of the new VT should be equal to original.
3286 EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3287 VT.getSizeInBits() / NewEltVT.getSizeInBits());
3288 assert(NewVT.bitsEq(VT));
3290 // cast operands to new VT
3291 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3292 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3294 // Convert the shuffle mask
3295 unsigned int factor =
3296 NewVT.getVectorNumElements()/VT.getVectorNumElements();
3298 // EltVT gets smaller
3301 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3303 for (unsigned fi = 0; fi < factor; ++fi)
3304 NewMask.push_back(Mask[i]);
3307 for (unsigned fi = 0; fi < factor; ++fi)
3308 NewMask.push_back(Mask[i]*factor+fi);
3316 unsigned NumElems = VT.getVectorNumElements();
3317 SmallVector<SDValue, 16> Ops;
3318 for (unsigned i = 0; i != NumElems; ++i) {
3320 Ops.push_back(DAG.getUNDEF(EltVT));
3323 unsigned Idx = Mask[i];
3325 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3327 DAG.getConstant(Idx, TLI.getVectorIdxTy())));
3329 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3331 DAG.getConstant(Idx - NumElems,
3332 TLI.getVectorIdxTy())));
3335 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
3336 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3337 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3338 Results.push_back(Tmp1);
3341 case ISD::EXTRACT_ELEMENT: {
3342 EVT OpTy = Node->getOperand(0).getValueType();
3343 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3345 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3346 DAG.getConstant(OpTy.getSizeInBits()/2,
3347 TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
3348 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3351 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3352 Node->getOperand(0));
3354 Results.push_back(Tmp1);
3357 case ISD::STACKSAVE:
3358 // Expand to CopyFromReg if the target set
3359 // StackPointerRegisterToSaveRestore.
3360 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3361 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3362 Node->getValueType(0)));
3363 Results.push_back(Results[0].getValue(1));
3365 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3366 Results.push_back(Node->getOperand(0));
3369 case ISD::STACKRESTORE:
3370 // Expand to CopyToReg if the target set
3371 // StackPointerRegisterToSaveRestore.
3372 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3373 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3374 Node->getOperand(1)));
3376 Results.push_back(Node->getOperand(0));
3379 case ISD::FCOPYSIGN:
3380 Results.push_back(ExpandFCOPYSIGN(Node));
3383 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3384 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3385 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3386 Node->getOperand(0));
3387 Results.push_back(Tmp1);
3390 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3391 EVT VT = Node->getValueType(0);
3392 Tmp1 = Node->getOperand(0);
3393 Tmp2 = DAG.getConstantFP(0.0, VT);
3394 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(Tmp1.getValueType()),
3395 Tmp1, Tmp2, ISD::SETUGT);
3396 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3397 Tmp1 = DAG.getSelect(dl, VT, Tmp2, Tmp1, Tmp3);
3398 Results.push_back(Tmp1);
3402 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3403 RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3404 RTLIB::SQRT_PPCF128));
3408 EVT VT = Node->getValueType(0);
3409 bool isSIN = Node->getOpcode() == ISD::FSIN;
3410 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3411 // fcos which share the same operand and both are used.
3412 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3413 canCombineSinCosLibcall(Node, TLI, TM))
3414 && useSinCos(Node)) {
3415 SDVTList VTs = DAG.getVTList(VT, VT);
3416 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3418 Tmp1 = Tmp1.getValue(1);
3419 Results.push_back(Tmp1);
3421 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3422 RTLIB::SIN_F80, RTLIB::SIN_F128,
3423 RTLIB::SIN_PPCF128));
3425 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3426 RTLIB::COS_F80, RTLIB::COS_F128,
3427 RTLIB::COS_PPCF128));
3432 // Expand into sincos libcall.
3433 ExpandSinCosLibCall(Node, Results);
3436 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3437 RTLIB::LOG_F80, RTLIB::LOG_F128,
3438 RTLIB::LOG_PPCF128));
3441 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3442 RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3443 RTLIB::LOG2_PPCF128));
3446 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3447 RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3448 RTLIB::LOG10_PPCF128));
3451 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3452 RTLIB::EXP_F80, RTLIB::EXP_F128,
3453 RTLIB::EXP_PPCF128));
3456 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3457 RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3458 RTLIB::EXP2_PPCF128));
3461 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3462 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3463 RTLIB::TRUNC_PPCF128));
3466 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3467 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3468 RTLIB::FLOOR_PPCF128));
3471 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3472 RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3473 RTLIB::CEIL_PPCF128));
3476 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3477 RTLIB::RINT_F80, RTLIB::RINT_F128,
3478 RTLIB::RINT_PPCF128));
3480 case ISD::FNEARBYINT:
3481 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3482 RTLIB::NEARBYINT_F64,
3483 RTLIB::NEARBYINT_F80,
3484 RTLIB::NEARBYINT_F128,
3485 RTLIB::NEARBYINT_PPCF128));
3488 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3492 RTLIB::ROUND_PPCF128));
3495 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3496 RTLIB::POWI_F80, RTLIB::POWI_F128,
3497 RTLIB::POWI_PPCF128));
3500 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3501 RTLIB::POW_F80, RTLIB::POW_F128,
3502 RTLIB::POW_PPCF128));
3505 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3506 RTLIB::DIV_F80, RTLIB::DIV_F128,
3507 RTLIB::DIV_PPCF128));
3510 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3511 RTLIB::REM_F80, RTLIB::REM_F128,
3512 RTLIB::REM_PPCF128));
3515 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3516 RTLIB::FMA_F80, RTLIB::FMA_F128,
3517 RTLIB::FMA_PPCF128));
3519 case ISD::FP16_TO_FP: {
3520 if (Node->getValueType(0) == MVT::f32) {
3521 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3525 // We can extend to types bigger than f32 in two steps without changing the
3526 // result. Since "f16 -> f32" is much more commonly available, give CodeGen
3527 // the option of emitting that before resorting to a libcall.
3529 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3531 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3534 case ISD::FP_TO_FP16: {
3536 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
3537 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
3538 Results.push_back(ExpandLibCall(LC, Node, false));
3541 case ISD::ConstantFP: {
3542 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3543 // Check to see if this FP immediate is already legal.
3544 // If this is a legal constant, turn it into a TargetConstantFP node.
3545 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3546 Results.push_back(ExpandConstantFP(CFP, true));
3550 EVT VT = Node->getValueType(0);
3551 assert(TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3552 TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
3553 "Don't know how to expand this FP subtraction!");
3554 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3555 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
3556 Results.push_back(Tmp1);
3560 EVT VT = Node->getValueType(0);
3561 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3562 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3563 "Don't know how to expand this subtraction!");
3564 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3565 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3566 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, VT));
3567 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3572 EVT VT = Node->getValueType(0);
3573 bool isSigned = Node->getOpcode() == ISD::SREM;
3574 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3575 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3576 Tmp2 = Node->getOperand(0);
3577 Tmp3 = Node->getOperand(1);
3578 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3579 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3580 // If div is legal, it's better to do the normal expansion
3581 !TLI.isOperationLegalOrCustom(DivOpc, Node->getValueType(0)) &&
3582 useDivRem(Node, isSigned, false))) {
3583 SDVTList VTs = DAG.getVTList(VT, VT);
3584 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3585 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3587 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3588 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3589 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3590 } else if (isSigned)
3591 Tmp1 = ExpandIntLibCall(Node, true,
3593 RTLIB::SREM_I16, RTLIB::SREM_I32,
3594 RTLIB::SREM_I64, RTLIB::SREM_I128);
3596 Tmp1 = ExpandIntLibCall(Node, false,
3598 RTLIB::UREM_I16, RTLIB::UREM_I32,
3599 RTLIB::UREM_I64, RTLIB::UREM_I128);
3600 Results.push_back(Tmp1);
3605 bool isSigned = Node->getOpcode() == ISD::SDIV;
3606 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3607 EVT VT = Node->getValueType(0);
3608 SDVTList VTs = DAG.getVTList(VT, VT);
3609 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3610 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3611 useDivRem(Node, isSigned, true)))
3612 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3613 Node->getOperand(1));
3615 Tmp1 = ExpandIntLibCall(Node, true,
3617 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3618 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3620 Tmp1 = ExpandIntLibCall(Node, false,
3622 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3623 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3624 Results.push_back(Tmp1);
3629 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3631 EVT VT = Node->getValueType(0);
3632 SDVTList VTs = DAG.getVTList(VT, VT);
3633 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3634 "If this wasn't legal, it shouldn't have been created!");
3635 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3636 Node->getOperand(1));
3637 Results.push_back(Tmp1.getValue(1));
3642 // Expand into divrem libcall
3643 ExpandDivRemLibCall(Node, Results);
3646 EVT VT = Node->getValueType(0);
3647 SDVTList VTs = DAG.getVTList(VT, VT);
3648 // See if multiply or divide can be lowered using two-result operations.
3649 // We just need the low half of the multiply; try both the signed
3650 // and unsigned forms. If the target supports both SMUL_LOHI and
3651 // UMUL_LOHI, form a preference by checking which forms of plain
3652 // MULH it supports.
3653 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3654 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3655 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3656 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3657 unsigned OpToUse = 0;
3658 if (HasSMUL_LOHI && !HasMULHS) {
3659 OpToUse = ISD::SMUL_LOHI;
3660 } else if (HasUMUL_LOHI && !HasMULHU) {
3661 OpToUse = ISD::UMUL_LOHI;
3662 } else if (HasSMUL_LOHI) {
3663 OpToUse = ISD::SMUL_LOHI;
3664 } else if (HasUMUL_LOHI) {
3665 OpToUse = ISD::UMUL_LOHI;
3668 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3669 Node->getOperand(1)));
3674 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3675 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3676 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3677 TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3678 TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3679 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
3680 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3681 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3682 SDValue Shift = DAG.getConstant(HalfType.getSizeInBits(),
3683 TLI.getShiftAmountTy(HalfType));
3684 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3685 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3689 Tmp1 = ExpandIntLibCall(Node, false,
3691 RTLIB::MUL_I16, RTLIB::MUL_I32,
3692 RTLIB::MUL_I64, RTLIB::MUL_I128);
3693 Results.push_back(Tmp1);
3698 SDValue LHS = Node->getOperand(0);
3699 SDValue RHS = Node->getOperand(1);
3700 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3701 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3703 Results.push_back(Sum);
3704 EVT ResultType = Node->getValueType(1);
3705 EVT OType = getSetCCResultType(Node->getValueType(0));
3707 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3709 // LHSSign -> LHS >= 0
3710 // RHSSign -> RHS >= 0
3711 // SumSign -> Sum >= 0
3714 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3716 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3718 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3719 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3720 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3721 Node->getOpcode() == ISD::SADDO ?
3722 ISD::SETEQ : ISD::SETNE);
3724 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3725 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3727 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3728 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
3733 SDValue LHS = Node->getOperand(0);
3734 SDValue RHS = Node->getOperand(1);
3735 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3736 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3738 Results.push_back(Sum);
3740 EVT ResultType = Node->getValueType(1);
3741 EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3743 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
3744 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3746 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
3751 EVT VT = Node->getValueType(0);
3752 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3753 SDValue LHS = Node->getOperand(0);
3754 SDValue RHS = Node->getOperand(1);
3757 static const unsigned Ops[2][3] =
3758 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3759 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3760 bool isSigned = Node->getOpcode() == ISD::SMULO;
3761 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3762 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3763 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3764 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3765 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3767 TopHalf = BottomHalf.getValue(1);
3768 } else if (TLI.isTypeLegal(WideVT)) {
3769 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3770 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3771 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3772 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3773 DAG.getIntPtrConstant(0));
3774 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3775 DAG.getIntPtrConstant(1));
3777 // We can fall back to a libcall with an illegal type for the MUL if we
3778 // have a libcall big enough.
3779 // Also, we can fall back to a division in some cases, but that's a big
3780 // performance hit in the general case.
3781 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3782 if (WideVT == MVT::i16)
3783 LC = RTLIB::MUL_I16;
3784 else if (WideVT == MVT::i32)
3785 LC = RTLIB::MUL_I32;
3786 else if (WideVT == MVT::i64)
3787 LC = RTLIB::MUL_I64;
3788 else if (WideVT == MVT::i128)
3789 LC = RTLIB::MUL_I128;
3790 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3792 // The high part is obtained by SRA'ing all but one of the bits of low
3794 unsigned LoSize = VT.getSizeInBits();
3795 SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3796 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3797 SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3798 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3800 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3801 // pre-lowered to the correct types. This all depends upon WideVT not
3802 // being a legal type for the architecture and thus has to be split to
3804 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3805 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3806 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3807 DAG.getIntPtrConstant(0));
3808 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3809 DAG.getIntPtrConstant(1));
3810 // Ret is a node with an illegal type. Because such things are not
3811 // generally permitted during this phase of legalization, delete the
3812 // node. The above EXTRACT_ELEMENT nodes should have been folded.
3813 DAG.DeleteNode(Ret.getNode());
3817 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3818 TLI.getShiftAmountTy(BottomHalf.getValueType()));
3819 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3820 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
3823 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
3824 DAG.getConstant(0, VT), ISD::SETNE);
3826 Results.push_back(BottomHalf);
3827 Results.push_back(TopHalf);
3830 case ISD::BUILD_PAIR: {
3831 EVT PairTy = Node->getValueType(0);
3832 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3833 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3834 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3835 DAG.getConstant(PairTy.getSizeInBits()/2,
3836 TLI.getShiftAmountTy(PairTy)));
3837 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3841 Tmp1 = Node->getOperand(0);
3842 Tmp2 = Node->getOperand(1);
3843 Tmp3 = Node->getOperand(2);
3844 if (Tmp1.getOpcode() == ISD::SETCC) {
3845 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3847 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3849 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3850 DAG.getConstant(0, Tmp1.getValueType()),
3851 Tmp2, Tmp3, ISD::SETNE);
3853 Results.push_back(Tmp1);
3856 SDValue Chain = Node->getOperand(0);
3857 SDValue Table = Node->getOperand(1);
3858 SDValue Index = Node->getOperand(2);
3860 EVT PTy = TLI.getPointerTy();
3862 const DataLayout &TD = *TLI.getDataLayout();
3863 unsigned EntrySize =
3864 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3866 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(),
3867 Index, DAG.getConstant(EntrySize, Index.getValueType()));
3868 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3871 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3872 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3873 MachinePointerInfo::getJumpTable(), MemVT,
3876 if (TM.getRelocationModel() == Reloc::PIC_) {
3877 // For PIC, the sequence is:
3878 // BRIND(load(Jumptable + index) + RelocBase)
3879 // RelocBase can be JumpTable, GOT or some sort of global base.
3880 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3881 TLI.getPICJumpTableRelocBase(Table, DAG));
3883 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3884 Results.push_back(Tmp1);
3888 // Expand brcond's setcc into its constituent parts and create a BR_CC
3890 Tmp1 = Node->getOperand(0);
3891 Tmp2 = Node->getOperand(1);
3892 if (Tmp2.getOpcode() == ISD::SETCC) {
3893 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3894 Tmp1, Tmp2.getOperand(2),
3895 Tmp2.getOperand(0), Tmp2.getOperand(1),
3896 Node->getOperand(2));
3898 // We test only the i1 bit. Skip the AND if UNDEF.
3899 Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3900 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3901 DAG.getConstant(1, Tmp2.getValueType()));
3902 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3903 DAG.getCondCode(ISD::SETNE), Tmp3,
3904 DAG.getConstant(0, Tmp3.getValueType()),
3905 Node->getOperand(2));
3907 Results.push_back(Tmp1);
3910 Tmp1 = Node->getOperand(0);
3911 Tmp2 = Node->getOperand(1);
3912 Tmp3 = Node->getOperand(2);
3913 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3914 Tmp3, NeedInvert, dl);
3917 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3918 // condition code, create a new SETCC node.
3920 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3923 // If we expanded the SETCC by inverting the condition code, then wrap
3924 // the existing SETCC in a NOT to restore the intended condition.
3926 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3928 Results.push_back(Tmp1);
3932 // Otherwise, SETCC for the given comparison type must be completely
3933 // illegal; expand it into a SELECT_CC.
3934 EVT VT = Node->getValueType(0);
3936 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
3937 case TargetLowering::ZeroOrOneBooleanContent:
3938 case TargetLowering::UndefinedBooleanContent:
3941 case TargetLowering::ZeroOrNegativeOneBooleanContent:
3945 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3946 DAG.getConstant(TrueValue, VT), DAG.getConstant(0, VT),
3948 Results.push_back(Tmp1);
3951 case ISD::SELECT_CC: {
3952 Tmp1 = Node->getOperand(0); // LHS
3953 Tmp2 = Node->getOperand(1); // RHS
3954 Tmp3 = Node->getOperand(2); // True
3955 Tmp4 = Node->getOperand(3); // False
3956 EVT VT = Node->getValueType(0);
3957 SDValue CC = Node->getOperand(4);
3958 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3960 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
3961 // If the condition code is legal, then we need to expand this
3962 // node using SETCC and SELECT.
3963 EVT CmpVT = Tmp1.getValueType();
3964 assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3965 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3967 EVT CCVT = TLI.getSetCCResultType(*DAG.getContext(), CmpVT);
3968 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
3969 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3973 // SELECT_CC is legal, so the condition code must not be.
3974 bool Legalized = false;
3975 // Try to legalize by inverting the condition. This is for targets that
3976 // might support an ordered version of a condition, but not the unordered
3977 // version (or vice versa).
3978 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3979 Tmp1.getValueType().isInteger());
3980 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
3981 // Use the new condition code and swap true and false
3983 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3985 // If The inverse is not legal, then try to swap the arguments using
3986 // the inverse condition code.
3987 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3988 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
3989 // The swapped inverse condition is legal, so swap true and false,
3992 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3997 Legalized = LegalizeSetCCCondCode(
3998 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
4001 assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
4003 // If we expanded the SETCC by inverting the condition code, then swap
4004 // the True/False operands to match.
4006 std::swap(Tmp3, Tmp4);
4008 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
4009 // condition code, create a new SELECT_CC node.
4011 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
4012 Tmp1, Tmp2, Tmp3, Tmp4, CC);
4014 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4015 CC = DAG.getCondCode(ISD::SETNE);
4016 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
4017 Tmp2, Tmp3, Tmp4, CC);
4020 Results.push_back(Tmp1);
4024 Tmp1 = Node->getOperand(0); // Chain
4025 Tmp2 = Node->getOperand(2); // LHS
4026 Tmp3 = Node->getOperand(3); // RHS
4027 Tmp4 = Node->getOperand(1); // CC
4029 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
4030 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
4032 assert(Legalized && "Can't legalize BR_CC with legal condition!");
4034 // If we expanded the SETCC by inverting the condition code, then wrap
4035 // the existing SETCC in a NOT to restore the intended condition.
4037 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
4039 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
4041 if (Tmp4.getNode()) {
4042 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
4043 Tmp4, Tmp2, Tmp3, Node->getOperand(4));
4045 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
4046 Tmp4 = DAG.getCondCode(ISD::SETNE);
4047 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
4048 Tmp2, Tmp3, Node->getOperand(4));
4050 Results.push_back(Tmp1);
4053 case ISD::BUILD_VECTOR:
4054 Results.push_back(ExpandBUILD_VECTOR(Node));
4059 // Scalarize vector SRA/SRL/SHL.
4060 EVT VT = Node->getValueType(0);
4061 assert(VT.isVector() && "Unable to legalize non-vector shift");
4062 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
4063 unsigned NumElem = VT.getVectorNumElements();
4065 SmallVector<SDValue, 8> Scalars;
4066 for (unsigned Idx = 0; Idx < NumElem; Idx++) {
4067 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4069 Node->getOperand(0), DAG.getConstant(Idx,
4070 TLI.getVectorIdxTy()));
4071 SDValue Sh = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4073 Node->getOperand(1), DAG.getConstant(Idx,
4074 TLI.getVectorIdxTy()));
4075 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
4076 VT.getScalarType(), Ex, Sh));
4079 DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
4080 ReplaceNode(SDValue(Node, 0), Result);
4083 case ISD::GLOBAL_OFFSET_TABLE:
4084 case ISD::GlobalAddress:
4085 case ISD::GlobalTLSAddress:
4086 case ISD::ExternalSymbol:
4087 case ISD::ConstantPool:
4088 case ISD::JumpTable:
4089 case ISD::INTRINSIC_W_CHAIN:
4090 case ISD::INTRINSIC_WO_CHAIN:
4091 case ISD::INTRINSIC_VOID:
4092 // FIXME: Custom lowering for these operations shouldn't return null!
4096 // Replace the original node with the legalized result.
4097 if (!Results.empty())
4098 ReplaceNode(Node, Results.data());
4101 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4102 SmallVector<SDValue, 8> Results;
4103 MVT OVT = Node->getSimpleValueType(0);
4104 if (Node->getOpcode() == ISD::UINT_TO_FP ||
4105 Node->getOpcode() == ISD::SINT_TO_FP ||
4106 Node->getOpcode() == ISD::SETCC) {
4107 OVT = Node->getOperand(0).getSimpleValueType();
4109 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4111 SDValue Tmp1, Tmp2, Tmp3;
4112 switch (Node->getOpcode()) {
4114 case ISD::CTTZ_ZERO_UNDEF:
4116 case ISD::CTLZ_ZERO_UNDEF:
4118 // Zero extend the argument.
4119 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4120 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4121 // already the correct result.
4122 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4123 if (Node->getOpcode() == ISD::CTTZ) {
4124 // FIXME: This should set a bit in the zero extended value instead.
4125 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT),
4126 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
4128 Tmp1 = DAG.getSelect(dl, NVT, Tmp2,
4129 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
4130 } else if (Node->getOpcode() == ISD::CTLZ ||
4131 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4132 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4133 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4134 DAG.getConstant(NVT.getSizeInBits() -
4135 OVT.getSizeInBits(), NVT));
4137 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4140 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4141 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4142 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4143 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
4144 DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
4145 Results.push_back(Tmp1);
4148 case ISD::FP_TO_UINT:
4149 case ISD::FP_TO_SINT:
4150 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4151 Node->getOpcode() == ISD::FP_TO_SINT, dl);
4152 Results.push_back(Tmp1);
4154 case ISD::UINT_TO_FP:
4155 case ISD::SINT_TO_FP:
4156 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4157 Node->getOpcode() == ISD::SINT_TO_FP, dl);
4158 Results.push_back(Tmp1);
4161 SDValue Chain = Node->getOperand(0); // Get the chain.
4162 SDValue Ptr = Node->getOperand(1); // Get the pointer.
4165 if (OVT.isVector()) {
4166 TruncOp = ISD::BITCAST;
4168 assert(OVT.isInteger()
4169 && "VAARG promotion is supported only for vectors or integer types");
4170 TruncOp = ISD::TRUNCATE;
4173 // Perform the larger operation, then convert back
4174 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4175 Node->getConstantOperandVal(3));
4176 Chain = Tmp1.getValue(1);
4178 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4180 // Modified the chain result - switch anything that used the old chain to
4182 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4183 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4185 UpdatedNodes->insert(Tmp2.getNode());
4186 UpdatedNodes->insert(Chain.getNode());
4194 unsigned ExtOp, TruncOp;
4195 if (OVT.isVector()) {
4196 ExtOp = ISD::BITCAST;
4197 TruncOp = ISD::BITCAST;
4199 assert(OVT.isInteger() && "Cannot promote logic operation");
4200 ExtOp = ISD::ANY_EXTEND;
4201 TruncOp = ISD::TRUNCATE;
4203 // Promote each of the values to the new type.
4204 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4205 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4206 // Perform the larger operation, then convert back
4207 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4208 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4212 unsigned ExtOp, TruncOp;
4213 if (Node->getValueType(0).isVector() ||
4214 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4215 ExtOp = ISD::BITCAST;
4216 TruncOp = ISD::BITCAST;
4217 } else if (Node->getValueType(0).isInteger()) {
4218 ExtOp = ISD::ANY_EXTEND;
4219 TruncOp = ISD::TRUNCATE;
4221 ExtOp = ISD::FP_EXTEND;
4222 TruncOp = ISD::FP_ROUND;
4224 Tmp1 = Node->getOperand(0);
4225 // Promote each of the values to the new type.
4226 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4227 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4228 // Perform the larger operation, then round down.
4229 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4230 if (TruncOp != ISD::FP_ROUND)
4231 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4233 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4234 DAG.getIntPtrConstant(0));
4235 Results.push_back(Tmp1);
4238 case ISD::VECTOR_SHUFFLE: {
4239 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4241 // Cast the two input vectors.
4242 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4243 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4245 // Convert the shuffle mask to the right # elements.
4246 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4247 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4248 Results.push_back(Tmp1);
4252 unsigned ExtOp = ISD::FP_EXTEND;
4253 if (NVT.isInteger()) {
4254 ISD::CondCode CCCode =
4255 cast<CondCodeSDNode>(Node->getOperand(2))->get();
4256 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4258 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4259 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4260 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
4261 Tmp1, Tmp2, Node->getOperand(2)));
4267 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4268 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4269 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4270 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4271 Tmp3, DAG.getIntPtrConstant(0)));
4278 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4279 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4280 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4281 Tmp2, DAG.getIntPtrConstant(0)));
4286 // Replace the original node with the legalized result.
4287 if (!Results.empty())
4288 ReplaceNode(Node, Results.data());
4291 // SelectionDAG::Legalize - This is the entry point for the file.
4293 void SelectionDAG::Legalize() {
4294 AssignTopologicalOrder();
4296 allnodes_iterator LegalizePosition;
4297 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4298 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes);
4300 // Visit all the nodes. We start in topological order, so that we see
4301 // nodes with their original operands intact. Legalization can produce
4302 // new nodes which may themselves need to be legalized. Iterate until all
4303 // nodes have been legalized.
4305 bool AnyLegalized = false;
4306 for (LegalizePosition = allnodes_end();
4307 LegalizePosition != allnodes_begin(); ) {
4310 SDNode *N = LegalizePosition;
4311 if (LegalizedNodes.insert(N)) {
4312 AnyLegalized = true;
4313 Legalizer.LegalizeOp(N);
4321 // Remove dead nodes now.
4325 bool SelectionDAG::LegalizeOp(SDNode *N,
4326 SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4327 allnodes_iterator LegalizePosition(N);
4328 SmallPtrSet<SDNode *, 16> LegalizedNodes;
4329 SelectionDAGLegalize Legalizer(*this, LegalizePosition, LegalizedNodes,
4332 // Directly insert the node in question, and legalize it. This will recurse
4333 // as needed through operands.
4334 LegalizedNodes.insert(N);
4335 Legalizer.LegalizeOp(N);
4337 return LegalizedNodes.count(N);