1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/Analysis/DebugInfo.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/Target/TargetFrameInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Target/TargetSubtarget.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/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/SmallPtrSet.h"
42 //===----------------------------------------------------------------------===//
43 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44 /// hacks on it until the target machine can handle it. This involves
45 /// eliminating value sizes the machine cannot handle (promoting small sizes to
46 /// large sizes or splitting up large values into small values) as well as
47 /// eliminating operations the machine cannot handle.
49 /// This code also does a small amount of optimization and recognition of idioms
50 /// as part of its processing. For example, if a target does not support a
51 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52 /// will attempt merge setcc and brc instructions into brcc's.
55 class SelectionDAGLegalize {
56 const TargetMachine &TM;
57 const TargetLowering &TLI;
59 CodeGenOpt::Level OptLevel;
61 // Libcall insertion helpers.
63 /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
64 /// legalized. We use this to ensure that calls are properly serialized
65 /// against each other, including inserted libcalls.
66 SDValue LastCALLSEQ_END;
68 /// IsLegalizingCall - This member is used *only* for purposes of providing
69 /// helpful assertions that a libcall isn't created while another call is
70 /// being legalized (which could lead to non-serialized call sequences).
71 bool IsLegalizingCall;
74 Legal, // The target natively supports this operation.
75 Promote, // This operation should be executed in a larger type.
76 Expand // Try to expand this to other ops, otherwise use a libcall.
79 /// ValueTypeActions - This is a bitvector that contains two bits for each
80 /// value type, where the two bits correspond to the LegalizeAction enum.
81 /// This can be queried with "getTypeAction(VT)".
82 TargetLowering::ValueTypeActionImpl ValueTypeActions;
84 /// LegalizedNodes - For nodes that are of legal width, and that have more
85 /// than one use, this map indicates what regularized operand to use. This
86 /// allows us to avoid legalizing the same thing more than once.
87 DenseMap<SDValue, SDValue> LegalizedNodes;
89 void AddLegalizedOperand(SDValue From, SDValue To) {
90 LegalizedNodes.insert(std::make_pair(From, To));
91 // If someone requests legalization of the new node, return itself.
93 LegalizedNodes.insert(std::make_pair(To, To));
97 SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
99 /// getTypeAction - Return how we should legalize values of this type, either
100 /// it is already legal or we need to expand it into multiple registers of
101 /// smaller integer type, or we need to promote it to a larger type.
102 LegalizeAction getTypeAction(EVT VT) const {
104 (LegalizeAction)ValueTypeActions.getTypeAction(*DAG.getContext(), 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 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
148 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
149 RTLIB::Libcall Call_PPCF128);
150 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
151 RTLIB::Libcall Call_I8,
152 RTLIB::Libcall Call_I16,
153 RTLIB::Libcall Call_I32,
154 RTLIB::Libcall Call_I64,
155 RTLIB::Libcall Call_I128);
157 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
158 SDValue ExpandBUILD_VECTOR(SDNode *Node);
159 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
160 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
161 SmallVectorImpl<SDValue> &Results);
162 SDValue ExpandFCOPYSIGN(SDNode *Node);
163 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
165 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
167 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
170 SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
171 SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
173 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
174 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
176 void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
177 void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
181 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
182 /// performs the same shuffe in terms of order or result bytes, but on a type
183 /// whose vector element type is narrower than the original shuffle type.
184 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
186 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
187 SDValue N1, SDValue N2,
188 SmallVectorImpl<int> &Mask) const {
189 unsigned NumMaskElts = VT.getVectorNumElements();
190 unsigned NumDestElts = NVT.getVectorNumElements();
191 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
193 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
195 if (NumEltsGrowth == 1)
196 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
198 SmallVector<int, 8> NewMask;
199 for (unsigned i = 0; i != NumMaskElts; ++i) {
201 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
203 NewMask.push_back(-1);
205 NewMask.push_back(Idx * NumEltsGrowth + j);
208 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
209 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
210 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
213 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
214 CodeGenOpt::Level ol)
215 : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
216 DAG(dag), OptLevel(ol),
217 ValueTypeActions(TLI.getValueTypeActions()) {
218 assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
219 "Too many value types for ValueTypeActions to hold!");
222 void SelectionDAGLegalize::LegalizeDAG() {
223 LastCALLSEQ_END = DAG.getEntryNode();
224 IsLegalizingCall = false;
226 // The legalize process is inherently a bottom-up recursive process (users
227 // legalize their uses before themselves). Given infinite stack space, we
228 // could just start legalizing on the root and traverse the whole graph. In
229 // practice however, this causes us to run out of stack space on large basic
230 // blocks. To avoid this problem, compute an ordering of the nodes where each
231 // node is only legalized after all of its operands are legalized.
232 DAG.AssignTopologicalOrder();
233 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
234 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
235 LegalizeOp(SDValue(I, 0));
237 // Finally, it's possible the root changed. Get the new root.
238 SDValue OldRoot = DAG.getRoot();
239 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
240 DAG.setRoot(LegalizedNodes[OldRoot]);
242 LegalizedNodes.clear();
244 // Remove dead nodes now.
245 DAG.RemoveDeadNodes();
249 /// FindCallEndFromCallStart - Given a chained node that is part of a call
250 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
251 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
252 if (Node->getOpcode() == ISD::CALLSEQ_END)
254 if (Node->use_empty())
255 return 0; // No CallSeqEnd
257 // The chain is usually at the end.
258 SDValue TheChain(Node, Node->getNumValues()-1);
259 if (TheChain.getValueType() != MVT::Other) {
260 // Sometimes it's at the beginning.
261 TheChain = SDValue(Node, 0);
262 if (TheChain.getValueType() != MVT::Other) {
263 // Otherwise, hunt for it.
264 for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
265 if (Node->getValueType(i) == MVT::Other) {
266 TheChain = SDValue(Node, i);
270 // Otherwise, we walked into a node without a chain.
271 if (TheChain.getValueType() != MVT::Other)
276 for (SDNode::use_iterator UI = Node->use_begin(),
277 E = Node->use_end(); UI != E; ++UI) {
279 // Make sure to only follow users of our token chain.
281 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
282 if (User->getOperand(i) == TheChain)
283 if (SDNode *Result = FindCallEndFromCallStart(User))
289 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
290 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
291 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
292 assert(Node && "Didn't find callseq_start for a call??");
293 if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
295 assert(Node->getOperand(0).getValueType() == MVT::Other &&
296 "Node doesn't have a token chain argument!");
297 return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
300 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
301 /// see if any uses can reach Dest. If no dest operands can get to dest,
302 /// legalize them, legalize ourself, and return false, otherwise, return true.
304 /// Keep track of the nodes we fine that actually do lead to Dest in
305 /// NodesLeadingTo. This avoids retraversing them exponential number of times.
307 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
308 SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
309 if (N == Dest) return true; // N certainly leads to Dest :)
311 // If we've already processed this node and it does lead to Dest, there is no
312 // need to reprocess it.
313 if (NodesLeadingTo.count(N)) return true;
315 // If the first result of this node has been already legalized, then it cannot
317 if (LegalizedNodes.count(SDValue(N, 0))) return false;
319 // Okay, this node has not already been legalized. Check and legalize all
320 // operands. If none lead to Dest, then we can legalize this node.
321 bool OperandsLeadToDest = false;
322 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
323 OperandsLeadToDest |= // If an operand leads to Dest, so do we.
324 LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
326 if (OperandsLeadToDest) {
327 NodesLeadingTo.insert(N);
331 // Okay, this node looks safe, legalize it and return false.
332 LegalizeOp(SDValue(N, 0));
336 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
337 /// a load from the constant pool.
338 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
339 SelectionDAG &DAG, const TargetLowering &TLI) {
341 DebugLoc dl = CFP->getDebugLoc();
343 // If a FP immediate is precise when represented as a float and if the
344 // target can do an extending load from float to double, we put it into
345 // the constant pool as a float, even if it's is statically typed as a
346 // double. This shrinks FP constants and canonicalizes them for targets where
347 // an FP extending load is the same cost as a normal load (such as on the x87
348 // fp stack or PPC FP unit).
349 EVT VT = CFP->getValueType(0);
350 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
352 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
353 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
354 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
359 while (SVT != MVT::f32) {
360 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
361 if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
362 // Only do this if the target has a native EXTLOAD instruction from
364 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
365 TLI.ShouldShrinkFPConstant(OrigVT)) {
366 const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
367 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
373 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
374 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
376 return DAG.getExtLoad(ISD::EXTLOAD, dl,
377 OrigVT, DAG.getEntryNode(),
378 CPIdx, PseudoSourceValue::getConstantPool(),
379 0, VT, false, false, Alignment);
380 return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
381 PseudoSourceValue::getConstantPool(), 0, false, false,
385 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
387 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
388 const TargetLowering &TLI) {
389 SDValue Chain = ST->getChain();
390 SDValue Ptr = ST->getBasePtr();
391 SDValue Val = ST->getValue();
392 EVT VT = Val.getValueType();
393 int Alignment = ST->getAlignment();
394 int SVOffset = ST->getSrcValueOffset();
395 DebugLoc dl = ST->getDebugLoc();
396 if (ST->getMemoryVT().isFloatingPoint() ||
397 ST->getMemoryVT().isVector()) {
398 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
399 if (TLI.isTypeLegal(intVT)) {
400 // Expand to a bitconvert of the value to the integer type of the
401 // same size, then a (misaligned) int store.
402 // FIXME: Does not handle truncating floating point stores!
403 SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
404 return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
405 SVOffset, ST->isVolatile(), ST->isNonTemporal(),
408 // Do a (aligned) store to a stack slot, then copy from the stack slot
409 // to the final destination using (unaligned) integer loads and stores.
410 EVT StoredVT = ST->getMemoryVT();
412 TLI.getRegisterType(*DAG.getContext(),
413 EVT::getIntegerVT(*DAG.getContext(),
414 StoredVT.getSizeInBits()));
415 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
416 unsigned RegBytes = RegVT.getSizeInBits() / 8;
417 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
419 // Make sure the stack slot is also aligned for the register type.
420 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
422 // Perform the original store, only redirected to the stack slot.
423 SDValue Store = DAG.getTruncStore(Chain, dl,
424 Val, StackPtr, NULL, 0, StoredVT,
426 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
427 SmallVector<SDValue, 8> Stores;
430 // Do all but one copies using the full register width.
431 for (unsigned i = 1; i < NumRegs; i++) {
432 // Load one integer register's worth from the stack slot.
433 SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0,
435 // Store it to the final location. Remember the store.
436 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
437 ST->getSrcValue(), SVOffset + Offset,
438 ST->isVolatile(), ST->isNonTemporal(),
439 MinAlign(ST->getAlignment(), Offset)));
440 // Increment the pointers.
442 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
444 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
447 // The last store may be partial. Do a truncating store. On big-endian
448 // machines this requires an extending load from the stack slot to ensure
449 // that the bits are in the right place.
450 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
451 8 * (StoredBytes - Offset));
453 // Load from the stack slot.
454 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
455 NULL, 0, MemVT, false, false, 0);
457 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
458 ST->getSrcValue(), SVOffset + Offset,
459 MemVT, ST->isVolatile(),
461 MinAlign(ST->getAlignment(), Offset)));
462 // The order of the stores doesn't matter - say it with a TokenFactor.
463 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
467 assert(ST->getMemoryVT().isInteger() &&
468 !ST->getMemoryVT().isVector() &&
469 "Unaligned store of unknown type.");
470 // Get the half-size VT
471 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
472 int NumBits = NewStoredVT.getSizeInBits();
473 int IncrementSize = NumBits / 8;
475 // Divide the stored value in two parts.
476 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
478 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
480 // Store the two parts
481 SDValue Store1, Store2;
482 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
483 ST->getSrcValue(), SVOffset, NewStoredVT,
484 ST->isVolatile(), ST->isNonTemporal(), Alignment);
485 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
486 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
487 Alignment = MinAlign(Alignment, IncrementSize);
488 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
489 ST->getSrcValue(), SVOffset + IncrementSize,
490 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
493 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
496 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
498 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
499 const TargetLowering &TLI) {
500 int SVOffset = LD->getSrcValueOffset();
501 SDValue Chain = LD->getChain();
502 SDValue Ptr = LD->getBasePtr();
503 EVT VT = LD->getValueType(0);
504 EVT LoadedVT = LD->getMemoryVT();
505 DebugLoc dl = LD->getDebugLoc();
506 if (VT.isFloatingPoint() || VT.isVector()) {
507 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
508 if (TLI.isTypeLegal(intVT)) {
509 // Expand to a (misaligned) integer load of the same size,
510 // then bitconvert to floating point or vector.
511 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
512 SVOffset, LD->isVolatile(),
513 LD->isNonTemporal(), LD->getAlignment());
514 SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
515 if (VT.isFloatingPoint() && LoadedVT != VT)
516 Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
518 SDValue Ops[] = { Result, Chain };
519 return DAG.getMergeValues(Ops, 2, dl);
521 // Copy the value to a (aligned) stack slot using (unaligned) integer
522 // loads and stores, then do a (aligned) load from the stack slot.
523 EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
524 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
525 unsigned RegBytes = RegVT.getSizeInBits() / 8;
526 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
528 // Make sure the stack slot is also aligned for the register type.
529 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
531 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
532 SmallVector<SDValue, 8> Stores;
533 SDValue StackPtr = StackBase;
536 // Do all but one copies using the full register width.
537 for (unsigned i = 1; i < NumRegs; i++) {
538 // Load one integer register's worth from the original location.
539 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
540 SVOffset + Offset, LD->isVolatile(),
542 MinAlign(LD->getAlignment(), Offset));
543 // Follow the load with a store to the stack slot. Remember the store.
544 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
545 NULL, 0, false, false, 0));
546 // Increment the pointers.
548 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
549 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
553 // The last copy may be partial. Do an extending load.
554 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
555 8 * (LoadedBytes - Offset));
556 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
557 LD->getSrcValue(), SVOffset + Offset,
558 MemVT, LD->isVolatile(),
560 MinAlign(LD->getAlignment(), Offset));
561 // Follow the load with a store to the stack slot. Remember the store.
562 // On big-endian machines this requires a truncating store to ensure
563 // that the bits end up in the right place.
564 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
565 NULL, 0, MemVT, false, false, 0));
567 // The order of the stores doesn't matter - say it with a TokenFactor.
568 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
571 // Finally, perform the original load only redirected to the stack slot.
572 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
573 NULL, 0, LoadedVT, false, false, 0);
575 // Callers expect a MERGE_VALUES node.
576 SDValue Ops[] = { Load, TF };
577 return DAG.getMergeValues(Ops, 2, dl);
580 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
581 "Unaligned load of unsupported type.");
583 // Compute the new VT that is half the size of the old one. This is an
585 unsigned NumBits = LoadedVT.getSizeInBits();
587 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
590 unsigned Alignment = LD->getAlignment();
591 unsigned IncrementSize = NumBits / 8;
592 ISD::LoadExtType HiExtType = LD->getExtensionType();
594 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
595 if (HiExtType == ISD::NON_EXTLOAD)
596 HiExtType = ISD::ZEXTLOAD;
598 // Load the value in two parts
600 if (TLI.isLittleEndian()) {
601 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
602 SVOffset, NewLoadedVT, LD->isVolatile(),
603 LD->isNonTemporal(), Alignment);
604 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
605 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
606 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
607 SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
608 LD->isNonTemporal(), MinAlign(Alignment, IncrementSize));
610 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
611 SVOffset, NewLoadedVT, LD->isVolatile(),
612 LD->isNonTemporal(), Alignment);
613 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
614 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
615 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
616 SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
617 LD->isNonTemporal(), MinAlign(Alignment, IncrementSize));
620 // aggregate the two parts
621 SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
622 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
623 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
625 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
628 SDValue Ops[] = { Result, TF };
629 return DAG.getMergeValues(Ops, 2, dl);
632 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
633 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
634 /// is necessary to spill the vector being inserted into to memory, perform
635 /// the insert there, and then read the result back.
636 SDValue SelectionDAGLegalize::
637 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
643 // If the target doesn't support this, we have to spill the input vector
644 // to a temporary stack slot, update the element, then reload it. This is
645 // badness. We could also load the value into a vector register (either
646 // with a "move to register" or "extload into register" instruction, then
647 // permute it into place, if the idx is a constant and if the idx is
648 // supported by the target.
649 EVT VT = Tmp1.getValueType();
650 EVT EltVT = VT.getVectorElementType();
651 EVT IdxVT = Tmp3.getValueType();
652 EVT PtrVT = TLI.getPointerTy();
653 SDValue StackPtr = DAG.CreateStackTemporary(VT);
655 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
658 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
659 PseudoSourceValue::getFixedStack(SPFI), 0,
662 // Truncate or zero extend offset to target pointer type.
663 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
664 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
665 // Add the offset to the index.
666 unsigned EltSize = EltVT.getSizeInBits()/8;
667 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
668 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
669 // Store the scalar value.
670 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
671 PseudoSourceValue::getFixedStack(SPFI), 0, EltVT,
673 // Load the updated vector.
674 return DAG.getLoad(VT, dl, Ch, StackPtr,
675 PseudoSourceValue::getFixedStack(SPFI), 0,
680 SDValue SelectionDAGLegalize::
681 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
682 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
683 // SCALAR_TO_VECTOR requires that the type of the value being inserted
684 // match the element type of the vector being created, except for
685 // integers in which case the inserted value can be over width.
686 EVT EltVT = Vec.getValueType().getVectorElementType();
687 if (Val.getValueType() == EltVT ||
688 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
689 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
690 Vec.getValueType(), Val);
692 unsigned NumElts = Vec.getValueType().getVectorNumElements();
693 // We generate a shuffle of InVec and ScVec, so the shuffle mask
694 // should be 0,1,2,3,4,5... with the appropriate element replaced with
696 SmallVector<int, 8> ShufOps;
697 for (unsigned i = 0; i != NumElts; ++i)
698 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
700 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
704 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
707 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
708 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
709 // FIXME: We shouldn't do this for TargetConstantFP's.
710 // FIXME: move this to the DAG Combiner! Note that we can't regress due
711 // to phase ordering between legalized code and the dag combiner. This
712 // probably means that we need to integrate dag combiner and legalizer
714 // We generally can't do this one for long doubles.
715 SDValue Tmp1 = ST->getChain();
716 SDValue Tmp2 = ST->getBasePtr();
718 int SVOffset = ST->getSrcValueOffset();
719 unsigned Alignment = ST->getAlignment();
720 bool isVolatile = ST->isVolatile();
721 bool isNonTemporal = ST->isNonTemporal();
722 DebugLoc dl = ST->getDebugLoc();
723 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
724 if (CFP->getValueType(0) == MVT::f32 &&
725 getTypeAction(MVT::i32) == Legal) {
726 Tmp3 = DAG.getConstant(CFP->getValueAPF().
727 bitcastToAPInt().zextOrTrunc(32),
729 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
730 SVOffset, isVolatile, isNonTemporal, Alignment);
731 } else if (CFP->getValueType(0) == MVT::f64) {
732 // If this target supports 64-bit registers, do a single 64-bit store.
733 if (getTypeAction(MVT::i64) == Legal) {
734 Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
735 zextOrTrunc(64), MVT::i64);
736 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
737 SVOffset, isVolatile, isNonTemporal, Alignment);
738 } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
739 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
740 // stores. If the target supports neither 32- nor 64-bits, this
741 // xform is certainly not worth it.
742 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
743 SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
744 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
745 if (TLI.isBigEndian()) std::swap(Lo, Hi);
747 Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
748 SVOffset, isVolatile, isNonTemporal, Alignment);
749 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
750 DAG.getIntPtrConstant(4));
751 Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
752 isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
754 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
761 /// LegalizeOp - We know that the specified value has a legal type, and
762 /// that its operands are legal. Now ensure that the operation itself
763 /// is legal, recursively ensuring that the operands' operations remain
765 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
766 if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
769 SDNode *Node = Op.getNode();
770 DebugLoc dl = Node->getDebugLoc();
772 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
773 assert(getTypeAction(Node->getValueType(i)) == Legal &&
774 "Unexpected illegal type!");
776 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
777 assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
778 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
779 "Unexpected illegal type!");
781 // Note that LegalizeOp may be reentered even from single-use nodes, which
782 // means that we always must cache transformed nodes.
783 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
784 if (I != LegalizedNodes.end()) return I->second;
786 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
788 bool isCustom = false;
790 // Figure out the correct action; the way to query this varies by opcode
791 TargetLowering::LegalizeAction Action;
792 bool SimpleFinishLegalizing = true;
793 switch (Node->getOpcode()) {
794 case ISD::INTRINSIC_W_CHAIN:
795 case ISD::INTRINSIC_WO_CHAIN:
796 case ISD::INTRINSIC_VOID:
799 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
801 case ISD::SINT_TO_FP:
802 case ISD::UINT_TO_FP:
803 case ISD::EXTRACT_VECTOR_ELT:
804 Action = TLI.getOperationAction(Node->getOpcode(),
805 Node->getOperand(0).getValueType());
807 case ISD::FP_ROUND_INREG:
808 case ISD::SIGN_EXTEND_INREG: {
809 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
810 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
816 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
817 Node->getOpcode() == ISD::SETCC ? 2 : 1;
818 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
819 EVT OpVT = Node->getOperand(CompareOperand).getValueType();
820 ISD::CondCode CCCode =
821 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
822 Action = TLI.getCondCodeAction(CCCode, OpVT);
823 if (Action == TargetLowering::Legal) {
824 if (Node->getOpcode() == ISD::SELECT_CC)
825 Action = TLI.getOperationAction(Node->getOpcode(),
826 Node->getValueType(0));
828 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
834 // FIXME: Model these properly. LOAD and STORE are complicated, and
835 // STORE expects the unlegalized operand in some cases.
836 SimpleFinishLegalizing = false;
838 case ISD::CALLSEQ_START:
839 case ISD::CALLSEQ_END:
840 // FIXME: This shouldn't be necessary. These nodes have special properties
841 // dealing with the recursive nature of legalization. Removing this
842 // special case should be done as part of making LegalizeDAG non-recursive.
843 SimpleFinishLegalizing = false;
845 case ISD::EXTRACT_ELEMENT:
846 case ISD::FLT_ROUNDS_:
854 case ISD::MERGE_VALUES:
856 case ISD::FRAME_TO_ARGS_OFFSET:
857 // These operations lie about being legal: when they claim to be legal,
858 // they should actually be expanded.
859 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
860 if (Action == TargetLowering::Legal)
861 Action = TargetLowering::Expand;
863 case ISD::TRAMPOLINE:
865 case ISD::RETURNADDR:
866 // These operations lie about being legal: when they claim to be legal,
867 // they should actually be custom-lowered.
868 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
869 if (Action == TargetLowering::Legal)
870 Action = TargetLowering::Custom;
872 case ISD::BUILD_VECTOR:
873 // A weird case: legalization for BUILD_VECTOR never legalizes the
875 // FIXME: This really sucks... changing it isn't semantically incorrect,
876 // but it massively pessimizes the code for floating-point BUILD_VECTORs
877 // because ConstantFP operands get legalized into constant pool loads
878 // before the BUILD_VECTOR code can see them. It doesn't usually bite,
879 // though, because BUILD_VECTORS usually get lowered into other nodes
880 // which get legalized properly.
881 SimpleFinishLegalizing = false;
884 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
885 Action = TargetLowering::Legal;
887 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
892 if (SimpleFinishLegalizing) {
893 SmallVector<SDValue, 8> Ops, ResultVals;
894 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
895 Ops.push_back(LegalizeOp(Node->getOperand(i)));
896 switch (Node->getOpcode()) {
903 // Branches tweak the chain to include LastCALLSEQ_END
904 Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
906 Ops[0] = LegalizeOp(Ops[0]);
907 LastCALLSEQ_END = DAG.getEntryNode();
914 // Legalizing shifts/rotates requires adjusting the shift amount
915 // to the appropriate width.
916 if (!Ops[1].getValueType().isVector())
917 Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
922 // Legalizing shifts/rotates requires adjusting the shift amount
923 // to the appropriate width.
924 if (!Ops[2].getValueType().isVector())
925 Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[2]));
929 Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(),
932 case TargetLowering::Legal:
933 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
934 ResultVals.push_back(Result.getValue(i));
936 case TargetLowering::Custom:
937 // FIXME: The handling for custom lowering with multiple results is
939 Tmp1 = TLI.LowerOperation(Result, DAG);
940 if (Tmp1.getNode()) {
941 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
943 ResultVals.push_back(Tmp1);
945 ResultVals.push_back(Tmp1.getValue(i));
951 case TargetLowering::Expand:
952 ExpandNode(Result.getNode(), ResultVals);
954 case TargetLowering::Promote:
955 PromoteNode(Result.getNode(), ResultVals);
958 if (!ResultVals.empty()) {
959 for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
960 if (ResultVals[i] != SDValue(Node, i))
961 ResultVals[i] = LegalizeOp(ResultVals[i]);
962 AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
964 return ResultVals[Op.getResNo()];
968 switch (Node->getOpcode()) {
975 assert(0 && "Do not know how to legalize this operator!");
977 case ISD::BUILD_VECTOR:
978 switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
979 default: assert(0 && "This action is not supported yet!");
980 case TargetLowering::Custom:
981 Tmp3 = TLI.LowerOperation(Result, DAG);
982 if (Tmp3.getNode()) {
987 case TargetLowering::Expand:
988 Result = ExpandBUILD_VECTOR(Result.getNode());
992 case ISD::CALLSEQ_START: {
993 SDNode *CallEnd = FindCallEndFromCallStart(Node);
995 // Recursively Legalize all of the inputs of the call end that do not lead
996 // to this call start. This ensures that any libcalls that need be inserted
997 // are inserted *before* the CALLSEQ_START.
998 {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
999 for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1000 LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1004 // Now that we legalized all of the inputs (which may have inserted
1005 // libcalls) create the new CALLSEQ_START node.
1006 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1008 // Merge in the last call, to ensure that this call start after the last
1010 if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1011 Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1012 Tmp1, LastCALLSEQ_END);
1013 Tmp1 = LegalizeOp(Tmp1);
1016 // Do not try to legalize the target-specific arguments (#1+).
1017 if (Tmp1 != Node->getOperand(0)) {
1018 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1020 Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1023 // Remember that the CALLSEQ_START is legalized.
1024 AddLegalizedOperand(Op.getValue(0), Result);
1025 if (Node->getNumValues() == 2) // If this has a flag result, remember it.
1026 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1028 // Now that the callseq_start and all of the non-call nodes above this call
1029 // sequence have been legalized, legalize the call itself. During this
1030 // process, no libcalls can/will be inserted, guaranteeing that no calls
1032 assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1033 // Note that we are selecting this call!
1034 LastCALLSEQ_END = SDValue(CallEnd, 0);
1035 IsLegalizingCall = true;
1037 // Legalize the call, starting from the CALLSEQ_END.
1038 LegalizeOp(LastCALLSEQ_END);
1039 assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1042 case ISD::CALLSEQ_END:
1043 // If the CALLSEQ_START node hasn't been legalized first, legalize it. This
1044 // will cause this node to be legalized as well as handling libcalls right.
1045 if (LastCALLSEQ_END.getNode() != Node) {
1046 LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1047 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1048 assert(I != LegalizedNodes.end() &&
1049 "Legalizing the call start should have legalized this node!");
1053 // Otherwise, the call start has been legalized and everything is going
1054 // according to plan. Just legalize ourselves normally here.
1055 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1056 // Do not try to legalize the target-specific arguments (#1+), except for
1057 // an optional flag input.
1058 if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1059 if (Tmp1 != Node->getOperand(0)) {
1060 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1062 Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1065 Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1066 if (Tmp1 != Node->getOperand(0) ||
1067 Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1068 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1071 Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1074 assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1075 // This finishes up call legalization.
1076 IsLegalizingCall = false;
1078 // If the CALLSEQ_END node has a flag, remember that we legalized it.
1079 AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1080 if (Node->getNumValues() == 2)
1081 AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1082 return Result.getValue(Op.getResNo());
1084 LoadSDNode *LD = cast<LoadSDNode>(Node);
1085 Tmp1 = LegalizeOp(LD->getChain()); // Legalize the chain.
1086 Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1088 ISD::LoadExtType ExtType = LD->getExtensionType();
1089 if (ExtType == ISD::NON_EXTLOAD) {
1090 EVT VT = Node->getValueType(0);
1091 Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1092 Tmp3 = Result.getValue(0);
1093 Tmp4 = Result.getValue(1);
1095 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1096 default: assert(0 && "This action is not supported yet!");
1097 case TargetLowering::Legal:
1098 // If this is an unaligned load and the target doesn't support it,
1100 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1101 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1102 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1103 if (LD->getAlignment() < ABIAlignment){
1104 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1106 Tmp3 = Result.getOperand(0);
1107 Tmp4 = Result.getOperand(1);
1108 Tmp3 = LegalizeOp(Tmp3);
1109 Tmp4 = LegalizeOp(Tmp4);
1113 case TargetLowering::Custom:
1114 Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1115 if (Tmp1.getNode()) {
1116 Tmp3 = LegalizeOp(Tmp1);
1117 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1120 case TargetLowering::Promote: {
1121 // Only promote a load of vector type to another.
1122 assert(VT.isVector() && "Cannot promote this load!");
1123 // Change base type to a different vector type.
1124 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1126 Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1127 LD->getSrcValueOffset(),
1128 LD->isVolatile(), LD->isNonTemporal(),
1129 LD->getAlignment());
1130 Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
1131 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1135 // Since loads produce two values, make sure to remember that we
1136 // legalized both of them.
1137 AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1138 AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1139 return Op.getResNo() ? Tmp4 : Tmp3;
1141 EVT SrcVT = LD->getMemoryVT();
1142 unsigned SrcWidth = SrcVT.getSizeInBits();
1143 int SVOffset = LD->getSrcValueOffset();
1144 unsigned Alignment = LD->getAlignment();
1145 bool isVolatile = LD->isVolatile();
1146 bool isNonTemporal = LD->isNonTemporal();
1148 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1149 // Some targets pretend to have an i1 loading operation, and actually
1150 // load an i8. This trick is correct for ZEXTLOAD because the top 7
1151 // bits are guaranteed to be zero; it helps the optimizers understand
1152 // that these bits are zero. It is also useful for EXTLOAD, since it
1153 // tells the optimizers that those bits are undefined. It would be
1154 // nice to have an effective generic way of getting these benefits...
1155 // Until such a way is found, don't insist on promoting i1 here.
1156 (SrcVT != MVT::i1 ||
1157 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1158 // Promote to a byte-sized load if not loading an integral number of
1159 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1160 unsigned NewWidth = SrcVT.getStoreSizeInBits();
1161 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1164 // The extra bits are guaranteed to be zero, since we stored them that
1165 // way. A zext load from NVT thus automatically gives zext from SrcVT.
1167 ISD::LoadExtType NewExtType =
1168 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1170 Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1171 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1172 NVT, isVolatile, isNonTemporal, Alignment);
1174 Ch = Result.getValue(1); // The chain.
1176 if (ExtType == ISD::SEXTLOAD)
1177 // Having the top bits zero doesn't help when sign extending.
1178 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1179 Result.getValueType(),
1180 Result, DAG.getValueType(SrcVT));
1181 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1182 // All the top bits are guaranteed to be zero - inform the optimizers.
1183 Result = DAG.getNode(ISD::AssertZext, dl,
1184 Result.getValueType(), Result,
1185 DAG.getValueType(SrcVT));
1187 Tmp1 = LegalizeOp(Result);
1188 Tmp2 = LegalizeOp(Ch);
1189 } else if (SrcWidth & (SrcWidth - 1)) {
1190 // If not loading a power-of-2 number of bits, expand as two loads.
1191 assert(!SrcVT.isVector() && "Unsupported extload!");
1192 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1193 assert(RoundWidth < SrcWidth);
1194 unsigned ExtraWidth = SrcWidth - RoundWidth;
1195 assert(ExtraWidth < RoundWidth);
1196 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1197 "Load size not an integral number of bytes!");
1198 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1199 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1201 unsigned IncrementSize;
1203 if (TLI.isLittleEndian()) {
1204 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1205 // Load the bottom RoundWidth bits.
1206 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1207 Node->getValueType(0), Tmp1, Tmp2,
1208 LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1209 isNonTemporal, Alignment);
1211 // Load the remaining ExtraWidth bits.
1212 IncrementSize = RoundWidth / 8;
1213 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1214 DAG.getIntPtrConstant(IncrementSize));
1215 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1216 LD->getSrcValue(), SVOffset + IncrementSize,
1217 ExtraVT, isVolatile, isNonTemporal,
1218 MinAlign(Alignment, IncrementSize));
1220 // Build a factor node to remember that this load is independent of the
1222 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1225 // Move the top bits to the right place.
1226 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1227 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1229 // Join the hi and lo parts.
1230 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1232 // Big endian - avoid unaligned loads.
1233 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1234 // Load the top RoundWidth bits.
1235 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1236 LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1237 isNonTemporal, Alignment);
1239 // Load the remaining ExtraWidth bits.
1240 IncrementSize = RoundWidth / 8;
1241 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1242 DAG.getIntPtrConstant(IncrementSize));
1243 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1244 Node->getValueType(0), Tmp1, Tmp2,
1245 LD->getSrcValue(), SVOffset + IncrementSize,
1246 ExtraVT, isVolatile, isNonTemporal,
1247 MinAlign(Alignment, IncrementSize));
1249 // Build a factor node to remember that this load is independent of the
1251 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1254 // Move the top bits to the right place.
1255 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1256 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1258 // Join the hi and lo parts.
1259 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1262 Tmp1 = LegalizeOp(Result);
1263 Tmp2 = LegalizeOp(Ch);
1265 switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1266 default: assert(0 && "This action is not supported yet!");
1267 case TargetLowering::Custom:
1270 case TargetLowering::Legal:
1271 Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1272 Tmp1 = Result.getValue(0);
1273 Tmp2 = Result.getValue(1);
1276 Tmp3 = TLI.LowerOperation(Result, DAG);
1277 if (Tmp3.getNode()) {
1278 Tmp1 = LegalizeOp(Tmp3);
1279 Tmp2 = LegalizeOp(Tmp3.getValue(1));
1282 // If this is an unaligned load and the target doesn't support it,
1284 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1285 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1286 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1287 if (LD->getAlignment() < ABIAlignment){
1288 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1290 Tmp1 = Result.getOperand(0);
1291 Tmp2 = Result.getOperand(1);
1292 Tmp1 = LegalizeOp(Tmp1);
1293 Tmp2 = LegalizeOp(Tmp2);
1298 case TargetLowering::Expand:
1299 // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1300 // f128 = EXTLOAD {f32,f64} too
1301 if ((SrcVT == MVT::f32 && (Node->getValueType(0) == MVT::f64 ||
1302 Node->getValueType(0) == MVT::f128)) ||
1303 (SrcVT == MVT::f64 && Node->getValueType(0) == MVT::f128)) {
1304 SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1305 LD->getSrcValueOffset(),
1306 LD->isVolatile(), LD->isNonTemporal(),
1307 LD->getAlignment());
1308 Result = DAG.getNode(ISD::FP_EXTEND, dl,
1309 Node->getValueType(0), Load);
1310 Tmp1 = LegalizeOp(Result); // Relegalize new nodes.
1311 Tmp2 = LegalizeOp(Load.getValue(1));
1314 assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1315 // Turn the unsupported load into an EXTLOAD followed by an explicit
1316 // zero/sign extend inreg.
1317 Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1318 Tmp1, Tmp2, LD->getSrcValue(),
1319 LD->getSrcValueOffset(), SrcVT,
1320 LD->isVolatile(), LD->isNonTemporal(),
1321 LD->getAlignment());
1323 if (ExtType == ISD::SEXTLOAD)
1324 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1325 Result.getValueType(),
1326 Result, DAG.getValueType(SrcVT));
1328 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1329 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1330 Tmp2 = LegalizeOp(Result.getValue(1)); // Relegalize new nodes.
1335 // Since loads produce two values, make sure to remember that we legalized
1337 AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1338 AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1339 return Op.getResNo() ? Tmp2 : Tmp1;
1343 StoreSDNode *ST = cast<StoreSDNode>(Node);
1344 Tmp1 = LegalizeOp(ST->getChain()); // Legalize the chain.
1345 Tmp2 = LegalizeOp(ST->getBasePtr()); // Legalize the pointer.
1346 int SVOffset = ST->getSrcValueOffset();
1347 unsigned Alignment = ST->getAlignment();
1348 bool isVolatile = ST->isVolatile();
1349 bool isNonTemporal = ST->isNonTemporal();
1351 if (!ST->isTruncatingStore()) {
1352 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1353 Result = SDValue(OptStore, 0);
1358 Tmp3 = LegalizeOp(ST->getValue());
1359 Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1362 EVT VT = Tmp3.getValueType();
1363 switch (TLI.getOperationAction(ISD::STORE, VT)) {
1364 default: assert(0 && "This action is not supported yet!");
1365 case TargetLowering::Legal:
1366 // If this is an unaligned store and the target doesn't support it,
1368 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1369 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1370 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1371 if (ST->getAlignment() < ABIAlignment)
1372 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1376 case TargetLowering::Custom:
1377 Tmp1 = TLI.LowerOperation(Result, DAG);
1378 if (Tmp1.getNode()) Result = Tmp1;
1380 case TargetLowering::Promote:
1381 assert(VT.isVector() && "Unknown legal promote case!");
1382 Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
1383 TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1384 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1385 ST->getSrcValue(), SVOffset, isVolatile,
1386 isNonTemporal, Alignment);
1392 Tmp3 = LegalizeOp(ST->getValue());
1394 EVT StVT = ST->getMemoryVT();
1395 unsigned StWidth = StVT.getSizeInBits();
1397 if (StWidth != StVT.getStoreSizeInBits()) {
1398 // Promote to a byte-sized store with upper bits zero if not
1399 // storing an integral number of bytes. For example, promote
1400 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1401 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1402 StVT.getStoreSizeInBits());
1403 Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1404 Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1405 SVOffset, NVT, isVolatile, isNonTemporal,
1407 } else if (StWidth & (StWidth - 1)) {
1408 // If not storing a power-of-2 number of bits, expand as two stores.
1409 assert(!StVT.isVector() && "Unsupported truncstore!");
1410 unsigned RoundWidth = 1 << Log2_32(StWidth);
1411 assert(RoundWidth < StWidth);
1412 unsigned ExtraWidth = StWidth - RoundWidth;
1413 assert(ExtraWidth < RoundWidth);
1414 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1415 "Store size not an integral number of bytes!");
1416 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1417 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1419 unsigned IncrementSize;
1421 if (TLI.isLittleEndian()) {
1422 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1423 // Store the bottom RoundWidth bits.
1424 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1426 isVolatile, isNonTemporal, Alignment);
1428 // Store the remaining ExtraWidth bits.
1429 IncrementSize = RoundWidth / 8;
1430 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1431 DAG.getIntPtrConstant(IncrementSize));
1432 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1433 DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1434 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1435 SVOffset + IncrementSize, ExtraVT, isVolatile,
1437 MinAlign(Alignment, IncrementSize));
1439 // Big endian - avoid unaligned stores.
1440 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1441 // Store the top RoundWidth bits.
1442 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1443 DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1444 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1445 SVOffset, RoundVT, isVolatile, isNonTemporal,
1448 // Store the remaining ExtraWidth bits.
1449 IncrementSize = RoundWidth / 8;
1450 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1451 DAG.getIntPtrConstant(IncrementSize));
1452 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1453 SVOffset + IncrementSize, ExtraVT, isVolatile,
1455 MinAlign(Alignment, IncrementSize));
1458 // The order of the stores doesn't matter.
1459 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1461 if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1462 Tmp2 != ST->getBasePtr())
1463 Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1466 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1467 default: assert(0 && "This action is not supported yet!");
1468 case TargetLowering::Legal:
1469 // If this is an unaligned store and the target doesn't support it,
1471 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1472 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1473 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1474 if (ST->getAlignment() < ABIAlignment)
1475 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1479 case TargetLowering::Custom:
1480 Result = TLI.LowerOperation(Result, DAG);
1483 // TRUNCSTORE:i16 i32 -> STORE i16
1484 assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1485 Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1486 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1487 SVOffset, isVolatile, isNonTemporal,
1496 assert(Result.getValueType() == Op.getValueType() &&
1497 "Bad legalization!");
1499 // Make sure that the generated code is itself legal.
1501 Result = LegalizeOp(Result);
1503 // Note that LegalizeOp may be reentered even from single-use nodes, which
1504 // means that we always must cache transformed nodes.
1505 AddLegalizedOperand(Op, Result);
1509 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1510 SDValue Vec = Op.getOperand(0);
1511 SDValue Idx = Op.getOperand(1);
1512 DebugLoc dl = Op.getDebugLoc();
1513 // Store the value to a temporary stack slot, then LOAD the returned part.
1514 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1515 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0,
1518 // Add the offset to the index.
1520 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1521 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1522 DAG.getConstant(EltSize, Idx.getValueType()));
1524 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1525 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1527 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1529 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1531 if (Op.getValueType().isVector())
1532 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0,
1535 return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1536 NULL, 0, Vec.getValueType().getVectorElementType(),
1540 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1541 // We can't handle this case efficiently. Allocate a sufficiently
1542 // aligned object on the stack, store each element into it, then load
1543 // the result as a vector.
1544 // Create the stack frame object.
1545 EVT VT = Node->getValueType(0);
1546 EVT EltVT = VT.getVectorElementType();
1547 DebugLoc dl = Node->getDebugLoc();
1548 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1549 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1550 const Value *SV = PseudoSourceValue::getFixedStack(FI);
1552 // Emit a store of each element to the stack slot.
1553 SmallVector<SDValue, 8> Stores;
1554 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1555 // Store (in the right endianness) the elements to memory.
1556 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1557 // Ignore undef elements.
1558 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1560 unsigned Offset = TypeByteSize*i;
1562 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1563 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1565 // If the destination vector element type is narrower than the source
1566 // element type, only store the bits necessary.
1567 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1568 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1569 Node->getOperand(i), Idx, SV, Offset,
1570 EltVT, false, false, 0));
1572 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1573 Node->getOperand(i), Idx, SV, Offset,
1578 if (!Stores.empty()) // Not all undef elements?
1579 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1580 &Stores[0], Stores.size());
1582 StoreChain = DAG.getEntryNode();
1584 // Result is a load from the stack slot.
1585 return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0, false, false, 0);
1588 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1589 DebugLoc dl = Node->getDebugLoc();
1590 SDValue Tmp1 = Node->getOperand(0);
1591 SDValue Tmp2 = Node->getOperand(1);
1593 // Get the sign bit of the RHS. First obtain a value that has the same
1594 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1596 EVT FloatVT = Tmp2.getValueType();
1597 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1598 if (isTypeLegal(IVT)) {
1599 // Convert to an integer with the same sign bit.
1600 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
1602 // Store the float to memory, then load the sign part out as an integer.
1603 MVT LoadTy = TLI.getPointerTy();
1604 // First create a temporary that is aligned for both the load and store.
1605 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1606 // Then store the float to it.
1608 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, NULL, 0,
1610 if (TLI.isBigEndian()) {
1611 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1612 // Load out a legal integer with the same sign bit as the float.
1613 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, NULL, 0, false, false, 0);
1614 } else { // Little endian
1615 SDValue LoadPtr = StackPtr;
1616 // The float may be wider than the integer we are going to load. Advance
1617 // the pointer so that the loaded integer will contain the sign bit.
1618 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1619 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1620 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1621 LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1622 // Load a legal integer containing the sign bit.
1623 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, NULL, 0, false, false, 0);
1624 // Move the sign bit to the top bit of the loaded integer.
1625 unsigned BitShift = LoadTy.getSizeInBits() -
1626 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1627 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1629 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1630 DAG.getConstant(BitShift,TLI.getShiftAmountTy()));
1633 // Now get the sign bit proper, by seeing whether the value is negative.
1634 SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1635 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1637 // Get the absolute value of the result.
1638 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1639 // Select between the nabs and abs value based on the sign bit of
1641 return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1642 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1646 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1647 SmallVectorImpl<SDValue> &Results) {
1648 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1649 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1650 " not tell us which reg is the stack pointer!");
1651 DebugLoc dl = Node->getDebugLoc();
1652 EVT VT = Node->getValueType(0);
1653 SDValue Tmp1 = SDValue(Node, 0);
1654 SDValue Tmp2 = SDValue(Node, 1);
1655 SDValue Tmp3 = Node->getOperand(2);
1656 SDValue Chain = Tmp1.getOperand(0);
1658 // Chain the dynamic stack allocation so that it doesn't modify the stack
1659 // pointer when other instructions are using the stack.
1660 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1662 SDValue Size = Tmp2.getOperand(1);
1663 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1664 Chain = SP.getValue(1);
1665 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1666 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment();
1667 if (Align > StackAlign)
1668 SP = DAG.getNode(ISD::AND, dl, VT, SP,
1669 DAG.getConstant(-(uint64_t)Align, VT));
1670 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1671 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1673 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1674 DAG.getIntPtrConstant(0, true), SDValue());
1676 Results.push_back(Tmp1);
1677 Results.push_back(Tmp2);
1680 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1681 /// condition code CC on the current target. This routine expands SETCC with
1682 /// illegal condition code into AND / OR of multiple SETCC values.
1683 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1684 SDValue &LHS, SDValue &RHS,
1687 EVT OpVT = LHS.getValueType();
1688 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1689 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1690 default: assert(0 && "Unknown condition code action!");
1691 case TargetLowering::Legal:
1694 case TargetLowering::Expand: {
1695 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1698 default: assert(0 && "Don't know how to expand this condition!");
1699 case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO; Opc = ISD::AND; break;
1700 case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1701 case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1702 case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1703 case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1704 case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1705 case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1706 case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1707 case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1708 case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1709 case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1710 case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1711 // FIXME: Implement more expansions.
1714 SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1715 SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1716 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1724 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1725 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1726 /// a load from the stack slot to DestVT, extending it if needed.
1727 /// The resultant code need not be legal.
1728 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1732 // Create the stack frame object.
1734 TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1735 getTypeForEVT(*DAG.getContext()));
1736 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1738 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1739 int SPFI = StackPtrFI->getIndex();
1740 const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
1742 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1743 unsigned SlotSize = SlotVT.getSizeInBits();
1744 unsigned DestSize = DestVT.getSizeInBits();
1745 const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1746 unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1748 // Emit a store to the stack slot. Use a truncstore if the input value is
1749 // later than DestVT.
1752 if (SrcSize > SlotSize)
1753 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1754 SV, 0, SlotVT, false, false, SrcAlign);
1756 assert(SrcSize == SlotSize && "Invalid store");
1757 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1758 SV, 0, false, false, SrcAlign);
1761 // Result is a load from the stack slot.
1762 if (SlotSize == DestSize)
1763 return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, false,
1766 assert(SlotSize < DestSize && "Unknown extension!");
1767 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
1768 false, false, DestAlign);
1771 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1772 DebugLoc dl = Node->getDebugLoc();
1773 // Create a vector sized/aligned stack slot, store the value to element #0,
1774 // then load the whole vector back out.
1775 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1777 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1778 int SPFI = StackPtrFI->getIndex();
1780 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1782 PseudoSourceValue::getFixedStack(SPFI), 0,
1783 Node->getValueType(0).getVectorElementType(),
1785 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1786 PseudoSourceValue::getFixedStack(SPFI), 0,
1791 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1792 /// support the operation, but do support the resultant vector type.
1793 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1794 unsigned NumElems = Node->getNumOperands();
1795 SDValue Value1, Value2;
1796 DebugLoc dl = Node->getDebugLoc();
1797 EVT VT = Node->getValueType(0);
1798 EVT OpVT = Node->getOperand(0).getValueType();
1799 EVT EltVT = VT.getVectorElementType();
1801 // If the only non-undef value is the low element, turn this into a
1802 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1803 bool isOnlyLowElement = true;
1804 bool MoreThanTwoValues = false;
1805 bool isConstant = true;
1806 for (unsigned i = 0; i < NumElems; ++i) {
1807 SDValue V = Node->getOperand(i);
1808 if (V.getOpcode() == ISD::UNDEF)
1811 isOnlyLowElement = false;
1812 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1815 if (!Value1.getNode()) {
1817 } else if (!Value2.getNode()) {
1820 } else if (V != Value1 && V != Value2) {
1821 MoreThanTwoValues = true;
1825 if (!Value1.getNode())
1826 return DAG.getUNDEF(VT);
1828 if (isOnlyLowElement)
1829 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1831 // If all elements are constants, create a load from the constant pool.
1833 std::vector<Constant*> CV;
1834 for (unsigned i = 0, e = NumElems; i != e; ++i) {
1835 if (ConstantFPSDNode *V =
1836 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1837 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1838 } else if (ConstantSDNode *V =
1839 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1841 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1843 // If OpVT and EltVT don't match, EltVT is not legal and the
1844 // element values have been promoted/truncated earlier. Undo this;
1845 // we don't want a v16i8 to become a v16i32 for example.
1846 const ConstantInt *CI = V->getConstantIntValue();
1847 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1848 CI->getZExtValue()));
1851 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1852 const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1853 CV.push_back(UndefValue::get(OpNTy));
1856 Constant *CP = ConstantVector::get(CV);
1857 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1858 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1859 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1860 PseudoSourceValue::getConstantPool(), 0,
1861 false, false, Alignment);
1864 if (!MoreThanTwoValues) {
1865 SmallVector<int, 8> ShuffleVec(NumElems, -1);
1866 for (unsigned i = 0; i < NumElems; ++i) {
1867 SDValue V = Node->getOperand(i);
1868 if (V.getOpcode() == ISD::UNDEF)
1870 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1872 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1873 // Get the splatted value into the low element of a vector register.
1874 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1876 if (Value2.getNode())
1877 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1879 Vec2 = DAG.getUNDEF(VT);
1881 // Return shuffle(LowValVec, undef, <0,0,0,0>)
1882 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1886 // Otherwise, we can't handle this case efficiently.
1887 return ExpandVectorBuildThroughStack(Node);
1890 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1891 // does not fit into a register, return the lo part and set the hi part to the
1892 // by-reg argument. If it does fit into a single register, return the result
1893 // and leave the Hi part unset.
1894 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1896 assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
1897 // The input chain to this libcall is the entry node of the function.
1898 // Legalizing the call will automatically add the previous call to the
1900 SDValue InChain = DAG.getEntryNode();
1902 TargetLowering::ArgListTy Args;
1903 TargetLowering::ArgListEntry Entry;
1904 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1905 EVT ArgVT = Node->getOperand(i).getValueType();
1906 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1907 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1908 Entry.isSExt = isSigned;
1909 Entry.isZExt = !isSigned;
1910 Args.push_back(Entry);
1912 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1913 TLI.getPointerTy());
1915 // Splice the libcall in wherever FindInputOutputChains tells us to.
1916 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1917 std::pair<SDValue, SDValue> CallInfo =
1918 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1919 0, TLI.getLibcallCallingConv(LC), false,
1920 /*isReturnValueUsed=*/true,
1921 Callee, Args, DAG, Node->getDebugLoc());
1923 // Legalize the call sequence, starting with the chain. This will advance
1924 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1925 // was added by LowerCallTo (guaranteeing proper serialization of calls).
1926 LegalizeOp(CallInfo.second);
1927 return CallInfo.first;
1930 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
1931 RTLIB::Libcall Call_F32,
1932 RTLIB::Libcall Call_F64,
1933 RTLIB::Libcall Call_F80,
1934 RTLIB::Libcall Call_PPCF128) {
1936 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1937 default: assert(0 && "Unexpected request for libcall!");
1938 case MVT::f32: LC = Call_F32; break;
1939 case MVT::f64: LC = Call_F64; break;
1940 case MVT::f80: LC = Call_F80; break;
1941 case MVT::ppcf128: LC = Call_PPCF128; break;
1943 return ExpandLibCall(LC, Node, false);
1946 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
1947 RTLIB::Libcall Call_I8,
1948 RTLIB::Libcall Call_I16,
1949 RTLIB::Libcall Call_I32,
1950 RTLIB::Libcall Call_I64,
1951 RTLIB::Libcall Call_I128) {
1953 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1954 default: assert(0 && "Unexpected request for libcall!");
1955 case MVT::i8: LC = Call_I8; break;
1956 case MVT::i16: LC = Call_I16; break;
1957 case MVT::i32: LC = Call_I32; break;
1958 case MVT::i64: LC = Call_I64; break;
1959 case MVT::i128: LC = Call_I128; break;
1961 return ExpandLibCall(LC, Node, isSigned);
1964 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
1965 /// INT_TO_FP operation of the specified operand when the target requests that
1966 /// we expand it. At this point, we know that the result and operand types are
1967 /// legal for the target.
1968 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
1972 if (Op0.getValueType() == MVT::i32) {
1973 // simple 32-bit [signed|unsigned] integer to float/double expansion
1975 // Get the stack frame index of a 8 byte buffer.
1976 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
1978 // word offset constant for Hi/Lo address computation
1979 SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
1980 // set up Hi and Lo (into buffer) address based on endian
1981 SDValue Hi = StackSlot;
1982 SDValue Lo = DAG.getNode(ISD::ADD, dl,
1983 TLI.getPointerTy(), StackSlot, WordOff);
1984 if (TLI.isLittleEndian())
1987 // if signed map to unsigned space
1990 // constant used to invert sign bit (signed to unsigned mapping)
1991 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
1992 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
1996 // store the lo of the constructed double - based on integer input
1997 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
1998 Op0Mapped, Lo, NULL, 0,
2000 // initial hi portion of constructed double
2001 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2002 // store the hi of the constructed double - biased exponent
2003 SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0,
2005 // load the constructed double
2006 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0,
2008 // FP constant to bias correct the final result
2009 SDValue Bias = DAG.getConstantFP(isSigned ?
2010 BitsToDouble(0x4330000080000000ULL) :
2011 BitsToDouble(0x4330000000000000ULL),
2013 // subtract the bias
2014 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2017 // handle final rounding
2018 if (DestVT == MVT::f64) {
2021 } else if (DestVT.bitsLT(MVT::f64)) {
2022 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2023 DAG.getIntPtrConstant(0));
2024 } else if (DestVT.bitsGT(MVT::f64)) {
2025 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2029 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2031 // Implementation of unsigned i64 to f64 following the algorithm in
2032 // __floatundidf in compiler_rt. This implementation has the advantage
2033 // of performing rounding correctly, both in the default rounding mode
2034 // and in all alternate rounding modes.
2035 // TODO: Generalize this for use with other types.
2036 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2038 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2039 SDValue TwoP84PlusTwoP52 =
2040 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2042 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2044 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2045 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2046 DAG.getConstant(32, MVT::i64));
2047 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2048 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2049 SDValue LoFlt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, LoOr);
2050 SDValue HiFlt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, HiOr);
2051 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt, TwoP84PlusTwoP52);
2052 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2055 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2057 SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2058 Op0, DAG.getConstant(0, Op0.getValueType()),
2060 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2061 SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2062 SignSet, Four, Zero);
2064 // If the sign bit of the integer is set, the large number will be treated
2065 // as a negative number. To counteract this, the dynamic code adds an
2066 // offset depending on the data type.
2068 switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2069 default: assert(0 && "Unsupported integer type!");
2070 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2071 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2072 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2073 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2075 if (TLI.isLittleEndian()) FF <<= 32;
2076 Constant *FudgeFactor = ConstantInt::get(
2077 Type::getInt64Ty(*DAG.getContext()), FF);
2079 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2080 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2081 CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2082 Alignment = std::min(Alignment, 4u);
2084 if (DestVT == MVT::f32)
2085 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2086 PseudoSourceValue::getConstantPool(), 0,
2087 false, false, Alignment);
2090 LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2091 DAG.getEntryNode(), CPIdx,
2092 PseudoSourceValue::getConstantPool(), 0,
2093 MVT::f32, false, false, Alignment));
2096 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2099 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2100 /// *INT_TO_FP operation of the specified operand when the target requests that
2101 /// we promote it. At this point, we know that the result and operand types are
2102 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2103 /// operation that takes a larger input.
2104 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2108 // First step, figure out the appropriate *INT_TO_FP operation to use.
2109 EVT NewInTy = LegalOp.getValueType();
2111 unsigned OpToUse = 0;
2113 // Scan for the appropriate larger type to use.
2115 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2116 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2118 // If the target supports SINT_TO_FP of this type, use it.
2119 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2120 OpToUse = ISD::SINT_TO_FP;
2123 if (isSigned) continue;
2125 // If the target supports UINT_TO_FP of this type, use it.
2126 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2127 OpToUse = ISD::UINT_TO_FP;
2131 // Otherwise, try a larger type.
2134 // Okay, we found the operation and type to use. Zero extend our input to the
2135 // desired type then run the operation on it.
2136 return DAG.getNode(OpToUse, dl, DestVT,
2137 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2138 dl, NewInTy, LegalOp));
2141 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2142 /// FP_TO_*INT operation of the specified operand when the target requests that
2143 /// we promote it. At this point, we know that the result and operand types are
2144 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2145 /// operation that returns a larger result.
2146 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2150 // First step, figure out the appropriate FP_TO*INT operation to use.
2151 EVT NewOutTy = DestVT;
2153 unsigned OpToUse = 0;
2155 // Scan for the appropriate larger type to use.
2157 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2158 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2160 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2161 OpToUse = ISD::FP_TO_SINT;
2165 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2166 OpToUse = ISD::FP_TO_UINT;
2170 // Otherwise, try a larger type.
2174 // Okay, we found the operation and type to use.
2175 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2177 // Truncate the result of the extended FP_TO_*INT operation to the desired
2179 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2182 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2184 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2185 EVT VT = Op.getValueType();
2186 EVT SHVT = TLI.getShiftAmountTy();
2187 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2188 switch (VT.getSimpleVT().SimpleTy) {
2189 default: assert(0 && "Unhandled Expand type in BSWAP!");
2191 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2192 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2193 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2195 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2196 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2197 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2198 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2199 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2200 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2201 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2202 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2203 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2205 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2206 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2207 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2208 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2209 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2210 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2211 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2212 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2213 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2214 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2215 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2216 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2217 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2218 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2219 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2220 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2221 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2222 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2223 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2224 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2225 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2229 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2231 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2234 default: assert(0 && "Cannot expand this yet!");
2236 static const uint64_t mask[6] = {
2237 0x5555555555555555ULL, 0x3333333333333333ULL,
2238 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2239 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2241 EVT VT = Op.getValueType();
2242 EVT ShVT = TLI.getShiftAmountTy();
2243 unsigned len = VT.getSizeInBits();
2244 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2245 //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2246 unsigned EltSize = VT.isVector() ?
2247 VT.getVectorElementType().getSizeInBits() : len;
2248 SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2249 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2250 Op = DAG.getNode(ISD::ADD, dl, VT,
2251 DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2252 DAG.getNode(ISD::AND, dl, VT,
2253 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2259 // for now, we do this:
2260 // x = x | (x >> 1);
2261 // x = x | (x >> 2);
2263 // x = x | (x >>16);
2264 // x = x | (x >>32); // for 64-bit input
2265 // return popcount(~x);
2267 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2268 EVT VT = Op.getValueType();
2269 EVT ShVT = TLI.getShiftAmountTy();
2270 unsigned len = VT.getSizeInBits();
2271 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2272 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2273 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2274 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2276 Op = DAG.getNOT(dl, Op, VT);
2277 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2280 // for now, we use: { return popcount(~x & (x - 1)); }
2281 // unless the target has ctlz but not ctpop, in which case we use:
2282 // { return 32 - nlz(~x & (x-1)); }
2283 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2284 EVT VT = Op.getValueType();
2285 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2286 DAG.getNOT(dl, Op, VT),
2287 DAG.getNode(ISD::SUB, dl, VT, Op,
2288 DAG.getConstant(1, VT)));
2289 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2290 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2291 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2292 return DAG.getNode(ISD::SUB, dl, VT,
2293 DAG.getConstant(VT.getSizeInBits(), VT),
2294 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2295 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2300 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2301 SmallVectorImpl<SDValue> &Results) {
2302 DebugLoc dl = Node->getDebugLoc();
2303 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2304 switch (Node->getOpcode()) {
2308 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2309 Results.push_back(Tmp1);
2312 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2314 case ISD::FRAMEADDR:
2315 case ISD::RETURNADDR:
2316 case ISD::FRAME_TO_ARGS_OFFSET:
2317 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2319 case ISD::FLT_ROUNDS_:
2320 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2322 case ISD::EH_RETURN:
2325 case ISD::MEMBARRIER:
2327 Results.push_back(Node->getOperand(0));
2329 case ISD::DYNAMIC_STACKALLOC:
2330 ExpandDYNAMIC_STACKALLOC(Node, Results);
2332 case ISD::MERGE_VALUES:
2333 for (unsigned i = 0; i < Node->getNumValues(); i++)
2334 Results.push_back(Node->getOperand(i));
2337 EVT VT = Node->getValueType(0);
2339 Results.push_back(DAG.getConstant(0, VT));
2341 assert(VT.isFloatingPoint() && "Unknown value type!");
2342 Results.push_back(DAG.getConstantFP(0, VT));
2347 // If this operation is not supported, lower it to 'abort()' call
2348 TargetLowering::ArgListTy Args;
2349 std::pair<SDValue, SDValue> CallResult =
2350 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2351 false, false, false, false, 0, CallingConv::C, false,
2352 /*isReturnValueUsed=*/true,
2353 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2355 Results.push_back(CallResult.second);
2359 case ISD::BIT_CONVERT:
2360 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2361 Node->getValueType(0), dl);
2362 Results.push_back(Tmp1);
2364 case ISD::FP_EXTEND:
2365 Tmp1 = EmitStackConvert(Node->getOperand(0),
2366 Node->getOperand(0).getValueType(),
2367 Node->getValueType(0), dl);
2368 Results.push_back(Tmp1);
2370 case ISD::SIGN_EXTEND_INREG: {
2371 // NOTE: we could fall back on load/store here too for targets without
2372 // SAR. However, it is doubtful that any exist.
2373 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2374 EVT VT = Node->getValueType(0);
2375 EVT ShiftAmountTy = TLI.getShiftAmountTy();
2378 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2379 ExtraVT.getScalarType().getSizeInBits();
2380 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2381 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2382 Node->getOperand(0), ShiftCst);
2383 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2384 Results.push_back(Tmp1);
2387 case ISD::FP_ROUND_INREG: {
2388 // The only way we can lower this is to turn it into a TRUNCSTORE,
2389 // EXTLOAD pair, targetting a temporary location (a stack slot).
2391 // NOTE: there is a choice here between constantly creating new stack
2392 // slots and always reusing the same one. We currently always create
2393 // new ones, as reuse may inhibit scheduling.
2394 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2395 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2396 Node->getValueType(0), dl);
2397 Results.push_back(Tmp1);
2400 case ISD::SINT_TO_FP:
2401 case ISD::UINT_TO_FP:
2402 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2403 Node->getOperand(0), Node->getValueType(0), dl);
2404 Results.push_back(Tmp1);
2406 case ISD::FP_TO_UINT: {
2407 SDValue True, False;
2408 EVT VT = Node->getOperand(0).getValueType();
2409 EVT NVT = Node->getValueType(0);
2410 const uint64_t zero[] = {0, 0};
2411 APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2412 APInt x = APInt::getSignBit(NVT.getSizeInBits());
2413 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2414 Tmp1 = DAG.getConstantFP(apf, VT);
2415 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2416 Node->getOperand(0),
2418 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2419 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2420 DAG.getNode(ISD::FSUB, dl, VT,
2421 Node->getOperand(0), Tmp1));
2422 False = DAG.getNode(ISD::XOR, dl, NVT, False,
2423 DAG.getConstant(x, NVT));
2424 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2425 Results.push_back(Tmp1);
2429 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2430 EVT VT = Node->getValueType(0);
2431 Tmp1 = Node->getOperand(0);
2432 Tmp2 = Node->getOperand(1);
2433 SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0,
2435 // Increment the pointer, VAList, to the next vaarg
2436 Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2437 DAG.getConstant(TLI.getTargetData()->
2438 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2439 TLI.getPointerTy()));
2440 // Store the incremented VAList to the legalized pointer
2441 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0,
2443 // Load the actual argument out of the pointer VAList
2444 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0,
2446 Results.push_back(Results[0].getValue(1));
2450 // This defaults to loading a pointer from the input and storing it to the
2451 // output, returning the chain.
2452 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2453 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2454 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2455 Node->getOperand(2), VS, 0, false, false, 0);
2456 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), VD, 0,
2458 Results.push_back(Tmp1);
2461 case ISD::EXTRACT_VECTOR_ELT:
2462 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2463 // This must be an access of the only element. Return it.
2464 Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
2465 Node->getOperand(0));
2467 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2468 Results.push_back(Tmp1);
2470 case ISD::EXTRACT_SUBVECTOR:
2471 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2473 case ISD::CONCAT_VECTORS: {
2474 Results.push_back(ExpandVectorBuildThroughStack(Node));
2477 case ISD::SCALAR_TO_VECTOR:
2478 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2480 case ISD::INSERT_VECTOR_ELT:
2481 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2482 Node->getOperand(1),
2483 Node->getOperand(2), dl));
2485 case ISD::VECTOR_SHUFFLE: {
2486 SmallVector<int, 8> Mask;
2487 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2489 EVT VT = Node->getValueType(0);
2490 EVT EltVT = VT.getVectorElementType();
2491 unsigned NumElems = VT.getVectorNumElements();
2492 SmallVector<SDValue, 8> Ops;
2493 for (unsigned i = 0; i != NumElems; ++i) {
2495 Ops.push_back(DAG.getUNDEF(EltVT));
2498 unsigned Idx = Mask[i];
2500 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2501 Node->getOperand(0),
2502 DAG.getIntPtrConstant(Idx)));
2504 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2505 Node->getOperand(1),
2506 DAG.getIntPtrConstant(Idx - NumElems)));
2508 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2509 Results.push_back(Tmp1);
2512 case ISD::EXTRACT_ELEMENT: {
2513 EVT OpTy = Node->getOperand(0).getValueType();
2514 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2516 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2517 DAG.getConstant(OpTy.getSizeInBits()/2,
2518 TLI.getShiftAmountTy()));
2519 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2522 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2523 Node->getOperand(0));
2525 Results.push_back(Tmp1);
2528 case ISD::STACKSAVE:
2529 // Expand to CopyFromReg if the target set
2530 // StackPointerRegisterToSaveRestore.
2531 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2532 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2533 Node->getValueType(0)));
2534 Results.push_back(Results[0].getValue(1));
2536 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2537 Results.push_back(Node->getOperand(0));
2540 case ISD::STACKRESTORE:
2541 // Expand to CopyToReg if the target set
2542 // StackPointerRegisterToSaveRestore.
2543 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2544 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2545 Node->getOperand(1)));
2547 Results.push_back(Node->getOperand(0));
2550 case ISD::FCOPYSIGN:
2551 Results.push_back(ExpandFCOPYSIGN(Node));
2554 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
2555 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2556 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2557 Node->getOperand(0));
2558 Results.push_back(Tmp1);
2561 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2562 EVT VT = Node->getValueType(0);
2563 Tmp1 = Node->getOperand(0);
2564 Tmp2 = DAG.getConstantFP(0.0, VT);
2565 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2566 Tmp1, Tmp2, ISD::SETUGT);
2567 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2568 Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2569 Results.push_back(Tmp1);
2573 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2574 RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2577 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2578 RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2581 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2582 RTLIB::COS_F80, RTLIB::COS_PPCF128));
2585 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2586 RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2589 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2590 RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2593 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2594 RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2597 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2598 RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2601 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2602 RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2605 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2606 RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2609 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2610 RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2613 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2614 RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2617 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2618 RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2620 case ISD::FNEARBYINT:
2621 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2622 RTLIB::NEARBYINT_F64,
2623 RTLIB::NEARBYINT_F80,
2624 RTLIB::NEARBYINT_PPCF128));
2627 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2628 RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2631 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2632 RTLIB::POW_F80, RTLIB::POW_PPCF128));
2635 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2636 RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2639 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2640 RTLIB::REM_F80, RTLIB::REM_PPCF128));
2642 case ISD::FP16_TO_FP32:
2643 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
2645 case ISD::FP32_TO_FP16:
2646 Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
2648 case ISD::ConstantFP: {
2649 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2650 // Check to see if this FP immediate is already legal.
2651 // If this is a legal constant, turn it into a TargetConstantFP node.
2652 if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
2653 Results.push_back(SDValue(Node, 0));
2655 Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2658 case ISD::EHSELECTION: {
2659 unsigned Reg = TLI.getExceptionSelectorRegister();
2660 assert(Reg && "Can't expand to unknown register!");
2661 Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2662 Node->getValueType(0)));
2663 Results.push_back(Results[0].getValue(1));
2666 case ISD::EXCEPTIONADDR: {
2667 unsigned Reg = TLI.getExceptionAddressRegister();
2668 assert(Reg && "Can't expand to unknown register!");
2669 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
2670 Node->getValueType(0)));
2671 Results.push_back(Results[0].getValue(1));
2675 EVT VT = Node->getValueType(0);
2676 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
2677 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
2678 "Don't know how to expand this subtraction!");
2679 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
2680 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
2681 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
2682 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
2687 EVT VT = Node->getValueType(0);
2688 SDVTList VTs = DAG.getVTList(VT, VT);
2689 bool isSigned = Node->getOpcode() == ISD::SREM;
2690 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
2691 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2692 Tmp2 = Node->getOperand(0);
2693 Tmp3 = Node->getOperand(1);
2694 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
2695 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
2696 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
2698 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
2699 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
2700 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
2701 } else if (isSigned) {
2702 Tmp1 = ExpandIntLibCall(Node, true,
2704 RTLIB::SREM_I16, RTLIB::SREM_I32,
2705 RTLIB::SREM_I64, RTLIB::SREM_I128);
2707 Tmp1 = ExpandIntLibCall(Node, false,
2709 RTLIB::UREM_I16, RTLIB::UREM_I32,
2710 RTLIB::UREM_I64, RTLIB::UREM_I128);
2712 Results.push_back(Tmp1);
2717 bool isSigned = Node->getOpcode() == ISD::SDIV;
2718 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2719 EVT VT = Node->getValueType(0);
2720 SDVTList VTs = DAG.getVTList(VT, VT);
2721 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
2722 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
2723 Node->getOperand(1));
2725 Tmp1 = ExpandIntLibCall(Node, true,
2727 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
2728 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
2730 Tmp1 = ExpandIntLibCall(Node, false,
2732 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
2733 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
2734 Results.push_back(Tmp1);
2739 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
2741 EVT VT = Node->getValueType(0);
2742 SDVTList VTs = DAG.getVTList(VT, VT);
2743 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
2744 "If this wasn't legal, it shouldn't have been created!");
2745 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
2746 Node->getOperand(1));
2747 Results.push_back(Tmp1.getValue(1));
2751 EVT VT = Node->getValueType(0);
2752 SDVTList VTs = DAG.getVTList(VT, VT);
2753 // See if multiply or divide can be lowered using two-result operations.
2754 // We just need the low half of the multiply; try both the signed
2755 // and unsigned forms. If the target supports both SMUL_LOHI and
2756 // UMUL_LOHI, form a preference by checking which forms of plain
2757 // MULH it supports.
2758 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
2759 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
2760 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
2761 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
2762 unsigned OpToUse = 0;
2763 if (HasSMUL_LOHI && !HasMULHS) {
2764 OpToUse = ISD::SMUL_LOHI;
2765 } else if (HasUMUL_LOHI && !HasMULHU) {
2766 OpToUse = ISD::UMUL_LOHI;
2767 } else if (HasSMUL_LOHI) {
2768 OpToUse = ISD::SMUL_LOHI;
2769 } else if (HasUMUL_LOHI) {
2770 OpToUse = ISD::UMUL_LOHI;
2773 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
2774 Node->getOperand(1)));
2777 Tmp1 = ExpandIntLibCall(Node, false,
2779 RTLIB::MUL_I16, RTLIB::MUL_I32,
2780 RTLIB::MUL_I64, RTLIB::MUL_I128);
2781 Results.push_back(Tmp1);
2786 SDValue LHS = Node->getOperand(0);
2787 SDValue RHS = Node->getOperand(1);
2788 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2789 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2791 Results.push_back(Sum);
2792 EVT OType = Node->getValueType(1);
2794 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2796 // LHSSign -> LHS >= 0
2797 // RHSSign -> RHS >= 0
2798 // SumSign -> Sum >= 0
2801 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2803 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2805 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2806 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2807 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2808 Node->getOpcode() == ISD::SADDO ?
2809 ISD::SETEQ : ISD::SETNE);
2811 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2812 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2814 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2815 Results.push_back(Cmp);
2820 SDValue LHS = Node->getOperand(0);
2821 SDValue RHS = Node->getOperand(1);
2822 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
2823 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2825 Results.push_back(Sum);
2826 Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
2827 Node->getOpcode () == ISD::UADDO ?
2828 ISD::SETULT : ISD::SETUGT));
2833 EVT VT = Node->getValueType(0);
2834 SDValue LHS = Node->getOperand(0);
2835 SDValue RHS = Node->getOperand(1);
2838 static const unsigned Ops[2][3] =
2839 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
2840 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
2841 bool isSigned = Node->getOpcode() == ISD::SMULO;
2842 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
2843 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
2844 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
2845 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
2846 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
2848 TopHalf = BottomHalf.getValue(1);
2850 // FIXME: We should be able to fall back to a libcall with an illegal
2851 // type in some cases.
2852 // Also, we can fall back to a division in some cases, but that's a big
2853 // performance hit in the general case.
2854 assert(TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
2855 VT.getSizeInBits() * 2)) &&
2856 "Don't know how to expand this operation yet!");
2857 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
2858 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
2859 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
2860 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
2861 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
2862 DAG.getIntPtrConstant(0));
2863 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
2864 DAG.getIntPtrConstant(1));
2867 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1, TLI.getShiftAmountTy());
2868 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
2869 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
2872 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
2873 DAG.getConstant(0, VT), ISD::SETNE);
2875 Results.push_back(BottomHalf);
2876 Results.push_back(TopHalf);
2879 case ISD::BUILD_PAIR: {
2880 EVT PairTy = Node->getValueType(0);
2881 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
2882 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
2883 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
2884 DAG.getConstant(PairTy.getSizeInBits()/2,
2885 TLI.getShiftAmountTy()));
2886 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
2890 Tmp1 = Node->getOperand(0);
2891 Tmp2 = Node->getOperand(1);
2892 Tmp3 = Node->getOperand(2);
2893 if (Tmp1.getOpcode() == ISD::SETCC) {
2894 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2896 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2898 Tmp1 = DAG.getSelectCC(dl, Tmp1,
2899 DAG.getConstant(0, Tmp1.getValueType()),
2900 Tmp2, Tmp3, ISD::SETNE);
2902 Results.push_back(Tmp1);
2905 SDValue Chain = Node->getOperand(0);
2906 SDValue Table = Node->getOperand(1);
2907 SDValue Index = Node->getOperand(2);
2909 EVT PTy = TLI.getPointerTy();
2911 const TargetData &TD = *TLI.getTargetData();
2912 unsigned EntrySize =
2913 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
2915 Index = DAG.getNode(ISD::MUL, dl, PTy,
2916 Index, DAG.getConstant(EntrySize, PTy));
2917 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2919 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
2920 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
2921 PseudoSourceValue::getJumpTable(), 0, MemVT,
2924 if (TM.getRelocationModel() == Reloc::PIC_) {
2925 // For PIC, the sequence is:
2926 // BRIND(load(Jumptable + index) + RelocBase)
2927 // RelocBase can be JumpTable, GOT or some sort of global base.
2928 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
2929 TLI.getPICJumpTableRelocBase(Table, DAG));
2931 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
2932 Results.push_back(Tmp1);
2936 // Expand brcond's setcc into its constituent parts and create a BR_CC
2938 Tmp1 = Node->getOperand(0);
2939 Tmp2 = Node->getOperand(1);
2940 if (Tmp2.getOpcode() == ISD::SETCC) {
2941 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
2942 Tmp1, Tmp2.getOperand(2),
2943 Tmp2.getOperand(0), Tmp2.getOperand(1),
2944 Node->getOperand(2));
2946 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
2947 DAG.getCondCode(ISD::SETNE), Tmp2,
2948 DAG.getConstant(0, Tmp2.getValueType()),
2949 Node->getOperand(2));
2951 Results.push_back(Tmp1);
2954 Tmp1 = Node->getOperand(0);
2955 Tmp2 = Node->getOperand(1);
2956 Tmp3 = Node->getOperand(2);
2957 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
2959 // If we expanded the SETCC into an AND/OR, return the new node
2960 if (Tmp2.getNode() == 0) {
2961 Results.push_back(Tmp1);
2965 // Otherwise, SETCC for the given comparison type must be completely
2966 // illegal; expand it into a SELECT_CC.
2967 EVT VT = Node->getValueType(0);
2968 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
2969 DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
2970 Results.push_back(Tmp1);
2973 case ISD::SELECT_CC: {
2974 Tmp1 = Node->getOperand(0); // LHS
2975 Tmp2 = Node->getOperand(1); // RHS
2976 Tmp3 = Node->getOperand(2); // True
2977 Tmp4 = Node->getOperand(3); // False
2978 SDValue CC = Node->getOperand(4);
2980 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
2981 Tmp1, Tmp2, CC, dl);
2983 assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
2984 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2985 CC = DAG.getCondCode(ISD::SETNE);
2986 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
2988 Results.push_back(Tmp1);
2992 Tmp1 = Node->getOperand(0); // Chain
2993 Tmp2 = Node->getOperand(2); // LHS
2994 Tmp3 = Node->getOperand(3); // RHS
2995 Tmp4 = Node->getOperand(1); // CC
2997 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
2998 Tmp2, Tmp3, Tmp4, dl);
2999 LastCALLSEQ_END = DAG.getEntryNode();
3001 assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3002 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3003 Tmp4 = DAG.getCondCode(ISD::SETNE);
3004 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3005 Tmp3, Node->getOperand(4));
3006 Results.push_back(Tmp1);
3009 case ISD::GLOBAL_OFFSET_TABLE:
3010 case ISD::GlobalAddress:
3011 case ISD::GlobalTLSAddress:
3012 case ISD::ExternalSymbol:
3013 case ISD::ConstantPool:
3014 case ISD::JumpTable:
3015 case ISD::INTRINSIC_W_CHAIN:
3016 case ISD::INTRINSIC_WO_CHAIN:
3017 case ISD::INTRINSIC_VOID:
3018 // FIXME: Custom lowering for these operations shouldn't return null!
3019 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3020 Results.push_back(SDValue(Node, i));
3024 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3025 SmallVectorImpl<SDValue> &Results) {
3026 EVT OVT = Node->getValueType(0);
3027 if (Node->getOpcode() == ISD::UINT_TO_FP ||
3028 Node->getOpcode() == ISD::SINT_TO_FP ||
3029 Node->getOpcode() == ISD::SETCC) {
3030 OVT = Node->getOperand(0).getValueType();
3032 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3033 DebugLoc dl = Node->getDebugLoc();
3034 SDValue Tmp1, Tmp2, Tmp3;
3035 switch (Node->getOpcode()) {
3039 // Zero extend the argument.
3040 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3041 // Perform the larger operation.
3042 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3043 if (Node->getOpcode() == ISD::CTTZ) {
3044 //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3045 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3046 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3048 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3049 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3050 } else if (Node->getOpcode() == ISD::CTLZ) {
3051 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3052 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3053 DAG.getConstant(NVT.getSizeInBits() -
3054 OVT.getSizeInBits(), NVT));
3056 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3059 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3060 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3061 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3062 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3063 DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3064 Results.push_back(Tmp1);
3067 case ISD::FP_TO_UINT:
3068 case ISD::FP_TO_SINT:
3069 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3070 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3071 Results.push_back(Tmp1);
3073 case ISD::UINT_TO_FP:
3074 case ISD::SINT_TO_FP:
3075 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3076 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3077 Results.push_back(Tmp1);
3082 unsigned ExtOp, TruncOp;
3083 if (OVT.isVector()) {
3084 ExtOp = ISD::BIT_CONVERT;
3085 TruncOp = ISD::BIT_CONVERT;
3087 assert(OVT.isInteger() && "Cannot promote logic operation");
3088 ExtOp = ISD::ANY_EXTEND;
3089 TruncOp = ISD::TRUNCATE;
3091 // Promote each of the values to the new type.
3092 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3093 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3094 // Perform the larger operation, then convert back
3095 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3096 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3100 unsigned ExtOp, TruncOp;
3101 if (Node->getValueType(0).isVector()) {
3102 ExtOp = ISD::BIT_CONVERT;
3103 TruncOp = ISD::BIT_CONVERT;
3104 } else if (Node->getValueType(0).isInteger()) {
3105 ExtOp = ISD::ANY_EXTEND;
3106 TruncOp = ISD::TRUNCATE;
3108 ExtOp = ISD::FP_EXTEND;
3109 TruncOp = ISD::FP_ROUND;
3111 Tmp1 = Node->getOperand(0);
3112 // Promote each of the values to the new type.
3113 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3114 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3115 // Perform the larger operation, then round down.
3116 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3117 if (TruncOp != ISD::FP_ROUND)
3118 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3120 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3121 DAG.getIntPtrConstant(0));
3122 Results.push_back(Tmp1);
3125 case ISD::VECTOR_SHUFFLE: {
3126 SmallVector<int, 8> Mask;
3127 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3129 // Cast the two input vectors.
3130 Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3131 Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3133 // Convert the shuffle mask to the right # elements.
3134 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3135 Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1);
3136 Results.push_back(Tmp1);
3140 unsigned ExtOp = ISD::FP_EXTEND;
3141 if (NVT.isInteger()) {
3142 ISD::CondCode CCCode =
3143 cast<CondCodeSDNode>(Node->getOperand(2))->get();
3144 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3146 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3147 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3148 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3149 Tmp1, Tmp2, Node->getOperand(2)));
3155 // SelectionDAG::Legalize - This is the entry point for the file.
3157 void SelectionDAG::Legalize(CodeGenOpt::Level OptLevel) {
3158 /// run - This is the main entry point to this class.
3160 SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();