1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/DebugInfo.h"
15 #include "llvm/CodeGen/Analysis.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/Target/TargetFrameLowering.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
36 //===----------------------------------------------------------------------===//
37 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38 /// hacks on it until the target machine can handle it. This involves
39 /// eliminating value sizes the machine cannot handle (promoting small sizes to
40 /// large sizes or splitting up large values into small values) as well as
41 /// eliminating operations the machine cannot handle.
43 /// This code also does a small amount of optimization and recognition of idioms
44 /// as part of its processing. For example, if a target does not support a
45 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46 /// will attempt merge setcc and brc instructions into brcc's.
49 class SelectionDAGLegalize {
50 const TargetMachine &TM;
51 const TargetLowering &TLI;
54 // Libcall insertion helpers.
56 /// LastCALLSEQ - This keeps track of the CALLSEQ_END node that has been
57 /// legalized. We use this to ensure that calls are properly serialized
58 /// against each other, including inserted libcalls.
59 SmallVector<SDValue, 8> LastCALLSEQ;
61 /// LegalizedNodes - For nodes that are of legal width, and that have more
62 /// than one use, this map indicates what regularized operand to use. This
63 /// allows us to avoid legalizing the same thing more than once.
64 DenseMap<SDValue, SDValue> LegalizedNodes;
66 void AddLegalizedOperand(SDValue From, SDValue To) {
67 LegalizedNodes.insert(std::make_pair(From, To));
68 // If someone requests legalization of the new node, return itself.
70 LegalizedNodes.insert(std::make_pair(To, To));
72 // Transfer SDDbgValues.
73 DAG.TransferDbgValues(From, To);
77 explicit SelectionDAGLegalize(SelectionDAG &DAG);
82 /// LegalizeOp - Return a legal replacement for the given operation, with
83 /// all legal operands.
84 SDValue LegalizeOp(SDValue O);
86 SDValue OptimizeFloatStore(StoreSDNode *ST);
88 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
89 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
90 /// is necessary to spill the vector being inserted into to memory, perform
91 /// the insert there, and then read the result back.
92 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
93 SDValue Idx, DebugLoc dl);
94 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
95 SDValue Idx, DebugLoc dl);
97 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
98 /// performs the same shuffe in terms of order or result bytes, but on a type
99 /// whose vector element type is narrower than the original shuffle type.
100 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
101 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
102 SDValue N1, SDValue N2,
103 SmallVectorImpl<int> &Mask) const;
105 bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
106 SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
108 void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
111 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
112 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
113 unsigned NumOps, bool isSigned, DebugLoc dl);
115 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
116 SDNode *Node, bool isSigned);
117 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
118 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
119 RTLIB::Libcall Call_PPCF128);
120 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
121 RTLIB::Libcall Call_I8,
122 RTLIB::Libcall Call_I16,
123 RTLIB::Libcall Call_I32,
124 RTLIB::Libcall Call_I64,
125 RTLIB::Libcall Call_I128);
126 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
128 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
129 SDValue ExpandBUILD_VECTOR(SDNode *Node);
130 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
131 void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
132 SmallVectorImpl<SDValue> &Results);
133 SDValue ExpandFCOPYSIGN(SDNode *Node);
134 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
136 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
138 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
141 SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
142 SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
144 SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
145 SDValue ExpandInsertToVectorThroughStack(SDValue Op);
146 SDValue ExpandVectorBuildThroughStack(SDNode* Node);
148 std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
150 void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
151 void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
153 SDValue getLastCALLSEQ() { return LastCALLSEQ.back(); }
154 void setLastCALLSEQ(const SDValue s) { LastCALLSEQ.back() = s; }
155 void pushLastCALLSEQ(SDValue s) {
156 LastCALLSEQ.push_back(s);
158 void popLastCALLSEQ() {
159 LastCALLSEQ.pop_back();
164 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
165 /// performs the same shuffe in terms of order or result bytes, but on a type
166 /// whose vector element type is narrower than the original shuffle type.
167 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
169 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
170 SDValue N1, SDValue N2,
171 SmallVectorImpl<int> &Mask) const {
172 unsigned NumMaskElts = VT.getVectorNumElements();
173 unsigned NumDestElts = NVT.getVectorNumElements();
174 unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
176 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
178 if (NumEltsGrowth == 1)
179 return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
181 SmallVector<int, 8> NewMask;
182 for (unsigned i = 0; i != NumMaskElts; ++i) {
184 for (unsigned j = 0; j != NumEltsGrowth; ++j) {
186 NewMask.push_back(-1);
188 NewMask.push_back(Idx * NumEltsGrowth + j);
191 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
192 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
193 return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
196 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
197 : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
201 void SelectionDAGLegalize::LegalizeDAG() {
202 pushLastCALLSEQ(DAG.getEntryNode());
204 // The legalize process is inherently a bottom-up recursive process (users
205 // legalize their uses before themselves). Given infinite stack space, we
206 // could just start legalizing on the root and traverse the whole graph. In
207 // practice however, this causes us to run out of stack space on large basic
208 // blocks. To avoid this problem, compute an ordering of the nodes where each
209 // node is only legalized after all of its operands are legalized.
210 DAG.AssignTopologicalOrder();
211 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
212 E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
213 LegalizeOp(SDValue(I, 0));
215 // Finally, it's possible the root changed. Get the new root.
216 SDValue OldRoot = DAG.getRoot();
217 assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
218 DAG.setRoot(LegalizedNodes[OldRoot]);
220 LegalizedNodes.clear();
222 // Remove dead nodes now.
223 DAG.RemoveDeadNodes();
227 /// FindCallEndFromCallStart - Given a chained node that is part of a call
228 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
229 static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth = 0) {
230 int next_depth = depth;
231 if (Node->getOpcode() == ISD::CALLSEQ_START)
232 next_depth = depth + 1;
233 if (Node->getOpcode() == ISD::CALLSEQ_END) {
234 assert(depth > 0 && "negative depth!");
238 next_depth = depth - 1;
240 if (Node->use_empty())
241 return 0; // No CallSeqEnd
243 // The chain is usually at the end.
244 SDValue TheChain(Node, Node->getNumValues()-1);
245 if (TheChain.getValueType() != MVT::Other) {
246 // Sometimes it's at the beginning.
247 TheChain = SDValue(Node, 0);
248 if (TheChain.getValueType() != MVT::Other) {
249 // Otherwise, hunt for it.
250 for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
251 if (Node->getValueType(i) == MVT::Other) {
252 TheChain = SDValue(Node, i);
256 // Otherwise, we walked into a node without a chain.
257 if (TheChain.getValueType() != MVT::Other)
262 for (SDNode::use_iterator UI = Node->use_begin(),
263 E = Node->use_end(); UI != E; ++UI) {
265 // Make sure to only follow users of our token chain.
267 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
268 if (User->getOperand(i) == TheChain)
269 if (SDNode *Result = FindCallEndFromCallStart(User, next_depth))
275 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
276 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
277 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
279 assert(Node && "Didn't find callseq_start for a call??");
280 while (Node->getOpcode() != ISD::CALLSEQ_START || nested) {
281 Node = Node->getOperand(0).getNode();
282 assert(Node->getOperand(0).getValueType() == MVT::Other &&
283 "Node doesn't have a token chain argument!");
284 switch (Node->getOpcode()) {
287 case ISD::CALLSEQ_START:
290 Node = Node->getOperand(0).getNode();
293 case ISD::CALLSEQ_END:
298 return (Node->getOpcode() == ISD::CALLSEQ_START) ? Node : 0;
301 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
302 /// see if any uses can reach Dest. If no dest operands can get to dest,
303 /// legalize them, legalize ourself, and return false, otherwise, return true.
305 /// Keep track of the nodes we fine that actually do lead to Dest in
306 /// NodesLeadingTo. This avoids retraversing them exponential number of times.
308 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
309 SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
310 if (N == Dest) return true; // N certainly leads to Dest :)
312 // If we've already processed this node and it does lead to Dest, there is no
313 // need to reprocess it.
314 if (NodesLeadingTo.count(N)) return true;
316 // If the first result of this node has been already legalized, then it cannot
318 if (LegalizedNodes.count(SDValue(N, 0))) return false;
320 // Okay, this node has not already been legalized. Check and legalize all
321 // operands. If none lead to Dest, then we can legalize this node.
322 bool OperandsLeadToDest = false;
323 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
324 OperandsLeadToDest |= // If an operand leads to Dest, so do we.
325 LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
328 if (OperandsLeadToDest) {
329 NodesLeadingTo.insert(N);
333 // Okay, this node looks safe, legalize it and return false.
334 LegalizeOp(SDValue(N, 0));
338 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
339 /// a load from the constant pool.
340 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
341 SelectionDAG &DAG, const TargetLowering &TLI) {
343 DebugLoc dl = CFP->getDebugLoc();
345 // If a FP immediate is precise when represented as a float and if the
346 // target can do an extending load from float to double, we put it into
347 // the constant pool as a float, even if it's is statically typed as a
348 // double. This shrinks FP constants and canonicalizes them for targets where
349 // an FP extending load is the same cost as a normal load (such as on the x87
350 // fp stack or PPC FP unit).
351 EVT VT = CFP->getValueType(0);
352 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
354 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
355 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
356 (VT == MVT::f64) ? MVT::i64 : MVT::i32);
361 while (SVT != MVT::f32) {
362 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
363 if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
364 // Only do this if the target has a native EXTLOAD instruction from
366 TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
367 TLI.ShouldShrinkFPConstant(OrigVT)) {
368 const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
369 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
375 SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
376 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
378 return DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
380 CPIdx, MachinePointerInfo::getConstantPool(),
381 VT, false, false, Alignment);
382 return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
383 MachinePointerInfo::getConstantPool(), false, false,
387 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
389 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
390 const TargetLowering &TLI) {
391 SDValue Chain = ST->getChain();
392 SDValue Ptr = ST->getBasePtr();
393 SDValue Val = ST->getValue();
394 EVT VT = Val.getValueType();
395 int Alignment = ST->getAlignment();
396 DebugLoc dl = ST->getDebugLoc();
397 if (ST->getMemoryVT().isFloatingPoint() ||
398 ST->getMemoryVT().isVector()) {
399 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
400 if (TLI.isTypeLegal(intVT)) {
401 // Expand to a bitconvert of the value to the integer type of the
402 // same size, then a (misaligned) int store.
403 // FIXME: Does not handle truncating floating point stores!
404 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
405 return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
406 ST->isVolatile(), ST->isNonTemporal(), Alignment);
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, MachinePointerInfo(),
425 StoredVT, false, false, 0);
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,
434 MachinePointerInfo(),
436 // Store it to the final location. Remember the store.
437 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
438 ST->getPointerInfo().getWithOffset(Offset),
439 ST->isVolatile(), ST->isNonTemporal(),
440 MinAlign(ST->getAlignment(), Offset)));
441 // Increment the pointers.
443 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
445 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
448 // The last store may be partial. Do a truncating store. On big-endian
449 // machines this requires an extending load from the stack slot to ensure
450 // that the bits are in the right place.
451 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
452 8 * (StoredBytes - Offset));
454 // Load from the stack slot.
455 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
456 MachinePointerInfo(),
457 MemVT, false, false, 0);
459 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
461 .getWithOffset(Offset),
462 MemVT, ST->isVolatile(),
464 MinAlign(ST->getAlignment(), Offset)));
465 // The order of the stores doesn't matter - say it with a TokenFactor.
466 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
469 assert(ST->getMemoryVT().isInteger() &&
470 !ST->getMemoryVT().isVector() &&
471 "Unaligned store of unknown type.");
472 // Get the half-size VT
473 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
474 int NumBits = NewStoredVT.getSizeInBits();
475 int IncrementSize = NumBits / 8;
477 // Divide the stored value in two parts.
478 SDValue ShiftAmount = DAG.getConstant(NumBits,
479 TLI.getShiftAmountTy(Val.getValueType()));
481 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
483 // Store the two parts
484 SDValue Store1, Store2;
485 Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
486 ST->getPointerInfo(), NewStoredVT,
487 ST->isVolatile(), ST->isNonTemporal(), Alignment);
488 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
489 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
490 Alignment = MinAlign(Alignment, IncrementSize);
491 Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
492 ST->getPointerInfo().getWithOffset(IncrementSize),
493 NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
496 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
499 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
501 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
502 const TargetLowering &TLI) {
503 SDValue Chain = LD->getChain();
504 SDValue Ptr = LD->getBasePtr();
505 EVT VT = LD->getValueType(0);
506 EVT LoadedVT = LD->getMemoryVT();
507 DebugLoc dl = LD->getDebugLoc();
508 if (VT.isFloatingPoint() || VT.isVector()) {
509 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
510 if (TLI.isTypeLegal(intVT)) {
511 // Expand to a (misaligned) integer load of the same size,
512 // then bitconvert to floating point or vector.
513 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
515 LD->isNonTemporal(), LD->getAlignment());
516 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
517 if (VT.isFloatingPoint() && LoadedVT != VT)
518 Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
520 SDValue Ops[] = { Result, Chain };
521 return DAG.getMergeValues(Ops, 2, dl);
524 // Copy the value to a (aligned) stack slot using (unaligned) integer
525 // loads and stores, then do a (aligned) load from the stack slot.
526 EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
527 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
528 unsigned RegBytes = RegVT.getSizeInBits() / 8;
529 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
531 // Make sure the stack slot is also aligned for the register type.
532 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
534 SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
535 SmallVector<SDValue, 8> Stores;
536 SDValue StackPtr = StackBase;
539 // Do all but one copies using the full register width.
540 for (unsigned i = 1; i < NumRegs; i++) {
541 // Load one integer register's worth from the original location.
542 SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
543 LD->getPointerInfo().getWithOffset(Offset),
544 LD->isVolatile(), LD->isNonTemporal(),
545 MinAlign(LD->getAlignment(), Offset));
546 // Follow the load with a store to the stack slot. Remember the store.
547 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
548 MachinePointerInfo(), false, false, 0));
549 // Increment the pointers.
551 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
552 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
556 // The last copy may be partial. Do an extending load.
557 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
558 8 * (LoadedBytes - Offset));
559 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
560 LD->getPointerInfo().getWithOffset(Offset),
561 MemVT, LD->isVolatile(),
563 MinAlign(LD->getAlignment(), Offset));
564 // Follow the load with a store to the stack slot. Remember the store.
565 // On big-endian machines this requires a truncating store to ensure
566 // that the bits end up in the right place.
567 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
568 MachinePointerInfo(), MemVT,
571 // The order of the stores doesn't matter - say it with a TokenFactor.
572 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
575 // Finally, perform the original load only redirected to the stack slot.
576 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
577 MachinePointerInfo(), LoadedVT, false, false, 0);
579 // Callers expect a MERGE_VALUES node.
580 SDValue Ops[] = { Load, TF };
581 return DAG.getMergeValues(Ops, 2, dl);
583 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
584 "Unaligned load of unsupported type.");
586 // Compute the new VT that is half the size of the old one. This is an
588 unsigned NumBits = LoadedVT.getSizeInBits();
590 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
593 unsigned Alignment = LD->getAlignment();
594 unsigned IncrementSize = NumBits / 8;
595 ISD::LoadExtType HiExtType = LD->getExtensionType();
597 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
598 if (HiExtType == ISD::NON_EXTLOAD)
599 HiExtType = ISD::ZEXTLOAD;
601 // Load the value in two parts
603 if (TLI.isLittleEndian()) {
604 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
605 NewLoadedVT, LD->isVolatile(),
606 LD->isNonTemporal(), Alignment);
607 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
608 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
609 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
610 LD->getPointerInfo().getWithOffset(IncrementSize),
611 NewLoadedVT, LD->isVolatile(),
612 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
614 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
615 NewLoadedVT, LD->isVolatile(),
616 LD->isNonTemporal(), Alignment);
617 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
618 DAG.getConstant(IncrementSize, TLI.getPointerTy()));
619 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
620 LD->getPointerInfo().getWithOffset(IncrementSize),
621 NewLoadedVT, LD->isVolatile(),
622 LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
625 // aggregate the two parts
626 SDValue ShiftAmount = DAG.getConstant(NumBits,
627 TLI.getShiftAmountTy(Hi.getValueType()));
628 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
629 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
631 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
634 SDValue Ops[] = { Result, TF };
635 return DAG.getMergeValues(Ops, 2, dl);
638 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
639 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
640 /// is necessary to spill the vector being inserted into to memory, perform
641 /// the insert there, and then read the result back.
642 SDValue SelectionDAGLegalize::
643 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
649 // If the target doesn't support this, we have to spill the input vector
650 // to a temporary stack slot, update the element, then reload it. This is
651 // badness. We could also load the value into a vector register (either
652 // with a "move to register" or "extload into register" instruction, then
653 // permute it into place, if the idx is a constant and if the idx is
654 // supported by the target.
655 EVT VT = Tmp1.getValueType();
656 EVT EltVT = VT.getVectorElementType();
657 EVT IdxVT = Tmp3.getValueType();
658 EVT PtrVT = TLI.getPointerTy();
659 SDValue StackPtr = DAG.CreateStackTemporary(VT);
661 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
664 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
665 MachinePointerInfo::getFixedStack(SPFI),
668 // Truncate or zero extend offset to target pointer type.
669 unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
670 Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
671 // Add the offset to the index.
672 unsigned EltSize = EltVT.getSizeInBits()/8;
673 Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
674 SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
675 // Store the scalar value.
676 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
678 // Load the updated vector.
679 return DAG.getLoad(VT, dl, Ch, StackPtr,
680 MachinePointerInfo::getFixedStack(SPFI), false, false, 0);
684 SDValue SelectionDAGLegalize::
685 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
686 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
687 // SCALAR_TO_VECTOR requires that the type of the value being inserted
688 // match the element type of the vector being created, except for
689 // integers in which case the inserted value can be over width.
690 EVT EltVT = Vec.getValueType().getVectorElementType();
691 if (Val.getValueType() == EltVT ||
692 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
693 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
694 Vec.getValueType(), Val);
696 unsigned NumElts = Vec.getValueType().getVectorNumElements();
697 // We generate a shuffle of InVec and ScVec, so the shuffle mask
698 // should be 0,1,2,3,4,5... with the appropriate element replaced with
700 SmallVector<int, 8> ShufOps;
701 for (unsigned i = 0; i != NumElts; ++i)
702 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
704 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
708 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
711 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
712 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
713 // FIXME: We shouldn't do this for TargetConstantFP's.
714 // FIXME: move this to the DAG Combiner! Note that we can't regress due
715 // to phase ordering between legalized code and the dag combiner. This
716 // probably means that we need to integrate dag combiner and legalizer
718 // We generally can't do this one for long doubles.
719 SDValue Tmp1 = ST->getChain();
720 SDValue Tmp2 = ST->getBasePtr();
722 unsigned Alignment = ST->getAlignment();
723 bool isVolatile = ST->isVolatile();
724 bool isNonTemporal = ST->isNonTemporal();
725 DebugLoc dl = ST->getDebugLoc();
726 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
727 if (CFP->getValueType(0) == MVT::f32 &&
728 TLI.isTypeLegal(MVT::i32)) {
729 Tmp3 = DAG.getConstant(CFP->getValueAPF().
730 bitcastToAPInt().zextOrTrunc(32),
732 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
733 isVolatile, isNonTemporal, Alignment);
736 if (CFP->getValueType(0) == MVT::f64) {
737 // If this target supports 64-bit registers, do a single 64-bit store.
738 if (TLI.isTypeLegal(MVT::i64)) {
739 Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
740 zextOrTrunc(64), MVT::i64);
741 return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
742 isVolatile, isNonTemporal, Alignment);
745 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
746 // Otherwise, if the target supports 32-bit registers, use 2 32-bit
747 // stores. If the target supports neither 32- nor 64-bits, this
748 // xform is certainly not worth it.
749 const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
750 SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
751 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
752 if (TLI.isBigEndian()) std::swap(Lo, Hi);
754 Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
755 isNonTemporal, Alignment);
756 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
757 DAG.getIntPtrConstant(4));
758 Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
759 ST->getPointerInfo().getWithOffset(4),
760 isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
762 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
766 return SDValue(0, 0);
769 /// LegalizeOp - Return a legal replacement for the given operation, with
770 /// all legal operands.
771 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
772 if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
775 SDNode *Node = Op.getNode();
776 DebugLoc dl = Node->getDebugLoc();
778 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
779 assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
780 TargetLowering::TypeLegal &&
781 "Unexpected illegal type!");
783 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
784 assert((TLI.getTypeAction(*DAG.getContext(),
785 Node->getOperand(i).getValueType()) ==
786 TargetLowering::TypeLegal ||
787 Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
788 "Unexpected illegal type!");
790 // Note that LegalizeOp may be reentered even from single-use nodes, which
791 // means that we always must cache transformed nodes.
792 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
793 if (I != LegalizedNodes.end()) return I->second;
795 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
797 bool isCustom = false;
799 // Figure out the correct action; the way to query this varies by opcode
800 TargetLowering::LegalizeAction Action = TargetLowering::Legal;
801 bool SimpleFinishLegalizing = true;
802 switch (Node->getOpcode()) {
803 case ISD::INTRINSIC_W_CHAIN:
804 case ISD::INTRINSIC_WO_CHAIN:
805 case ISD::INTRINSIC_VOID:
808 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
810 case ISD::SINT_TO_FP:
811 case ISD::UINT_TO_FP:
812 case ISD::EXTRACT_VECTOR_ELT:
813 Action = TLI.getOperationAction(Node->getOpcode(),
814 Node->getOperand(0).getValueType());
816 case ISD::FP_ROUND_INREG:
817 case ISD::SIGN_EXTEND_INREG: {
818 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
819 Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
825 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
826 Node->getOpcode() == ISD::SETCC ? 2 : 1;
827 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
828 EVT OpVT = Node->getOperand(CompareOperand).getValueType();
829 ISD::CondCode CCCode =
830 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
831 Action = TLI.getCondCodeAction(CCCode, OpVT);
832 if (Action == TargetLowering::Legal) {
833 if (Node->getOpcode() == ISD::SELECT_CC)
834 Action = TLI.getOperationAction(Node->getOpcode(),
835 Node->getValueType(0));
837 Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
843 // FIXME: Model these properly. LOAD and STORE are complicated, and
844 // STORE expects the unlegalized operand in some cases.
845 SimpleFinishLegalizing = false;
847 case ISD::CALLSEQ_START:
848 case ISD::CALLSEQ_END:
849 // FIXME: This shouldn't be necessary. These nodes have special properties
850 // dealing with the recursive nature of legalization. Removing this
851 // special case should be done as part of making LegalizeDAG non-recursive.
852 SimpleFinishLegalizing = false;
854 case ISD::EXTRACT_ELEMENT:
855 case ISD::FLT_ROUNDS_:
863 case ISD::MERGE_VALUES:
865 case ISD::FRAME_TO_ARGS_OFFSET:
866 case ISD::EH_SJLJ_SETJMP:
867 case ISD::EH_SJLJ_LONGJMP:
868 case ISD::EH_SJLJ_DISPATCHSETUP:
869 // These operations lie about being legal: when they claim to be legal,
870 // they should actually be expanded.
871 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
872 if (Action == TargetLowering::Legal)
873 Action = TargetLowering::Expand;
875 case ISD::TRAMPOLINE:
877 case ISD::RETURNADDR:
878 // These operations lie about being legal: when they claim to be legal,
879 // they should actually be custom-lowered.
880 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
881 if (Action == TargetLowering::Legal)
882 Action = TargetLowering::Custom;
884 case ISD::BUILD_VECTOR:
885 // A weird case: legalization for BUILD_VECTOR never legalizes the
887 // FIXME: This really sucks... changing it isn't semantically incorrect,
888 // but it massively pessimizes the code for floating-point BUILD_VECTORs
889 // because ConstantFP operands get legalized into constant pool loads
890 // before the BUILD_VECTOR code can see them. It doesn't usually bite,
891 // though, because BUILD_VECTORS usually get lowered into other nodes
892 // which get legalized properly.
893 SimpleFinishLegalizing = false;
896 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
897 Action = TargetLowering::Legal;
899 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
904 if (SimpleFinishLegalizing) {
905 SmallVector<SDValue, 8> Ops, ResultVals;
906 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
907 Ops.push_back(LegalizeOp(Node->getOperand(i)));
908 switch (Node->getOpcode()) {
915 assert(LastCALLSEQ.size() == 1 && "branch inside CALLSEQ_BEGIN/END?");
916 // Branches tweak the chain to include LastCALLSEQ
917 Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
919 Ops[0] = LegalizeOp(Ops[0]);
920 setLastCALLSEQ(DAG.getEntryNode());
927 // Legalizing shifts/rotates requires adjusting the shift amount
928 // to the appropriate width.
929 if (!Ops[1].getValueType().isVector())
930 Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueType(),
936 // Legalizing shifts/rotates requires adjusting the shift amount
937 // to the appropriate width.
938 if (!Ops[2].getValueType().isVector())
939 Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueType(),
944 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
947 case TargetLowering::Legal:
948 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
949 ResultVals.push_back(Result.getValue(i));
951 case TargetLowering::Custom:
952 // FIXME: The handling for custom lowering with multiple results is
954 Tmp1 = TLI.LowerOperation(Result, DAG);
955 if (Tmp1.getNode()) {
956 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
958 ResultVals.push_back(Tmp1);
960 ResultVals.push_back(Tmp1.getValue(i));
966 case TargetLowering::Expand:
967 ExpandNode(Result.getNode(), ResultVals);
969 case TargetLowering::Promote:
970 PromoteNode(Result.getNode(), ResultVals);
973 if (!ResultVals.empty()) {
974 for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
975 if (ResultVals[i] != SDValue(Node, i))
976 ResultVals[i] = LegalizeOp(ResultVals[i]);
977 AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
979 return ResultVals[Op.getResNo()];
983 switch (Node->getOpcode()) {
990 assert(0 && "Do not know how to legalize this operator!");
992 case ISD::BUILD_VECTOR:
993 switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
994 default: assert(0 && "This action is not supported yet!");
995 case TargetLowering::Custom:
996 Tmp3 = TLI.LowerOperation(Result, DAG);
997 if (Tmp3.getNode()) {
1002 case TargetLowering::Expand:
1003 Result = ExpandBUILD_VECTOR(Result.getNode());
1007 case ISD::CALLSEQ_START: {
1008 SDNode *CallEnd = FindCallEndFromCallStart(Node);
1009 assert(CallEnd && "didn't find CALLSEQ_END!");
1011 // Recursively Legalize all of the inputs of the call end that do not lead
1012 // to this call start. This ensures that any libcalls that need be inserted
1013 // are inserted *before* the CALLSEQ_START.
1014 {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1015 for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1016 LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1020 // Now that we have legalized all of the inputs (which may have inserted
1021 // libcalls), create the new CALLSEQ_START node.
1022 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1024 // Merge in the last call to ensure that this call starts after the last
1026 if (getLastCALLSEQ().getOpcode() != ISD::EntryToken) {
1027 Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1028 Tmp1, getLastCALLSEQ());
1029 Tmp1 = LegalizeOp(Tmp1);
1032 // Do not try to legalize the target-specific arguments (#1+).
1033 if (Tmp1 != Node->getOperand(0)) {
1034 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1036 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
1037 Ops.size()), Result.getResNo());
1040 // Remember that the CALLSEQ_START is legalized.
1041 AddLegalizedOperand(Op.getValue(0), Result);
1042 if (Node->getNumValues() == 2) // If this has a flag result, remember it.
1043 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1045 // Now that the callseq_start and all of the non-call nodes above this call
1046 // sequence have been legalized, legalize the call itself. During this
1047 // process, no libcalls can/will be inserted, guaranteeing that no calls
1049 // Note that we are selecting this call!
1050 setLastCALLSEQ(SDValue(CallEnd, 0));
1052 // Legalize the call, starting from the CALLSEQ_END.
1053 LegalizeOp(getLastCALLSEQ());
1056 case ISD::CALLSEQ_END:
1058 SDNode *myCALLSEQ_BEGIN = FindCallStartFromCallEnd(Node);
1060 // If the CALLSEQ_START node hasn't been legalized first, legalize it.
1061 // This will cause this node to be legalized as well as handling libcalls
1063 if (getLastCALLSEQ().getNode() != Node) {
1064 LegalizeOp(SDValue(myCALLSEQ_BEGIN, 0));
1065 DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1066 assert(I != LegalizedNodes.end() &&
1067 "Legalizing the call start should have legalized this node!");
1071 pushLastCALLSEQ(SDValue(myCALLSEQ_BEGIN, 0));
1074 // Otherwise, the call start has been legalized and everything is going
1075 // according to plan. Just legalize ourselves normally here.
1076 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1077 // Do not try to legalize the target-specific arguments (#1+), except for
1078 // an optional flag input.
1079 if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Glue){
1080 if (Tmp1 != Node->getOperand(0)) {
1081 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1083 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1084 &Ops[0], Ops.size()),
1088 Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1089 if (Tmp1 != Node->getOperand(0) ||
1090 Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1091 SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1094 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1095 &Ops[0], Ops.size()),
1099 // This finishes up call legalization.
1102 // If the CALLSEQ_END node has a flag, remember that we legalized it.
1103 AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1104 if (Node->getNumValues() == 2)
1105 AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1106 return Result.getValue(Op.getResNo());
1108 LoadSDNode *LD = cast<LoadSDNode>(Node);
1109 Tmp1 = LegalizeOp(LD->getChain()); // Legalize the chain.
1110 Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1112 ISD::LoadExtType ExtType = LD->getExtensionType();
1113 if (ExtType == ISD::NON_EXTLOAD) {
1114 EVT VT = Node->getValueType(0);
1115 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1116 Tmp1, Tmp2, LD->getOffset()),
1118 Tmp3 = Result.getValue(0);
1119 Tmp4 = Result.getValue(1);
1121 switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1122 default: assert(0 && "This action is not supported yet!");
1123 case TargetLowering::Legal:
1124 // If this is an unaligned load and the target doesn't support it,
1126 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1127 const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1128 unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1129 if (LD->getAlignment() < ABIAlignment){
1130 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1132 Tmp3 = Result.getOperand(0);
1133 Tmp4 = Result.getOperand(1);
1134 Tmp3 = LegalizeOp(Tmp3);
1135 Tmp4 = LegalizeOp(Tmp4);
1139 case TargetLowering::Custom:
1140 Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1141 if (Tmp1.getNode()) {
1142 Tmp3 = LegalizeOp(Tmp1);
1143 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1146 case TargetLowering::Promote: {
1147 // Only promote a load of vector type to another.
1148 assert(VT.isVector() && "Cannot promote this load!");
1149 // Change base type to a different vector type.
1150 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1152 Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
1153 LD->isVolatile(), LD->isNonTemporal(),
1154 LD->getAlignment());
1155 Tmp3 = LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
1156 Tmp4 = LegalizeOp(Tmp1.getValue(1));
1160 // Since loads produce two values, make sure to remember that we
1161 // legalized both of them.
1162 AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1163 AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1164 return Op.getResNo() ? Tmp4 : Tmp3;
1167 EVT SrcVT = LD->getMemoryVT();
1168 unsigned SrcWidth = SrcVT.getSizeInBits();
1169 unsigned Alignment = LD->getAlignment();
1170 bool isVolatile = LD->isVolatile();
1171 bool isNonTemporal = LD->isNonTemporal();
1173 if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1174 // Some targets pretend to have an i1 loading operation, and actually
1175 // load an i8. This trick is correct for ZEXTLOAD because the top 7
1176 // bits are guaranteed to be zero; it helps the optimizers understand
1177 // that these bits are zero. It is also useful for EXTLOAD, since it
1178 // tells the optimizers that those bits are undefined. It would be
1179 // nice to have an effective generic way of getting these benefits...
1180 // Until such a way is found, don't insist on promoting i1 here.
1181 (SrcVT != MVT::i1 ||
1182 TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1183 // Promote to a byte-sized load if not loading an integral number of
1184 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1185 unsigned NewWidth = SrcVT.getStoreSizeInBits();
1186 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1189 // The extra bits are guaranteed to be zero, since we stored them that
1190 // way. A zext load from NVT thus automatically gives zext from SrcVT.
1192 ISD::LoadExtType NewExtType =
1193 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1195 Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1196 Tmp1, Tmp2, LD->getPointerInfo(),
1197 NVT, isVolatile, isNonTemporal, Alignment);
1199 Ch = Result.getValue(1); // The chain.
1201 if (ExtType == ISD::SEXTLOAD)
1202 // Having the top bits zero doesn't help when sign extending.
1203 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1204 Result.getValueType(),
1205 Result, DAG.getValueType(SrcVT));
1206 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1207 // All the top bits are guaranteed to be zero - inform the optimizers.
1208 Result = DAG.getNode(ISD::AssertZext, dl,
1209 Result.getValueType(), Result,
1210 DAG.getValueType(SrcVT));
1212 Tmp1 = LegalizeOp(Result);
1213 Tmp2 = LegalizeOp(Ch);
1214 } else if (SrcWidth & (SrcWidth - 1)) {
1215 // If not loading a power-of-2 number of bits, expand as two loads.
1216 assert(!SrcVT.isVector() && "Unsupported extload!");
1217 unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1218 assert(RoundWidth < SrcWidth);
1219 unsigned ExtraWidth = SrcWidth - RoundWidth;
1220 assert(ExtraWidth < RoundWidth);
1221 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1222 "Load size not an integral number of bytes!");
1223 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1224 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1226 unsigned IncrementSize;
1228 if (TLI.isLittleEndian()) {
1229 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1230 // Load the bottom RoundWidth bits.
1231 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1233 LD->getPointerInfo(), RoundVT, isVolatile,
1234 isNonTemporal, Alignment);
1236 // Load the remaining ExtraWidth bits.
1237 IncrementSize = RoundWidth / 8;
1238 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1239 DAG.getIntPtrConstant(IncrementSize));
1240 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1241 LD->getPointerInfo().getWithOffset(IncrementSize),
1242 ExtraVT, isVolatile, isNonTemporal,
1243 MinAlign(Alignment, IncrementSize));
1245 // Build a factor node to remember that this load is independent of
1247 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1250 // Move the top bits to the right place.
1251 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1252 DAG.getConstant(RoundWidth,
1253 TLI.getShiftAmountTy(Hi.getValueType())));
1255 // Join the hi and lo parts.
1256 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1258 // Big endian - avoid unaligned loads.
1259 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1260 // Load the top RoundWidth bits.
1261 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1262 LD->getPointerInfo(), RoundVT, isVolatile,
1263 isNonTemporal, Alignment);
1265 // Load the remaining ExtraWidth bits.
1266 IncrementSize = RoundWidth / 8;
1267 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1268 DAG.getIntPtrConstant(IncrementSize));
1269 Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1270 dl, Node->getValueType(0), Tmp1, Tmp2,
1271 LD->getPointerInfo().getWithOffset(IncrementSize),
1272 ExtraVT, isVolatile, isNonTemporal,
1273 MinAlign(Alignment, IncrementSize));
1275 // Build a factor node to remember that this load is independent of
1277 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1280 // Move the top bits to the right place.
1281 Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1282 DAG.getConstant(ExtraWidth,
1283 TLI.getShiftAmountTy(Hi.getValueType())));
1285 // Join the hi and lo parts.
1286 Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1289 Tmp1 = LegalizeOp(Result);
1290 Tmp2 = LegalizeOp(Ch);
1292 switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1293 default: assert(0 && "This action is not supported yet!");
1294 case TargetLowering::Custom:
1297 case TargetLowering::Legal:
1298 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1299 Tmp1, Tmp2, LD->getOffset()),
1301 Tmp1 = Result.getValue(0);
1302 Tmp2 = Result.getValue(1);
1305 Tmp3 = TLI.LowerOperation(Result, DAG);
1306 if (Tmp3.getNode()) {
1307 Tmp1 = LegalizeOp(Tmp3);
1308 Tmp2 = LegalizeOp(Tmp3.getValue(1));
1311 // If this is an unaligned load and the target doesn't support it,
1313 if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1315 LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1316 unsigned ABIAlignment =
1317 TLI.getTargetData()->getABITypeAlignment(Ty);
1318 if (LD->getAlignment() < ABIAlignment){
1319 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1321 Tmp1 = Result.getOperand(0);
1322 Tmp2 = Result.getOperand(1);
1323 Tmp1 = LegalizeOp(Tmp1);
1324 Tmp2 = LegalizeOp(Tmp2);
1329 case TargetLowering::Expand:
1330 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && TLI.isTypeLegal(SrcVT)) {
1331 SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1332 LD->getPointerInfo(),
1333 LD->isVolatile(), LD->isNonTemporal(),
1334 LD->getAlignment());
1338 ExtendOp = (SrcVT.isFloatingPoint() ?
1339 ISD::FP_EXTEND : ISD::ANY_EXTEND);
1341 case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1342 case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1343 default: llvm_unreachable("Unexpected extend load type!");
1345 Result = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1346 Tmp1 = LegalizeOp(Result); // Relegalize new nodes.
1347 Tmp2 = LegalizeOp(Load.getValue(1));
1351 // If this is a promoted vector load, and the vector element types are
1352 // legal, then scalarize it.
1353 if (ExtType == ISD::EXTLOAD && SrcVT.isVector() &&
1354 TLI.isTypeLegal(Node->getValueType(0).getScalarType())) {
1355 SmallVector<SDValue, 8> LoadVals;
1356 SmallVector<SDValue, 8> LoadChains;
1357 unsigned NumElem = SrcVT.getVectorNumElements();
1358 unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
1360 for (unsigned Idx=0; Idx<NumElem; Idx++) {
1361 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1362 DAG.getIntPtrConstant(Stride));
1363 SDValue ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl,
1364 Node->getValueType(0).getScalarType(),
1365 Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Stride),
1366 SrcVT.getScalarType(),
1367 LD->isVolatile(), LD->isNonTemporal(),
1368 LD->getAlignment());
1370 LoadVals.push_back(ScalarLoad.getValue(0));
1371 LoadChains.push_back(ScalarLoad.getValue(1));
1373 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1374 &LoadChains[0], LoadChains.size());
1375 SDValue ValRes = DAG.getNode(ISD::BUILD_VECTOR, dl,
1376 Node->getValueType(0), &LoadVals[0], LoadVals.size());
1378 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1379 Tmp2 = LegalizeOp(Result.getValue(0)); // Relegalize new nodes.
1383 // If this is a promoted vector load, and the vector element types are
1384 // illegal, create the promoted vector from bitcasted segments.
1385 if (ExtType == ISD::EXTLOAD && SrcVT.isVector()) {
1386 EVT MemElemTy = Node->getValueType(0).getScalarType();
1387 EVT SrcSclrTy = SrcVT.getScalarType();
1388 unsigned SizeRatio =
1389 (MemElemTy.getSizeInBits() / SrcSclrTy.getSizeInBits());
1391 SmallVector<SDValue, 8> LoadVals;
1392 SmallVector<SDValue, 8> LoadChains;
1393 unsigned NumElem = SrcVT.getVectorNumElements();
1394 unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
1396 for (unsigned Idx=0; Idx<NumElem; Idx++) {
1397 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1398 DAG.getIntPtrConstant(Stride));
1399 SDValue ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl,
1400 SrcVT.getScalarType(),
1401 Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Stride),
1402 SrcVT.getScalarType(),
1403 LD->isVolatile(), LD->isNonTemporal(),
1404 LD->getAlignment());
1405 if (TLI.isBigEndian()) {
1406 // MSB (which is garbage, comes first)
1407 LoadVals.push_back(ScalarLoad.getValue(0));
1408 for (unsigned i = 0; i<SizeRatio-1; ++i)
1409 LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
1411 // LSB (which is data, comes first)
1412 for (unsigned i = 0; i<SizeRatio-1; ++i)
1413 LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
1414 LoadVals.push_back(ScalarLoad.getValue(0));
1416 LoadChains.push_back(ScalarLoad.getValue(1));
1419 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1420 &LoadChains[0], LoadChains.size());
1421 EVT TempWideVector = EVT::getVectorVT(*DAG.getContext(),
1422 SrcVT.getScalarType(), NumElem*SizeRatio);
1423 SDValue ValRes = DAG.getNode(ISD::BUILD_VECTOR, dl,
1424 TempWideVector, &LoadVals[0], LoadVals.size());
1426 // Cast to the correct type
1427 ValRes = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), ValRes);
1429 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1430 Tmp2 = LegalizeOp(Result.getValue(0)); // Relegalize new nodes.
1435 // FIXME: This does not work for vectors on most targets. Sign- and
1436 // zero-extend operations are currently folded into extending loads,
1437 // whether they are legal or not, and then we end up here without any
1438 // support for legalizing them.
1439 assert(ExtType != ISD::EXTLOAD &&
1440 "EXTLOAD should always be supported!");
1441 // Turn the unsupported load into an EXTLOAD followed by an explicit
1442 // zero/sign extend inreg.
1443 Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1444 Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
1445 LD->isVolatile(), LD->isNonTemporal(),
1446 LD->getAlignment());
1448 if (ExtType == ISD::SEXTLOAD)
1449 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1450 Result.getValueType(),
1451 Result, DAG.getValueType(SrcVT));
1453 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
1454 Tmp1 = LegalizeOp(ValRes); // Relegalize new nodes.
1455 Tmp2 = LegalizeOp(Result.getValue(1)); // Relegalize new nodes.
1460 // Since loads produce two values, make sure to remember that we legalized
1462 AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1463 AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1464 return Op.getResNo() ? Tmp2 : Tmp1;
1467 StoreSDNode *ST = cast<StoreSDNode>(Node);
1468 Tmp1 = LegalizeOp(ST->getChain()); // Legalize the chain.
1469 Tmp2 = LegalizeOp(ST->getBasePtr()); // Legalize the pointer.
1470 unsigned Alignment = ST->getAlignment();
1471 bool isVolatile = ST->isVolatile();
1472 bool isNonTemporal = ST->isNonTemporal();
1474 if (!ST->isTruncatingStore()) {
1475 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1476 Result = SDValue(OptStore, 0);
1481 Tmp3 = LegalizeOp(ST->getValue());
1482 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1487 EVT VT = Tmp3.getValueType();
1488 switch (TLI.getOperationAction(ISD::STORE, VT)) {
1489 default: assert(0 && "This action is not supported yet!");
1490 case TargetLowering::Legal:
1491 // If this is an unaligned store and the target doesn't support it,
1493 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1494 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1495 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1496 if (ST->getAlignment() < ABIAlignment)
1497 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1501 case TargetLowering::Custom:
1502 Tmp1 = TLI.LowerOperation(Result, DAG);
1503 if (Tmp1.getNode()) Result = Tmp1;
1505 case TargetLowering::Promote:
1506 assert(VT.isVector() && "Unknown legal promote case!");
1507 Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1508 TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1509 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1510 ST->getPointerInfo(), isVolatile,
1511 isNonTemporal, Alignment);
1517 Tmp3 = LegalizeOp(ST->getValue());
1519 EVT StVT = ST->getMemoryVT();
1520 unsigned StWidth = StVT.getSizeInBits();
1522 if (StWidth != StVT.getStoreSizeInBits()) {
1523 // Promote to a byte-sized store with upper bits zero if not
1524 // storing an integral number of bytes. For example, promote
1525 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1526 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1527 StVT.getStoreSizeInBits());
1528 Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1529 Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1530 NVT, isVolatile, isNonTemporal, Alignment);
1531 } else if (StWidth & (StWidth - 1)) {
1532 // If not storing a power-of-2 number of bits, expand as two stores.
1533 assert(!StVT.isVector() && "Unsupported truncstore!");
1534 unsigned RoundWidth = 1 << Log2_32(StWidth);
1535 assert(RoundWidth < StWidth);
1536 unsigned ExtraWidth = StWidth - RoundWidth;
1537 assert(ExtraWidth < RoundWidth);
1538 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1539 "Store size not an integral number of bytes!");
1540 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1541 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1543 unsigned IncrementSize;
1545 if (TLI.isLittleEndian()) {
1546 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1547 // Store the bottom RoundWidth bits.
1548 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1550 isVolatile, isNonTemporal, Alignment);
1552 // Store the remaining ExtraWidth bits.
1553 IncrementSize = RoundWidth / 8;
1554 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1555 DAG.getIntPtrConstant(IncrementSize));
1556 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1557 DAG.getConstant(RoundWidth,
1558 TLI.getShiftAmountTy(Tmp3.getValueType())));
1559 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
1560 ST->getPointerInfo().getWithOffset(IncrementSize),
1561 ExtraVT, isVolatile, isNonTemporal,
1562 MinAlign(Alignment, IncrementSize));
1564 // Big endian - avoid unaligned stores.
1565 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1566 // Store the top RoundWidth bits.
1567 Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1568 DAG.getConstant(ExtraWidth,
1569 TLI.getShiftAmountTy(Tmp3.getValueType())));
1570 Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
1571 RoundVT, isVolatile, isNonTemporal, Alignment);
1573 // Store the remaining ExtraWidth bits.
1574 IncrementSize = RoundWidth / 8;
1575 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1576 DAG.getIntPtrConstant(IncrementSize));
1577 Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
1578 ST->getPointerInfo().getWithOffset(IncrementSize),
1579 ExtraVT, isVolatile, isNonTemporal,
1580 MinAlign(Alignment, IncrementSize));
1583 // The order of the stores doesn't matter.
1584 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1586 if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1587 Tmp2 != ST->getBasePtr())
1588 Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1593 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1594 default: assert(0 && "This action is not supported yet!");
1595 case TargetLowering::Legal:
1596 // If this is an unaligned store and the target doesn't support it,
1598 if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1599 const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1600 unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1601 if (ST->getAlignment() < ABIAlignment)
1602 Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1606 case TargetLowering::Custom:
1607 Result = TLI.LowerOperation(Result, DAG);
1609 case TargetLowering::Expand:
1611 EVT WideScalarVT = Tmp3.getValueType().getScalarType();
1612 EVT NarrowScalarVT = StVT.getScalarType();
1614 // The Store type is illegal, must scalarize the vector store.
1615 SmallVector<SDValue, 8> Stores;
1616 bool ScalarLegal = TLI.isTypeLegal(WideScalarVT);
1617 if (!TLI.isTypeLegal(StVT) && StVT.isVector() && ScalarLegal) {
1618 unsigned NumElem = StVT.getVectorNumElements();
1620 unsigned ScalarSize = StVT.getScalarType().getSizeInBits();
1621 // Round odd types to the next pow of two.
1622 if (!isPowerOf2_32(ScalarSize))
1623 ScalarSize = NextPowerOf2(ScalarSize);
1624 // Types smaller than 8 bits are promoted to 8 bits.
1625 ScalarSize = std::max<unsigned>(ScalarSize, 8);
1627 unsigned Stride = ScalarSize/8;
1628 assert(isPowerOf2_32(Stride) && "Stride must be a power of two");
1630 for (unsigned Idx=0; Idx<NumElem; Idx++) {
1631 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1632 WideScalarVT, Tmp3, DAG.getIntPtrConstant(Idx));
1635 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), ScalarSize);
1637 Ex = DAG.getNode(ISD::TRUNCATE, dl, NVT, Ex);
1638 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1639 DAG.getIntPtrConstant(Stride));
1640 SDValue Store = DAG.getStore(Tmp1, dl, Ex, Tmp2,
1641 ST->getPointerInfo().getWithOffset(Idx*Stride),
1642 isVolatile, isNonTemporal, Alignment);
1643 Stores.push_back(Store);
1645 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1646 &Stores[0], Stores.size());
1650 // The Store type is illegal, must scalarize the vector store.
1651 // However, the scalar type is illegal. Must bitcast the result
1652 // and store it in smaller parts.
1653 if (!TLI.isTypeLegal(StVT) && StVT.isVector()) {
1654 unsigned WideNumElem = StVT.getVectorNumElements();
1655 unsigned Stride = NarrowScalarVT.getSizeInBits()/8;
1657 unsigned SizeRatio =
1658 (WideScalarVT.getSizeInBits() / NarrowScalarVT.getSizeInBits());
1660 EVT CastValueVT = EVT::getVectorVT(*DAG.getContext(), NarrowScalarVT,
1661 SizeRatio*WideNumElem);
1663 // Cast the wide elem vector to wider vec with smaller elem type.
1664 // Example <2 x i64> -> <4 x i32>
1665 Tmp3 = DAG.getNode(ISD::BITCAST, dl, CastValueVT, Tmp3);
1667 for (unsigned Idx=0; Idx<WideNumElem*SizeRatio; Idx++) {
1669 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1670 NarrowScalarVT, Tmp3, DAG.getIntPtrConstant(Idx));
1672 Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1673 DAG.getIntPtrConstant(Stride));
1675 // Store if, this element is:
1676 // - First element on big endian, or
1677 // - Last element on little endian
1678 if (( TLI.isBigEndian() && (Idx%SizeRatio == 0)) ||
1679 ((!TLI.isBigEndian() && (Idx%SizeRatio == SizeRatio-1)))) {
1680 SDValue Store = DAG.getStore(Tmp1, dl, Ex, Tmp2,
1681 ST->getPointerInfo().getWithOffset(Idx*Stride),
1682 isVolatile, isNonTemporal, Alignment);
1683 Stores.push_back(Store);
1686 Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1687 &Stores[0], Stores.size());
1692 // TRUNCSTORE:i16 i32 -> STORE i16
1693 assert(TLI.isTypeLegal(StVT) && "Do not know how to expand this store!");
1694 Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1695 Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1696 isVolatile, isNonTemporal, Alignment);
1704 assert(Result.getValueType() == Op.getValueType() &&
1705 "Bad legalization!");
1707 // Make sure that the generated code is itself legal.
1709 Result = LegalizeOp(Result);
1711 // Note that LegalizeOp may be reentered even from single-use nodes, which
1712 // means that we always must cache transformed nodes.
1713 AddLegalizedOperand(Op, Result);
1717 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1718 SDValue Vec = Op.getOperand(0);
1719 SDValue Idx = Op.getOperand(1);
1720 DebugLoc dl = Op.getDebugLoc();
1721 // Store the value to a temporary stack slot, then LOAD the returned part.
1722 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1723 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1724 MachinePointerInfo(), false, false, 0);
1726 // Add the offset to the index.
1728 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1729 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1730 DAG.getConstant(EltSize, Idx.getValueType()));
1732 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1733 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1735 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1737 StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1739 if (Op.getValueType().isVector())
1740 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1742 return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1743 MachinePointerInfo(),
1744 Vec.getValueType().getVectorElementType(),
1748 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1749 assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1751 SDValue Vec = Op.getOperand(0);
1752 SDValue Part = Op.getOperand(1);
1753 SDValue Idx = Op.getOperand(2);
1754 DebugLoc dl = Op.getDebugLoc();
1756 // Store the value to a temporary stack slot, then LOAD the returned part.
1758 SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1759 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1760 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1762 // First store the whole vector.
1763 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1766 // Then store the inserted part.
1768 // Add the offset to the index.
1770 Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1772 Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1773 DAG.getConstant(EltSize, Idx.getValueType()));
1775 if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1776 Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1778 Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1780 SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1783 // Store the subvector.
1784 Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1785 MachinePointerInfo(), false, false, 0);
1787 // Finally, load the updated vector.
1788 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1792 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1793 // We can't handle this case efficiently. Allocate a sufficiently
1794 // aligned object on the stack, store each element into it, then load
1795 // the result as a vector.
1796 // Create the stack frame object.
1797 EVT VT = Node->getValueType(0);
1798 EVT EltVT = VT.getVectorElementType();
1799 DebugLoc dl = Node->getDebugLoc();
1800 SDValue FIPtr = DAG.CreateStackTemporary(VT);
1801 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1802 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1804 // Emit a store of each element to the stack slot.
1805 SmallVector<SDValue, 8> Stores;
1806 unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1807 // Store (in the right endianness) the elements to memory.
1808 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1809 // Ignore undef elements.
1810 if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1812 unsigned Offset = TypeByteSize*i;
1814 SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1815 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1817 // If the destination vector element type is narrower than the source
1818 // element type, only store the bits necessary.
1819 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1820 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1821 Node->getOperand(i), Idx,
1822 PtrInfo.getWithOffset(Offset),
1823 EltVT, false, false, 0));
1825 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1826 Node->getOperand(i), Idx,
1827 PtrInfo.getWithOffset(Offset),
1832 if (!Stores.empty()) // Not all undef elements?
1833 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1834 &Stores[0], Stores.size());
1836 StoreChain = DAG.getEntryNode();
1838 // Result is a load from the stack slot.
1839 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
1842 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1843 DebugLoc dl = Node->getDebugLoc();
1844 SDValue Tmp1 = Node->getOperand(0);
1845 SDValue Tmp2 = Node->getOperand(1);
1847 // Get the sign bit of the RHS. First obtain a value that has the same
1848 // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1850 EVT FloatVT = Tmp2.getValueType();
1851 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1852 if (TLI.isTypeLegal(IVT)) {
1853 // Convert to an integer with the same sign bit.
1854 SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1856 // Store the float to memory, then load the sign part out as an integer.
1857 MVT LoadTy = TLI.getPointerTy();
1858 // First create a temporary that is aligned for both the load and store.
1859 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1860 // Then store the float to it.
1862 DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1864 if (TLI.isBigEndian()) {
1865 assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1866 // Load out a legal integer with the same sign bit as the float.
1867 SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1869 } else { // Little endian
1870 SDValue LoadPtr = StackPtr;
1871 // The float may be wider than the integer we are going to load. Advance
1872 // the pointer so that the loaded integer will contain the sign bit.
1873 unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1874 unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1875 LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1876 LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1877 // Load a legal integer containing the sign bit.
1878 SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1880 // Move the sign bit to the top bit of the loaded integer.
1881 unsigned BitShift = LoadTy.getSizeInBits() -
1882 (FloatVT.getSizeInBits() - 8 * ByteOffset);
1883 assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1885 SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1886 DAG.getConstant(BitShift,
1887 TLI.getShiftAmountTy(SignBit.getValueType())));
1890 // Now get the sign bit proper, by seeing whether the value is negative.
1891 SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1892 SignBit, DAG.getConstant(0, SignBit.getValueType()),
1894 // Get the absolute value of the result.
1895 SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1896 // Select between the nabs and abs value based on the sign bit of
1898 return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1899 DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1903 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1904 SmallVectorImpl<SDValue> &Results) {
1905 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1906 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1907 " not tell us which reg is the stack pointer!");
1908 DebugLoc dl = Node->getDebugLoc();
1909 EVT VT = Node->getValueType(0);
1910 SDValue Tmp1 = SDValue(Node, 0);
1911 SDValue Tmp2 = SDValue(Node, 1);
1912 SDValue Tmp3 = Node->getOperand(2);
1913 SDValue Chain = Tmp1.getOperand(0);
1915 // Chain the dynamic stack allocation so that it doesn't modify the stack
1916 // pointer when other instructions are using the stack.
1917 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1919 SDValue Size = Tmp2.getOperand(1);
1920 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1921 Chain = SP.getValue(1);
1922 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1923 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1924 if (Align > StackAlign)
1925 SP = DAG.getNode(ISD::AND, dl, VT, SP,
1926 DAG.getConstant(-(uint64_t)Align, VT));
1927 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1928 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1930 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1931 DAG.getIntPtrConstant(0, true), SDValue());
1933 Results.push_back(Tmp1);
1934 Results.push_back(Tmp2);
1937 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1938 /// condition code CC on the current target. This routine expands SETCC with
1939 /// illegal condition code into AND / OR of multiple SETCC values.
1940 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1941 SDValue &LHS, SDValue &RHS,
1944 EVT OpVT = LHS.getValueType();
1945 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1946 switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1947 default: assert(0 && "Unknown condition code action!");
1948 case TargetLowering::Legal:
1951 case TargetLowering::Expand: {
1952 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1955 default: assert(0 && "Don't know how to expand this condition!");
1956 case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO; Opc = ISD::AND; break;
1957 case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1958 case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1959 case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO; Opc = ISD::AND; break;
1960 case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1961 case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO; Opc = ISD::AND; break;
1962 case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1963 case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1964 case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1965 case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1966 case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1967 case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR; break;
1968 // FIXME: Implement more expansions.
1971 SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1972 SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1973 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1981 /// EmitStackConvert - Emit a store/load combination to the stack. This stores
1982 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1983 /// a load from the stack slot to DestVT, extending it if needed.
1984 /// The resultant code need not be legal.
1985 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1989 // Create the stack frame object.
1991 TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1992 getTypeForEVT(*DAG.getContext()));
1993 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1995 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1996 int SPFI = StackPtrFI->getIndex();
1997 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1999 unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
2000 unsigned SlotSize = SlotVT.getSizeInBits();
2001 unsigned DestSize = DestVT.getSizeInBits();
2002 const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
2003 unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
2005 // Emit a store to the stack slot. Use a truncstore if the input value is
2006 // later than DestVT.
2009 if (SrcSize > SlotSize)
2010 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2011 PtrInfo, SlotVT, false, false, SrcAlign);
2013 assert(SrcSize == SlotSize && "Invalid store");
2014 Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2015 PtrInfo, false, false, SrcAlign);
2018 // Result is a load from the stack slot.
2019 if (SlotSize == DestSize)
2020 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
2021 false, false, DestAlign);
2023 assert(SlotSize < DestSize && "Unknown extension!");
2024 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
2025 PtrInfo, SlotVT, false, false, DestAlign);
2028 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
2029 DebugLoc dl = Node->getDebugLoc();
2030 // Create a vector sized/aligned stack slot, store the value to element #0,
2031 // then load the whole vector back out.
2032 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
2034 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
2035 int SPFI = StackPtrFI->getIndex();
2037 SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
2039 MachinePointerInfo::getFixedStack(SPFI),
2040 Node->getValueType(0).getVectorElementType(),
2042 return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
2043 MachinePointerInfo::getFixedStack(SPFI),
2048 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
2049 /// support the operation, but do support the resultant vector type.
2050 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2051 unsigned NumElems = Node->getNumOperands();
2052 SDValue Value1, Value2;
2053 DebugLoc dl = Node->getDebugLoc();
2054 EVT VT = Node->getValueType(0);
2055 EVT OpVT = Node->getOperand(0).getValueType();
2056 EVT EltVT = VT.getVectorElementType();
2058 // If the only non-undef value is the low element, turn this into a
2059 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
2060 bool isOnlyLowElement = true;
2061 bool MoreThanTwoValues = false;
2062 bool isConstant = true;
2063 for (unsigned i = 0; i < NumElems; ++i) {
2064 SDValue V = Node->getOperand(i);
2065 if (V.getOpcode() == ISD::UNDEF)
2068 isOnlyLowElement = false;
2069 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
2072 if (!Value1.getNode()) {
2074 } else if (!Value2.getNode()) {
2077 } else if (V != Value1 && V != Value2) {
2078 MoreThanTwoValues = true;
2082 if (!Value1.getNode())
2083 return DAG.getUNDEF(VT);
2085 if (isOnlyLowElement)
2086 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2088 // If all elements are constants, create a load from the constant pool.
2090 std::vector<Constant*> CV;
2091 for (unsigned i = 0, e = NumElems; i != e; ++i) {
2092 if (ConstantFPSDNode *V =
2093 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2094 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2095 } else if (ConstantSDNode *V =
2096 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2098 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2100 // If OpVT and EltVT don't match, EltVT is not legal and the
2101 // element values have been promoted/truncated earlier. Undo this;
2102 // we don't want a v16i8 to become a v16i32 for example.
2103 const ConstantInt *CI = V->getConstantIntValue();
2104 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2105 CI->getZExtValue()));
2108 assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
2109 const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2110 CV.push_back(UndefValue::get(OpNTy));
2113 Constant *CP = ConstantVector::get(CV);
2114 SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
2115 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2116 return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
2117 MachinePointerInfo::getConstantPool(),
2118 false, false, Alignment);
2121 if (!MoreThanTwoValues) {
2122 SmallVector<int, 8> ShuffleVec(NumElems, -1);
2123 for (unsigned i = 0; i < NumElems; ++i) {
2124 SDValue V = Node->getOperand(i);
2125 if (V.getOpcode() == ISD::UNDEF)
2127 ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2129 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2130 // Get the splatted value into the low element of a vector register.
2131 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2133 if (Value2.getNode())
2134 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2136 Vec2 = DAG.getUNDEF(VT);
2138 // Return shuffle(LowValVec, undef, <0,0,0,0>)
2139 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2143 // Otherwise, we can't handle this case efficiently.
2144 return ExpandVectorBuildThroughStack(Node);
2147 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
2148 // does not fit into a register, return the lo part and set the hi part to the
2149 // by-reg argument. If it does fit into a single register, return the result
2150 // and leave the Hi part unset.
2151 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2153 // The input chain to this libcall is the entry node of the function.
2154 // Legalizing the call will automatically add the previous call to the
2156 SDValue InChain = DAG.getEntryNode();
2158 TargetLowering::ArgListTy Args;
2159 TargetLowering::ArgListEntry Entry;
2160 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2161 EVT ArgVT = Node->getOperand(i).getValueType();
2162 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2163 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2164 Entry.isSExt = isSigned;
2165 Entry.isZExt = !isSigned;
2166 Args.push_back(Entry);
2168 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2169 TLI.getPointerTy());
2171 // Splice the libcall in wherever FindInputOutputChains tells us to.
2172 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2174 // isTailCall may be true since the callee does not reference caller stack
2175 // frame. Check if it's in the right position.
2176 bool isTailCall = isInTailCallPosition(DAG, Node, TLI);
2177 std::pair<SDValue, SDValue> CallInfo =
2178 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2179 0, TLI.getLibcallCallingConv(LC), isTailCall,
2180 /*isReturnValueUsed=*/true,
2181 Callee, Args, DAG, Node->getDebugLoc());
2183 if (!CallInfo.second.getNode())
2184 // It's a tailcall, return the chain (which is the DAG root).
2185 return DAG.getRoot();
2187 // Legalize the call sequence, starting with the chain. This will advance
2188 // the LastCALLSEQ to the legalized version of the CALLSEQ_END node that
2189 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2190 LegalizeOp(CallInfo.second);
2191 return CallInfo.first;
2194 /// ExpandLibCall - Generate a libcall taking the given operands as arguments
2195 /// and returning a result of type RetVT.
2196 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2197 const SDValue *Ops, unsigned NumOps,
2198 bool isSigned, DebugLoc dl) {
2199 TargetLowering::ArgListTy Args;
2200 Args.reserve(NumOps);
2202 TargetLowering::ArgListEntry Entry;
2203 for (unsigned i = 0; i != NumOps; ++i) {
2204 Entry.Node = Ops[i];
2205 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2206 Entry.isSExt = isSigned;
2207 Entry.isZExt = !isSigned;
2208 Args.push_back(Entry);
2210 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2211 TLI.getPointerTy());
2213 const Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2214 std::pair<SDValue,SDValue> CallInfo =
2215 TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
2216 false, 0, TLI.getLibcallCallingConv(LC), false,
2217 /*isReturnValueUsed=*/true,
2218 Callee, Args, DAG, dl);
2220 // Legalize the call sequence, starting with the chain. This will advance
2221 // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2222 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2223 LegalizeOp(CallInfo.second);
2225 return CallInfo.first;
2228 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
2229 // ExpandLibCall except that the first operand is the in-chain.
2230 std::pair<SDValue, SDValue>
2231 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2234 SDValue InChain = Node->getOperand(0);
2236 TargetLowering::ArgListTy Args;
2237 TargetLowering::ArgListEntry Entry;
2238 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2239 EVT ArgVT = Node->getOperand(i).getValueType();
2240 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2241 Entry.Node = Node->getOperand(i);
2243 Entry.isSExt = isSigned;
2244 Entry.isZExt = !isSigned;
2245 Args.push_back(Entry);
2247 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2248 TLI.getPointerTy());
2250 // Splice the libcall in wherever FindInputOutputChains tells us to.
2251 const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2252 std::pair<SDValue, SDValue> CallInfo =
2253 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2254 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2255 /*isReturnValueUsed=*/true,
2256 Callee, Args, DAG, Node->getDebugLoc());
2258 // Legalize the call sequence, starting with the chain. This will advance
2259 // the LastCALLSEQ to the legalized version of the CALLSEQ_END node that
2260 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2261 LegalizeOp(CallInfo.second);
2265 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2266 RTLIB::Libcall Call_F32,
2267 RTLIB::Libcall Call_F64,
2268 RTLIB::Libcall Call_F80,
2269 RTLIB::Libcall Call_PPCF128) {
2271 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2272 default: assert(0 && "Unexpected request for libcall!");
2273 case MVT::f32: LC = Call_F32; break;
2274 case MVT::f64: LC = Call_F64; break;
2275 case MVT::f80: LC = Call_F80; break;
2276 case MVT::ppcf128: LC = Call_PPCF128; break;
2278 return ExpandLibCall(LC, Node, false);
2281 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2282 RTLIB::Libcall Call_I8,
2283 RTLIB::Libcall Call_I16,
2284 RTLIB::Libcall Call_I32,
2285 RTLIB::Libcall Call_I64,
2286 RTLIB::Libcall Call_I128) {
2288 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2289 default: assert(0 && "Unexpected request for libcall!");
2290 case MVT::i8: LC = Call_I8; break;
2291 case MVT::i16: LC = Call_I16; break;
2292 case MVT::i32: LC = Call_I32; break;
2293 case MVT::i64: LC = Call_I64; break;
2294 case MVT::i128: LC = Call_I128; break;
2296 return ExpandLibCall(LC, Node, isSigned);
2299 /// isDivRemLibcallAvailable - Return true if divmod libcall is available.
2300 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2301 const TargetLowering &TLI) {
2303 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2304 default: assert(0 && "Unexpected request for libcall!");
2305 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2306 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2307 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2308 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2309 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2312 return TLI.getLibcallName(LC) != 0;
2315 /// UseDivRem - Only issue divrem libcall if both quotient and remainder are
2317 static bool UseDivRem(SDNode *Node, bool isSigned, bool isDIV) {
2318 unsigned OtherOpcode = 0;
2320 OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
2322 OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
2324 SDValue Op0 = Node->getOperand(0);
2325 SDValue Op1 = Node->getOperand(1);
2326 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2327 UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2331 if (User->getOpcode() == OtherOpcode &&
2332 User->getOperand(0) == Op0 &&
2333 User->getOperand(1) == Op1)
2339 /// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
2342 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2343 SmallVectorImpl<SDValue> &Results) {
2344 unsigned Opcode = Node->getOpcode();
2345 bool isSigned = Opcode == ISD::SDIVREM;
2348 switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2349 default: assert(0 && "Unexpected request for libcall!");
2350 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2351 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2352 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2353 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2354 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2357 // The input chain to this libcall is the entry node of the function.
2358 // Legalizing the call will automatically add the previous call to the
2360 SDValue InChain = DAG.getEntryNode();
2362 EVT RetVT = Node->getValueType(0);
2363 const Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2365 TargetLowering::ArgListTy Args;
2366 TargetLowering::ArgListEntry Entry;
2367 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2368 EVT ArgVT = Node->getOperand(i).getValueType();
2369 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2370 Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2371 Entry.isSExt = isSigned;
2372 Entry.isZExt = !isSigned;
2373 Args.push_back(Entry);
2376 // Also pass the return address of the remainder.
2377 SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2379 Entry.Ty = RetTy->getPointerTo();
2380 Entry.isSExt = isSigned;
2381 Entry.isZExt = !isSigned;
2382 Args.push_back(Entry);
2384 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2385 TLI.getPointerTy());
2387 // Splice the libcall in wherever FindInputOutputChains tells us to.
2388 DebugLoc dl = Node->getDebugLoc();
2389 std::pair<SDValue, SDValue> CallInfo =
2390 TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2391 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2392 /*isReturnValueUsed=*/true, Callee, Args, DAG, dl);
2394 // Legalize the call sequence, starting with the chain. This will advance
2395 // the LastCALLSEQ to the legalized version of the CALLSEQ_END node that
2396 // was added by LowerCallTo (guaranteeing proper serialization of calls).
2397 LegalizeOp(CallInfo.second);
2399 // Remainder is loaded back from the stack frame.
2400 SDValue Rem = DAG.getLoad(RetVT, dl, getLastCALLSEQ(), FIPtr,
2401 MachinePointerInfo(), false, false, 0);
2402 Results.push_back(CallInfo.first);
2403 Results.push_back(Rem);
2406 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2407 /// INT_TO_FP operation of the specified operand when the target requests that
2408 /// we expand it. At this point, we know that the result and operand types are
2409 /// legal for the target.
2410 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2414 if (Op0.getValueType() == MVT::i32) {
2415 // simple 32-bit [signed|unsigned] integer to float/double expansion
2417 // Get the stack frame index of a 8 byte buffer.
2418 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2420 // word offset constant for Hi/Lo address computation
2421 SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2422 // set up Hi and Lo (into buffer) address based on endian
2423 SDValue Hi = StackSlot;
2424 SDValue Lo = DAG.getNode(ISD::ADD, dl,
2425 TLI.getPointerTy(), StackSlot, WordOff);
2426 if (TLI.isLittleEndian())
2429 // if signed map to unsigned space
2432 // constant used to invert sign bit (signed to unsigned mapping)
2433 SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2434 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2438 // store the lo of the constructed double - based on integer input
2439 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2440 Op0Mapped, Lo, MachinePointerInfo(),
2442 // initial hi portion of constructed double
2443 SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2444 // store the hi of the constructed double - biased exponent
2445 SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2446 MachinePointerInfo(),
2448 // load the constructed double
2449 SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2450 MachinePointerInfo(), false, false, 0);
2451 // FP constant to bias correct the final result
2452 SDValue Bias = DAG.getConstantFP(isSigned ?
2453 BitsToDouble(0x4330000080000000ULL) :
2454 BitsToDouble(0x4330000000000000ULL),
2456 // subtract the bias
2457 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2460 // handle final rounding
2461 if (DestVT == MVT::f64) {
2464 } else if (DestVT.bitsLT(MVT::f64)) {
2465 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2466 DAG.getIntPtrConstant(0));
2467 } else if (DestVT.bitsGT(MVT::f64)) {
2468 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2472 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2473 // Code below here assumes !isSigned without checking again.
2475 // Implementation of unsigned i64 to f64 following the algorithm in
2476 // __floatundidf in compiler_rt. This implementation has the advantage
2477 // of performing rounding correctly, both in the default rounding mode
2478 // and in all alternate rounding modes.
2479 // TODO: Generalize this for use with other types.
2480 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2482 DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2483 SDValue TwoP84PlusTwoP52 =
2484 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2486 DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2488 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2489 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2490 DAG.getConstant(32, MVT::i64));
2491 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2492 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2493 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2494 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2495 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2497 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2500 // Implementation of unsigned i64 to f32.
2501 // TODO: Generalize this for use with other types.
2502 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2503 // For unsigned conversions, convert them to signed conversions using the
2504 // algorithm from the x86_64 __floatundidf in compiler_rt.
2506 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2508 SDValue ShiftConst =
2509 DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2510 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2511 SDValue AndConst = DAG.getConstant(1, MVT::i64);
2512 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2513 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2515 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2516 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2518 // TODO: This really should be implemented using a branch rather than a
2519 // select. We happen to get lucky and machinesink does the right
2520 // thing most of the time. This would be a good candidate for a
2521 //pseudo-op, or, even better, for whole-function isel.
2522 SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2523 Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2524 return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2527 // Otherwise, implement the fully general conversion.
2529 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2530 DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2531 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2532 DAG.getConstant(UINT64_C(0x800), MVT::i64));
2533 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2534 DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2535 SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2536 And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2537 SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2538 SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2539 Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2541 SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2542 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2544 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2545 DAG.getConstant(32, SHVT));
2546 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2547 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2549 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2550 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2551 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2552 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2553 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2554 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2555 DAG.getIntPtrConstant(0));
2558 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2560 SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2561 Op0, DAG.getConstant(0, Op0.getValueType()),
2563 SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2564 SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2565 SignSet, Four, Zero);
2567 // If the sign bit of the integer is set, the large number will be treated
2568 // as a negative number. To counteract this, the dynamic code adds an
2569 // offset depending on the data type.
2571 switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2572 default: assert(0 && "Unsupported integer type!");
2573 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2574 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2575 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2576 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2578 if (TLI.isLittleEndian()) FF <<= 32;
2579 Constant *FudgeFactor = ConstantInt::get(
2580 Type::getInt64Ty(*DAG.getContext()), FF);
2582 SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2583 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2584 CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2585 Alignment = std::min(Alignment, 4u);
2587 if (DestVT == MVT::f32)
2588 FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2589 MachinePointerInfo::getConstantPool(),
2590 false, false, Alignment);
2593 LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2594 DAG.getEntryNode(), CPIdx,
2595 MachinePointerInfo::getConstantPool(),
2596 MVT::f32, false, false, Alignment));
2599 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2602 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2603 /// *INT_TO_FP operation of the specified operand when the target requests that
2604 /// we promote it. At this point, we know that the result and operand types are
2605 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2606 /// operation that takes a larger input.
2607 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2611 // First step, figure out the appropriate *INT_TO_FP operation to use.
2612 EVT NewInTy = LegalOp.getValueType();
2614 unsigned OpToUse = 0;
2616 // Scan for the appropriate larger type to use.
2618 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2619 assert(NewInTy.isInteger() && "Ran out of possibilities!");
2621 // If the target supports SINT_TO_FP of this type, use it.
2622 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2623 OpToUse = ISD::SINT_TO_FP;
2626 if (isSigned) continue;
2628 // If the target supports UINT_TO_FP of this type, use it.
2629 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2630 OpToUse = ISD::UINT_TO_FP;
2634 // Otherwise, try a larger type.
2637 // Okay, we found the operation and type to use. Zero extend our input to the
2638 // desired type then run the operation on it.
2639 return DAG.getNode(OpToUse, dl, DestVT,
2640 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2641 dl, NewInTy, LegalOp));
2644 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2645 /// FP_TO_*INT operation of the specified operand when the target requests that
2646 /// we promote it. At this point, we know that the result and operand types are
2647 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2648 /// operation that returns a larger result.
2649 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2653 // First step, figure out the appropriate FP_TO*INT operation to use.
2654 EVT NewOutTy = DestVT;
2656 unsigned OpToUse = 0;
2658 // Scan for the appropriate larger type to use.
2660 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2661 assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2663 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2664 OpToUse = ISD::FP_TO_SINT;
2668 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2669 OpToUse = ISD::FP_TO_UINT;
2673 // Otherwise, try a larger type.
2677 // Okay, we found the operation and type to use.
2678 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2680 // Truncate the result of the extended FP_TO_*INT operation to the desired
2682 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2685 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2687 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2688 EVT VT = Op.getValueType();
2689 EVT SHVT = TLI.getShiftAmountTy(VT);
2690 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2691 switch (VT.getSimpleVT().SimpleTy) {
2692 default: assert(0 && "Unhandled Expand type in BSWAP!");
2694 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2695 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2696 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2698 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2699 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2700 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2701 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2702 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2703 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2704 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2705 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2706 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2708 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2709 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2710 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2711 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2712 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2713 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2714 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2715 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2716 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2717 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2718 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2719 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2720 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2721 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2722 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2723 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2724 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2725 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2726 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2727 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2728 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2732 /// SplatByte - Distribute ByteVal over NumBits bits.
2733 // FIXME: Move this helper to a common place.
2734 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
2735 APInt Val = APInt(NumBits, ByteVal);
2737 for (unsigned i = NumBits; i > 8; i >>= 1) {
2738 Val = (Val << Shift) | Val;
2744 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2746 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2749 default: assert(0 && "Cannot expand this yet!");
2751 EVT VT = Op.getValueType();
2752 EVT ShVT = TLI.getShiftAmountTy(VT);
2753 unsigned Len = VT.getSizeInBits();
2755 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2756 "CTPOP not implemented for this type.");
2758 // This is the "best" algorithm from
2759 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2761 SDValue Mask55 = DAG.getConstant(SplatByte(Len, 0x55), VT);
2762 SDValue Mask33 = DAG.getConstant(SplatByte(Len, 0x33), VT);
2763 SDValue Mask0F = DAG.getConstant(SplatByte(Len, 0x0F), VT);
2764 SDValue Mask01 = DAG.getConstant(SplatByte(Len, 0x01), VT);
2766 // v = v - ((v >> 1) & 0x55555555...)
2767 Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2768 DAG.getNode(ISD::AND, dl, VT,
2769 DAG.getNode(ISD::SRL, dl, VT, Op,
2770 DAG.getConstant(1, ShVT)),
2772 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2773 Op = DAG.getNode(ISD::ADD, dl, VT,
2774 DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2775 DAG.getNode(ISD::AND, dl, VT,
2776 DAG.getNode(ISD::SRL, dl, VT, Op,
2777 DAG.getConstant(2, ShVT)),
2779 // v = (v + (v >> 4)) & 0x0F0F0F0F...
2780 Op = DAG.getNode(ISD::AND, dl, VT,
2781 DAG.getNode(ISD::ADD, dl, VT, Op,
2782 DAG.getNode(ISD::SRL, dl, VT, Op,
2783 DAG.getConstant(4, ShVT))),
2785 // v = (v * 0x01010101...) >> (Len - 8)
2786 Op = DAG.getNode(ISD::SRL, dl, VT,
2787 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2788 DAG.getConstant(Len - 8, ShVT));
2793 // for now, we do this:
2794 // x = x | (x >> 1);
2795 // x = x | (x >> 2);
2797 // x = x | (x >>16);
2798 // x = x | (x >>32); // for 64-bit input
2799 // return popcount(~x);
2801 // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2802 EVT VT = Op.getValueType();
2803 EVT ShVT = TLI.getShiftAmountTy(VT);
2804 unsigned len = VT.getSizeInBits();
2805 for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2806 SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2807 Op = DAG.getNode(ISD::OR, dl, VT, Op,
2808 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2810 Op = DAG.getNOT(dl, Op, VT);
2811 return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2814 // for now, we use: { return popcount(~x & (x - 1)); }
2815 // unless the target has ctlz but not ctpop, in which case we use:
2816 // { return 32 - nlz(~x & (x-1)); }
2817 // see also http://www.hackersdelight.org/HDcode/ntz.cc
2818 EVT VT = Op.getValueType();
2819 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2820 DAG.getNOT(dl, Op, VT),
2821 DAG.getNode(ISD::SUB, dl, VT, Op,
2822 DAG.getConstant(1, VT)));
2823 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2824 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2825 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2826 return DAG.getNode(ISD::SUB, dl, VT,
2827 DAG.getConstant(VT.getSizeInBits(), VT),
2828 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2829 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2834 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2835 unsigned Opc = Node->getOpcode();
2836 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2841 llvm_unreachable("Unhandled atomic intrinsic Expand!");
2843 case ISD::ATOMIC_SWAP:
2844 switch (VT.SimpleTy) {
2845 default: llvm_unreachable("Unexpected value type for atomic!");
2846 case MVT::i8: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2847 case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2848 case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2849 case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2852 case ISD::ATOMIC_CMP_SWAP:
2853 switch (VT.SimpleTy) {
2854 default: llvm_unreachable("Unexpected value type for atomic!");
2855 case MVT::i8: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2856 case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2857 case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2858 case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2861 case ISD::ATOMIC_LOAD_ADD:
2862 switch (VT.SimpleTy) {
2863 default: llvm_unreachable("Unexpected value type for atomic!");
2864 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2865 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2866 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2867 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2870 case ISD::ATOMIC_LOAD_SUB:
2871 switch (VT.SimpleTy) {
2872 default: llvm_unreachable("Unexpected value type for atomic!");
2873 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2874 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2875 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2876 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2879 case ISD::ATOMIC_LOAD_AND:
2880 switch (VT.SimpleTy) {
2881 default: llvm_unreachable("Unexpected value type for atomic!");
2882 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2883 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2884 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2885 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2888 case ISD::ATOMIC_LOAD_OR:
2889 switch (VT.SimpleTy) {
2890 default: llvm_unreachable("Unexpected value type for atomic!");
2891 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2892 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2893 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2894 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2897 case ISD::ATOMIC_LOAD_XOR:
2898 switch (VT.SimpleTy) {
2899 default: llvm_unreachable("Unexpected value type for atomic!");
2900 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2901 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2902 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2903 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2906 case ISD::ATOMIC_LOAD_NAND:
2907 switch (VT.SimpleTy) {
2908 default: llvm_unreachable("Unexpected value type for atomic!");
2909 case MVT::i8: LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2910 case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2911 case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2912 case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2917 return ExpandChainLibCall(LC, Node, false);
2920 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2921 SmallVectorImpl<SDValue> &Results) {
2922 DebugLoc dl = Node->getDebugLoc();
2923 SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2924 switch (Node->getOpcode()) {
2928 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2929 Results.push_back(Tmp1);
2932 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2934 case ISD::FRAMEADDR:
2935 case ISD::RETURNADDR:
2936 case ISD::FRAME_TO_ARGS_OFFSET:
2937 Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2939 case ISD::FLT_ROUNDS_:
2940 Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2942 case ISD::EH_RETURN:
2946 case ISD::EH_SJLJ_LONGJMP:
2947 case ISD::EH_SJLJ_DISPATCHSETUP:
2948 // If the target didn't expand these, there's nothing to do, so just
2949 // preserve the chain and be done.
2950 Results.push_back(Node->getOperand(0));
2952 case ISD::EH_SJLJ_SETJMP:
2953 // If the target didn't expand this, just return 'zero' and preserve the
2955 Results.push_back(DAG.getConstant(0, MVT::i32));
2956 Results.push_back(Node->getOperand(0));
2958 case ISD::MEMBARRIER: {
2959 // If the target didn't lower this, lower it to '__sync_synchronize()' call
2960 TargetLowering::ArgListTy Args;
2961 std::pair<SDValue, SDValue> CallResult =
2962 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2963 false, false, false, false, 0, CallingConv::C,
2964 /*isTailCall=*/false,
2965 /*isReturnValueUsed=*/true,
2966 DAG.getExternalSymbol("__sync_synchronize",
2967 TLI.getPointerTy()),
2969 Results.push_back(CallResult.second);
2972 // By default, atomic intrinsics are marked Legal and lowered. Targets
2973 // which don't support them directly, however, may want libcalls, in which
2974 // case they mark them Expand, and we get here.
2975 case ISD::ATOMIC_SWAP:
2976 case ISD::ATOMIC_LOAD_ADD:
2977 case ISD::ATOMIC_LOAD_SUB:
2978 case ISD::ATOMIC_LOAD_AND:
2979 case ISD::ATOMIC_LOAD_OR:
2980 case ISD::ATOMIC_LOAD_XOR:
2981 case ISD::ATOMIC_LOAD_NAND:
2982 case ISD::ATOMIC_LOAD_MIN:
2983 case ISD::ATOMIC_LOAD_MAX:
2984 case ISD::ATOMIC_LOAD_UMIN:
2985 case ISD::ATOMIC_LOAD_UMAX:
2986 case ISD::ATOMIC_CMP_SWAP: {
2987 std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
2988 Results.push_back(Tmp.first);
2989 Results.push_back(Tmp.second);
2992 case ISD::DYNAMIC_STACKALLOC:
2993 ExpandDYNAMIC_STACKALLOC(Node, Results);
2995 case ISD::MERGE_VALUES:
2996 for (unsigned i = 0; i < Node->getNumValues(); i++)
2997 Results.push_back(Node->getOperand(i));
3000 EVT VT = Node->getValueType(0);
3002 Results.push_back(DAG.getConstant(0, VT));
3004 assert(VT.isFloatingPoint() && "Unknown value type!");
3005 Results.push_back(DAG.getConstantFP(0, VT));
3010 // If this operation is not supported, lower it to 'abort()' call
3011 TargetLowering::ArgListTy Args;
3012 std::pair<SDValue, SDValue> CallResult =
3013 TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
3014 false, false, false, false, 0, CallingConv::C,
3015 /*isTailCall=*/false,
3016 /*isReturnValueUsed=*/true,
3017 DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3019 Results.push_back(CallResult.second);
3024 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3025 Node->getValueType(0), dl);
3026 Results.push_back(Tmp1);
3028 case ISD::FP_EXTEND:
3029 Tmp1 = EmitStackConvert(Node->getOperand(0),
3030 Node->getOperand(0).getValueType(),
3031 Node->getValueType(0), dl);
3032 Results.push_back(Tmp1);
3034 case ISD::SIGN_EXTEND_INREG: {
3035 // NOTE: we could fall back on load/store here too for targets without
3036 // SAR. However, it is doubtful that any exist.
3037 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3038 EVT VT = Node->getValueType(0);
3039 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
3042 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3043 ExtraVT.getScalarType().getSizeInBits();
3044 SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
3045 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3046 Node->getOperand(0), ShiftCst);
3047 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3048 Results.push_back(Tmp1);
3051 case ISD::FP_ROUND_INREG: {
3052 // The only way we can lower this is to turn it into a TRUNCSTORE,
3053 // EXTLOAD pair, targeting a temporary location (a stack slot).
3055 // NOTE: there is a choice here between constantly creating new stack
3056 // slots and always reusing the same one. We currently always create
3057 // new ones, as reuse may inhibit scheduling.
3058 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3059 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3060 Node->getValueType(0), dl);
3061 Results.push_back(Tmp1);
3064 case ISD::SINT_TO_FP:
3065 case ISD::UINT_TO_FP:
3066 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3067 Node->getOperand(0), Node->getValueType(0), dl);
3068 Results.push_back(Tmp1);
3070 case ISD::FP_TO_UINT: {
3071 SDValue True, False;
3072 EVT VT = Node->getOperand(0).getValueType();
3073 EVT NVT = Node->getValueType(0);
3074 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
3075 APInt x = APInt::getSignBit(NVT.getSizeInBits());
3076 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3077 Tmp1 = DAG.getConstantFP(apf, VT);
3078 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
3079 Node->getOperand(0),
3081 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3082 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3083 DAG.getNode(ISD::FSUB, dl, VT,
3084 Node->getOperand(0), Tmp1));
3085 False = DAG.getNode(ISD::XOR, dl, NVT, False,
3086 DAG.getConstant(x, NVT));
3087 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
3088 Results.push_back(Tmp1);
3092 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3093 EVT VT = Node->getValueType(0);
3094 Tmp1 = Node->getOperand(0);
3095 Tmp2 = Node->getOperand(1);
3096 unsigned Align = Node->getConstantOperandVal(3);
3098 SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
3099 MachinePointerInfo(V), false, false, 0);
3100 SDValue VAList = VAListLoad;
3102 if (Align > TLI.getMinStackArgumentAlignment()) {
3103 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
3105 VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3106 DAG.getConstant(Align - 1,
3107 TLI.getPointerTy()));
3109 VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
3110 DAG.getConstant(-(int64_t)Align,
3111 TLI.getPointerTy()));
3114 // Increment the pointer, VAList, to the next vaarg
3115 Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3116 DAG.getConstant(TLI.getTargetData()->
3117 getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
3118 TLI.getPointerTy()));
3119 // Store the incremented VAList to the legalized pointer
3120 Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
3121 MachinePointerInfo(V), false, false, 0);
3122 // Load the actual argument out of the pointer VAList
3123 Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
3125 Results.push_back(Results[0].getValue(1));
3129 // This defaults to loading a pointer from the input and storing it to the
3130 // output, returning the chain.
3131 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3132 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3133 Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
3134 Node->getOperand(2), MachinePointerInfo(VS),
3136 Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
3137 MachinePointerInfo(VD), false, false, 0);
3138 Results.push_back(Tmp1);
3141 case ISD::EXTRACT_VECTOR_ELT:
3142 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3143 // This must be an access of the only element. Return it.
3144 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3145 Node->getOperand(0));
3147 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3148 Results.push_back(Tmp1);
3150 case ISD::EXTRACT_SUBVECTOR:
3151 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3153 case ISD::INSERT_SUBVECTOR:
3154 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3156 case ISD::CONCAT_VECTORS: {
3157 Results.push_back(ExpandVectorBuildThroughStack(Node));
3160 case ISD::SCALAR_TO_VECTOR:
3161 Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3163 case ISD::INSERT_VECTOR_ELT:
3164 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3165 Node->getOperand(1),
3166 Node->getOperand(2), dl));
3168 case ISD::VECTOR_SHUFFLE: {
3169 SmallVector<int, 8> Mask;
3170 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3172 EVT VT = Node->getValueType(0);
3173 EVT EltVT = VT.getVectorElementType();
3174 if (!TLI.isTypeLegal(EltVT))
3175 EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3176 unsigned NumElems = VT.getVectorNumElements();
3177 SmallVector<SDValue, 8> Ops;
3178 for (unsigned i = 0; i != NumElems; ++i) {
3180 Ops.push_back(DAG.getUNDEF(EltVT));
3183 unsigned Idx = Mask[i];
3185 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3186 Node->getOperand(0),
3187 DAG.getIntPtrConstant(Idx)));
3189 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3190 Node->getOperand(1),
3191 DAG.getIntPtrConstant(Idx - NumElems)));
3193 Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
3194 Results.push_back(Tmp1);
3197 case ISD::EXTRACT_ELEMENT: {
3198 EVT OpTy = Node->getOperand(0).getValueType();
3199 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3201 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3202 DAG.getConstant(OpTy.getSizeInBits()/2,
3203 TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
3204 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3207 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3208 Node->getOperand(0));
3210 Results.push_back(Tmp1);
3213 case ISD::STACKSAVE:
3214 // Expand to CopyFromReg if the target set
3215 // StackPointerRegisterToSaveRestore.
3216 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3217 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3218 Node->getValueType(0)));
3219 Results.push_back(Results[0].getValue(1));
3221 Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3222 Results.push_back(Node->getOperand(0));
3225 case ISD::STACKRESTORE:
3226 // Expand to CopyToReg if the target set
3227 // StackPointerRegisterToSaveRestore.
3228 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3229 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3230 Node->getOperand(1)));
3232 Results.push_back(Node->getOperand(0));
3235 case ISD::FCOPYSIGN:
3236 Results.push_back(ExpandFCOPYSIGN(Node));
3239 // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3240 Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3241 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3242 Node->getOperand(0));
3243 Results.push_back(Tmp1);
3246 // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3247 EVT VT = Node->getValueType(0);
3248 Tmp1 = Node->getOperand(0);
3249 Tmp2 = DAG.getConstantFP(0.0, VT);
3250 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3251 Tmp1, Tmp2, ISD::SETUGT);
3252 Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3253 Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
3254 Results.push_back(Tmp1);
3258 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3259 RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
3262 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3263 RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
3266 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3267 RTLIB::COS_F80, RTLIB::COS_PPCF128));
3270 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3271 RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
3274 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3275 RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
3278 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3279 RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
3282 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3283 RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
3286 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3287 RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
3290 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3291 RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
3294 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3295 RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
3298 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3299 RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
3302 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3303 RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
3305 case ISD::FNEARBYINT:
3306 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3307 RTLIB::NEARBYINT_F64,
3308 RTLIB::NEARBYINT_F80,
3309 RTLIB::NEARBYINT_PPCF128));
3312 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3313 RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
3316 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3317 RTLIB::POW_F80, RTLIB::POW_PPCF128));
3320 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3321 RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
3324 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3325 RTLIB::REM_F80, RTLIB::REM_PPCF128));
3328 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3329 RTLIB::FMA_F80, RTLIB::FMA_PPCF128));
3331 case ISD::FP16_TO_FP32:
3332 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3334 case ISD::FP32_TO_FP16:
3335 Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
3337 case ISD::ConstantFP: {
3338 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3339 // Check to see if this FP immediate is already legal.
3340 // If this is a legal constant, turn it into a TargetConstantFP node.
3341 if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3342 Results.push_back(SDValue(Node, 0));
3344 Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
3347 case ISD::EHSELECTION: {
3348 unsigned Reg = TLI.getExceptionSelectorRegister();
3349 assert(Reg && "Can't expand to unknown register!");
3350 Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
3351 Node->getValueType(0)));
3352 Results.push_back(Results[0].getValue(1));
3355 case ISD::EXCEPTIONADDR: {
3356 unsigned Reg = TLI.getExceptionAddressRegister();
3357 assert(Reg && "Can't expand to unknown register!");
3358 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3359 Node->getValueType(0)));
3360 Results.push_back(Results[0].getValue(1));
3364 EVT VT = Node->getValueType(0);
3365 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3366 TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3367 "Don't know how to expand this subtraction!");
3368 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3369 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3370 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3371 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3376 EVT VT = Node->getValueType(0);
3377 SDVTList VTs = DAG.getVTList(VT, VT);
3378 bool isSigned = Node->getOpcode() == ISD::SREM;
3379 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3380 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3381 Tmp2 = Node->getOperand(0);
3382 Tmp3 = Node->getOperand(1);
3383 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3384 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3385 UseDivRem(Node, isSigned, false))) {
3386 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3387 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3389 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3390 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3391 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3392 } else if (isSigned)
3393 Tmp1 = ExpandIntLibCall(Node, true,
3395 RTLIB::SREM_I16, RTLIB::SREM_I32,
3396 RTLIB::SREM_I64, RTLIB::SREM_I128);
3398 Tmp1 = ExpandIntLibCall(Node, false,
3400 RTLIB::UREM_I16, RTLIB::UREM_I32,
3401 RTLIB::UREM_I64, RTLIB::UREM_I128);
3402 Results.push_back(Tmp1);
3407 bool isSigned = Node->getOpcode() == ISD::SDIV;
3408 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3409 EVT VT = Node->getValueType(0);
3410 SDVTList VTs = DAG.getVTList(VT, VT);
3411 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3412 (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3413 UseDivRem(Node, isSigned, true)))
3414 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3415 Node->getOperand(1));
3417 Tmp1 = ExpandIntLibCall(Node, true,
3419 RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3420 RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3422 Tmp1 = ExpandIntLibCall(Node, false,
3424 RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3425 RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3426 Results.push_back(Tmp1);
3431 unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3433 EVT VT = Node->getValueType(0);
3434 SDVTList VTs = DAG.getVTList(VT, VT);
3435 assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3436 "If this wasn't legal, it shouldn't have been created!");
3437 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3438 Node->getOperand(1));
3439 Results.push_back(Tmp1.getValue(1));
3444 // Expand into divrem libcall
3445 ExpandDivRemLibCall(Node, Results);
3448 EVT VT = Node->getValueType(0);
3449 SDVTList VTs = DAG.getVTList(VT, VT);
3450 // See if multiply or divide can be lowered using two-result operations.
3451 // We just need the low half of the multiply; try both the signed
3452 // and unsigned forms. If the target supports both SMUL_LOHI and
3453 // UMUL_LOHI, form a preference by checking which forms of plain
3454 // MULH it supports.
3455 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3456 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3457 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3458 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3459 unsigned OpToUse = 0;
3460 if (HasSMUL_LOHI && !HasMULHS) {
3461 OpToUse = ISD::SMUL_LOHI;
3462 } else if (HasUMUL_LOHI && !HasMULHU) {
3463 OpToUse = ISD::UMUL_LOHI;
3464 } else if (HasSMUL_LOHI) {
3465 OpToUse = ISD::SMUL_LOHI;
3466 } else if (HasUMUL_LOHI) {
3467 OpToUse = ISD::UMUL_LOHI;
3470 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3471 Node->getOperand(1)));
3474 Tmp1 = ExpandIntLibCall(Node, false,
3476 RTLIB::MUL_I16, RTLIB::MUL_I32,
3477 RTLIB::MUL_I64, RTLIB::MUL_I128);
3478 Results.push_back(Tmp1);
3483 SDValue LHS = Node->getOperand(0);
3484 SDValue RHS = Node->getOperand(1);
3485 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3486 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3488 Results.push_back(Sum);
3489 EVT OType = Node->getValueType(1);
3491 SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3493 // LHSSign -> LHS >= 0
3494 // RHSSign -> RHS >= 0
3495 // SumSign -> Sum >= 0
3498 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3500 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3502 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3503 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3504 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3505 Node->getOpcode() == ISD::SADDO ?
3506 ISD::SETEQ : ISD::SETNE);
3508 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3509 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3511 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3512 Results.push_back(Cmp);
3517 SDValue LHS = Node->getOperand(0);
3518 SDValue RHS = Node->getOperand(1);
3519 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3520 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3522 Results.push_back(Sum);
3523 Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3524 Node->getOpcode () == ISD::UADDO ?
3525 ISD::SETULT : ISD::SETUGT));
3530 EVT VT = Node->getValueType(0);
3531 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3532 SDValue LHS = Node->getOperand(0);
3533 SDValue RHS = Node->getOperand(1);
3536 static const unsigned Ops[2][3] =
3537 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3538 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3539 bool isSigned = Node->getOpcode() == ISD::SMULO;
3540 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3541 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3542 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3543 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3544 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3546 TopHalf = BottomHalf.getValue(1);
3547 } else if (TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3548 VT.getSizeInBits() * 2))) {
3549 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3550 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3551 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3552 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3553 DAG.getIntPtrConstant(0));
3554 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3555 DAG.getIntPtrConstant(1));
3557 // We can fall back to a libcall with an illegal type for the MUL if we
3558 // have a libcall big enough.
3559 // Also, we can fall back to a division in some cases, but that's a big
3560 // performance hit in the general case.
3561 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3562 if (WideVT == MVT::i16)
3563 LC = RTLIB::MUL_I16;
3564 else if (WideVT == MVT::i32)
3565 LC = RTLIB::MUL_I32;
3566 else if (WideVT == MVT::i64)
3567 LC = RTLIB::MUL_I64;
3568 else if (WideVT == MVT::i128)
3569 LC = RTLIB::MUL_I128;
3570 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3572 // The high part is obtained by SRA'ing all but one of the bits of low
3574 unsigned LoSize = VT.getSizeInBits();
3575 SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3576 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3577 SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3578 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3580 // Here we're passing the 2 arguments explicitly as 4 arguments that are
3581 // pre-lowered to the correct types. This all depends upon WideVT not
3582 // being a legal type for the architecture and thus has to be split to
3584 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3585 SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3586 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3587 DAG.getIntPtrConstant(0));
3588 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3589 DAG.getIntPtrConstant(1));
3593 Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3594 TLI.getShiftAmountTy(BottomHalf.getValueType()));
3595 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3596 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3599 TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3600 DAG.getConstant(0, VT), ISD::SETNE);
3602 Results.push_back(BottomHalf);
3603 Results.push_back(TopHalf);
3606 case ISD::BUILD_PAIR: {
3607 EVT PairTy = Node->getValueType(0);
3608 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3609 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3610 Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3611 DAG.getConstant(PairTy.getSizeInBits()/2,
3612 TLI.getShiftAmountTy(PairTy)));
3613 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3617 Tmp1 = Node->getOperand(0);
3618 Tmp2 = Node->getOperand(1);
3619 Tmp3 = Node->getOperand(2);
3620 if (Tmp1.getOpcode() == ISD::SETCC) {
3621 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3623 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3625 Tmp1 = DAG.getSelectCC(dl, Tmp1,
3626 DAG.getConstant(0, Tmp1.getValueType()),
3627 Tmp2, Tmp3, ISD::SETNE);
3629 Results.push_back(Tmp1);
3632 SDValue Chain = Node->getOperand(0);
3633 SDValue Table = Node->getOperand(1);
3634 SDValue Index = Node->getOperand(2);
3636 EVT PTy = TLI.getPointerTy();
3638 const TargetData &TD = *TLI.getTargetData();
3639 unsigned EntrySize =
3640 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3642 Index = DAG.getNode(ISD::MUL, dl, PTy,
3643 Index, DAG.getConstant(EntrySize, PTy));
3644 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3646 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3647 SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3648 MachinePointerInfo::getJumpTable(), MemVT,
3651 if (TM.getRelocationModel() == Reloc::PIC_) {
3652 // For PIC, the sequence is:
3653 // BRIND(load(Jumptable + index) + RelocBase)
3654 // RelocBase can be JumpTable, GOT or some sort of global base.
3655 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3656 TLI.getPICJumpTableRelocBase(Table, DAG));
3658 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3659 Results.push_back(Tmp1);
3663 // Expand brcond's setcc into its constituent parts and create a BR_CC
3665 Tmp1 = Node->getOperand(0);
3666 Tmp2 = Node->getOperand(1);
3667 if (Tmp2.getOpcode() == ISD::SETCC) {
3668 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3669 Tmp1, Tmp2.getOperand(2),
3670 Tmp2.getOperand(0), Tmp2.getOperand(1),
3671 Node->getOperand(2));
3673 // We test only the i1 bit. Skip the AND if UNDEF.
3674 Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3675 DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3676 DAG.getConstant(1, Tmp2.getValueType()));
3677 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3678 DAG.getCondCode(ISD::SETNE), Tmp3,
3679 DAG.getConstant(0, Tmp3.getValueType()),
3680 Node->getOperand(2));
3682 Results.push_back(Tmp1);
3685 Tmp1 = Node->getOperand(0);
3686 Tmp2 = Node->getOperand(1);
3687 Tmp3 = Node->getOperand(2);
3688 LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3690 // If we expanded the SETCC into an AND/OR, return the new node
3691 if (Tmp2.getNode() == 0) {
3692 Results.push_back(Tmp1);
3696 // Otherwise, SETCC for the given comparison type must be completely
3697 // illegal; expand it into a SELECT_CC.
3698 EVT VT = Node->getValueType(0);
3699 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3700 DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3701 Results.push_back(Tmp1);
3704 case ISD::SELECT_CC: {
3705 Tmp1 = Node->getOperand(0); // LHS
3706 Tmp2 = Node->getOperand(1); // RHS
3707 Tmp3 = Node->getOperand(2); // True
3708 Tmp4 = Node->getOperand(3); // False
3709 SDValue CC = Node->getOperand(4);
3711 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3712 Tmp1, Tmp2, CC, dl);
3714 assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3715 Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3716 CC = DAG.getCondCode(ISD::SETNE);
3717 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3719 Results.push_back(Tmp1);
3723 Tmp1 = Node->getOperand(0); // Chain
3724 Tmp2 = Node->getOperand(2); // LHS
3725 Tmp3 = Node->getOperand(3); // RHS
3726 Tmp4 = Node->getOperand(1); // CC
3728 LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3729 Tmp2, Tmp3, Tmp4, dl);
3730 assert(LastCALLSEQ.size() == 1 && "branch inside CALLSEQ_BEGIN/END?");
3731 setLastCALLSEQ(DAG.getEntryNode());
3733 assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3734 Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3735 Tmp4 = DAG.getCondCode(ISD::SETNE);
3736 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3737 Tmp3, Node->getOperand(4));
3738 Results.push_back(Tmp1);
3741 case ISD::GLOBAL_OFFSET_TABLE:
3742 case ISD::GlobalAddress:
3743 case ISD::GlobalTLSAddress:
3744 case ISD::ExternalSymbol:
3745 case ISD::ConstantPool:
3746 case ISD::JumpTable:
3747 case ISD::INTRINSIC_W_CHAIN:
3748 case ISD::INTRINSIC_WO_CHAIN:
3749 case ISD::INTRINSIC_VOID:
3750 // FIXME: Custom lowering for these operations shouldn't return null!
3751 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3752 Results.push_back(SDValue(Node, i));
3756 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3757 SmallVectorImpl<SDValue> &Results) {
3758 EVT OVT = Node->getValueType(0);
3759 if (Node->getOpcode() == ISD::UINT_TO_FP ||
3760 Node->getOpcode() == ISD::SINT_TO_FP ||
3761 Node->getOpcode() == ISD::SETCC) {
3762 OVT = Node->getOperand(0).getValueType();
3764 EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3765 DebugLoc dl = Node->getDebugLoc();
3766 SDValue Tmp1, Tmp2, Tmp3;
3767 switch (Node->getOpcode()) {
3771 // Zero extend the argument.
3772 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3773 // Perform the larger operation.
3774 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3775 if (Node->getOpcode() == ISD::CTTZ) {
3776 //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3777 Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3778 Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3780 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3781 DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3782 } else if (Node->getOpcode() == ISD::CTLZ) {
3783 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3784 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3785 DAG.getConstant(NVT.getSizeInBits() -
3786 OVT.getSizeInBits(), NVT));
3788 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3791 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3792 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3793 Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3794 Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3795 DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
3796 Results.push_back(Tmp1);
3799 case ISD::FP_TO_UINT:
3800 case ISD::FP_TO_SINT:
3801 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3802 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3803 Results.push_back(Tmp1);
3805 case ISD::UINT_TO_FP:
3806 case ISD::SINT_TO_FP:
3807 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3808 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3809 Results.push_back(Tmp1);
3814 unsigned ExtOp, TruncOp;
3815 if (OVT.isVector()) {
3816 ExtOp = ISD::BITCAST;
3817 TruncOp = ISD::BITCAST;
3819 assert(OVT.isInteger() && "Cannot promote logic operation");
3820 ExtOp = ISD::ANY_EXTEND;
3821 TruncOp = ISD::TRUNCATE;
3823 // Promote each of the values to the new type.
3824 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3825 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3826 // Perform the larger operation, then convert back
3827 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3828 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3832 unsigned ExtOp, TruncOp;
3833 if (Node->getValueType(0).isVector()) {
3834 ExtOp = ISD::BITCAST;
3835 TruncOp = ISD::BITCAST;
3836 } else if (Node->getValueType(0).isInteger()) {
3837 ExtOp = ISD::ANY_EXTEND;
3838 TruncOp = ISD::TRUNCATE;
3840 ExtOp = ISD::FP_EXTEND;
3841 TruncOp = ISD::FP_ROUND;
3843 Tmp1 = Node->getOperand(0);
3844 // Promote each of the values to the new type.
3845 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3846 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3847 // Perform the larger operation, then round down.
3848 Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3849 if (TruncOp != ISD::FP_ROUND)
3850 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3852 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3853 DAG.getIntPtrConstant(0));
3854 Results.push_back(Tmp1);
3857 case ISD::VECTOR_SHUFFLE: {
3858 SmallVector<int, 8> Mask;
3859 cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3861 // Cast the two input vectors.
3862 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3863 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3865 // Convert the shuffle mask to the right # elements.
3866 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3867 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3868 Results.push_back(Tmp1);
3872 unsigned ExtOp = ISD::FP_EXTEND;
3873 if (NVT.isInteger()) {
3874 ISD::CondCode CCCode =
3875 cast<CondCodeSDNode>(Node->getOperand(2))->get();
3876 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3878 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3879 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3880 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3881 Tmp1, Tmp2, Node->getOperand(2)));
3887 // SelectionDAG::Legalize - This is the entry point for the file.
3889 void SelectionDAG::Legalize() {
3890 /// run - This is the main entry point to this class.
3892 SelectionDAGLegalize(*this).LegalizeDAG();