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/Analysis/DebugInfo.h"
15 #include "llvm/CodeGen/Analysis.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/Target/TargetFrameLowering.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Function.h"
31 #include "llvm/GlobalVariable.h"
32 #include "llvm/LLVMContext.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/SmallPtrSet.h"
43 //===----------------------------------------------------------------------===//
44 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
45 /// hacks on it until the target machine can handle it. This involves
46 /// eliminating value sizes the machine cannot handle (promoting small sizes to
47 /// large sizes or splitting up large values into small values) as well as
48 /// eliminating operations the machine cannot handle.
50 /// This code also does a small amount of optimization and recognition of idioms
51 /// as part of its processing. For example, if a target does not support a
52 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
53 /// will attempt merge setcc and brc instructions into brcc's.
56 class SelectionDAGLegalize {
57 const TargetMachine &TM;
58 const TargetLowering &TLI;
60 CodeGenOpt::Level OptLevel;
62 // Libcall insertion helpers.
64 /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
65 /// legalized. We use this to ensure that calls are properly serialized
66 /// against each other, including inserted libcalls.
67 SDValue LastCALLSEQ_END;
69 /// IsLegalizingCall - This member is used *only* for purposes of providing
70 /// helpful assertions that a libcall isn't created while another call is
71 /// being legalized (which could lead to non-serialized call sequences).
72 bool IsLegalizingCall;
75 Legal, // The target natively supports this operation.
76 Promote, // This operation should be executed in a larger type.
77 Expand // Try to expand this to other ops, otherwise use a libcall.
80 /// ValueTypeActions - This is a bitvector that contains two bits for each
81 /// value type, where the two bits correspond to the LegalizeAction enum.
82 /// This can be queried with "getTypeAction(VT)".
83 TargetLowering::ValueTypeActionImpl ValueTypeActions;
85 /// LegalizedNodes - For nodes that are of legal width, and that have more
86 /// than one use, this map indicates what regularized operand to use. This
87 /// allows us to avoid legalizing the same thing more than once.
88 DenseMap<SDValue, SDValue> LegalizedNodes;
90 void AddLegalizedOperand(SDValue From, SDValue To) {
91 LegalizedNodes.insert(std::make_pair(From, To));
92 // If someone requests legalization of the new node, return itself.
94 LegalizedNodes.insert(std::make_pair(To, To));
98 SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
100 /// getTypeAction - Return how we should legalize values of this type, either
101 /// it is already legal or we need to expand it into multiple registers of
102 /// smaller integer type, or we need to promote it to a larger type.
103 LegalizeAction getTypeAction(EVT VT) const {
104 return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
107 /// isTypeLegal - Return true if this type is legal on this target.
109 bool isTypeLegal(EVT VT) const {
110 return getTypeAction(VT) == Legal;
116 /// LegalizeOp - We know that the specified value has a legal type.
117 /// Recursively ensure that the operands have legal types, then return the
119 SDValue LegalizeOp(SDValue O);
121 SDValue OptimizeFloatStore(StoreSDNode *ST);
123 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
124 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
125 /// is necessary to spill the vector being inserted into to memory, perform
126 /// the insert there, and then read the result back.
127 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
128 SDValue Idx, DebugLoc dl);
129 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
130 SDValue Idx, DebugLoc dl);
132 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
133 /// performs the same shuffe in terms of order or result bytes, but on a type
134 /// whose vector element type is narrower than the original shuffle type.
135 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
136 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
137 SDValue N1, SDValue N2,
138 SmallVectorImpl<int> &Mask) const;
140 bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
141 SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
143 void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
146 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
147 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
148 SDNode *Node, bool isSigned);
149 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
150 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
151 RTLIB::Libcall Call_PPCF128);
152 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
153 RTLIB::Libcall Call_I8,
154 RTLIB::Libcall Call_I16,
155 RTLIB::Libcall Call_I32,
156 RTLIB::Libcall Call_I64,
157 RTLIB::Libcall Call_I128);
159 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
160 SDValue ExpandBUILD_VECTOR(SDNode *Node);
161 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
162 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
163 SmallVectorImpl<SDValue> &Results);
164 SDValue ExpandFCOPYSIGN(SDNode *Node);
165 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
167 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
169 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
172 SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
173 SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
175 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
176 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
178 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
180 void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
181 void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
185 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
186 /// performs the same shuffe in terms of order or result bytes, but on a type
187 /// whose vector element type is narrower than the original shuffle type.
188 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
190 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
191 SDValue N1, SDValue N2,
192 SmallVectorImpl<int> &Mask) const {
193 unsigned NumMaskElts = VT.getVectorNumElements();
194 unsigned NumDestElts = NVT.getVectorNumElements();
195 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
197 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
199 if (NumEltsGrowth == 1)
200 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
202 SmallVector<int, 8> NewMask;
203 for (unsigned i = 0; i != NumMaskElts; ++i) {
205 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
207 NewMask.push_back(-1);
209 NewMask.push_back(Idx * NumEltsGrowth + j);
212 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
213 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
214 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
217 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
218 CodeGenOpt::Level ol)
219 : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
220 DAG(dag), OptLevel(ol),
221 ValueTypeActions(TLI.getValueTypeActions()) {
222 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
223 "Too many value types for ValueTypeActions to hold!");
226 void SelectionDAGLegalize::LegalizeDAG() {
227 LastCALLSEQ_END = DAG.getEntryNode();
228 IsLegalizingCall = false;
230 // The legalize process is inherently a bottom-up recursive process (users
231 // legalize their uses before themselves). Given infinite stack space, we
232 // could just start legalizing on the root and traverse the whole graph. In
233 // practice however, this causes us to run out of stack space on large basic
234 // blocks. To avoid this problem, compute an ordering of the nodes where each
235 // node is only legalized after all of its operands are legalized.
236 DAG.AssignTopologicalOrder();
237 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
238 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
239 LegalizeOp(SDValue(I, 0));
241 // Finally, it's possible the root changed. Get the new root.
242 SDValue OldRoot = DAG.getRoot();
243 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
244 DAG.setRoot(LegalizedNodes[OldRoot]);
246 LegalizedNodes.clear();
248 // Remove dead nodes now.
249 DAG.RemoveDeadNodes();
253 /// FindCallEndFromCallStart - Given a chained node that is part of a call
254 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
255 static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth = 0) {
256 // Nested CALLSEQ_START/END constructs aren't yet legal,
257 // but we can DTRT and handle them correctly here.
258 if (Node->getOpcode() == ISD::CALLSEQ_START)
260 else if (Node->getOpcode() == ISD::CALLSEQ_END) {
265 if (Node->use_empty())
266 return 0; // No CallSeqEnd
268 // The chain is usually at the end.
269 SDValue TheChain(Node, Node->getNumValues()-1);
270 if (TheChain.getValueType() != MVT::Other) {
271 // Sometimes it's at the beginning.
272 TheChain = SDValue(Node, 0);
273 if (TheChain.getValueType() != MVT::Other) {
274 // Otherwise, hunt for it.
275 for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
276 if (Node->getValueType(i) == MVT::Other) {
277 TheChain = SDValue(Node, i);
281 // Otherwise, we walked into a node without a chain.
282 if (TheChain.getValueType() != MVT::Other)
287 for (SDNode::use_iterator UI = Node->use_begin(),
288 E = Node->use_end(); UI != E; ++UI) {
290 // Make sure to only follow users of our token chain.
292 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
293 if (User->getOperand(i) == TheChain)
294 if (SDNode *Result = FindCallEndFromCallStart(User, depth))
300 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
301 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
302 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
304 assert(Node && "Didn't find callseq_start for a call??");
305 while (Node->getOpcode() != ISD::CALLSEQ_START || nested) {
306 Node = Node->getOperand(0).getNode();
307 assert(Node->getOperand(0).getValueType() == MVT::Other &&
308 "Node doesn't have a token chain argument!");
309 switch (Node->getOpcode()) {
312 case ISD::CALLSEQ_START:
317 case ISD::CALLSEQ_END:
325 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
326 /// see if any uses can reach Dest. If no dest operands can get to dest,
327 /// legalize them, legalize ourself, and return false, otherwise, return true.
329 /// Keep track of the nodes we fine that actually do lead to Dest in
330 /// NodesLeadingTo. This avoids retraversing them exponential number of times.
332 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
333 SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
334 if (N == Dest) return true; // N certainly leads to Dest :)
336 // If we've already processed this node and it does lead to Dest, there is no
337 // need to reprocess it.
338 if (NodesLeadingTo.count(N)) return true;
340 // If the first result of this node has been already legalized, then it cannot
342 if (LegalizedNodes.count(SDValue(N, 0))) return false;
344 // Okay, this node has not already been legalized. Check and legalize all
345 // operands. If none lead to Dest, then we can legalize this node.
346 bool OperandsLeadToDest = false;
347 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
348 OperandsLeadToDest |= // If an operand leads to Dest, so do we.
349 LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
352 if (OperandsLeadToDest) {
353 NodesLeadingTo.insert(N);
357 // Okay, this node looks safe, legalize it and return false.
358 LegalizeOp(SDValue(N, 0));
362 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
363 /// a load from the constant pool.
364 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
365 SelectionDAG &DAG, const TargetLowering &TLI) {
367 DebugLoc dl = CFP->getDebugLoc();
369 // If a FP immediate is precise when represented as a float and if the
370 // target can do an extending load from float to double, we put it into
371 // the constant pool as a float, even if it's is statically typed as a
372 // double. This shrinks FP constants and canonicalizes them for targets where
373 // an FP extending load is the same cost as a normal load (such as on the x87
374 // fp stack or PPC FP unit).
375 EVT VT = CFP->getValueType(0);
376 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
378 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
379 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
380 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
385 while (SVT != MVT::f32) {
386 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
387 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
388 // Only do this if the target has a native EXTLOAD instruction from
390 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
391 TLI.ShouldShrinkFPConstant(OrigVT)) {
392 const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
393 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
399 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
400 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
402 return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, dl,
404 CPIdx, MachinePointerInfo::getConstantPool(),
405 VT, false, false, Alignment);
406 return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
407 MachinePointerInfo::getConstantPool(), false, false,
411 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
413 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
414 const TargetLowering &TLI) {
415 SDValue Chain = ST->getChain();
416 SDValue Ptr = ST->getBasePtr();
417 SDValue Val = ST->getValue();
418 EVT VT = Val.getValueType();
419 int Alignment = ST->getAlignment();
420 DebugLoc dl = ST->getDebugLoc();
421 if (ST->getMemoryVT().isFloatingPoint() ||
422 ST->getMemoryVT().isVector()) {
423 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
424 if (TLI.isTypeLegal(intVT)) {
425 // Expand to a bitconvert of the value to the integer type of the
426 // same size, then a (misaligned) int store.
427 // FIXME: Does not handle truncating floating point stores!
428 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
429 return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
430 ST->isVolatile(), ST->isNonTemporal(), Alignment);
432 // Do a (aligned) store to a stack slot, then copy from the stack slot
433 // to the final destination using (unaligned) integer loads and stores.
434 EVT StoredVT = ST->getMemoryVT();
436 TLI.getRegisterType(*DAG.getContext(),
437 EVT::getIntegerVT(*DAG.getContext(),
438 StoredVT.getSizeInBits()));
439 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
440 unsigned RegBytes = RegVT.getSizeInBits() / 8;
441 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
443 // Make sure the stack slot is also aligned for the register type.
444 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
446 // Perform the original store, only redirected to the stack slot.
447 SDValue Store = DAG.getTruncStore(Chain, dl,
448 Val, StackPtr, MachinePointerInfo(),
449 StoredVT, false, false, 0);
450 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
451 SmallVector<SDValue, 8> Stores;
454 // Do all but one copies using the full register width.
455 for (unsigned i = 1; i < NumRegs; i++) {
456 // Load one integer register's worth from the stack slot.
457 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
458 MachinePointerInfo(),
460 // Store it to the final location. Remember the store.
461 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
462 ST->getPointerInfo().getWithOffset(Offset),
463 ST->isVolatile(), ST->isNonTemporal(),
464 MinAlign(ST->getAlignment(), Offset)));
465 // Increment the pointers.
467 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
469 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
472 // The last store may be partial. Do a truncating store. On big-endian
473 // machines this requires an extending load from the stack slot to ensure
474 // that the bits are in the right place.
475 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
476 8 * (StoredBytes - Offset));
478 // Load from the stack slot.
479 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Store, StackPtr,
480 MachinePointerInfo(),
481 MemVT, false, false, 0);
483 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
485 .getWithOffset(Offset),
486 MemVT, ST->isVolatile(),
488 MinAlign(ST->getAlignment(), Offset)));
489 // The order of the stores doesn't matter - say it with a TokenFactor.
490 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
494 assert(ST->getMemoryVT().isInteger() &&
495 !ST->getMemoryVT().isVector() &&
496 "Unaligned store of unknown type.");
497 // Get the half-size VT
498 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
499 int NumBits = NewStoredVT.getSizeInBits();
500 int IncrementSize = NumBits / 8;
502 // Divide the stored value in two parts.
503 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
505 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
507 // Store the two parts
508 SDValue Store1, Store2;
509 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
510 ST->getPointerInfo(), NewStoredVT,
511 ST->isVolatile(), ST->isNonTemporal(), Alignment);
512 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
513 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
514 Alignment = MinAlign(Alignment, IncrementSize);
515 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
516 ST->getPointerInfo().getWithOffset(IncrementSize),
517 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
520 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
523 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
525 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
526 const TargetLowering &TLI) {
527 SDValue Chain = LD->getChain();
528 SDValue Ptr = LD->getBasePtr();
529 EVT VT = LD->getValueType(0);
530 EVT LoadedVT = LD->getMemoryVT();
531 DebugLoc dl = LD->getDebugLoc();
532 if (VT.isFloatingPoint() || VT.isVector()) {
533 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
534 if (TLI.isTypeLegal(intVT)) {
535 // Expand to a (misaligned) integer load of the same size,
536 // then bitconvert to floating point or vector.
537 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
539 LD->isNonTemporal(), LD->getAlignment());
540 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
541 if (VT.isFloatingPoint() && LoadedVT != VT)
542 Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
544 SDValue Ops[] = { Result, Chain };
545 return DAG.getMergeValues(Ops, 2, dl);
548 // Copy the value to a (aligned) stack slot using (unaligned) integer
549 // loads and stores, then do a (aligned) load from the stack slot.
550 EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
551 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
552 unsigned RegBytes = RegVT.getSizeInBits() / 8;
553 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
555 // Make sure the stack slot is also aligned for the register type.
556 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
558 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
559 SmallVector<SDValue, 8> Stores;
560 SDValue StackPtr = StackBase;
563 // Do all but one copies using the full register width.
564 for (unsigned i = 1; i < NumRegs; i++) {
565 // Load one integer register's worth from the original location.
566 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
567 LD->getPointerInfo().getWithOffset(Offset),
568 LD->isVolatile(), LD->isNonTemporal(),
569 MinAlign(LD->getAlignment(), Offset));
570 // Follow the load with a store to the stack slot. Remember the store.
571 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
572 MachinePointerInfo(), false, false, 0));
573 // Increment the pointers.
575 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
576 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
580 // The last copy may be partial. Do an extending load.
581 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
582 8 * (LoadedBytes - Offset));
583 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, dl, Chain, Ptr,
584 LD->getPointerInfo().getWithOffset(Offset),
585 MemVT, LD->isVolatile(),
587 MinAlign(LD->getAlignment(), Offset));
588 // Follow the load with a store to the stack slot. Remember the store.
589 // On big-endian machines this requires a truncating store to ensure
590 // that the bits end up in the right place.
591 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
592 MachinePointerInfo(), MemVT,
595 // The order of the stores doesn't matter - say it with a TokenFactor.
596 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
599 // Finally, perform the original load only redirected to the stack slot.
600 Load = DAG.getExtLoad(LD->getExtensionType(), VT, dl, TF, StackBase,
601 MachinePointerInfo(), LoadedVT, false, false, 0);
603 // Callers expect a MERGE_VALUES node.
604 SDValue Ops[] = { Load, TF };
605 return DAG.getMergeValues(Ops, 2, dl);
607 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
608 "Unaligned load of unsupported type.");
610 // Compute the new VT that is half the size of the old one. This is an
612 unsigned NumBits = LoadedVT.getSizeInBits();
614 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
617 unsigned Alignment = LD->getAlignment();
618 unsigned IncrementSize = NumBits / 8;
619 ISD::LoadExtType HiExtType = LD->getExtensionType();
621 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
622 if (HiExtType == ISD::NON_EXTLOAD)
623 HiExtType = ISD::ZEXTLOAD;
625 // Load the value in two parts
627 if (TLI.isLittleEndian()) {
628 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr, LD->getPointerInfo(),
629 NewLoadedVT, LD->isVolatile(),
630 LD->isNonTemporal(), Alignment);
631 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
632 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
633 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr,
634 LD->getPointerInfo().getWithOffset(IncrementSize),
635 NewLoadedVT, LD->isVolatile(),
636 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
638 Hi = DAG.getExtLoad(HiExtType, VT, dl, Chain, Ptr, LD->getPointerInfo(),
639 NewLoadedVT, LD->isVolatile(),
640 LD->isNonTemporal(), Alignment);
641 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
642 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
643 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, dl, Chain, Ptr,
644 LD->getPointerInfo().getWithOffset(IncrementSize),
645 NewLoadedVT, LD->isVolatile(),
646 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
649 // aggregate the two parts
650 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
651 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
652 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
654 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
657 SDValue Ops[] = { Result, TF };
658 return DAG.getMergeValues(Ops, 2, dl);
661 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
662 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
663 /// is necessary to spill the vector being inserted into to memory, perform
664 /// the insert there, and then read the result back.
665 SDValue SelectionDAGLegalize::
666 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
672 // If the target doesn't support this, we have to spill the input vector
673 // to a temporary stack slot, update the element, then reload it. This is
674 // badness. We could also load the value into a vector register (either
675 // with a "move to register" or "extload into register" instruction, then
676 // permute it into place, if the idx is a constant and if the idx is
677 // supported by the target.
678 EVT VT = Tmp1.getValueType();
679 EVT EltVT = VT.getVectorElementType();
680 EVT IdxVT = Tmp3.getValueType();
681 EVT PtrVT = TLI.getPointerTy();
682 SDValue StackPtr = DAG.CreateStackTemporary(VT);
684 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
687 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
688 MachinePointerInfo::getFixedStack(SPFI),
691 // Truncate or zero extend offset to target pointer type.
692 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
693 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
694 // Add the offset to the index.
695 unsigned EltSize = EltVT.getSizeInBits()/8;
696 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
697 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
698 // Store the scalar value.
699 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
701 // Load the updated vector.
702 return DAG.getLoad(VT, dl, Ch, StackPtr,
703 MachinePointerInfo::getFixedStack(SPFI), false, false, 0);
707 SDValue SelectionDAGLegalize::
708 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
709 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
710 // SCALAR_TO_VECTOR requires that the type of the value being inserted
711 // match the element type of the vector being created, except for
712 // integers in which case the inserted value can be over width.
713 EVT EltVT = Vec.getValueType().getVectorElementType();
714 if (Val.getValueType() == EltVT ||
715 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
716 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
717 Vec.getValueType(), Val);
719 unsigned NumElts = Vec.getValueType().getVectorNumElements();
720 // We generate a shuffle of InVec and ScVec, so the shuffle mask
721 // should be 0,1,2,3,4,5... with the appropriate element replaced with
723 SmallVector<int, 8> ShufOps;
724 for (unsigned i = 0; i != NumElts; ++i)
725 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
727 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
731 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
734 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
735 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
736 // FIXME: We shouldn't do this for TargetConstantFP's.
737 // FIXME: move this to the DAG Combiner! Note that we can't regress due
738 // to phase ordering between legalized code and the dag combiner. This
739 // probably means that we need to integrate dag combiner and legalizer
741 // We generally can't do this one for long doubles.
742 SDValue Tmp1 = ST->getChain();
743 SDValue Tmp2 = ST->getBasePtr();
745 unsigned Alignment = ST->getAlignment();
746 bool isVolatile = ST->isVolatile();
747 bool isNonTemporal = ST->isNonTemporal();
748 DebugLoc dl = ST->getDebugLoc();
749 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
750 if (CFP->getValueType(0) == MVT::f32 &&
751 getTypeAction(MVT::i32) == Legal) {
752 Tmp3 = DAG.getConstant(CFP->getValueAPF().
753 bitcastToAPInt().zextOrTrunc(32),
755 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
756 isVolatile, isNonTemporal, Alignment);
759 if (CFP->getValueType(0) == MVT::f64) {
760 // If this target supports 64-bit registers, do a single 64-bit store.
761 if (getTypeAction(MVT::i64) == Legal) {
762 Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
763 zextOrTrunc(64), MVT::i64);
764 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
765 isVolatile, isNonTemporal, Alignment);
768 if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
769 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
770 // stores. If the target supports neither 32- nor 64-bits, this
771 // xform is certainly not worth it.
772 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
773 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
774 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
775 if (TLI.isBigEndian()) std::swap(Lo, Hi);
777 Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
778 isNonTemporal, Alignment);
779 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
780 DAG.getIntPtrConstant(4));
781 Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
782 ST->getPointerInfo().getWithOffset(4),
783 isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
785 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
792 /// LegalizeOp - We know that the specified value has a legal type, and
793 /// that its operands are legal. Now ensure that the operation itself
794 /// is legal, recursively ensuring that the operands' operations remain
796 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
797 if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
800 SDNode *Node = Op.getNode();
801 DebugLoc dl = Node->getDebugLoc();
803 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
804 assert(getTypeAction(Node->getValueType(i)) == Legal &&
805 "Unexpected illegal type!");
807 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
808 assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
809 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
810 "Unexpected illegal type!");
812 // Note that LegalizeOp may be reentered even from single-use nodes, which
813 // means that we always must cache transformed nodes.
814 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
815 if (I != LegalizedNodes.end()) return I->second;
817 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
819 bool isCustom = false;
821 // Figure out the correct action; the way to query this varies by opcode
822 TargetLowering::LegalizeAction Action;
823 bool SimpleFinishLegalizing = true;
824 switch (Node->getOpcode()) {
825 case ISD::INTRINSIC_W_CHAIN:
826 case ISD::INTRINSIC_WO_CHAIN:
827 case ISD::INTRINSIC_VOID:
830 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
832 case ISD::SINT_TO_FP:
833 case ISD::UINT_TO_FP:
834 case ISD::EXTRACT_VECTOR_ELT:
835 Action = TLI.getOperationAction(Node->getOpcode(),
836 Node->getOperand(0).getValueType());
838 case ISD::FP_ROUND_INREG:
839 case ISD::SIGN_EXTEND_INREG: {
840 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
841 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
847 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
848 Node->getOpcode() == ISD::SETCC ? 2 : 1;
849 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
850 EVT OpVT = Node->getOperand(CompareOperand).getValueType();
851 ISD::CondCode CCCode =
852 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
853 Action = TLI.getCondCodeAction(CCCode, OpVT);
854 if (Action == TargetLowering::Legal) {
855 if (Node->getOpcode() == ISD::SELECT_CC)
856 Action = TLI.getOperationAction(Node->getOpcode(),
857 Node->getValueType(0));
859 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
865 // FIXME: Model these properly. LOAD and STORE are complicated, and
866 // STORE expects the unlegalized operand in some cases.
867 SimpleFinishLegalizing = false;
869 case ISD::CALLSEQ_START:
870 case ISD::CALLSEQ_END:
871 // FIXME: This shouldn't be necessary. These nodes have special properties
872 // dealing with the recursive nature of legalization. Removing this
873 // special case should be done as part of making LegalizeDAG non-recursive.
874 SimpleFinishLegalizing = false;
876 case ISD::EXTRACT_ELEMENT:
877 case ISD::FLT_ROUNDS_:
885 case ISD::MERGE_VALUES:
887 case ISD::FRAME_TO_ARGS_OFFSET:
888 case ISD::EH_SJLJ_SETJMP:
889 case ISD::EH_SJLJ_LONGJMP:
890 case ISD::EH_SJLJ_DISPATCHSETUP:
891 // These operations lie about being legal: when they claim to be legal,
892 // they should actually be expanded.
893 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
894 if (Action == TargetLowering::Legal)
895 Action = TargetLowering::Expand;
897 case ISD::TRAMPOLINE:
899 case ISD::RETURNADDR:
900 // These operations lie about being legal: when they claim to be legal,
901 // they should actually be custom-lowered.
902 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
903 if (Action == TargetLowering::Legal)
904 Action = TargetLowering::Custom;
906 case ISD::BUILD_VECTOR:
907 // A weird case: legalization for BUILD_VECTOR never legalizes the
909 // FIXME: This really sucks... changing it isn't semantically incorrect,
910 // but it massively pessimizes the code for floating-point BUILD_VECTORs
911 // because ConstantFP operands get legalized into constant pool loads
912 // before the BUILD_VECTOR code can see them. It doesn't usually bite,
913 // though, because BUILD_VECTORS usually get lowered into other nodes
914 // which get legalized properly.
915 SimpleFinishLegalizing = false;
918 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
919 Action = TargetLowering::Legal;
921 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
926 if (SimpleFinishLegalizing) {
927 SmallVector<SDValue, 8> Ops, ResultVals;
928 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
929 Ops.push_back(LegalizeOp(Node->getOperand(i)));
930 switch (Node->getOpcode()) {
937 // Branches tweak the chain to include LastCALLSEQ_END
938 Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
940 Ops[0] = LegalizeOp(Ops[0]);
941 LastCALLSEQ_END = DAG.getEntryNode();
948 // Legalizing shifts/rotates requires adjusting the shift amount
949 // to the appropriate width.
950 if (!Ops[1].getValueType().isVector())
951 Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
956 // Legalizing shifts/rotates requires adjusting the shift amount
957 // to the appropriate width.
958 if (!Ops[2].getValueType().isVector())
959 Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[2]));
963 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
966 case TargetLowering::Legal:
967 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
968 ResultVals.push_back(Result.getValue(i));
970 case TargetLowering::Custom:
971 // FIXME: The handling for custom lowering with multiple results is
973 Tmp1 = TLI.LowerOperation(Result, DAG);
974 if (Tmp1.getNode()) {
975 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
977 ResultVals.push_back(Tmp1);
979 ResultVals.push_back(Tmp1.getValue(i));
985 case TargetLowering::Expand:
986 ExpandNode(Result.getNode(), ResultVals);
988 case TargetLowering::Promote:
989 PromoteNode(Result.getNode(), ResultVals);
992 if (!ResultVals.empty()) {
993 for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
994 if (ResultVals[i] != SDValue(Node, i))
995 ResultVals[i] = LegalizeOp(ResultVals[i]);
996 AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
998 return ResultVals[Op.getResNo()];
1002 switch (Node->getOpcode()) {
1009 assert(0 && "Do not know how to legalize this operator!");
1011 case ISD::BUILD_VECTOR:
1012 switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1013 default: assert(0 && "This action is not supported yet!");
1014 case TargetLowering::Custom:
1015 Tmp3 = TLI.LowerOperation(Result, DAG);
1016 if (Tmp3.getNode()) {
1021 case TargetLowering::Expand:
1022 Result = ExpandBUILD_VECTOR(Result.getNode());
1026 case ISD::CALLSEQ_START: {
1027 SDNode *CallEnd = FindCallEndFromCallStart(Node);
1029 // Recursively Legalize all of the inputs of the call end that do not lead
1030 // to this call start. This ensures that any libcalls that need be inserted
1031 // are inserted *before* the CALLSEQ_START.
1032 {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1033 for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1034 LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1038 // Now that we have legalized all of the inputs (which may have inserted
1039 // libcalls), create the new CALLSEQ_START node.
1040 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1042 // Merge in the last call to ensure that this call starts after the last
1044 if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1045 Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1046 Tmp1, LastCALLSEQ_END);
1047 Tmp1 = LegalizeOp(Tmp1);
1050 // Do not try to legalize the target-specific arguments (#1+).
1051 if (Tmp1 != Node->getOperand(0)) {
1052 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1054 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
1055 Ops.size()), Result.getResNo());
1058 // Remember that the CALLSEQ_START is legalized.
1059 AddLegalizedOperand(Op.getValue(0), Result);
1060 if (Node->getNumValues() == 2) // If this has a flag result, remember it.
1061 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1063 // Now that the callseq_start and all of the non-call nodes above this call
1064 // sequence have been legalized, legalize the call itself. During this
1065 // process, no libcalls can/will be inserted, guaranteeing that no calls
1067 assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1068 // Note that we are selecting this call!
1069 LastCALLSEQ_END = SDValue(CallEnd, 0);
1070 IsLegalizingCall = true;
1072 // Legalize the call, starting from the CALLSEQ_END.
1073 LegalizeOp(LastCALLSEQ_END);
1074 assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1077 case ISD::CALLSEQ_END:
1078 // If the CALLSEQ_START node hasn't been legalized first, legalize it. This
1079 // will cause this node to be legalized as well as handling libcalls right.
1080 if (LastCALLSEQ_END.getNode() != Node) {
1081 LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1082 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1083 assert(I != LegalizedNodes.end() &&
1084 "Legalizing the call start should have legalized this node!");
1088 // Otherwise, the call start has been legalized and everything is going
1089 // according to plan. Just legalize ourselves normally here.
1090 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1091 // Do not try to legalize the target-specific arguments (#1+), except for
1092 // an optional flag input.
1093 if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Glue){
1094 if (Tmp1 != Node->getOperand(0)) {
1095 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1097 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1098 &Ops[0], Ops.size()),
1102 Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1103 if (Tmp1 != Node->getOperand(0) ||
1104 Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1105 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1108 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1109 &Ops[0], Ops.size()),
1113 assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1114 // This finishes up call legalization.
1115 IsLegalizingCall = false;
1117 // If the CALLSEQ_END node has a flag, remember that we legalized it.
1118 AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1119 if (Node->getNumValues() == 2)
1120 AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1121 return Result.getValue(Op.getResNo());
1123 LoadSDNode *LD = cast<LoadSDNode>(Node);
1124 Tmp1 = LegalizeOp(LD->getChain()); // Legalize the chain.
1125 Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1127 ISD::LoadExtType ExtType = LD->getExtensionType();
1128 if (ExtType == ISD::NON_EXTLOAD) {
1129 EVT VT = Node->getValueType(0);
1130 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1131 Tmp1, Tmp2, LD->getOffset()),
1133 Tmp3 = Result.getValue(0);
1134 Tmp4 = Result.getValue(1);
1136 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1137 default: assert(0 && "This action is not supported yet!");
1138 case TargetLowering::Legal:
1139 // If this is an unaligned load and the target doesn't support it,
1141 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1142 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1143 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1144 if (LD->getAlignment() < ABIAlignment){
1145 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1147 Tmp3 = Result.getOperand(0);
1148 Tmp4 = Result.getOperand(1);
1149 Tmp3 = LegalizeOp(Tmp3);
1150 Tmp4 = LegalizeOp(Tmp4);
1154 case TargetLowering::Custom:
1155 Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1156 if (Tmp1.getNode()) {
1157 Tmp3 = LegalizeOp(Tmp1);
1158 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1161 case TargetLowering::Promote: {
1162 // Only promote a load of vector type to another.
1163 assert(VT.isVector() && "Cannot promote this load!");
1164 // Change base type to a different vector type.
1165 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1167 Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
1168 LD->isVolatile(), LD->isNonTemporal(),
1169 LD->getAlignment());
1170 Tmp3 = LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
1171 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1175 // Since loads produce two values, make sure to remember that we
1176 // legalized both of them.
1177 AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1178 AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1179 return Op.getResNo() ? Tmp4 : Tmp3;
1182 EVT SrcVT = LD->getMemoryVT();
1183 unsigned SrcWidth = SrcVT.getSizeInBits();
1184 unsigned Alignment = LD->getAlignment();
1185 bool isVolatile = LD->isVolatile();
1186 bool isNonTemporal = LD->isNonTemporal();
1188 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1189 // Some targets pretend to have an i1 loading operation, and actually
1190 // load an i8. This trick is correct for ZEXTLOAD because the top 7
1191 // bits are guaranteed to be zero; it helps the optimizers understand
1192 // that these bits are zero. It is also useful for EXTLOAD, since it
1193 // tells the optimizers that those bits are undefined. It would be
1194 // nice to have an effective generic way of getting these benefits...
1195 // Until such a way is found, don't insist on promoting i1 here.
1196 (SrcVT != MVT::i1 ||
1197 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1198 // Promote to a byte-sized load if not loading an integral number of
1199 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1200 unsigned NewWidth = SrcVT.getStoreSizeInBits();
1201 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1204 // The extra bits are guaranteed to be zero, since we stored them that
1205 // way. A zext load from NVT thus automatically gives zext from SrcVT.
1207 ISD::LoadExtType NewExtType =
1208 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1210 Result = DAG.getExtLoad(NewExtType, Node->getValueType(0), dl,
1211 Tmp1, Tmp2, LD->getPointerInfo(),
1212 NVT, isVolatile, isNonTemporal, Alignment);
1214 Ch = Result.getValue(1); // The chain.
1216 if (ExtType == ISD::SEXTLOAD)
1217 // Having the top bits zero doesn't help when sign extending.
1218 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1219 Result.getValueType(),
1220 Result, DAG.getValueType(SrcVT));
1221 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1222 // All the top bits are guaranteed to be zero - inform the optimizers.
1223 Result = DAG.getNode(ISD::AssertZext, dl,
1224 Result.getValueType(), Result,
1225 DAG.getValueType(SrcVT));
1227 Tmp1 = LegalizeOp(Result);
1228 Tmp2 = LegalizeOp(Ch);
1229 } else if (SrcWidth & (SrcWidth - 1)) {
1230 // If not loading a power-of-2 number of bits, expand as two loads.
1231 assert(!SrcVT.isVector() && "Unsupported extload!");
1232 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1233 assert(RoundWidth < SrcWidth);
1234 unsigned ExtraWidth = SrcWidth - RoundWidth;
1235 assert(ExtraWidth < RoundWidth);
1236 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1237 "Load size not an integral number of bytes!");
1238 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1239 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1241 unsigned IncrementSize;
1243 if (TLI.isLittleEndian()) {
1244 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1245 // Load the bottom RoundWidth bits.
1246 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), dl,
1248 LD->getPointerInfo(), RoundVT, isVolatile,
1249 isNonTemporal, Alignment);
1251 // Load the remaining ExtraWidth bits.
1252 IncrementSize = RoundWidth / 8;
1253 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1254 DAG.getIntPtrConstant(IncrementSize));
1255 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1256 LD->getPointerInfo().getWithOffset(IncrementSize),
1257 ExtraVT, isVolatile, isNonTemporal,
1258 MinAlign(Alignment, IncrementSize));
1260 // Build a factor node to remember that this load is independent of
1262 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1265 // Move the top bits to the right place.
1266 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1267 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1269 // Join the hi and lo parts.
1270 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1272 // Big endian - avoid unaligned loads.
1273 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1274 // Load the top RoundWidth bits.
1275 Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), dl, Tmp1, Tmp2,
1276 LD->getPointerInfo(), RoundVT, isVolatile,
1277 isNonTemporal, Alignment);
1279 // Load the remaining ExtraWidth bits.
1280 IncrementSize = RoundWidth / 8;
1281 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1282 DAG.getIntPtrConstant(IncrementSize));
1283 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1284 Node->getValueType(0), dl, Tmp1, Tmp2,
1285 LD->getPointerInfo().getWithOffset(IncrementSize),
1286 ExtraVT, isVolatile, isNonTemporal,
1287 MinAlign(Alignment, IncrementSize));
1289 // Build a factor node to remember that this load is independent of
1291 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1294 // Move the top bits to the right place.
1295 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1296 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1298 // Join the hi and lo parts.
1299 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1302 Tmp1 = LegalizeOp(Result);
1303 Tmp2 = LegalizeOp(Ch);
1305 switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1306 default: assert(0 && "This action is not supported yet!");
1307 case TargetLowering::Custom:
1310 case TargetLowering::Legal:
1311 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1312 Tmp1, Tmp2, LD->getOffset()),
1314 Tmp1 = Result.getValue(0);
1315 Tmp2 = Result.getValue(1);
1318 Tmp3 = TLI.LowerOperation(Result, DAG);
1319 if (Tmp3.getNode()) {
1320 Tmp1 = LegalizeOp(Tmp3);
1321 Tmp2 = LegalizeOp(Tmp3.getValue(1));
1324 // If this is an unaligned load and the target doesn't support it,
1326 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1328 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1329 unsigned ABIAlignment =
1330 TLI.getTargetData()->getABITypeAlignment(Ty);
1331 if (LD->getAlignment() < ABIAlignment){
1332 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1334 Tmp1 = Result.getOperand(0);
1335 Tmp2 = Result.getOperand(1);
1336 Tmp1 = LegalizeOp(Tmp1);
1337 Tmp2 = LegalizeOp(Tmp2);
1342 case TargetLowering::Expand:
1343 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && isTypeLegal(SrcVT)) {
1344 SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1345 LD->getPointerInfo(),
1346 LD->isVolatile(), LD->isNonTemporal(),
1347 LD->getAlignment());
1351 ExtendOp = (SrcVT.isFloatingPoint() ?
1352 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1354 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1355 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1356 default: llvm_unreachable("Unexpected extend load type!");
1358 Result = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1359 Tmp1 = LegalizeOp(Result); // Relegalize new nodes.
1360 Tmp2 = LegalizeOp(Load.getValue(1));
1363 // FIXME: This does not work for vectors on most targets. Sign- and
1364 // zero-extend operations are currently folded into extending loads,
1365 // whether they are legal or not, and then we end up here without any
1366 // support for legalizing them.
1367 assert(ExtType != ISD::EXTLOAD &&
1368 "EXTLOAD should always be supported!");
1369 // Turn the unsupported load into an EXTLOAD followed by an explicit
1370 // zero/sign extend inreg.
1371 Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), dl,
1372 Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
1373 LD->isVolatile(), LD->isNonTemporal(),
1374 LD->getAlignment());
1376 if (ExtType == ISD::SEXTLOAD)
1377 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1378 Result.getValueType(),
1379 Result, DAG.getValueType(SrcVT));
1381 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1382 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1383 Tmp2 = LegalizeOp(Result.getValue(1)); // Relegalize new nodes.
1388 // Since loads produce two values, make sure to remember that we legalized
1390 AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1391 AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1392 return Op.getResNo() ? Tmp2 : Tmp1;
1395 StoreSDNode *ST = cast<StoreSDNode>(Node);
1396 Tmp1 = LegalizeOp(ST->getChain()); // Legalize the chain.
1397 Tmp2 = LegalizeOp(ST->getBasePtr()); // Legalize the pointer.
1398 unsigned Alignment = ST->getAlignment();
1399 bool isVolatile = ST->isVolatile();
1400 bool isNonTemporal = ST->isNonTemporal();
1402 if (!ST->isTruncatingStore()) {
1403 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1404 Result = SDValue(OptStore, 0);
1409 Tmp3 = LegalizeOp(ST->getValue());
1410 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1415 EVT VT = Tmp3.getValueType();
1416 switch (TLI.getOperationAction(ISD::STORE, VT)) {
1417 default: assert(0 && "This action is not supported yet!");
1418 case TargetLowering::Legal:
1419 // If this is an unaligned store and the target doesn't support it,
1421 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1422 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1423 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1424 if (ST->getAlignment() < ABIAlignment)
1425 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1429 case TargetLowering::Custom:
1430 Tmp1 = TLI.LowerOperation(Result, DAG);
1431 if (Tmp1.getNode()) Result = Tmp1;
1433 case TargetLowering::Promote:
1434 assert(VT.isVector() && "Unknown legal promote case!");
1435 Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1436 TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1437 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1438 ST->getPointerInfo(), isVolatile,
1439 isNonTemporal, Alignment);
1445 Tmp3 = LegalizeOp(ST->getValue());
1447 EVT StVT = ST->getMemoryVT();
1448 unsigned StWidth = StVT.getSizeInBits();
1450 if (StWidth != StVT.getStoreSizeInBits()) {
1451 // Promote to a byte-sized store with upper bits zero if not
1452 // storing an integral number of bytes. For example, promote
1453 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1454 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1455 StVT.getStoreSizeInBits());
1456 Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1457 Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1458 NVT, isVolatile, isNonTemporal, Alignment);
1459 } else if (StWidth & (StWidth - 1)) {
1460 // If not storing a power-of-2 number of bits, expand as two stores.
1461 assert(!StVT.isVector() && "Unsupported truncstore!");
1462 unsigned RoundWidth = 1 << Log2_32(StWidth);
1463 assert(RoundWidth < StWidth);
1464 unsigned ExtraWidth = StWidth - RoundWidth;
1465 assert(ExtraWidth < RoundWidth);
1466 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1467 "Store size not an integral number of bytes!");
1468 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1469 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1471 unsigned IncrementSize;
1473 if (TLI.isLittleEndian()) {
1474 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1475 // Store the bottom RoundWidth bits.
1476 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1478 isVolatile, isNonTemporal, Alignment);
1480 // Store the remaining ExtraWidth bits.
1481 IncrementSize = RoundWidth / 8;
1482 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1483 DAG.getIntPtrConstant(IncrementSize));
1484 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1485 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1486 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
1487 ST->getPointerInfo().getWithOffset(IncrementSize),
1488 ExtraVT, isVolatile, isNonTemporal,
1489 MinAlign(Alignment, IncrementSize));
1491 // Big endian - avoid unaligned stores.
1492 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1493 // Store the top RoundWidth bits.
1494 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1495 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1496 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
1497 RoundVT, isVolatile, isNonTemporal, Alignment);
1499 // Store the remaining ExtraWidth bits.
1500 IncrementSize = RoundWidth / 8;
1501 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1502 DAG.getIntPtrConstant(IncrementSize));
1503 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
1504 ST->getPointerInfo().getWithOffset(IncrementSize),
1505 ExtraVT, isVolatile, isNonTemporal,
1506 MinAlign(Alignment, IncrementSize));
1509 // The order of the stores doesn't matter.
1510 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1512 if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1513 Tmp2 != ST->getBasePtr())
1514 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1519 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1520 default: assert(0 && "This action is not supported yet!");
1521 case TargetLowering::Legal:
1522 // If this is an unaligned store and the target doesn't support it,
1524 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1525 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1526 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1527 if (ST->getAlignment() < ABIAlignment)
1528 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1532 case TargetLowering::Custom:
1533 Result = TLI.LowerOperation(Result, DAG);
1536 // TRUNCSTORE:i16 i32 -> STORE i16
1537 assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1538 Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1539 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1540 isVolatile, isNonTemporal, Alignment);
1548 assert(Result.getValueType() == Op.getValueType() &&
1549 "Bad legalization!");
1551 // Make sure that the generated code is itself legal.
1553 Result = LegalizeOp(Result);
1555 // Note that LegalizeOp may be reentered even from single-use nodes, which
1556 // means that we always must cache transformed nodes.
1557 AddLegalizedOperand(Op, Result);
1561 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1562 SDValue Vec = Op.getOperand(0);
1563 SDValue Idx = Op.getOperand(1);
1564 DebugLoc dl = Op.getDebugLoc();
1565 // Store the value to a temporary stack slot, then LOAD the returned part.
1566 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1567 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1568 MachinePointerInfo(), false, false, 0);
1570 // Add the offset to the index.
1572 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1573 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1574 DAG.getConstant(EltSize, Idx.getValueType()));
1576 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1577 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1579 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1581 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1583 if (Op.getValueType().isVector())
1584 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1586 return DAG.getExtLoad(ISD::EXTLOAD, Op.getValueType(), dl, Ch, StackPtr,
1587 MachinePointerInfo(),
1588 Vec.getValueType().getVectorElementType(),
1592 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1593 // We can't handle this case efficiently. Allocate a sufficiently
1594 // aligned object on the stack, store each element into it, then load
1595 // the result as a vector.
1596 // Create the stack frame object.
1597 EVT VT = Node->getValueType(0);
1598 EVT EltVT = VT.getVectorElementType();
1599 DebugLoc dl = Node->getDebugLoc();
1600 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1601 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1602 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1604 // Emit a store of each element to the stack slot.
1605 SmallVector<SDValue, 8> Stores;
1606 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1607 // Store (in the right endianness) the elements to memory.
1608 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1609 // Ignore undef elements.
1610 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1612 unsigned Offset = TypeByteSize*i;
1614 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1615 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1617 // If the destination vector element type is narrower than the source
1618 // element type, only store the bits necessary.
1619 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1620 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1621 Node->getOperand(i), Idx,
1622 PtrInfo.getWithOffset(Offset),
1623 EltVT, false, false, 0));
1625 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1626 Node->getOperand(i), Idx,
1627 PtrInfo.getWithOffset(Offset),
1632 if (!Stores.empty()) // Not all undef elements?
1633 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1634 &Stores[0], Stores.size());
1636 StoreChain = DAG.getEntryNode();
1638 // Result is a load from the stack slot.
1639 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
1642 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1643 DebugLoc dl = Node->getDebugLoc();
1644 SDValue Tmp1 = Node->getOperand(0);
1645 SDValue Tmp2 = Node->getOperand(1);
1647 // Get the sign bit of the RHS. First obtain a value that has the same
1648 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1650 EVT FloatVT = Tmp2.getValueType();
1651 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1652 if (isTypeLegal(IVT)) {
1653 // Convert to an integer with the same sign bit.
1654 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1656 // Store the float to memory, then load the sign part out as an integer.
1657 MVT LoadTy = TLI.getPointerTy();
1658 // First create a temporary that is aligned for both the load and store.
1659 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1660 // Then store the float to it.
1662 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1664 if (TLI.isBigEndian()) {
1665 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1666 // Load out a legal integer with the same sign bit as the float.
1667 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1669 } else { // Little endian
1670 SDValue LoadPtr = StackPtr;
1671 // The float may be wider than the integer we are going to load. Advance
1672 // the pointer so that the loaded integer will contain the sign bit.
1673 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1674 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1675 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1676 LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1677 // Load a legal integer containing the sign bit.
1678 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1680 // Move the sign bit to the top bit of the loaded integer.
1681 unsigned BitShift = LoadTy.getSizeInBits() -
1682 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1683 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1685 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1686 DAG.getConstant(BitShift,TLI.getShiftAmountTy()));
1689 // Now get the sign bit proper, by seeing whether the value is negative.
1690 SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1691 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1693 // Get the absolute value of the result.
1694 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1695 // Select between the nabs and abs value based on the sign bit of
1697 return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1698 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1702 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1703 SmallVectorImpl<SDValue> &Results) {
1704 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1705 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1706 " not tell us which reg is the stack pointer!");
1707 DebugLoc dl = Node->getDebugLoc();
1708 EVT VT = Node->getValueType(0);
1709 SDValue Tmp1 = SDValue(Node, 0);
1710 SDValue Tmp2 = SDValue(Node, 1);
1711 SDValue Tmp3 = Node->getOperand(2);
1712 SDValue Chain = Tmp1.getOperand(0);
1714 // Chain the dynamic stack allocation so that it doesn't modify the stack
1715 // pointer when other instructions are using the stack.
1716 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1718 SDValue Size = Tmp2.getOperand(1);
1719 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1720 Chain = SP.getValue(1);
1721 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1722 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1723 if (Align > StackAlign)
1724 SP = DAG.getNode(ISD::AND, dl, VT, SP,
1725 DAG.getConstant(-(uint64_t)Align, VT));
1726 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1727 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1729 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1730 DAG.getIntPtrConstant(0, true), SDValue());
1732 Results.push_back(Tmp1);
1733 Results.push_back(Tmp2);
1736 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1737 /// condition code CC on the current target. This routine expands SETCC with
1738 /// illegal condition code into AND / OR of multiple SETCC values.
1739 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1740 SDValue &LHS, SDValue &RHS,
1743 EVT OpVT = LHS.getValueType();
1744 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1745 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1746 default: assert(0 && "Unknown condition code action!");
1747 case TargetLowering::Legal:
1750 case TargetLowering::Expand: {
1751 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1754 default: assert(0 && "Don't know how to expand this condition!");
1755 case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO; Opc = ISD::AND; break;
1756 case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1757 case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1758 case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1759 case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1760 case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1761 case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1762 case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1763 case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1764 case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1765 case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1766 case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1767 // FIXME: Implement more expansions.
1770 SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1771 SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1772 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1780 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1781 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1782 /// a load from the stack slot to DestVT, extending it if needed.
1783 /// The resultant code need not be legal.
1784 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1788 // Create the stack frame object.
1790 TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1791 getTypeForEVT(*DAG.getContext()));
1792 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1794 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1795 int SPFI = StackPtrFI->getIndex();
1796 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1798 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1799 unsigned SlotSize = SlotVT.getSizeInBits();
1800 unsigned DestSize = DestVT.getSizeInBits();
1801 const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1802 unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1804 // Emit a store to the stack slot. Use a truncstore if the input value is
1805 // later than DestVT.
1808 if (SrcSize > SlotSize)
1809 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1810 PtrInfo, SlotVT, false, false, SrcAlign);
1812 assert(SrcSize == SlotSize && "Invalid store");
1813 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1814 PtrInfo, false, false, SrcAlign);
1817 // Result is a load from the stack slot.
1818 if (SlotSize == DestSize)
1819 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1820 false, false, DestAlign);
1822 assert(SlotSize < DestSize && "Unknown extension!");
1823 return DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl, Store, FIPtr,
1824 PtrInfo, SlotVT, false, false, DestAlign);
1827 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1828 DebugLoc dl = Node->getDebugLoc();
1829 // Create a vector sized/aligned stack slot, store the value to element #0,
1830 // then load the whole vector back out.
1831 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1833 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1834 int SPFI = StackPtrFI->getIndex();
1836 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1838 MachinePointerInfo::getFixedStack(SPFI),
1839 Node->getValueType(0).getVectorElementType(),
1841 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1842 MachinePointerInfo::getFixedStack(SPFI),
1847 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1848 /// support the operation, but do support the resultant vector type.
1849 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1850 unsigned NumElems = Node->getNumOperands();
1851 SDValue Value1, Value2;
1852 DebugLoc dl = Node->getDebugLoc();
1853 EVT VT = Node->getValueType(0);
1854 EVT OpVT = Node->getOperand(0).getValueType();
1855 EVT EltVT = VT.getVectorElementType();
1857 // If the only non-undef value is the low element, turn this into a
1858 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1859 bool isOnlyLowElement = true;
1860 bool MoreThanTwoValues = false;
1861 bool isConstant = true;
1862 for (unsigned i = 0; i < NumElems; ++i) {
1863 SDValue V = Node->getOperand(i);
1864 if (V.getOpcode() == ISD::UNDEF)
1867 isOnlyLowElement = false;
1868 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1871 if (!Value1.getNode()) {
1873 } else if (!Value2.getNode()) {
1876 } else if (V != Value1 && V != Value2) {
1877 MoreThanTwoValues = true;
1881 if (!Value1.getNode())
1882 return DAG.getUNDEF(VT);
1884 if (isOnlyLowElement)
1885 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1887 // If all elements are constants, create a load from the constant pool.
1889 std::vector<Constant*> CV;
1890 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1891 if (ConstantFPSDNode *V =
1892 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1893 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1894 } else if (ConstantSDNode *V =
1895 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1897 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1899 // If OpVT and EltVT don't match, EltVT is not legal and the
1900 // element values have been promoted/truncated earlier. Undo this;
1901 // we don't want a v16i8 to become a v16i32 for example.
1902 const ConstantInt *CI = V->getConstantIntValue();
1903 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1904 CI->getZExtValue()));
1907 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1908 const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1909 CV.push_back(UndefValue::get(OpNTy));
1912 Constant *CP = ConstantVector::get(CV);
1913 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1914 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1915 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1916 MachinePointerInfo::getConstantPool(),
1917 false, false, Alignment);
1920 if (!MoreThanTwoValues) {
1921 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1922 for (unsigned i = 0; i < NumElems; ++i) {
1923 SDValue V = Node->getOperand(i);
1924 if (V.getOpcode() == ISD::UNDEF)
1926 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1928 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1929 // Get the splatted value into the low element of a vector register.
1930 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1932 if (Value2.getNode())
1933 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1935 Vec2 = DAG.getUNDEF(VT);
1937 // Return shuffle(LowValVec, undef, <0,0,0,0>)
1938 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1942 // Otherwise, we can't handle this case efficiently.
1943 return ExpandVectorBuildThroughStack(Node);
1946 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1947 // does not fit into a register, return the lo part and set the hi part to the
1948 // by-reg argument. If it does fit into a single register, return the result
1949 // and leave the Hi part unset.
1950 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1952 assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
1953 // The input chain to this libcall is the entry node of the function.
1954 // Legalizing the call will automatically add the previous call to the
1956 SDValue InChain = DAG.getEntryNode();
1958 TargetLowering::ArgListTy Args;
1959 TargetLowering::ArgListEntry Entry;
1960 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1961 EVT ArgVT = Node->getOperand(i).getValueType();
1962 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1963 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1964 Entry.isSExt = isSigned;
1965 Entry.isZExt = !isSigned;
1966 Args.push_back(Entry);
1968 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1969 TLI.getPointerTy());
1971 // Splice the libcall in wherever FindInputOutputChains tells us to.
1972 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1974 // isTailCall may be true since the callee does not reference caller stack
1975 // frame. Check if it's in the right position.
1976 bool isTailCall = isInTailCallPosition(DAG, Node, TLI);
1977 std::pair<SDValue, SDValue> CallInfo =
1978 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1979 0, TLI.getLibcallCallingConv(LC), isTailCall,
1980 /*isReturnValueUsed=*/true,
1981 Callee, Args, DAG, Node->getDebugLoc());
1983 if (!CallInfo.second.getNode())
1984 // It's a tailcall, return the chain (which is the DAG root).
1985 return DAG.getRoot();
1987 // Legalize the call sequence, starting with the chain. This will advance
1988 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1989 // was added by LowerCallTo (guaranteeing proper serialization of calls).
1990 LegalizeOp(CallInfo.second);
1991 return CallInfo.first;
1994 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1995 // ExpandLibCall except that the first operand is the in-chain.
1996 std::pair<SDValue, SDValue>
1997 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2000 assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
2001 SDValue InChain = Node->getOperand(0);
2003 TargetLowering::ArgListTy Args;
2004 TargetLowering::ArgListEntry Entry;
2005 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2006 EVT ArgVT = Node->getOperand(i).getValueType();
2007 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2008 Entry.Node = Node->getOperand(i);
2010 Entry.isSExt = isSigned;
2011 Entry.isZExt = !isSigned;
2012 Args.push_back(Entry);
2014 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2015 TLI.getPointerTy());
2017 // Splice the libcall in wherever FindInputOutputChains tells us to.
2018 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2019 std::pair<SDValue, SDValue> CallInfo =
2020 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2021 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2022 /*isReturnValueUsed=*/true,
2023 Callee, Args, DAG, Node->getDebugLoc());
2025 // Legalize the call sequence, starting with the chain. This will advance
2026 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2027 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2028 LegalizeOp(CallInfo.second);
2032 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2033 RTLIB::Libcall Call_F32,
2034 RTLIB::Libcall Call_F64,
2035 RTLIB::Libcall Call_F80,
2036 RTLIB::Libcall Call_PPCF128) {
2038 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2039 default: assert(0 && "Unexpected request for libcall!");
2040 case MVT::f32: LC = Call_F32; break;
2041 case MVT::f64: LC = Call_F64; break;
2042 case MVT::f80: LC = Call_F80; break;
2043 case MVT::ppcf128: LC = Call_PPCF128; break;
2045 return ExpandLibCall(LC, Node, false);
2048 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2049 RTLIB::Libcall Call_I8,
2050 RTLIB::Libcall Call_I16,
2051 RTLIB::Libcall Call_I32,
2052 RTLIB::Libcall Call_I64,
2053 RTLIB::Libcall Call_I128) {
2055 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2056 default: assert(0 && "Unexpected request for libcall!");
2057 case MVT::i8: LC = Call_I8; break;
2058 case MVT::i16: LC = Call_I16; break;
2059 case MVT::i32: LC = Call_I32; break;
2060 case MVT::i64: LC = Call_I64; break;
2061 case MVT::i128: LC = Call_I128; break;
2063 return ExpandLibCall(LC, Node, isSigned);
2066 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2067 /// INT_TO_FP operation of the specified operand when the target requests that
2068 /// we expand it. At this point, we know that the result and operand types are
2069 /// legal for the target.
2070 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2074 if (Op0.getValueType() == MVT::i32) {
2075 // simple 32-bit [signed|unsigned] integer to float/double expansion
2077 // Get the stack frame index of a 8 byte buffer.
2078 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2080 // word offset constant for Hi/Lo address computation
2081 SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2082 // set up Hi and Lo (into buffer) address based on endian
2083 SDValue Hi = StackSlot;
2084 SDValue Lo = DAG.getNode(ISD::ADD, dl,
2085 TLI.getPointerTy(), StackSlot, WordOff);
2086 if (TLI.isLittleEndian())
2089 // if signed map to unsigned space
2092 // constant used to invert sign bit (signed to unsigned mapping)
2093 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2094 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2098 // store the lo of the constructed double - based on integer input
2099 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2100 Op0Mapped, Lo, MachinePointerInfo(),
2102 // initial hi portion of constructed double
2103 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2104 // store the hi of the constructed double - biased exponent
2105 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2106 MachinePointerInfo(),
2108 // load the constructed double
2109 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2110 MachinePointerInfo(), false, false, 0);
2111 // FP constant to bias correct the final result
2112 SDValue Bias = DAG.getConstantFP(isSigned ?
2113 BitsToDouble(0x4330000080000000ULL) :
2114 BitsToDouble(0x4330000000000000ULL),
2116 // subtract the bias
2117 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2120 // handle final rounding
2121 if (DestVT == MVT::f64) {
2124 } else if (DestVT.bitsLT(MVT::f64)) {
2125 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2126 DAG.getIntPtrConstant(0));
2127 } else if (DestVT.bitsGT(MVT::f64)) {
2128 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2132 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2133 // Code below here assumes !isSigned without checking again.
2135 // Implementation of unsigned i64 to f64 following the algorithm in
2136 // __floatundidf in compiler_rt. This implementation has the advantage
2137 // of performing rounding correctly, both in the default rounding mode
2138 // and in all alternate rounding modes.
2139 // TODO: Generalize this for use with other types.
2140 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2142 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2143 SDValue TwoP84PlusTwoP52 =
2144 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2146 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2148 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2149 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2150 DAG.getConstant(32, MVT::i64));
2151 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2152 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2153 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2154 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2155 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2157 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2160 // Implementation of unsigned i64 to f32.
2161 // TODO: Generalize this for use with other types.
2162 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2163 // For unsigned conversions, convert them to signed conversions using the
2164 // algorithm from the x86_64 __floatundidf in compiler_rt.
2166 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2168 SDValue ShiftConst = DAG.getConstant(1, TLI.getShiftAmountTy());
2169 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2170 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2171 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2172 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2174 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2175 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2177 // TODO: This really should be implemented using a branch rather than a
2178 // select. We happen to get lucky and machinesink does the right
2179 // thing most of the time. This would be a good candidate for a
2180 //pseudo-op, or, even better, for whole-function isel.
2181 SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2182 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2183 return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2186 // Otherwise, implement the fully general conversion.
2187 EVT SHVT = TLI.getShiftAmountTy();
2189 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2190 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2191 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2192 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2193 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2194 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2195 SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2196 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2197 SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2198 SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2199 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2201 SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2203 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2204 DAG.getConstant(32, SHVT));
2205 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2206 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2208 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2209 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2210 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2211 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2212 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2213 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2214 DAG.getIntPtrConstant(0));
2217 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2219 SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2220 Op0, DAG.getConstant(0, Op0.getValueType()),
2222 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2223 SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2224 SignSet, Four, Zero);
2226 // If the sign bit of the integer is set, the large number will be treated
2227 // as a negative number. To counteract this, the dynamic code adds an
2228 // offset depending on the data type.
2230 switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2231 default: assert(0 && "Unsupported integer type!");
2232 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2233 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2234 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2235 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2237 if (TLI.isLittleEndian()) FF <<= 32;
2238 Constant *FudgeFactor = ConstantInt::get(
2239 Type::getInt64Ty(*DAG.getContext()), FF);
2241 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2242 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2243 CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2244 Alignment = std::min(Alignment, 4u);
2246 if (DestVT == MVT::f32)
2247 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2248 MachinePointerInfo::getConstantPool(),
2249 false, false, Alignment);
2252 LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT, dl,
2253 DAG.getEntryNode(), CPIdx,
2254 MachinePointerInfo::getConstantPool(),
2255 MVT::f32, false, false, Alignment));
2258 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2261 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2262 /// *INT_TO_FP operation of the specified operand when the target requests that
2263 /// we promote it. At this point, we know that the result and operand types are
2264 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2265 /// operation that takes a larger input.
2266 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2270 // First step, figure out the appropriate *INT_TO_FP operation to use.
2271 EVT NewInTy = LegalOp.getValueType();
2273 unsigned OpToUse = 0;
2275 // Scan for the appropriate larger type to use.
2277 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2278 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2280 // If the target supports SINT_TO_FP of this type, use it.
2281 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2282 OpToUse = ISD::SINT_TO_FP;
2285 if (isSigned) continue;
2287 // If the target supports UINT_TO_FP of this type, use it.
2288 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2289 OpToUse = ISD::UINT_TO_FP;
2293 // Otherwise, try a larger type.
2296 // Okay, we found the operation and type to use. Zero extend our input to the
2297 // desired type then run the operation on it.
2298 return DAG.getNode(OpToUse, dl, DestVT,
2299 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2300 dl, NewInTy, LegalOp));
2303 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2304 /// FP_TO_*INT operation of the specified operand when the target requests that
2305 /// we promote it. At this point, we know that the result and operand types are
2306 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2307 /// operation that returns a larger result.
2308 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2312 // First step, figure out the appropriate FP_TO*INT operation to use.
2313 EVT NewOutTy = DestVT;
2315 unsigned OpToUse = 0;
2317 // Scan for the appropriate larger type to use.
2319 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2320 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2322 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2323 OpToUse = ISD::FP_TO_SINT;
2327 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2328 OpToUse = ISD::FP_TO_UINT;
2332 // Otherwise, try a larger type.
2336 // Okay, we found the operation and type to use.
2337 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2339 // Truncate the result of the extended FP_TO_*INT operation to the desired
2341 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2344 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2346 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2347 EVT VT = Op.getValueType();
2348 EVT SHVT = TLI.getShiftAmountTy();
2349 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2350 switch (VT.getSimpleVT().SimpleTy) {
2351 default: assert(0 && "Unhandled Expand type in BSWAP!");
2353 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2354 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2355 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2357 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2358 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2359 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2360 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2361 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2362 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2363 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2364 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2365 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2367 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2368 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2369 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2370 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2371 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2372 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2373 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2374 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2375 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2376 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2377 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2378 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2379 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2380 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2381 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2382 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2383 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2384 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2385 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2386 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2387 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2391 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2393 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2396 default: assert(0 && "Cannot expand this yet!");
2398 static const uint64_t mask[6] = {
2399 0x5555555555555555ULL, 0x3333333333333333ULL,
2400 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2401 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2403 EVT VT = Op.getValueType();
2404 EVT ShVT = TLI.getShiftAmountTy();
2405 unsigned len = VT.getSizeInBits();
2406 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2407 //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2408 unsigned EltSize = VT.isVector() ?
2409 VT.getVectorElementType().getSizeInBits() : len;
2410 SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2411 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2412 Op = DAG.getNode(ISD::ADD, dl, VT,
2413 DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2414 DAG.getNode(ISD::AND, dl, VT,
2415 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2421 // for now, we do this:
2422 // x = x | (x >> 1);
2423 // x = x | (x >> 2);
2425 // x = x | (x >>16);
2426 // x = x | (x >>32); // for 64-bit input
2427 // return popcount(~x);
2429 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2430 EVT VT = Op.getValueType();
2431 EVT ShVT = TLI.getShiftAmountTy();
2432 unsigned len = VT.getSizeInBits();
2433 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2434 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2435 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2436 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2438 Op = DAG.getNOT(dl, Op, VT);
2439 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2442 // for now, we use: { return popcount(~x & (x - 1)); }
2443 // unless the target has ctlz but not ctpop, in which case we use:
2444 // { return 32 - nlz(~x & (x-1)); }
2445 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2446 EVT VT = Op.getValueType();
2447 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2448 DAG.getNOT(dl, Op, VT),
2449 DAG.getNode(ISD::SUB, dl, VT, Op,
2450 DAG.getConstant(1, VT)));
2451 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2452 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2453 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2454 return DAG.getNode(ISD::SUB, dl, VT,
2455 DAG.getConstant(VT.getSizeInBits(), VT),
2456 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2457 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2462 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2463 unsigned Opc = Node->getOpcode();
2464 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2469 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2471 case ISD::ATOMIC_SWAP:
2472 switch (VT.SimpleTy) {
2473 default: llvm_unreachable("Unexpected value type for atomic!");
2474 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2475 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2476 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2477 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2480 case ISD::ATOMIC_CMP_SWAP:
2481 switch (VT.SimpleTy) {
2482 default: llvm_unreachable("Unexpected value type for atomic!");
2483 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2484 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2485 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2486 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2489 case ISD::ATOMIC_LOAD_ADD:
2490 switch (VT.SimpleTy) {
2491 default: llvm_unreachable("Unexpected value type for atomic!");
2492 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2493 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2494 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2495 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2498 case ISD::ATOMIC_LOAD_SUB:
2499 switch (VT.SimpleTy) {
2500 default: llvm_unreachable("Unexpected value type for atomic!");
2501 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2502 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2503 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2504 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2507 case ISD::ATOMIC_LOAD_AND:
2508 switch (VT.SimpleTy) {
2509 default: llvm_unreachable("Unexpected value type for atomic!");
2510 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2511 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2512 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2513 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2516 case ISD::ATOMIC_LOAD_OR:
2517 switch (VT.SimpleTy) {
2518 default: llvm_unreachable("Unexpected value type for atomic!");
2519 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2520 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2521 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2522 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2525 case ISD::ATOMIC_LOAD_XOR:
2526 switch (VT.SimpleTy) {
2527 default: llvm_unreachable("Unexpected value type for atomic!");
2528 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2529 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2530 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2531 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2534 case ISD::ATOMIC_LOAD_NAND:
2535 switch (VT.SimpleTy) {
2536 default: llvm_unreachable("Unexpected value type for atomic!");
2537 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2538 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2539 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2540 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2545 return ExpandChainLibCall(LC, Node, false);
2548 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2549 SmallVectorImpl<SDValue> &Results) {
2550 DebugLoc dl = Node->getDebugLoc();
2551 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2552 switch (Node->getOpcode()) {
2556 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2557 Results.push_back(Tmp1);
2560 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2562 case ISD::FRAMEADDR:
2563 case ISD::RETURNADDR:
2564 case ISD::FRAME_TO_ARGS_OFFSET:
2565 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2567 case ISD::FLT_ROUNDS_:
2568 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2570 case ISD::EH_RETURN:
2574 case ISD::EH_SJLJ_LONGJMP:
2575 case ISD::EH_SJLJ_DISPATCHSETUP:
2576 // If the target didn't expand these, there's nothing to do, so just
2577 // preserve the chain and be done.
2578 Results.push_back(Node->getOperand(0));
2580 case ISD::EH_SJLJ_SETJMP:
2581 // If the target didn't expand this, just return 'zero' and preserve the
2583 Results.push_back(DAG.getConstant(0, MVT::i32));
2584 Results.push_back(Node->getOperand(0));
2586 case ISD::MEMBARRIER: {
2587 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2588 TargetLowering::ArgListTy Args;
2589 std::pair<SDValue, SDValue> CallResult =
2590 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2591 false, false, false, false, 0, CallingConv::C,
2592 /*isTailCall=*/false,
2593 /*isReturnValueUsed=*/true,
2594 DAG.getExternalSymbol("__sync_synchronize",
2595 TLI.getPointerTy()),
2597 Results.push_back(CallResult.second);
2600 // By default, atomic intrinsics are marked Legal and lowered. Targets
2601 // which don't support them directly, however, may want libcalls, in which
2602 // case they mark them Expand, and we get here.
2603 case ISD::ATOMIC_SWAP:
2604 case ISD::ATOMIC_LOAD_ADD:
2605 case ISD::ATOMIC_LOAD_SUB:
2606 case ISD::ATOMIC_LOAD_AND:
2607 case ISD::ATOMIC_LOAD_OR:
2608 case ISD::ATOMIC_LOAD_XOR:
2609 case ISD::ATOMIC_LOAD_NAND:
2610 case ISD::ATOMIC_LOAD_MIN:
2611 case ISD::ATOMIC_LOAD_MAX:
2612 case ISD::ATOMIC_LOAD_UMIN:
2613 case ISD::ATOMIC_LOAD_UMAX:
2614 case ISD::ATOMIC_CMP_SWAP: {
2615 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
2616 Results.push_back(Tmp.first);
2617 Results.push_back(Tmp.second);
2620 case ISD::DYNAMIC_STACKALLOC:
2621 ExpandDYNAMIC_STACKALLOC(Node, Results);
2623 case ISD::MERGE_VALUES:
2624 for (unsigned i = 0; i < Node->getNumValues(); i++)
2625 Results.push_back(Node->getOperand(i));
2628 EVT VT = Node->getValueType(0);
2630 Results.push_back(DAG.getConstant(0, VT));
2632 assert(VT.isFloatingPoint() && "Unknown value type!");
2633 Results.push_back(DAG.getConstantFP(0, VT));
2638 // If this operation is not supported, lower it to 'abort()' call
2639 TargetLowering::ArgListTy Args;
2640 std::pair<SDValue, SDValue> CallResult =
2641 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2642 false, false, false, false, 0, CallingConv::C,
2643 /*isTailCall=*/false,
2644 /*isReturnValueUsed=*/true,
2645 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2647 Results.push_back(CallResult.second);
2652 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2653 Node->getValueType(0), dl);
2654 Results.push_back(Tmp1);
2656 case ISD::FP_EXTEND:
2657 Tmp1 = EmitStackConvert(Node->getOperand(0),
2658 Node->getOperand(0).getValueType(),
2659 Node->getValueType(0), dl);
2660 Results.push_back(Tmp1);
2662 case ISD::SIGN_EXTEND_INREG: {
2663 // NOTE: we could fall back on load/store here too for targets without
2664 // SAR. However, it is doubtful that any exist.
2665 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2666 EVT VT = Node->getValueType(0);
2667 EVT ShiftAmountTy = TLI.getShiftAmountTy();
2670 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2671 ExtraVT.getScalarType().getSizeInBits();
2672 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2673 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2674 Node->getOperand(0), ShiftCst);
2675 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2676 Results.push_back(Tmp1);
2679 case ISD::FP_ROUND_INREG: {
2680 // The only way we can lower this is to turn it into a TRUNCSTORE,
2681 // EXTLOAD pair, targetting a temporary location (a stack slot).
2683 // NOTE: there is a choice here between constantly creating new stack
2684 // slots and always reusing the same one. We currently always create
2685 // new ones, as reuse may inhibit scheduling.
2686 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2687 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2688 Node->getValueType(0), dl);
2689 Results.push_back(Tmp1);
2692 case ISD::SINT_TO_FP:
2693 case ISD::UINT_TO_FP:
2694 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2695 Node->getOperand(0), Node->getValueType(0), dl);
2696 Results.push_back(Tmp1);
2698 case ISD::FP_TO_UINT: {
2699 SDValue True, False;
2700 EVT VT = Node->getOperand(0).getValueType();
2701 EVT NVT = Node->getValueType(0);
2702 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2703 APInt x = APInt::getSignBit(NVT.getSizeInBits());
2704 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2705 Tmp1 = DAG.getConstantFP(apf, VT);
2706 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2707 Node->getOperand(0),
2709 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2710 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2711 DAG.getNode(ISD::FSUB, dl, VT,
2712 Node->getOperand(0), Tmp1));
2713 False = DAG.getNode(ISD::XOR, dl, NVT, False,
2714 DAG.getConstant(x, NVT));
2715 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2716 Results.push_back(Tmp1);
2720 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2721 EVT VT = Node->getValueType(0);
2722 Tmp1 = Node->getOperand(0);
2723 Tmp2 = Node->getOperand(1);
2724 unsigned Align = Node->getConstantOperandVal(3);
2726 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
2727 MachinePointerInfo(V), false, false, 0);
2728 SDValue VAList = VAListLoad;
2730 if (Align > TLI.getMinStackArgumentAlignment()) {
2731 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2733 VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2734 DAG.getConstant(Align - 1,
2735 TLI.getPointerTy()));
2737 VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
2738 DAG.getConstant(-(int64_t)Align,
2739 TLI.getPointerTy()));
2742 // Increment the pointer, VAList, to the next vaarg
2743 Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2744 DAG.getConstant(TLI.getTargetData()->
2745 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2746 TLI.getPointerTy()));
2747 // Store the incremented VAList to the legalized pointer
2748 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
2749 MachinePointerInfo(V), false, false, 0);
2750 // Load the actual argument out of the pointer VAList
2751 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
2753 Results.push_back(Results[0].getValue(1));
2757 // This defaults to loading a pointer from the input and storing it to the
2758 // output, returning the chain.
2759 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2760 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2761 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2762 Node->getOperand(2), MachinePointerInfo(VS),
2764 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2765 MachinePointerInfo(VD), false, false, 0);
2766 Results.push_back(Tmp1);
2769 case ISD::EXTRACT_VECTOR_ELT:
2770 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2771 // This must be an access of the only element. Return it.
2772 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2773 Node->getOperand(0));
2775 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2776 Results.push_back(Tmp1);
2778 case ISD::EXTRACT_SUBVECTOR:
2779 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2781 case ISD::CONCAT_VECTORS: {
2782 Results.push_back(ExpandVectorBuildThroughStack(Node));
2785 case ISD::SCALAR_TO_VECTOR:
2786 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2788 case ISD::INSERT_VECTOR_ELT:
2789 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2790 Node->getOperand(1),
2791 Node->getOperand(2), dl));
2793 case ISD::VECTOR_SHUFFLE: {
2794 SmallVector<int, 8> Mask;
2795 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2797 EVT VT = Node->getValueType(0);
2798 EVT EltVT = VT.getVectorElementType();
2799 if (getTypeAction(EltVT) == Promote)
2800 EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2801 unsigned NumElems = VT.getVectorNumElements();
2802 SmallVector<SDValue, 8> Ops;
2803 for (unsigned i = 0; i != NumElems; ++i) {
2805 Ops.push_back(DAG.getUNDEF(EltVT));
2808 unsigned Idx = Mask[i];
2810 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2811 Node->getOperand(0),
2812 DAG.getIntPtrConstant(Idx)));
2814 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2815 Node->getOperand(1),
2816 DAG.getIntPtrConstant(Idx - NumElems)));
2818 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2819 Results.push_back(Tmp1);
2822 case ISD::EXTRACT_ELEMENT: {
2823 EVT OpTy = Node->getOperand(0).getValueType();
2824 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2826 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2827 DAG.getConstant(OpTy.getSizeInBits()/2,
2828 TLI.getShiftAmountTy()));
2829 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2832 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2833 Node->getOperand(0));
2835 Results.push_back(Tmp1);
2838 case ISD::STACKSAVE:
2839 // Expand to CopyFromReg if the target set
2840 // StackPointerRegisterToSaveRestore.
2841 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2842 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2843 Node->getValueType(0)));
2844 Results.push_back(Results[0].getValue(1));
2846 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2847 Results.push_back(Node->getOperand(0));
2850 case ISD::STACKRESTORE:
2851 // Expand to CopyToReg if the target set
2852 // StackPointerRegisterToSaveRestore.
2853 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2854 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2855 Node->getOperand(1)));
2857 Results.push_back(Node->getOperand(0));
2860 case ISD::FCOPYSIGN:
2861 Results.push_back(ExpandFCOPYSIGN(Node));
2864 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
2865 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2866 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2867 Node->getOperand(0));
2868 Results.push_back(Tmp1);
2871 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2872 EVT VT = Node->getValueType(0);
2873 Tmp1 = Node->getOperand(0);
2874 Tmp2 = DAG.getConstantFP(0.0, VT);
2875 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2876 Tmp1, Tmp2, ISD::SETUGT);
2877 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2878 Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2879 Results.push_back(Tmp1);
2883 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2884 RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2887 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2888 RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2891 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2892 RTLIB::COS_F80, RTLIB::COS_PPCF128));
2895 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2896 RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2899 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2900 RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2903 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2904 RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2907 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2908 RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2911 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2912 RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2915 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2916 RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2919 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2920 RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2923 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2924 RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2927 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2928 RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2930 case ISD::FNEARBYINT:
2931 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2932 RTLIB::NEARBYINT_F64,
2933 RTLIB::NEARBYINT_F80,
2934 RTLIB::NEARBYINT_PPCF128));
2937 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2938 RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2941 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2942 RTLIB::POW_F80, RTLIB::POW_PPCF128));
2945 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2946 RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2949 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2950 RTLIB::REM_F80, RTLIB::REM_PPCF128));
2952 case ISD::FP16_TO_FP32:
2953 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
2955 case ISD::FP32_TO_FP16:
2956 Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
2958 case ISD::ConstantFP: {
2959 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2960 // Check to see if this FP immediate is already legal.
2961 // If this is a legal constant, turn it into a TargetConstantFP node.
2962 if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
2963 Results.push_back(SDValue(Node, 0));
2965 Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2968 case ISD::EHSELECTION: {
2969 unsigned Reg = TLI.getExceptionSelectorRegister();
2970 assert(Reg && "Can't expand to unknown register!");
2971 Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2972 Node->getValueType(0)));
2973 Results.push_back(Results[0].getValue(1));
2976 case ISD::EXCEPTIONADDR: {
2977 unsigned Reg = TLI.getExceptionAddressRegister();
2978 assert(Reg && "Can't expand to unknown register!");
2979 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
2980 Node->getValueType(0)));
2981 Results.push_back(Results[0].getValue(1));
2985 EVT VT = Node->getValueType(0);
2986 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
2987 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
2988 "Don't know how to expand this subtraction!");
2989 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
2990 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
2991 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
2992 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
2997 EVT VT = Node->getValueType(0);
2998 SDVTList VTs = DAG.getVTList(VT, VT);
2999 bool isSigned = Node->getOpcode() == ISD::SREM;
3000 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3001 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3002 Tmp2 = Node->getOperand(0);
3003 Tmp3 = Node->getOperand(1);
3004 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3005 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3006 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3008 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3009 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3010 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3011 } else if (isSigned) {
3012 Tmp1 = ExpandIntLibCall(Node, true,
3014 RTLIB::SREM_I16, RTLIB::SREM_I32,
3015 RTLIB::SREM_I64, RTLIB::SREM_I128);
3017 Tmp1 = ExpandIntLibCall(Node, false,
3019 RTLIB::UREM_I16, RTLIB::UREM_I32,
3020 RTLIB::UREM_I64, RTLIB::UREM_I128);
3022 Results.push_back(Tmp1);
3027 bool isSigned = Node->getOpcode() == ISD::SDIV;
3028 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3029 EVT VT = Node->getValueType(0);
3030 SDVTList VTs = DAG.getVTList(VT, VT);
3031 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
3032 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3033 Node->getOperand(1));
3035 Tmp1 = ExpandIntLibCall(Node, true,
3037 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3038 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3040 Tmp1 = ExpandIntLibCall(Node, false,
3042 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3043 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3044 Results.push_back(Tmp1);
3049 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3051 EVT VT = Node->getValueType(0);
3052 SDVTList VTs = DAG.getVTList(VT, VT);
3053 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3054 "If this wasn't legal, it shouldn't have been created!");
3055 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3056 Node->getOperand(1));
3057 Results.push_back(Tmp1.getValue(1));
3061 EVT VT = Node->getValueType(0);
3062 SDVTList VTs = DAG.getVTList(VT, VT);
3063 // See if multiply or divide can be lowered using two-result operations.
3064 // We just need the low half of the multiply; try both the signed
3065 // and unsigned forms. If the target supports both SMUL_LOHI and
3066 // UMUL_LOHI, form a preference by checking which forms of plain
3067 // MULH it supports.
3068 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3069 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3070 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3071 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3072 unsigned OpToUse = 0;
3073 if (HasSMUL_LOHI && !HasMULHS) {
3074 OpToUse = ISD::SMUL_LOHI;
3075 } else if (HasUMUL_LOHI && !HasMULHU) {
3076 OpToUse = ISD::UMUL_LOHI;
3077 } else if (HasSMUL_LOHI) {
3078 OpToUse = ISD::SMUL_LOHI;
3079 } else if (HasUMUL_LOHI) {
3080 OpToUse = ISD::UMUL_LOHI;
3083 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3084 Node->getOperand(1)));
3087 Tmp1 = ExpandIntLibCall(Node, false,
3089 RTLIB::MUL_I16, RTLIB::MUL_I32,
3090 RTLIB::MUL_I64, RTLIB::MUL_I128);
3091 Results.push_back(Tmp1);
3096 SDValue LHS = Node->getOperand(0);
3097 SDValue RHS = Node->getOperand(1);
3098 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3099 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3101 Results.push_back(Sum);
3102 EVT OType = Node->getValueType(1);
3104 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3106 // LHSSign -> LHS >= 0
3107 // RHSSign -> RHS >= 0
3108 // SumSign -> Sum >= 0
3111 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3113 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3115 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3116 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3117 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3118 Node->getOpcode() == ISD::SADDO ?
3119 ISD::SETEQ : ISD::SETNE);
3121 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3122 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3124 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3125 Results.push_back(Cmp);
3130 SDValue LHS = Node->getOperand(0);
3131 SDValue RHS = Node->getOperand(1);
3132 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3133 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3135 Results.push_back(Sum);
3136 Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3137 Node->getOpcode () == ISD::UADDO ?
3138 ISD::SETULT : ISD::SETUGT));
3143 EVT VT = Node->getValueType(0);
3144 SDValue LHS = Node->getOperand(0);
3145 SDValue RHS = Node->getOperand(1);
3148 static const unsigned Ops[2][3] =
3149 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3150 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3151 bool isSigned = Node->getOpcode() == ISD::SMULO;
3152 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3153 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3154 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3155 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3156 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3158 TopHalf = BottomHalf.getValue(1);
3160 // FIXME: We should be able to fall back to a libcall with an illegal
3161 // type in some cases.
3162 // Also, we can fall back to a division in some cases, but that's a big
3163 // performance hit in the general case.
3164 assert(TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3165 VT.getSizeInBits() * 2)) &&
3166 "Don't know how to expand this operation yet!");
3167 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3168 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3169 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3170 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3171 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3172 DAG.getIntPtrConstant(0));
3173 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3174 DAG.getIntPtrConstant(1));
3177 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1, TLI.getShiftAmountTy());
3178 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3179 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3182 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3183 DAG.getConstant(0, VT), ISD::SETNE);
3185 Results.push_back(BottomHalf);
3186 Results.push_back(TopHalf);
3189 case ISD::BUILD_PAIR: {
3190 EVT PairTy = Node->getValueType(0);
3191 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3192 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3193 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3194 DAG.getConstant(PairTy.getSizeInBits()/2,
3195 TLI.getShiftAmountTy()));
3196 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3200 Tmp1 = Node->getOperand(0);
3201 Tmp2 = Node->getOperand(1);
3202 Tmp3 = Node->getOperand(2);
3203 if (Tmp1.getOpcode() == ISD::SETCC) {
3204 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3206 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3208 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3209 DAG.getConstant(0, Tmp1.getValueType()),
3210 Tmp2, Tmp3, ISD::SETNE);
3212 Results.push_back(Tmp1);
3215 SDValue Chain = Node->getOperand(0);
3216 SDValue Table = Node->getOperand(1);
3217 SDValue Index = Node->getOperand(2);
3219 EVT PTy = TLI.getPointerTy();
3221 const TargetData &TD = *TLI.getTargetData();
3222 unsigned EntrySize =
3223 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3225 Index = DAG.getNode(ISD::MUL, dl, PTy,
3226 Index, DAG.getConstant(EntrySize, PTy));
3227 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3229 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3230 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, PTy, dl, Chain, Addr,
3231 MachinePointerInfo::getJumpTable(), MemVT,
3234 if (TM.getRelocationModel() == Reloc::PIC_) {
3235 // For PIC, the sequence is:
3236 // BRIND(load(Jumptable + index) + RelocBase)
3237 // RelocBase can be JumpTable, GOT or some sort of global base.
3238 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3239 TLI.getPICJumpTableRelocBase(Table, DAG));
3241 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3242 Results.push_back(Tmp1);
3246 // Expand brcond's setcc into its constituent parts and create a BR_CC
3248 Tmp1 = Node->getOperand(0);
3249 Tmp2 = Node->getOperand(1);
3250 if (Tmp2.getOpcode() == ISD::SETCC) {
3251 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3252 Tmp1, Tmp2.getOperand(2),
3253 Tmp2.getOperand(0), Tmp2.getOperand(1),
3254 Node->getOperand(2));
3256 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3257 DAG.getCondCode(ISD::SETNE), Tmp2,
3258 DAG.getConstant(0, Tmp2.getValueType()),
3259 Node->getOperand(2));
3261 Results.push_back(Tmp1);
3264 Tmp1 = Node->getOperand(0);
3265 Tmp2 = Node->getOperand(1);
3266 Tmp3 = Node->getOperand(2);
3267 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3269 // If we expanded the SETCC into an AND/OR, return the new node
3270 if (Tmp2.getNode() == 0) {
3271 Results.push_back(Tmp1);
3275 // Otherwise, SETCC for the given comparison type must be completely
3276 // illegal; expand it into a SELECT_CC.
3277 EVT VT = Node->getValueType(0);
3278 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3279 DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3280 Results.push_back(Tmp1);
3283 case ISD::SELECT_CC: {
3284 Tmp1 = Node->getOperand(0); // LHS
3285 Tmp2 = Node->getOperand(1); // RHS
3286 Tmp3 = Node->getOperand(2); // True
3287 Tmp4 = Node->getOperand(3); // False
3288 SDValue CC = Node->getOperand(4);
3290 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3291 Tmp1, Tmp2, CC, dl);
3293 assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3294 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3295 CC = DAG.getCondCode(ISD::SETNE);
3296 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3298 Results.push_back(Tmp1);
3302 Tmp1 = Node->getOperand(0); // Chain
3303 Tmp2 = Node->getOperand(2); // LHS
3304 Tmp3 = Node->getOperand(3); // RHS
3305 Tmp4 = Node->getOperand(1); // CC
3307 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3308 Tmp2, Tmp3, Tmp4, dl);
3309 LastCALLSEQ_END = DAG.getEntryNode();
3311 assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3312 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3313 Tmp4 = DAG.getCondCode(ISD::SETNE);
3314 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3315 Tmp3, Node->getOperand(4));
3316 Results.push_back(Tmp1);
3319 case ISD::GLOBAL_OFFSET_TABLE:
3320 case ISD::GlobalAddress:
3321 case ISD::GlobalTLSAddress:
3322 case ISD::ExternalSymbol:
3323 case ISD::ConstantPool:
3324 case ISD::JumpTable:
3325 case ISD::INTRINSIC_W_CHAIN:
3326 case ISD::INTRINSIC_WO_CHAIN:
3327 case ISD::INTRINSIC_VOID:
3328 // FIXME: Custom lowering for these operations shouldn't return null!
3329 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3330 Results.push_back(SDValue(Node, i));
3334 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3335 SmallVectorImpl<SDValue> &Results) {
3336 EVT OVT = Node->getValueType(0);
3337 if (Node->getOpcode() == ISD::UINT_TO_FP ||
3338 Node->getOpcode() == ISD::SINT_TO_FP ||
3339 Node->getOpcode() == ISD::SETCC) {
3340 OVT = Node->getOperand(0).getValueType();
3342 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3343 DebugLoc dl = Node->getDebugLoc();
3344 SDValue Tmp1, Tmp2, Tmp3;
3345 switch (Node->getOpcode()) {
3349 // Zero extend the argument.
3350 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3351 // Perform the larger operation.
3352 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3353 if (Node->getOpcode() == ISD::CTTZ) {
3354 //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3355 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3356 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3358 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3359 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3360 } else if (Node->getOpcode() == ISD::CTLZ) {
3361 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3362 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3363 DAG.getConstant(NVT.getSizeInBits() -
3364 OVT.getSizeInBits(), NVT));
3366 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3369 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3370 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3371 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3372 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3373 DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3374 Results.push_back(Tmp1);
3377 case ISD::FP_TO_UINT:
3378 case ISD::FP_TO_SINT:
3379 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3380 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3381 Results.push_back(Tmp1);
3383 case ISD::UINT_TO_FP:
3384 case ISD::SINT_TO_FP:
3385 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3386 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3387 Results.push_back(Tmp1);
3392 unsigned ExtOp, TruncOp;
3393 if (OVT.isVector()) {
3394 ExtOp = ISD::BITCAST;
3395 TruncOp = ISD::BITCAST;
3397 assert(OVT.isInteger() && "Cannot promote logic operation");
3398 ExtOp = ISD::ANY_EXTEND;
3399 TruncOp = ISD::TRUNCATE;
3401 // Promote each of the values to the new type.
3402 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3403 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3404 // Perform the larger operation, then convert back
3405 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3406 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3410 unsigned ExtOp, TruncOp;
3411 if (Node->getValueType(0).isVector()) {
3412 ExtOp = ISD::BITCAST;
3413 TruncOp = ISD::BITCAST;
3414 } else if (Node->getValueType(0).isInteger()) {
3415 ExtOp = ISD::ANY_EXTEND;
3416 TruncOp = ISD::TRUNCATE;
3418 ExtOp = ISD::FP_EXTEND;
3419 TruncOp = ISD::FP_ROUND;
3421 Tmp1 = Node->getOperand(0);
3422 // Promote each of the values to the new type.
3423 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3424 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3425 // Perform the larger operation, then round down.
3426 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3427 if (TruncOp != ISD::FP_ROUND)
3428 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3430 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3431 DAG.getIntPtrConstant(0));
3432 Results.push_back(Tmp1);
3435 case ISD::VECTOR_SHUFFLE: {
3436 SmallVector<int, 8> Mask;
3437 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3439 // Cast the two input vectors.
3440 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3441 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3443 // Convert the shuffle mask to the right # elements.
3444 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3445 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3446 Results.push_back(Tmp1);
3450 unsigned ExtOp = ISD::FP_EXTEND;
3451 if (NVT.isInteger()) {
3452 ISD::CondCode CCCode =
3453 cast<CondCodeSDNode>(Node->getOperand(2))->get();
3454 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3456 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3457 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3458 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3459 Tmp1, Tmp2, Node->getOperand(2)));
3465 // SelectionDAG::Legalize - This is the entry point for the file.
3467 void SelectionDAG::Legalize(CodeGenOpt::Level OptLevel) {
3468 /// run - This is the main entry point to this class.
3470 SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();