1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the SelectionDAG::Legalize method. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/APFloat.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/CodeGen/ISDOpcodes.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineJumpTableInfo.h" 24 #include "llvm/CodeGen/MachineMemOperand.h" 25 #include "llvm/CodeGen/MachineValueType.h" 26 #include "llvm/CodeGen/RuntimeLibcalls.h" 27 #include "llvm/CodeGen/SelectionDAG.h" 28 #include "llvm/CodeGen/SelectionDAGNodes.h" 29 #include "llvm/CodeGen/TargetFrameLowering.h" 30 #include "llvm/CodeGen/TargetLowering.h" 31 #include "llvm/CodeGen/TargetSubtargetInfo.h" 32 #include "llvm/CodeGen/ValueTypes.h" 33 #include "llvm/IR/CallingConv.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/Metadata.h" 39 #include "llvm/IR/Type.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/Compiler.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/MathExtras.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <cstdint> 51 #include <tuple> 52 #include <utility> 53 54 using namespace llvm; 55 56 #define DEBUG_TYPE "legalizedag" 57 58 namespace { 59 60 /// Keeps track of state when getting the sign of a floating-point value as an 61 /// integer. 62 struct FloatSignAsInt { 63 EVT FloatVT; 64 SDValue Chain; 65 SDValue FloatPtr; 66 SDValue IntPtr; 67 MachinePointerInfo IntPointerInfo; 68 MachinePointerInfo FloatPointerInfo; 69 SDValue IntValue; 70 APInt SignMask; 71 uint8_t SignBit; 72 }; 73 74 //===----------------------------------------------------------------------===// 75 /// This takes an arbitrary SelectionDAG as input and 76 /// hacks on it until the target machine can handle it. This involves 77 /// eliminating value sizes the machine cannot handle (promoting small sizes to 78 /// large sizes or splitting up large values into small values) as well as 79 /// eliminating operations the machine cannot handle. 80 /// 81 /// This code also does a small amount of optimization and recognition of idioms 82 /// as part of its processing. For example, if a target does not support a 83 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this 84 /// will attempt merge setcc and brc instructions into brcc's. 85 class SelectionDAGLegalize { 86 const TargetMachine &TM; 87 const TargetLowering &TLI; 88 SelectionDAG &DAG; 89 90 /// \brief The set of nodes which have already been legalized. We hold a 91 /// reference to it in order to update as necessary on node deletion. 92 SmallPtrSetImpl<SDNode *> &LegalizedNodes; 93 94 /// \brief A set of all the nodes updated during legalization. 95 SmallSetVector<SDNode *, 16> *UpdatedNodes; 96 97 EVT getSetCCResultType(EVT VT) const { 98 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 99 } 100 101 // Libcall insertion helpers. 102 103 public: 104 SelectionDAGLegalize(SelectionDAG &DAG, 105 SmallPtrSetImpl<SDNode *> &LegalizedNodes, 106 SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr) 107 : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG), 108 LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {} 109 110 /// \brief Legalizes the given operation. 111 void LegalizeOp(SDNode *Node); 112 113 private: 114 SDValue OptimizeFloatStore(StoreSDNode *ST); 115 116 void LegalizeLoadOps(SDNode *Node); 117 void LegalizeStoreOps(SDNode *Node); 118 119 /// Some targets cannot handle a variable 120 /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it 121 /// is necessary to spill the vector being inserted into to memory, perform 122 /// the insert there, and then read the result back. 123 SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx, 124 const SDLoc &dl); 125 SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, 126 const SDLoc &dl); 127 128 /// Return a vector shuffle operation which 129 /// performs the same shuffe in terms of order or result bytes, but on a type 130 /// whose vector element type is narrower than the original shuffle type. 131 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 132 SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl, 133 SDValue N1, SDValue N2, 134 ArrayRef<int> Mask) const; 135 136 bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC, 137 bool &NeedInvert, const SDLoc &dl); 138 139 SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned); 140 SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops, 141 unsigned NumOps, bool isSigned, const SDLoc &dl); 142 143 std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC, 144 SDNode *Node, bool isSigned); 145 SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32, 146 RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80, 147 RTLIB::Libcall Call_F128, 148 RTLIB::Libcall Call_PPCF128); 149 SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, 150 RTLIB::Libcall Call_I8, 151 RTLIB::Libcall Call_I16, 152 RTLIB::Libcall Call_I32, 153 RTLIB::Libcall Call_I64, 154 RTLIB::Libcall Call_I128); 155 void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 156 void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results); 157 158 SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, 159 const SDLoc &dl); 160 SDValue ExpandBUILD_VECTOR(SDNode *Node); 161 SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node); 162 void ExpandDYNAMIC_STACKALLOC(SDNode *Node, 163 SmallVectorImpl<SDValue> &Results); 164 void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL, 165 SDValue Value) const; 166 SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL, 167 SDValue NewIntValue) const; 168 SDValue ExpandFCOPYSIGN(SDNode *Node) const; 169 SDValue ExpandFABS(SDNode *Node) const; 170 SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT, 171 const SDLoc &dl); 172 SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned, 173 const SDLoc &dl); 174 SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned, 175 const SDLoc &dl); 176 177 SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl); 178 SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl); 179 SDValue ExpandBitCount(unsigned Opc, SDValue Op, const SDLoc &dl); 180 181 SDValue ExpandExtractFromVectorThroughStack(SDValue Op); 182 SDValue ExpandInsertToVectorThroughStack(SDValue Op); 183 SDValue ExpandVectorBuildThroughStack(SDNode* Node); 184 185 SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP); 186 SDValue ExpandConstant(ConstantSDNode *CP); 187 188 // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall 189 bool ExpandNode(SDNode *Node); 190 void ConvertNodeToLibcall(SDNode *Node); 191 void PromoteNode(SDNode *Node); 192 193 public: 194 // Node replacement helpers 195 196 void ReplacedNode(SDNode *N) { 197 LegalizedNodes.erase(N); 198 if (UpdatedNodes) 199 UpdatedNodes->insert(N); 200 } 201 202 void ReplaceNode(SDNode *Old, SDNode *New) { 203 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 204 dbgs() << " with: "; New->dump(&DAG)); 205 206 assert(Old->getNumValues() == New->getNumValues() && 207 "Replacing one node with another that produces a different number " 208 "of values!"); 209 DAG.ReplaceAllUsesWith(Old, New); 210 if (UpdatedNodes) 211 UpdatedNodes->insert(New); 212 ReplacedNode(Old); 213 } 214 215 void ReplaceNode(SDValue Old, SDValue New) { 216 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG); 217 dbgs() << " with: "; New->dump(&DAG)); 218 219 DAG.ReplaceAllUsesWith(Old, New); 220 if (UpdatedNodes) 221 UpdatedNodes->insert(New.getNode()); 222 ReplacedNode(Old.getNode()); 223 } 224 225 void ReplaceNode(SDNode *Old, const SDValue *New) { 226 DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG)); 227 228 DAG.ReplaceAllUsesWith(Old, New); 229 for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) { 230 DEBUG(dbgs() << (i == 0 ? " with: " 231 : " and: "); 232 New[i]->dump(&DAG)); 233 if (UpdatedNodes) 234 UpdatedNodes->insert(New[i].getNode()); 235 } 236 ReplacedNode(Old); 237 } 238 }; 239 240 } // end anonymous namespace 241 242 /// Return a vector shuffle operation which 243 /// performs the same shuffe in terms of order or result bytes, but on a type 244 /// whose vector element type is narrower than the original shuffle type. 245 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3> 246 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType( 247 EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, 248 ArrayRef<int> Mask) const { 249 unsigned NumMaskElts = VT.getVectorNumElements(); 250 unsigned NumDestElts = NVT.getVectorNumElements(); 251 unsigned NumEltsGrowth = NumDestElts / NumMaskElts; 252 253 assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!"); 254 255 if (NumEltsGrowth == 1) 256 return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask); 257 258 SmallVector<int, 8> NewMask; 259 for (unsigned i = 0; i != NumMaskElts; ++i) { 260 int Idx = Mask[i]; 261 for (unsigned j = 0; j != NumEltsGrowth; ++j) { 262 if (Idx < 0) 263 NewMask.push_back(-1); 264 else 265 NewMask.push_back(Idx * NumEltsGrowth + j); 266 } 267 } 268 assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?"); 269 assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?"); 270 return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask); 271 } 272 273 /// Expands the ConstantFP node to an integer constant or 274 /// a load from the constant pool. 275 SDValue 276 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) { 277 bool Extend = false; 278 SDLoc dl(CFP); 279 280 // If a FP immediate is precise when represented as a float and if the 281 // target can do an extending load from float to double, we put it into 282 // the constant pool as a float, even if it's is statically typed as a 283 // double. This shrinks FP constants and canonicalizes them for targets where 284 // an FP extending load is the same cost as a normal load (such as on the x87 285 // fp stack or PPC FP unit). 286 EVT VT = CFP->getValueType(0); 287 ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue()); 288 if (!UseCP) { 289 assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion"); 290 return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl, 291 (VT == MVT::f64) ? MVT::i64 : MVT::i32); 292 } 293 294 APFloat APF = CFP->getValueAPF(); 295 EVT OrigVT = VT; 296 EVT SVT = VT; 297 298 // We don't want to shrink SNaNs. Converting the SNaN back to its real type 299 // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ). 300 if (!APF.isSignaling()) { 301 while (SVT != MVT::f32 && SVT != MVT::f16) { 302 SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1); 303 if (ConstantFPSDNode::isValueValidForType(SVT, APF) && 304 // Only do this if the target has a native EXTLOAD instruction from 305 // smaller type. 306 TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) && 307 TLI.ShouldShrinkFPConstant(OrigVT)) { 308 Type *SType = SVT.getTypeForEVT(*DAG.getContext()); 309 LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType)); 310 VT = SVT; 311 Extend = true; 312 } 313 } 314 } 315 316 SDValue CPIdx = 317 DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout())); 318 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 319 if (Extend) { 320 SDValue Result = DAG.getExtLoad( 321 ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx, 322 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT, 323 Alignment); 324 return Result; 325 } 326 SDValue Result = DAG.getLoad( 327 OrigVT, dl, DAG.getEntryNode(), CPIdx, 328 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 329 return Result; 330 } 331 332 /// Expands the Constant node to a load from the constant pool. 333 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) { 334 SDLoc dl(CP); 335 EVT VT = CP->getValueType(0); 336 SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(), 337 TLI.getPointerTy(DAG.getDataLayout())); 338 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 339 SDValue Result = DAG.getLoad( 340 VT, dl, DAG.getEntryNode(), CPIdx, 341 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment); 342 return Result; 343 } 344 345 /// Some target cannot handle a variable insertion index for the 346 /// INSERT_VECTOR_ELT instruction. In this case, it 347 /// is necessary to spill the vector being inserted into to memory, perform 348 /// the insert there, and then read the result back. 349 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec, 350 SDValue Val, 351 SDValue Idx, 352 const SDLoc &dl) { 353 SDValue Tmp1 = Vec; 354 SDValue Tmp2 = Val; 355 SDValue Tmp3 = Idx; 356 357 // If the target doesn't support this, we have to spill the input vector 358 // to a temporary stack slot, update the element, then reload it. This is 359 // badness. We could also load the value into a vector register (either 360 // with a "move to register" or "extload into register" instruction, then 361 // permute it into place, if the idx is a constant and if the idx is 362 // supported by the target. 363 EVT VT = Tmp1.getValueType(); 364 EVT EltVT = VT.getVectorElementType(); 365 SDValue StackPtr = DAG.CreateStackTemporary(VT); 366 367 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 368 369 // Store the vector. 370 SDValue Ch = DAG.getStore( 371 DAG.getEntryNode(), dl, Tmp1, StackPtr, 372 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 373 374 SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3); 375 376 // Store the scalar value. 377 Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT); 378 // Load the updated vector. 379 return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack( 380 DAG.getMachineFunction(), SPFI)); 381 } 382 383 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, 384 SDValue Idx, 385 const SDLoc &dl) { 386 if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) { 387 // SCALAR_TO_VECTOR requires that the type of the value being inserted 388 // match the element type of the vector being created, except for 389 // integers in which case the inserted value can be over width. 390 EVT EltVT = Vec.getValueType().getVectorElementType(); 391 if (Val.getValueType() == EltVT || 392 (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) { 393 SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 394 Vec.getValueType(), Val); 395 396 unsigned NumElts = Vec.getValueType().getVectorNumElements(); 397 // We generate a shuffle of InVec and ScVec, so the shuffle mask 398 // should be 0,1,2,3,4,5... with the appropriate element replaced with 399 // elt 0 of the RHS. 400 SmallVector<int, 8> ShufOps; 401 for (unsigned i = 0; i != NumElts; ++i) 402 ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts); 403 404 return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps); 405 } 406 } 407 return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl); 408 } 409 410 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) { 411 DEBUG(dbgs() << "Optimizing float store operations\n"); 412 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 413 // FIXME: We shouldn't do this for TargetConstantFP's. 414 // FIXME: move this to the DAG Combiner! Note that we can't regress due 415 // to phase ordering between legalized code and the dag combiner. This 416 // probably means that we need to integrate dag combiner and legalizer 417 // together. 418 // We generally can't do this one for long doubles. 419 SDValue Chain = ST->getChain(); 420 SDValue Ptr = ST->getBasePtr(); 421 unsigned Alignment = ST->getAlignment(); 422 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 423 AAMDNodes AAInfo = ST->getAAInfo(); 424 SDLoc dl(ST); 425 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) { 426 if (CFP->getValueType(0) == MVT::f32 && 427 TLI.isTypeLegal(MVT::i32)) { 428 SDValue Con = DAG.getConstant(CFP->getValueAPF(). 429 bitcastToAPInt().zextOrTrunc(32), 430 SDLoc(CFP), MVT::i32); 431 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), Alignment, 432 MMOFlags, AAInfo); 433 } 434 435 if (CFP->getValueType(0) == MVT::f64) { 436 // If this target supports 64-bit registers, do a single 64-bit store. 437 if (TLI.isTypeLegal(MVT::i64)) { 438 SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 439 zextOrTrunc(64), SDLoc(CFP), MVT::i64); 440 return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), 441 Alignment, MMOFlags, AAInfo); 442 } 443 444 if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) { 445 // Otherwise, if the target supports 32-bit registers, use 2 32-bit 446 // stores. If the target supports neither 32- nor 64-bits, this 447 // xform is certainly not worth it. 448 const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt(); 449 SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32); 450 SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32); 451 if (DAG.getDataLayout().isBigEndian()) 452 std::swap(Lo, Hi); 453 454 Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), Alignment, 455 MMOFlags, AAInfo); 456 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 457 DAG.getConstant(4, dl, Ptr.getValueType())); 458 Hi = DAG.getStore(Chain, dl, Hi, Ptr, 459 ST->getPointerInfo().getWithOffset(4), 460 MinAlign(Alignment, 4U), MMOFlags, AAInfo); 461 462 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 463 } 464 } 465 } 466 return SDValue(nullptr, 0); 467 } 468 469 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) { 470 StoreSDNode *ST = cast<StoreSDNode>(Node); 471 SDValue Chain = ST->getChain(); 472 SDValue Ptr = ST->getBasePtr(); 473 SDLoc dl(Node); 474 475 unsigned Alignment = ST->getAlignment(); 476 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 477 AAMDNodes AAInfo = ST->getAAInfo(); 478 479 if (!ST->isTruncatingStore()) { 480 DEBUG(dbgs() << "Legalizing store operation\n"); 481 if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) { 482 ReplaceNode(ST, OptStore); 483 return; 484 } 485 486 SDValue Value = ST->getValue(); 487 MVT VT = Value.getSimpleValueType(); 488 switch (TLI.getOperationAction(ISD::STORE, VT)) { 489 default: llvm_unreachable("This action is not supported yet!"); 490 case TargetLowering::Legal: { 491 // If this is an unaligned store and the target doesn't support it, 492 // expand it. 493 EVT MemVT = ST->getMemoryVT(); 494 unsigned AS = ST->getAddressSpace(); 495 unsigned Align = ST->getAlignment(); 496 const DataLayout &DL = DAG.getDataLayout(); 497 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 498 DEBUG(dbgs() << "Expanding unsupported unaligned store\n"); 499 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 500 ReplaceNode(SDValue(ST, 0), Result); 501 } else 502 DEBUG(dbgs() << "Legal store\n"); 503 break; 504 } 505 case TargetLowering::Custom: { 506 DEBUG(dbgs() << "Trying custom lowering\n"); 507 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 508 if (Res && Res != SDValue(Node, 0)) 509 ReplaceNode(SDValue(Node, 0), Res); 510 return; 511 } 512 case TargetLowering::Promote: { 513 MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT); 514 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 515 "Can only promote stores to same size type"); 516 Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value); 517 SDValue Result = 518 DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 519 Alignment, MMOFlags, AAInfo); 520 ReplaceNode(SDValue(Node, 0), Result); 521 break; 522 } 523 } 524 return; 525 } 526 527 DEBUG(dbgs() << "Legalizing truncating store operations\n"); 528 SDValue Value = ST->getValue(); 529 EVT StVT = ST->getMemoryVT(); 530 unsigned StWidth = StVT.getSizeInBits(); 531 auto &DL = DAG.getDataLayout(); 532 533 if (StWidth != StVT.getStoreSizeInBits()) { 534 // Promote to a byte-sized store with upper bits zero if not 535 // storing an integral number of bytes. For example, promote 536 // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1) 537 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), 538 StVT.getStoreSizeInBits()); 539 Value = DAG.getZeroExtendInReg(Value, dl, StVT); 540 SDValue Result = 541 DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT, 542 Alignment, MMOFlags, AAInfo); 543 ReplaceNode(SDValue(Node, 0), Result); 544 } else if (StWidth & (StWidth - 1)) { 545 // If not storing a power-of-2 number of bits, expand as two stores. 546 assert(!StVT.isVector() && "Unsupported truncstore!"); 547 unsigned RoundWidth = 1 << Log2_32(StWidth); 548 assert(RoundWidth < StWidth); 549 unsigned ExtraWidth = StWidth - RoundWidth; 550 assert(ExtraWidth < RoundWidth); 551 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 552 "Store size not an integral number of bytes!"); 553 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 554 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 555 SDValue Lo, Hi; 556 unsigned IncrementSize; 557 558 if (DL.isLittleEndian()) { 559 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16) 560 // Store the bottom RoundWidth bits. 561 Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 562 RoundVT, Alignment, MMOFlags, AAInfo); 563 564 // Store the remaining ExtraWidth bits. 565 IncrementSize = RoundWidth / 8; 566 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 567 DAG.getConstant(IncrementSize, dl, 568 Ptr.getValueType())); 569 Hi = DAG.getNode( 570 ISD::SRL, dl, Value.getValueType(), Value, 571 DAG.getConstant(RoundWidth, dl, 572 TLI.getShiftAmountTy(Value.getValueType(), DL))); 573 Hi = DAG.getTruncStore( 574 Chain, dl, Hi, Ptr, 575 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT, 576 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo); 577 } else { 578 // Big endian - avoid unaligned stores. 579 // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X 580 // Store the top RoundWidth bits. 581 Hi = DAG.getNode( 582 ISD::SRL, dl, Value.getValueType(), Value, 583 DAG.getConstant(ExtraWidth, dl, 584 TLI.getShiftAmountTy(Value.getValueType(), DL))); 585 Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), 586 RoundVT, Alignment, MMOFlags, AAInfo); 587 588 // Store the remaining ExtraWidth bits. 589 IncrementSize = RoundWidth / 8; 590 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 591 DAG.getConstant(IncrementSize, dl, 592 Ptr.getValueType())); 593 Lo = DAG.getTruncStore( 594 Chain, dl, Value, Ptr, 595 ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT, 596 MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo); 597 } 598 599 // The order of the stores doesn't matter. 600 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi); 601 ReplaceNode(SDValue(Node, 0), Result); 602 } else { 603 switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) { 604 default: llvm_unreachable("This action is not supported yet!"); 605 case TargetLowering::Legal: { 606 EVT MemVT = ST->getMemoryVT(); 607 unsigned AS = ST->getAddressSpace(); 608 unsigned Align = ST->getAlignment(); 609 // If this is an unaligned store and the target doesn't support it, 610 // expand it. 611 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 612 SDValue Result = TLI.expandUnalignedStore(ST, DAG); 613 ReplaceNode(SDValue(ST, 0), Result); 614 } 615 break; 616 } 617 case TargetLowering::Custom: { 618 SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG); 619 if (Res && Res != SDValue(Node, 0)) 620 ReplaceNode(SDValue(Node, 0), Res); 621 return; 622 } 623 case TargetLowering::Expand: 624 assert(!StVT.isVector() && 625 "Vector Stores are handled in LegalizeVectorOps"); 626 627 SDValue Result; 628 629 // TRUNCSTORE:i16 i32 -> STORE i16 630 if (TLI.isTypeLegal(StVT)) { 631 Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value); 632 Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 633 Alignment, MMOFlags, AAInfo); 634 } else { 635 // The in-memory type isn't legal. Truncate to the type it would promote 636 // to, and then do a truncstore. 637 Value = DAG.getNode(ISD::TRUNCATE, dl, 638 TLI.getTypeToTransformTo(*DAG.getContext(), StVT), 639 Value); 640 Result = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), 641 StVT, Alignment, MMOFlags, AAInfo); 642 } 643 644 ReplaceNode(SDValue(Node, 0), Result); 645 break; 646 } 647 } 648 } 649 650 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) { 651 LoadSDNode *LD = cast<LoadSDNode>(Node); 652 SDValue Chain = LD->getChain(); // The chain. 653 SDValue Ptr = LD->getBasePtr(); // The base pointer. 654 SDValue Value; // The value returned by the load op. 655 SDLoc dl(Node); 656 657 ISD::LoadExtType ExtType = LD->getExtensionType(); 658 if (ExtType == ISD::NON_EXTLOAD) { 659 DEBUG(dbgs() << "Legalizing non-extending load operation\n"); 660 MVT VT = Node->getSimpleValueType(0); 661 SDValue RVal = SDValue(Node, 0); 662 SDValue RChain = SDValue(Node, 1); 663 664 switch (TLI.getOperationAction(Node->getOpcode(), VT)) { 665 default: llvm_unreachable("This action is not supported yet!"); 666 case TargetLowering::Legal: { 667 EVT MemVT = LD->getMemoryVT(); 668 unsigned AS = LD->getAddressSpace(); 669 unsigned Align = LD->getAlignment(); 670 const DataLayout &DL = DAG.getDataLayout(); 671 // If this is an unaligned load and the target doesn't support it, 672 // expand it. 673 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 674 std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG); 675 } 676 break; 677 } 678 case TargetLowering::Custom: 679 if (SDValue Res = TLI.LowerOperation(RVal, DAG)) { 680 RVal = Res; 681 RChain = Res.getValue(1); 682 } 683 break; 684 685 case TargetLowering::Promote: { 686 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT); 687 assert(NVT.getSizeInBits() == VT.getSizeInBits() && 688 "Can only promote loads to same size type"); 689 690 SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand()); 691 RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res); 692 RChain = Res.getValue(1); 693 break; 694 } 695 } 696 if (RChain.getNode() != Node) { 697 assert(RVal.getNode() != Node && "Load must be completely replaced"); 698 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal); 699 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain); 700 if (UpdatedNodes) { 701 UpdatedNodes->insert(RVal.getNode()); 702 UpdatedNodes->insert(RChain.getNode()); 703 } 704 ReplacedNode(Node); 705 } 706 return; 707 } 708 709 DEBUG(dbgs() << "Legalizing extending load operation\n"); 710 EVT SrcVT = LD->getMemoryVT(); 711 unsigned SrcWidth = SrcVT.getSizeInBits(); 712 unsigned Alignment = LD->getAlignment(); 713 MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags(); 714 AAMDNodes AAInfo = LD->getAAInfo(); 715 716 if (SrcWidth != SrcVT.getStoreSizeInBits() && 717 // Some targets pretend to have an i1 loading operation, and actually 718 // load an i8. This trick is correct for ZEXTLOAD because the top 7 719 // bits are guaranteed to be zero; it helps the optimizers understand 720 // that these bits are zero. It is also useful for EXTLOAD, since it 721 // tells the optimizers that those bits are undefined. It would be 722 // nice to have an effective generic way of getting these benefits... 723 // Until such a way is found, don't insist on promoting i1 here. 724 (SrcVT != MVT::i1 || 725 TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) == 726 TargetLowering::Promote)) { 727 // Promote to a byte-sized load if not loading an integral number of 728 // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24. 729 unsigned NewWidth = SrcVT.getStoreSizeInBits(); 730 EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth); 731 SDValue Ch; 732 733 // The extra bits are guaranteed to be zero, since we stored them that 734 // way. A zext load from NVT thus automatically gives zext from SrcVT. 735 736 ISD::LoadExtType NewExtType = 737 ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD; 738 739 SDValue Result = 740 DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), Chain, Ptr, 741 LD->getPointerInfo(), NVT, Alignment, MMOFlags, AAInfo); 742 743 Ch = Result.getValue(1); // The chain. 744 745 if (ExtType == ISD::SEXTLOAD) 746 // Having the top bits zero doesn't help when sign extending. 747 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 748 Result.getValueType(), 749 Result, DAG.getValueType(SrcVT)); 750 else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType()) 751 // All the top bits are guaranteed to be zero - inform the optimizers. 752 Result = DAG.getNode(ISD::AssertZext, dl, 753 Result.getValueType(), Result, 754 DAG.getValueType(SrcVT)); 755 756 Value = Result; 757 Chain = Ch; 758 } else if (SrcWidth & (SrcWidth - 1)) { 759 // If not loading a power-of-2 number of bits, expand as two loads. 760 assert(!SrcVT.isVector() && "Unsupported extload!"); 761 unsigned RoundWidth = 1 << Log2_32(SrcWidth); 762 assert(RoundWidth < SrcWidth); 763 unsigned ExtraWidth = SrcWidth - RoundWidth; 764 assert(ExtraWidth < RoundWidth); 765 assert(!(RoundWidth % 8) && !(ExtraWidth % 8) && 766 "Load size not an integral number of bytes!"); 767 EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth); 768 EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth); 769 SDValue Lo, Hi, Ch; 770 unsigned IncrementSize; 771 auto &DL = DAG.getDataLayout(); 772 773 if (DL.isLittleEndian()) { 774 // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16) 775 // Load the bottom RoundWidth bits. 776 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 777 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags, 778 AAInfo); 779 780 // Load the remaining ExtraWidth bits. 781 IncrementSize = RoundWidth / 8; 782 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 783 DAG.getConstant(IncrementSize, dl, 784 Ptr.getValueType())); 785 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 786 LD->getPointerInfo().getWithOffset(IncrementSize), 787 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags, 788 AAInfo); 789 790 // Build a factor node to remember that this load is independent of 791 // the other one. 792 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 793 Hi.getValue(1)); 794 795 // Move the top bits to the right place. 796 Hi = DAG.getNode( 797 ISD::SHL, dl, Hi.getValueType(), Hi, 798 DAG.getConstant(RoundWidth, dl, 799 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 800 801 // Join the hi and lo parts. 802 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 803 } else { 804 // Big endian - avoid unaligned loads. 805 // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8 806 // Load the top RoundWidth bits. 807 Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr, 808 LD->getPointerInfo(), RoundVT, Alignment, MMOFlags, 809 AAInfo); 810 811 // Load the remaining ExtraWidth bits. 812 IncrementSize = RoundWidth / 8; 813 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 814 DAG.getConstant(IncrementSize, dl, 815 Ptr.getValueType())); 816 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr, 817 LD->getPointerInfo().getWithOffset(IncrementSize), 818 ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags, 819 AAInfo); 820 821 // Build a factor node to remember that this load is independent of 822 // the other one. 823 Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 824 Hi.getValue(1)); 825 826 // Move the top bits to the right place. 827 Hi = DAG.getNode( 828 ISD::SHL, dl, Hi.getValueType(), Hi, 829 DAG.getConstant(ExtraWidth, dl, 830 TLI.getShiftAmountTy(Hi.getValueType(), DL))); 831 832 // Join the hi and lo parts. 833 Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi); 834 } 835 836 Chain = Ch; 837 } else { 838 bool isCustom = false; 839 switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0), 840 SrcVT.getSimpleVT())) { 841 default: llvm_unreachable("This action is not supported yet!"); 842 case TargetLowering::Custom: 843 isCustom = true; 844 LLVM_FALLTHROUGH; 845 case TargetLowering::Legal: 846 Value = SDValue(Node, 0); 847 Chain = SDValue(Node, 1); 848 849 if (isCustom) { 850 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 851 Value = Res; 852 Chain = Res.getValue(1); 853 } 854 } else { 855 // If this is an unaligned load and the target doesn't support it, 856 // expand it. 857 EVT MemVT = LD->getMemoryVT(); 858 unsigned AS = LD->getAddressSpace(); 859 unsigned Align = LD->getAlignment(); 860 const DataLayout &DL = DAG.getDataLayout(); 861 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT, AS, Align)) { 862 std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG); 863 } 864 } 865 break; 866 867 case TargetLowering::Expand: { 868 EVT DestVT = Node->getValueType(0); 869 if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) { 870 // If the source type is not legal, see if there is a legal extload to 871 // an intermediate type that we can then extend further. 872 EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT()); 873 if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT? 874 TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) { 875 // If we are loading a legal type, this is a non-extload followed by a 876 // full extend. 877 ISD::LoadExtType MidExtType = 878 (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType; 879 880 SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr, 881 SrcVT, LD->getMemOperand()); 882 unsigned ExtendOp = 883 ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType); 884 Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load); 885 Chain = Load.getValue(1); 886 break; 887 } 888 889 // Handle the special case of fp16 extloads. EXTLOAD doesn't have the 890 // normal undefined upper bits behavior to allow using an in-reg extend 891 // with the illegal FP type, so load as an integer and do the 892 // from-integer conversion. 893 if (SrcVT.getScalarType() == MVT::f16) { 894 EVT ISrcVT = SrcVT.changeTypeToInteger(); 895 EVT IDestVT = DestVT.changeTypeToInteger(); 896 EVT LoadVT = TLI.getRegisterType(IDestVT.getSimpleVT()); 897 898 SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, LoadVT, 899 Chain, Ptr, ISrcVT, 900 LD->getMemOperand()); 901 Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result); 902 Chain = Result.getValue(1); 903 break; 904 } 905 } 906 907 assert(!SrcVT.isVector() && 908 "Vector Loads are handled in LegalizeVectorOps"); 909 910 // FIXME: This does not work for vectors on most targets. Sign- 911 // and zero-extend operations are currently folded into extending 912 // loads, whether they are legal or not, and then we end up here 913 // without any support for legalizing them. 914 assert(ExtType != ISD::EXTLOAD && 915 "EXTLOAD should always be supported!"); 916 // Turn the unsupported load into an EXTLOAD followed by an 917 // explicit zero/sign extend inreg. 918 SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl, 919 Node->getValueType(0), 920 Chain, Ptr, SrcVT, 921 LD->getMemOperand()); 922 SDValue ValRes; 923 if (ExtType == ISD::SEXTLOAD) 924 ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, 925 Result.getValueType(), 926 Result, DAG.getValueType(SrcVT)); 927 else 928 ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType()); 929 Value = ValRes; 930 Chain = Result.getValue(1); 931 break; 932 } 933 } 934 } 935 936 // Since loads produce two values, make sure to remember that we legalized 937 // both of them. 938 if (Chain.getNode() != Node) { 939 assert(Value.getNode() != Node && "Load must be completely replaced"); 940 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value); 941 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 942 if (UpdatedNodes) { 943 UpdatedNodes->insert(Value.getNode()); 944 UpdatedNodes->insert(Chain.getNode()); 945 } 946 ReplacedNode(Node); 947 } 948 } 949 950 static TargetLowering::LegalizeAction 951 getStrictFPOpcodeAction(const TargetLowering &TLI, unsigned Opcode, EVT VT) { 952 unsigned EqOpc; 953 switch (Opcode) { 954 default: llvm_unreachable("Unexpected FP pseudo-opcode"); 955 case ISD::STRICT_FSQRT: EqOpc = ISD::FSQRT; break; 956 case ISD::STRICT_FPOW: EqOpc = ISD::FPOW; break; 957 case ISD::STRICT_FPOWI: EqOpc = ISD::FPOWI; break; 958 case ISD::STRICT_FMA: EqOpc = ISD::FMA; break; 959 case ISD::STRICT_FSIN: EqOpc = ISD::FSIN; break; 960 case ISD::STRICT_FCOS: EqOpc = ISD::FCOS; break; 961 case ISD::STRICT_FEXP: EqOpc = ISD::FEXP; break; 962 case ISD::STRICT_FEXP2: EqOpc = ISD::FEXP2; break; 963 case ISD::STRICT_FLOG: EqOpc = ISD::FLOG; break; 964 case ISD::STRICT_FLOG10: EqOpc = ISD::FLOG10; break; 965 case ISD::STRICT_FLOG2: EqOpc = ISD::FLOG2; break; 966 case ISD::STRICT_FRINT: EqOpc = ISD::FRINT; break; 967 case ISD::STRICT_FNEARBYINT: EqOpc = ISD::FNEARBYINT; break; 968 } 969 970 auto Action = TLI.getOperationAction(EqOpc, VT); 971 972 // We don't currently handle Custom or Promote for strict FP pseudo-ops. 973 // For now, we just expand for those cases. 974 if (Action != TargetLowering::Legal) 975 Action = TargetLowering::Expand; 976 977 return Action; 978 } 979 980 /// Return a legal replacement for the given operation, with all legal operands. 981 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) { 982 DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG)); 983 984 // Allow illegal target nodes and illegal registers. 985 if (Node->getOpcode() == ISD::TargetConstant || 986 Node->getOpcode() == ISD::Register) 987 return; 988 989 #ifndef NDEBUG 990 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 991 assert((TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) == 992 TargetLowering::TypeLegal || 993 TLI.isTypeLegal(Node->getValueType(i))) && 994 "Unexpected illegal type!"); 995 996 for (const SDValue &Op : Node->op_values()) 997 assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) == 998 TargetLowering::TypeLegal || 999 TLI.isTypeLegal(Op.getValueType()) || 1000 Op.getOpcode() == ISD::TargetConstant || 1001 Op.getOpcode() == ISD::Register) && 1002 "Unexpected illegal type!"); 1003 #endif 1004 1005 // Figure out the correct action; the way to query this varies by opcode 1006 TargetLowering::LegalizeAction Action = TargetLowering::Legal; 1007 bool SimpleFinishLegalizing = true; 1008 switch (Node->getOpcode()) { 1009 case ISD::INTRINSIC_W_CHAIN: 1010 case ISD::INTRINSIC_WO_CHAIN: 1011 case ISD::INTRINSIC_VOID: 1012 case ISD::STACKSAVE: 1013 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 1014 break; 1015 case ISD::GET_DYNAMIC_AREA_OFFSET: 1016 Action = TLI.getOperationAction(Node->getOpcode(), 1017 Node->getValueType(0)); 1018 break; 1019 case ISD::VAARG: 1020 Action = TLI.getOperationAction(Node->getOpcode(), 1021 Node->getValueType(0)); 1022 if (Action != TargetLowering::Promote) 1023 Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other); 1024 break; 1025 case ISD::FP_TO_FP16: 1026 case ISD::SINT_TO_FP: 1027 case ISD::UINT_TO_FP: 1028 case ISD::EXTRACT_VECTOR_ELT: 1029 Action = TLI.getOperationAction(Node->getOpcode(), 1030 Node->getOperand(0).getValueType()); 1031 break; 1032 case ISD::FP_ROUND_INREG: 1033 case ISD::SIGN_EXTEND_INREG: { 1034 EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT(); 1035 Action = TLI.getOperationAction(Node->getOpcode(), InnerType); 1036 break; 1037 } 1038 case ISD::ATOMIC_STORE: 1039 Action = TLI.getOperationAction(Node->getOpcode(), 1040 Node->getOperand(2).getValueType()); 1041 break; 1042 case ISD::SELECT_CC: 1043 case ISD::SETCC: 1044 case ISD::BR_CC: { 1045 unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 : 1046 Node->getOpcode() == ISD::SETCC ? 2 : 1047 Node->getOpcode() == ISD::SETCCE ? 3 : 1; 1048 unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0; 1049 MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType(); 1050 ISD::CondCode CCCode = 1051 cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get(); 1052 Action = TLI.getCondCodeAction(CCCode, OpVT); 1053 if (Action == TargetLowering::Legal) { 1054 if (Node->getOpcode() == ISD::SELECT_CC) 1055 Action = TLI.getOperationAction(Node->getOpcode(), 1056 Node->getValueType(0)); 1057 else 1058 Action = TLI.getOperationAction(Node->getOpcode(), OpVT); 1059 } 1060 break; 1061 } 1062 case ISD::LOAD: 1063 case ISD::STORE: 1064 // FIXME: Model these properly. LOAD and STORE are complicated, and 1065 // STORE expects the unlegalized operand in some cases. 1066 SimpleFinishLegalizing = false; 1067 break; 1068 case ISD::CALLSEQ_START: 1069 case ISD::CALLSEQ_END: 1070 // FIXME: This shouldn't be necessary. These nodes have special properties 1071 // dealing with the recursive nature of legalization. Removing this 1072 // special case should be done as part of making LegalizeDAG non-recursive. 1073 SimpleFinishLegalizing = false; 1074 break; 1075 case ISD::EXTRACT_ELEMENT: 1076 case ISD::FLT_ROUNDS_: 1077 case ISD::MERGE_VALUES: 1078 case ISD::EH_RETURN: 1079 case ISD::FRAME_TO_ARGS_OFFSET: 1080 case ISD::EH_DWARF_CFA: 1081 case ISD::EH_SJLJ_SETJMP: 1082 case ISD::EH_SJLJ_LONGJMP: 1083 case ISD::EH_SJLJ_SETUP_DISPATCH: 1084 // These operations lie about being legal: when they claim to be legal, 1085 // they should actually be expanded. 1086 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1087 if (Action == TargetLowering::Legal) 1088 Action = TargetLowering::Expand; 1089 break; 1090 case ISD::INIT_TRAMPOLINE: 1091 case ISD::ADJUST_TRAMPOLINE: 1092 case ISD::FRAMEADDR: 1093 case ISD::RETURNADDR: 1094 case ISD::ADDROFRETURNADDR: 1095 // These operations lie about being legal: when they claim to be legal, 1096 // they should actually be custom-lowered. 1097 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1098 if (Action == TargetLowering::Legal) 1099 Action = TargetLowering::Custom; 1100 break; 1101 case ISD::READCYCLECOUNTER: 1102 // READCYCLECOUNTER returns an i64, even if type legalization might have 1103 // expanded that to several smaller types. 1104 Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64); 1105 break; 1106 case ISD::READ_REGISTER: 1107 case ISD::WRITE_REGISTER: 1108 // Named register is legal in the DAG, but blocked by register name 1109 // selection if not implemented by target (to chose the correct register) 1110 // They'll be converted to Copy(To/From)Reg. 1111 Action = TargetLowering::Legal; 1112 break; 1113 case ISD::DEBUGTRAP: 1114 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1115 if (Action == TargetLowering::Expand) { 1116 // replace ISD::DEBUGTRAP with ISD::TRAP 1117 SDValue NewVal; 1118 NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(), 1119 Node->getOperand(0)); 1120 ReplaceNode(Node, NewVal.getNode()); 1121 LegalizeOp(NewVal.getNode()); 1122 return; 1123 } 1124 break; 1125 case ISD::STRICT_FSQRT: 1126 case ISD::STRICT_FMA: 1127 case ISD::STRICT_FPOW: 1128 case ISD::STRICT_FPOWI: 1129 case ISD::STRICT_FSIN: 1130 case ISD::STRICT_FCOS: 1131 case ISD::STRICT_FEXP: 1132 case ISD::STRICT_FEXP2: 1133 case ISD::STRICT_FLOG: 1134 case ISD::STRICT_FLOG10: 1135 case ISD::STRICT_FLOG2: 1136 case ISD::STRICT_FRINT: 1137 case ISD::STRICT_FNEARBYINT: 1138 // These pseudo-ops get legalized as if they were their non-strict 1139 // equivalent. For instance, if ISD::FSQRT is legal then ISD::STRICT_FSQRT 1140 // is also legal, but if ISD::FSQRT requires expansion then so does 1141 // ISD::STRICT_FSQRT. 1142 Action = getStrictFPOpcodeAction(TLI, Node->getOpcode(), 1143 Node->getValueType(0)); 1144 break; 1145 default: 1146 if (Node->getOpcode() >= ISD::BUILTIN_OP_END) { 1147 Action = TargetLowering::Legal; 1148 } else { 1149 Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)); 1150 } 1151 break; 1152 } 1153 1154 if (SimpleFinishLegalizing) { 1155 SDNode *NewNode = Node; 1156 switch (Node->getOpcode()) { 1157 default: break; 1158 case ISD::SHL: 1159 case ISD::SRL: 1160 case ISD::SRA: 1161 case ISD::ROTL: 1162 case ISD::ROTR: { 1163 // Legalizing shifts/rotates requires adjusting the shift amount 1164 // to the appropriate width. 1165 SDValue Op0 = Node->getOperand(0); 1166 SDValue Op1 = Node->getOperand(1); 1167 if (!Op1.getValueType().isVector()) { 1168 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1); 1169 // The getShiftAmountOperand() may create a new operand node or 1170 // return the existing one. If new operand is created we need 1171 // to update the parent node. 1172 // Do not try to legalize SAO here! It will be automatically legalized 1173 // in the next round. 1174 if (SAO != Op1) 1175 NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO); 1176 } 1177 } 1178 break; 1179 case ISD::SRL_PARTS: 1180 case ISD::SRA_PARTS: 1181 case ISD::SHL_PARTS: { 1182 // Legalizing shifts/rotates requires adjusting the shift amount 1183 // to the appropriate width. 1184 SDValue Op0 = Node->getOperand(0); 1185 SDValue Op1 = Node->getOperand(1); 1186 SDValue Op2 = Node->getOperand(2); 1187 if (!Op2.getValueType().isVector()) { 1188 SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2); 1189 // The getShiftAmountOperand() may create a new operand node or 1190 // return the existing one. If new operand is created we need 1191 // to update the parent node. 1192 if (SAO != Op2) 1193 NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO); 1194 } 1195 break; 1196 } 1197 } 1198 1199 if (NewNode != Node) { 1200 ReplaceNode(Node, NewNode); 1201 Node = NewNode; 1202 } 1203 switch (Action) { 1204 case TargetLowering::Legal: 1205 DEBUG(dbgs() << "Legal node: nothing to do\n"); 1206 return; 1207 case TargetLowering::Custom: 1208 DEBUG(dbgs() << "Trying custom legalization\n"); 1209 // FIXME: The handling for custom lowering with multiple results is 1210 // a complete mess. 1211 if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) { 1212 if (!(Res.getNode() != Node || Res.getResNo() != 0)) 1213 return; 1214 1215 if (Node->getNumValues() == 1) { 1216 DEBUG(dbgs() << "Successfully custom legalized node\n"); 1217 // We can just directly replace this node with the lowered value. 1218 ReplaceNode(SDValue(Node, 0), Res); 1219 return; 1220 } 1221 1222 SmallVector<SDValue, 8> ResultVals; 1223 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) 1224 ResultVals.push_back(Res.getValue(i)); 1225 DEBUG(dbgs() << "Successfully custom legalized node\n"); 1226 ReplaceNode(Node, ResultVals.data()); 1227 return; 1228 } 1229 DEBUG(dbgs() << "Could not custom legalize node\n"); 1230 LLVM_FALLTHROUGH; 1231 case TargetLowering::Expand: 1232 if (ExpandNode(Node)) 1233 return; 1234 LLVM_FALLTHROUGH; 1235 case TargetLowering::LibCall: 1236 ConvertNodeToLibcall(Node); 1237 return; 1238 case TargetLowering::Promote: 1239 PromoteNode(Node); 1240 return; 1241 } 1242 } 1243 1244 switch (Node->getOpcode()) { 1245 default: 1246 #ifndef NDEBUG 1247 dbgs() << "NODE: "; 1248 Node->dump( &DAG); 1249 dbgs() << "\n"; 1250 #endif 1251 llvm_unreachable("Do not know how to legalize this operator!"); 1252 1253 case ISD::CALLSEQ_START: 1254 case ISD::CALLSEQ_END: 1255 break; 1256 case ISD::LOAD: 1257 return LegalizeLoadOps(Node); 1258 case ISD::STORE: 1259 return LegalizeStoreOps(Node); 1260 } 1261 } 1262 1263 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) { 1264 SDValue Vec = Op.getOperand(0); 1265 SDValue Idx = Op.getOperand(1); 1266 SDLoc dl(Op); 1267 1268 // Before we generate a new store to a temporary stack slot, see if there is 1269 // already one that we can use. There often is because when we scalarize 1270 // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole 1271 // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in 1272 // the vector. If all are expanded here, we don't want one store per vector 1273 // element. 1274 1275 // Caches for hasPredecessorHelper 1276 SmallPtrSet<const SDNode *, 32> Visited; 1277 SmallVector<const SDNode *, 16> Worklist; 1278 Worklist.push_back(Idx.getNode()); 1279 SDValue StackPtr, Ch; 1280 for (SDNode::use_iterator UI = Vec.getNode()->use_begin(), 1281 UE = Vec.getNode()->use_end(); UI != UE; ++UI) { 1282 SDNode *User = *UI; 1283 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) { 1284 if (ST->isIndexed() || ST->isTruncatingStore() || 1285 ST->getValue() != Vec) 1286 continue; 1287 1288 // Make sure that nothing else could have stored into the destination of 1289 // this store. 1290 if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode())) 1291 continue; 1292 1293 // If the index is dependent on the store we will introduce a cycle when 1294 // creating the load (the load uses the index, and by replacing the chain 1295 // we will make the index dependent on the load). Also, the store might be 1296 // dependent on the extractelement and introduce a cycle when creating 1297 // the load. 1298 if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) || 1299 ST->hasPredecessor(Op.getNode())) 1300 continue; 1301 1302 StackPtr = ST->getBasePtr(); 1303 Ch = SDValue(ST, 0); 1304 break; 1305 } 1306 } 1307 1308 EVT VecVT = Vec.getValueType(); 1309 1310 if (!Ch.getNode()) { 1311 // Store the value to a temporary stack slot, then LOAD the returned part. 1312 StackPtr = DAG.CreateStackTemporary(VecVT); 1313 Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, 1314 MachinePointerInfo()); 1315 } 1316 1317 StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1318 1319 SDValue NewLoad; 1320 1321 if (Op.getValueType().isVector()) 1322 NewLoad = 1323 DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo()); 1324 else 1325 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, 1326 MachinePointerInfo(), 1327 VecVT.getVectorElementType()); 1328 1329 // Replace the chain going out of the store, by the one out of the load. 1330 DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1)); 1331 1332 // We introduced a cycle though, so update the loads operands, making sure 1333 // to use the original store's chain as an incoming chain. 1334 SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(), 1335 NewLoad->op_end()); 1336 NewLoadOperands[0] = Ch; 1337 NewLoad = 1338 SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0); 1339 return NewLoad; 1340 } 1341 1342 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) { 1343 assert(Op.getValueType().isVector() && "Non-vector insert subvector!"); 1344 1345 SDValue Vec = Op.getOperand(0); 1346 SDValue Part = Op.getOperand(1); 1347 SDValue Idx = Op.getOperand(2); 1348 SDLoc dl(Op); 1349 1350 // Store the value to a temporary stack slot, then LOAD the returned part. 1351 EVT VecVT = Vec.getValueType(); 1352 SDValue StackPtr = DAG.CreateStackTemporary(VecVT); 1353 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1354 MachinePointerInfo PtrInfo = 1355 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1356 1357 // First store the whole vector. 1358 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo); 1359 1360 // Then store the inserted part. 1361 SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx); 1362 1363 // Store the subvector. 1364 Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, MachinePointerInfo()); 1365 1366 // Finally, load the updated vector. 1367 return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo); 1368 } 1369 1370 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) { 1371 // We can't handle this case efficiently. Allocate a sufficiently 1372 // aligned object on the stack, store each element into it, then load 1373 // the result as a vector. 1374 // Create the stack frame object. 1375 EVT VT = Node->getValueType(0); 1376 EVT EltVT = VT.getVectorElementType(); 1377 SDLoc dl(Node); 1378 SDValue FIPtr = DAG.CreateStackTemporary(VT); 1379 int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex(); 1380 MachinePointerInfo PtrInfo = 1381 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 1382 1383 // Emit a store of each element to the stack slot. 1384 SmallVector<SDValue, 8> Stores; 1385 unsigned TypeByteSize = EltVT.getSizeInBits() / 8; 1386 // Store (in the right endianness) the elements to memory. 1387 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) { 1388 // Ignore undef elements. 1389 if (Node->getOperand(i).isUndef()) continue; 1390 1391 unsigned Offset = TypeByteSize*i; 1392 1393 SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType()); 1394 Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx); 1395 1396 // If the destination vector element type is narrower than the source 1397 // element type, only store the bits necessary. 1398 if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) { 1399 Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, 1400 Node->getOperand(i), Idx, 1401 PtrInfo.getWithOffset(Offset), EltVT)); 1402 } else 1403 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i), 1404 Idx, PtrInfo.getWithOffset(Offset))); 1405 } 1406 1407 SDValue StoreChain; 1408 if (!Stores.empty()) // Not all undef elements? 1409 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 1410 else 1411 StoreChain = DAG.getEntryNode(); 1412 1413 // Result is a load from the stack slot. 1414 return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo); 1415 } 1416 1417 /// Bitcast a floating-point value to an integer value. Only bitcast the part 1418 /// containing the sign bit if the target has no integer value capable of 1419 /// holding all bits of the floating-point value. 1420 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State, 1421 const SDLoc &DL, 1422 SDValue Value) const { 1423 EVT FloatVT = Value.getValueType(); 1424 unsigned NumBits = FloatVT.getSizeInBits(); 1425 State.FloatVT = FloatVT; 1426 EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 1427 // Convert to an integer of the same size. 1428 if (TLI.isTypeLegal(IVT)) { 1429 State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value); 1430 State.SignMask = APInt::getSignMask(NumBits); 1431 State.SignBit = NumBits - 1; 1432 return; 1433 } 1434 1435 auto &DataLayout = DAG.getDataLayout(); 1436 // Store the float to memory, then load the sign part out as an integer. 1437 MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8); 1438 // First create a temporary that is aligned for both the load and store. 1439 SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy); 1440 int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 1441 // Then store the float to it. 1442 State.FloatPtr = StackPtr; 1443 MachineFunction &MF = DAG.getMachineFunction(); 1444 State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI); 1445 State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr, 1446 State.FloatPointerInfo); 1447 1448 SDValue IntPtr; 1449 if (DataLayout.isBigEndian()) { 1450 assert(FloatVT.isByteSized() && "Unsupported floating point type!"); 1451 // Load out a legal integer with the same sign bit as the float. 1452 IntPtr = StackPtr; 1453 State.IntPointerInfo = State.FloatPointerInfo; 1454 } else { 1455 // Advance the pointer so that the loaded byte will contain the sign bit. 1456 unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1; 1457 IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr, 1458 DAG.getConstant(ByteOffset, DL, StackPtr.getValueType())); 1459 State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI, 1460 ByteOffset); 1461 } 1462 1463 State.IntPtr = IntPtr; 1464 State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr, 1465 State.IntPointerInfo, MVT::i8); 1466 State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7); 1467 State.SignBit = 7; 1468 } 1469 1470 /// Replace the integer value produced by getSignAsIntValue() with a new value 1471 /// and cast the result back to a floating-point type. 1472 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State, 1473 const SDLoc &DL, 1474 SDValue NewIntValue) const { 1475 if (!State.Chain) 1476 return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue); 1477 1478 // Override the part containing the sign bit in the value stored on the stack. 1479 SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr, 1480 State.IntPointerInfo, MVT::i8); 1481 return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr, 1482 State.FloatPointerInfo); 1483 } 1484 1485 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const { 1486 SDLoc DL(Node); 1487 SDValue Mag = Node->getOperand(0); 1488 SDValue Sign = Node->getOperand(1); 1489 1490 // Get sign bit into an integer value. 1491 FloatSignAsInt SignAsInt; 1492 getSignAsIntValue(SignAsInt, DL, Sign); 1493 1494 EVT IntVT = SignAsInt.IntValue.getValueType(); 1495 SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT); 1496 SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue, 1497 SignMask); 1498 1499 // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X) 1500 EVT FloatVT = Mag.getValueType(); 1501 if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) && 1502 TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) { 1503 SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag); 1504 SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue); 1505 SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit, 1506 DAG.getConstant(0, DL, IntVT), ISD::SETNE); 1507 return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue); 1508 } 1509 1510 // Transform Mag value to integer, and clear the sign bit. 1511 FloatSignAsInt MagAsInt; 1512 getSignAsIntValue(MagAsInt, DL, Mag); 1513 EVT MagVT = MagAsInt.IntValue.getValueType(); 1514 SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT); 1515 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue, 1516 ClearSignMask); 1517 1518 // Get the signbit at the right position for MagAsInt. 1519 int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit; 1520 if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) { 1521 if (ShiftAmount > 0) { 1522 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, IntVT); 1523 SignBit = DAG.getNode(ISD::SRL, DL, IntVT, SignBit, ShiftCnst); 1524 } else if (ShiftAmount < 0) { 1525 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, IntVT); 1526 SignBit = DAG.getNode(ISD::SHL, DL, IntVT, SignBit, ShiftCnst); 1527 } 1528 SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit); 1529 } else if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) { 1530 SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit); 1531 if (ShiftAmount > 0) { 1532 SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, MagVT); 1533 SignBit = DAG.getNode(ISD::SRL, DL, MagVT, SignBit, ShiftCnst); 1534 } else if (ShiftAmount < 0) { 1535 SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, MagVT); 1536 SignBit = DAG.getNode(ISD::SHL, DL, MagVT, SignBit, ShiftCnst); 1537 } 1538 } 1539 1540 // Store the part with the modified sign and convert back to float. 1541 SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit); 1542 return modifySignAsInt(MagAsInt, DL, CopiedSign); 1543 } 1544 1545 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const { 1546 SDLoc DL(Node); 1547 SDValue Value = Node->getOperand(0); 1548 1549 // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal. 1550 EVT FloatVT = Value.getValueType(); 1551 if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) { 1552 SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT); 1553 return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero); 1554 } 1555 1556 // Transform value to integer, clear the sign bit and transform back. 1557 FloatSignAsInt ValueAsInt; 1558 getSignAsIntValue(ValueAsInt, DL, Value); 1559 EVT IntVT = ValueAsInt.IntValue.getValueType(); 1560 SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT); 1561 SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue, 1562 ClearSignMask); 1563 return modifySignAsInt(ValueAsInt, DL, ClearedSign); 1564 } 1565 1566 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node, 1567 SmallVectorImpl<SDValue> &Results) { 1568 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1569 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and" 1570 " not tell us which reg is the stack pointer!"); 1571 SDLoc dl(Node); 1572 EVT VT = Node->getValueType(0); 1573 SDValue Tmp1 = SDValue(Node, 0); 1574 SDValue Tmp2 = SDValue(Node, 1); 1575 SDValue Tmp3 = Node->getOperand(2); 1576 SDValue Chain = Tmp1.getOperand(0); 1577 1578 // Chain the dynamic stack allocation so that it doesn't modify the stack 1579 // pointer when other instructions are using the stack. 1580 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 1581 1582 SDValue Size = Tmp2.getOperand(1); 1583 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 1584 Chain = SP.getValue(1); 1585 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue(); 1586 unsigned StackAlign = 1587 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 1588 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value 1589 if (Align > StackAlign) 1590 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 1591 DAG.getConstant(-(uint64_t)Align, dl, VT)); 1592 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 1593 1594 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 1595 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 1596 1597 Results.push_back(Tmp1); 1598 Results.push_back(Tmp2); 1599 } 1600 1601 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current 1602 /// target. 1603 /// 1604 /// If the SETCC has been legalized using AND / OR, then the legalized node 1605 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert 1606 /// will be set to false. 1607 /// 1608 /// If the SETCC has been legalized by using getSetCCSwappedOperands(), 1609 /// then the values of LHS and RHS will be swapped, CC will be set to the 1610 /// new condition, and NeedInvert will be set to false. 1611 /// 1612 /// If the SETCC has been legalized using the inverse condcode, then LHS and 1613 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert 1614 /// will be set to true. The caller must invert the result of the SETCC with 1615 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect 1616 /// of a true/false result. 1617 /// 1618 /// \returns true if the SetCC has been legalized, false if it hasn't. 1619 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS, 1620 SDValue &RHS, SDValue &CC, 1621 bool &NeedInvert, 1622 const SDLoc &dl) { 1623 MVT OpVT = LHS.getSimpleValueType(); 1624 ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get(); 1625 NeedInvert = false; 1626 switch (TLI.getCondCodeAction(CCCode, OpVT)) { 1627 default: llvm_unreachable("Unknown condition code action!"); 1628 case TargetLowering::Legal: 1629 // Nothing to do. 1630 break; 1631 case TargetLowering::Expand: { 1632 ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode); 1633 if (TLI.isCondCodeLegal(InvCC, OpVT)) { 1634 std::swap(LHS, RHS); 1635 CC = DAG.getCondCode(InvCC); 1636 return true; 1637 } 1638 ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID; 1639 unsigned Opc = 0; 1640 switch (CCCode) { 1641 default: llvm_unreachable("Don't know how to expand this condition!"); 1642 case ISD::SETO: 1643 assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT) 1644 == TargetLowering::Legal 1645 && "If SETO is expanded, SETOEQ must be legal!"); 1646 CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break; 1647 case ISD::SETUO: 1648 assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT) 1649 == TargetLowering::Legal 1650 && "If SETUO is expanded, SETUNE must be legal!"); 1651 CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break; 1652 case ISD::SETOEQ: 1653 case ISD::SETOGT: 1654 case ISD::SETOGE: 1655 case ISD::SETOLT: 1656 case ISD::SETOLE: 1657 case ISD::SETONE: 1658 case ISD::SETUEQ: 1659 case ISD::SETUNE: 1660 case ISD::SETUGT: 1661 case ISD::SETUGE: 1662 case ISD::SETULT: 1663 case ISD::SETULE: 1664 // If we are floating point, assign and break, otherwise fall through. 1665 if (!OpVT.isInteger()) { 1666 // We can use the 4th bit to tell if we are the unordered 1667 // or ordered version of the opcode. 1668 CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO; 1669 Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND; 1670 CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10); 1671 break; 1672 } 1673 // Fallthrough if we are unsigned integer. 1674 LLVM_FALLTHROUGH; 1675 case ISD::SETLE: 1676 case ISD::SETGT: 1677 case ISD::SETGE: 1678 case ISD::SETLT: 1679 // We only support using the inverted operation, which is computed above 1680 // and not a different manner of supporting expanding these cases. 1681 llvm_unreachable("Don't know how to expand this condition!"); 1682 case ISD::SETNE: 1683 case ISD::SETEQ: 1684 // Try inverting the result of the inverse condition. 1685 InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ; 1686 if (TLI.isCondCodeLegal(InvCC, OpVT)) { 1687 CC = DAG.getCondCode(InvCC); 1688 NeedInvert = true; 1689 return true; 1690 } 1691 // If inverting the condition didn't work then we have no means to expand 1692 // the condition. 1693 llvm_unreachable("Don't know how to expand this condition!"); 1694 } 1695 1696 SDValue SetCC1, SetCC2; 1697 if (CCCode != ISD::SETO && CCCode != ISD::SETUO) { 1698 // If we aren't the ordered or unorder operation, 1699 // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS). 1700 SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1); 1701 SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2); 1702 } else { 1703 // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS) 1704 SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1); 1705 SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2); 1706 } 1707 LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2); 1708 RHS = SDValue(); 1709 CC = SDValue(); 1710 return true; 1711 } 1712 } 1713 return false; 1714 } 1715 1716 /// Emit a store/load combination to the stack. This stores 1717 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does 1718 /// a load from the stack slot to DestVT, extending it if needed. 1719 /// The resultant code need not be legal. 1720 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT, 1721 EVT DestVT, const SDLoc &dl) { 1722 // Create the stack frame object. 1723 unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment( 1724 SrcOp.getValueType().getTypeForEVT(*DAG.getContext())); 1725 SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign); 1726 1727 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr); 1728 int SPFI = StackPtrFI->getIndex(); 1729 MachinePointerInfo PtrInfo = 1730 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI); 1731 1732 unsigned SrcSize = SrcOp.getValueSizeInBits(); 1733 unsigned SlotSize = SlotVT.getSizeInBits(); 1734 unsigned DestSize = DestVT.getSizeInBits(); 1735 Type *DestType = DestVT.getTypeForEVT(*DAG.getContext()); 1736 unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType); 1737 1738 // Emit a store to the stack slot. Use a truncstore if the input value is 1739 // later than DestVT. 1740 SDValue Store; 1741 1742 if (SrcSize > SlotSize) 1743 Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo, 1744 SlotVT, SrcAlign); 1745 else { 1746 assert(SrcSize == SlotSize && "Invalid store"); 1747 Store = 1748 DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr, PtrInfo, SrcAlign); 1749 } 1750 1751 // Result is a load from the stack slot. 1752 if (SlotSize == DestSize) 1753 return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign); 1754 1755 assert(SlotSize < DestSize && "Unknown extension!"); 1756 return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT, 1757 DestAlign); 1758 } 1759 1760 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) { 1761 SDLoc dl(Node); 1762 // Create a vector sized/aligned stack slot, store the value to element #0, 1763 // then load the whole vector back out. 1764 SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0)); 1765 1766 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr); 1767 int SPFI = StackPtrFI->getIndex(); 1768 1769 SDValue Ch = DAG.getTruncStore( 1770 DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr, 1771 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI), 1772 Node->getValueType(0).getVectorElementType()); 1773 return DAG.getLoad( 1774 Node->getValueType(0), dl, Ch, StackPtr, 1775 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI)); 1776 } 1777 1778 static bool 1779 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG, 1780 const TargetLowering &TLI, SDValue &Res) { 1781 unsigned NumElems = Node->getNumOperands(); 1782 SDLoc dl(Node); 1783 EVT VT = Node->getValueType(0); 1784 1785 // Try to group the scalars into pairs, shuffle the pairs together, then 1786 // shuffle the pairs of pairs together, etc. until the vector has 1787 // been built. This will work only if all of the necessary shuffle masks 1788 // are legal. 1789 1790 // We do this in two phases; first to check the legality of the shuffles, 1791 // and next, assuming that all shuffles are legal, to create the new nodes. 1792 for (int Phase = 0; Phase < 2; ++Phase) { 1793 SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals, 1794 NewIntermedVals; 1795 for (unsigned i = 0; i < NumElems; ++i) { 1796 SDValue V = Node->getOperand(i); 1797 if (V.isUndef()) 1798 continue; 1799 1800 SDValue Vec; 1801 if (Phase) 1802 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V); 1803 IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i))); 1804 } 1805 1806 while (IntermedVals.size() > 2) { 1807 NewIntermedVals.clear(); 1808 for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) { 1809 // This vector and the next vector are shuffled together (simply to 1810 // append the one to the other). 1811 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1812 1813 SmallVector<int, 16> FinalIndices; 1814 FinalIndices.reserve(IntermedVals[i].second.size() + 1815 IntermedVals[i+1].second.size()); 1816 1817 int k = 0; 1818 for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f; 1819 ++j, ++k) { 1820 ShuffleVec[k] = j; 1821 FinalIndices.push_back(IntermedVals[i].second[j]); 1822 } 1823 for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f; 1824 ++j, ++k) { 1825 ShuffleVec[k] = NumElems + j; 1826 FinalIndices.push_back(IntermedVals[i+1].second[j]); 1827 } 1828 1829 SDValue Shuffle; 1830 if (Phase) 1831 Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first, 1832 IntermedVals[i+1].first, 1833 ShuffleVec); 1834 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1835 return false; 1836 NewIntermedVals.push_back( 1837 std::make_pair(Shuffle, std::move(FinalIndices))); 1838 } 1839 1840 // If we had an odd number of defined values, then append the last 1841 // element to the array of new vectors. 1842 if ((IntermedVals.size() & 1) != 0) 1843 NewIntermedVals.push_back(IntermedVals.back()); 1844 1845 IntermedVals.swap(NewIntermedVals); 1846 } 1847 1848 assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 && 1849 "Invalid number of intermediate vectors"); 1850 SDValue Vec1 = IntermedVals[0].first; 1851 SDValue Vec2; 1852 if (IntermedVals.size() > 1) 1853 Vec2 = IntermedVals[1].first; 1854 else if (Phase) 1855 Vec2 = DAG.getUNDEF(VT); 1856 1857 SmallVector<int, 16> ShuffleVec(NumElems, -1); 1858 for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i) 1859 ShuffleVec[IntermedVals[0].second[i]] = i; 1860 for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i) 1861 ShuffleVec[IntermedVals[1].second[i]] = NumElems + i; 1862 1863 if (Phase) 1864 Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1865 else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT)) 1866 return false; 1867 } 1868 1869 return true; 1870 } 1871 1872 /// Expand a BUILD_VECTOR node on targets that don't 1873 /// support the operation, but do support the resultant vector type. 1874 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) { 1875 unsigned NumElems = Node->getNumOperands(); 1876 SDValue Value1, Value2; 1877 SDLoc dl(Node); 1878 EVT VT = Node->getValueType(0); 1879 EVT OpVT = Node->getOperand(0).getValueType(); 1880 EVT EltVT = VT.getVectorElementType(); 1881 1882 // If the only non-undef value is the low element, turn this into a 1883 // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X. 1884 bool isOnlyLowElement = true; 1885 bool MoreThanTwoValues = false; 1886 bool isConstant = true; 1887 for (unsigned i = 0; i < NumElems; ++i) { 1888 SDValue V = Node->getOperand(i); 1889 if (V.isUndef()) 1890 continue; 1891 if (i > 0) 1892 isOnlyLowElement = false; 1893 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 1894 isConstant = false; 1895 1896 if (!Value1.getNode()) { 1897 Value1 = V; 1898 } else if (!Value2.getNode()) { 1899 if (V != Value1) 1900 Value2 = V; 1901 } else if (V != Value1 && V != Value2) { 1902 MoreThanTwoValues = true; 1903 } 1904 } 1905 1906 if (!Value1.getNode()) 1907 return DAG.getUNDEF(VT); 1908 1909 if (isOnlyLowElement) 1910 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0)); 1911 1912 // If all elements are constants, create a load from the constant pool. 1913 if (isConstant) { 1914 SmallVector<Constant*, 16> CV; 1915 for (unsigned i = 0, e = NumElems; i != e; ++i) { 1916 if (ConstantFPSDNode *V = 1917 dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) { 1918 CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue())); 1919 } else if (ConstantSDNode *V = 1920 dyn_cast<ConstantSDNode>(Node->getOperand(i))) { 1921 if (OpVT==EltVT) 1922 CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue())); 1923 else { 1924 // If OpVT and EltVT don't match, EltVT is not legal and the 1925 // element values have been promoted/truncated earlier. Undo this; 1926 // we don't want a v16i8 to become a v16i32 for example. 1927 const ConstantInt *CI = V->getConstantIntValue(); 1928 CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()), 1929 CI->getZExtValue())); 1930 } 1931 } else { 1932 assert(Node->getOperand(i).isUndef()); 1933 Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext()); 1934 CV.push_back(UndefValue::get(OpNTy)); 1935 } 1936 } 1937 Constant *CP = ConstantVector::get(CV); 1938 SDValue CPIdx = 1939 DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout())); 1940 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 1941 return DAG.getLoad( 1942 VT, dl, DAG.getEntryNode(), CPIdx, 1943 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 1944 Alignment); 1945 } 1946 1947 SmallSet<SDValue, 16> DefinedValues; 1948 for (unsigned i = 0; i < NumElems; ++i) { 1949 if (Node->getOperand(i).isUndef()) 1950 continue; 1951 DefinedValues.insert(Node->getOperand(i)); 1952 } 1953 1954 if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) { 1955 if (!MoreThanTwoValues) { 1956 SmallVector<int, 8> ShuffleVec(NumElems, -1); 1957 for (unsigned i = 0; i < NumElems; ++i) { 1958 SDValue V = Node->getOperand(i); 1959 if (V.isUndef()) 1960 continue; 1961 ShuffleVec[i] = V == Value1 ? 0 : NumElems; 1962 } 1963 if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) { 1964 // Get the splatted value into the low element of a vector register. 1965 SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1); 1966 SDValue Vec2; 1967 if (Value2.getNode()) 1968 Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2); 1969 else 1970 Vec2 = DAG.getUNDEF(VT); 1971 1972 // Return shuffle(LowValVec, undef, <0,0,0,0>) 1973 return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec); 1974 } 1975 } else { 1976 SDValue Res; 1977 if (ExpandBVWithShuffles(Node, DAG, TLI, Res)) 1978 return Res; 1979 } 1980 } 1981 1982 // Otherwise, we can't handle this case efficiently. 1983 return ExpandVectorBuildThroughStack(Node); 1984 } 1985 1986 // Expand a node into a call to a libcall. If the result value 1987 // does not fit into a register, return the lo part and set the hi part to the 1988 // by-reg argument. If it does fit into a single register, return the result 1989 // and leave the Hi part unset. 1990 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, 1991 bool isSigned) { 1992 TargetLowering::ArgListTy Args; 1993 TargetLowering::ArgListEntry Entry; 1994 for (const SDValue &Op : Node->op_values()) { 1995 EVT ArgVT = Op.getValueType(); 1996 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 1997 Entry.Node = Op; 1998 Entry.Ty = ArgTy; 1999 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2000 Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned); 2001 Args.push_back(Entry); 2002 } 2003 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2004 TLI.getPointerTy(DAG.getDataLayout())); 2005 2006 EVT RetVT = Node->getValueType(0); 2007 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2008 2009 // By default, the input chain to this libcall is the entry node of the 2010 // function. If the libcall is going to be emitted as a tail call then 2011 // TLI.isUsedByReturnOnly will change it to the right chain if the return 2012 // node which is being folded has a non-entry input chain. 2013 SDValue InChain = DAG.getEntryNode(); 2014 2015 // isTailCall may be true since the callee does not reference caller stack 2016 // frame. Check if it's in the right position and that the return types match. 2017 SDValue TCChain = InChain; 2018 const Function &F = DAG.getMachineFunction().getFunction(); 2019 bool isTailCall = 2020 TLI.isInTailCallPosition(DAG, Node, TCChain) && 2021 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 2022 if (isTailCall) 2023 InChain = TCChain; 2024 2025 TargetLowering::CallLoweringInfo CLI(DAG); 2026 bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned); 2027 CLI.setDebugLoc(SDLoc(Node)) 2028 .setChain(InChain) 2029 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2030 std::move(Args)) 2031 .setTailCall(isTailCall) 2032 .setSExtResult(signExtend) 2033 .setZExtResult(!signExtend) 2034 .setIsPostTypeLegalization(true); 2035 2036 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2037 2038 if (!CallInfo.second.getNode()) { 2039 DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump()); 2040 // It's a tailcall, return the chain (which is the DAG root). 2041 return DAG.getRoot(); 2042 } 2043 2044 DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump()); 2045 return CallInfo.first; 2046 } 2047 2048 /// Generate a libcall taking the given operands as arguments 2049 /// and returning a result of type RetVT. 2050 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, 2051 const SDValue *Ops, unsigned NumOps, 2052 bool isSigned, const SDLoc &dl) { 2053 TargetLowering::ArgListTy Args; 2054 Args.reserve(NumOps); 2055 2056 TargetLowering::ArgListEntry Entry; 2057 for (unsigned i = 0; i != NumOps; ++i) { 2058 Entry.Node = Ops[i]; 2059 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 2060 Entry.IsSExt = isSigned; 2061 Entry.IsZExt = !isSigned; 2062 Args.push_back(Entry); 2063 } 2064 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2065 TLI.getPointerTy(DAG.getDataLayout())); 2066 2067 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2068 2069 TargetLowering::CallLoweringInfo CLI(DAG); 2070 CLI.setDebugLoc(dl) 2071 .setChain(DAG.getEntryNode()) 2072 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2073 std::move(Args)) 2074 .setSExtResult(isSigned) 2075 .setZExtResult(!isSigned) 2076 .setIsPostTypeLegalization(true); 2077 2078 std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI); 2079 2080 return CallInfo.first; 2081 } 2082 2083 // Expand a node into a call to a libcall. Similar to 2084 // ExpandLibCall except that the first operand is the in-chain. 2085 std::pair<SDValue, SDValue> 2086 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC, 2087 SDNode *Node, 2088 bool isSigned) { 2089 SDValue InChain = Node->getOperand(0); 2090 2091 TargetLowering::ArgListTy Args; 2092 TargetLowering::ArgListEntry Entry; 2093 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) { 2094 EVT ArgVT = Node->getOperand(i).getValueType(); 2095 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2096 Entry.Node = Node->getOperand(i); 2097 Entry.Ty = ArgTy; 2098 Entry.IsSExt = isSigned; 2099 Entry.IsZExt = !isSigned; 2100 Args.push_back(Entry); 2101 } 2102 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2103 TLI.getPointerTy(DAG.getDataLayout())); 2104 2105 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext()); 2106 2107 TargetLowering::CallLoweringInfo CLI(DAG); 2108 CLI.setDebugLoc(SDLoc(Node)) 2109 .setChain(InChain) 2110 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2111 std::move(Args)) 2112 .setSExtResult(isSigned) 2113 .setZExtResult(!isSigned); 2114 2115 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2116 2117 return CallInfo; 2118 } 2119 2120 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node, 2121 RTLIB::Libcall Call_F32, 2122 RTLIB::Libcall Call_F64, 2123 RTLIB::Libcall Call_F80, 2124 RTLIB::Libcall Call_F128, 2125 RTLIB::Libcall Call_PPCF128) { 2126 if (Node->isStrictFPOpcode()) 2127 Node = DAG.mutateStrictFPToFP(Node); 2128 2129 RTLIB::Libcall LC; 2130 switch (Node->getSimpleValueType(0).SimpleTy) { 2131 default: llvm_unreachable("Unexpected request for libcall!"); 2132 case MVT::f32: LC = Call_F32; break; 2133 case MVT::f64: LC = Call_F64; break; 2134 case MVT::f80: LC = Call_F80; break; 2135 case MVT::f128: LC = Call_F128; break; 2136 case MVT::ppcf128: LC = Call_PPCF128; break; 2137 } 2138 return ExpandLibCall(LC, Node, false); 2139 } 2140 2141 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned, 2142 RTLIB::Libcall Call_I8, 2143 RTLIB::Libcall Call_I16, 2144 RTLIB::Libcall Call_I32, 2145 RTLIB::Libcall Call_I64, 2146 RTLIB::Libcall Call_I128) { 2147 RTLIB::Libcall LC; 2148 switch (Node->getSimpleValueType(0).SimpleTy) { 2149 default: llvm_unreachable("Unexpected request for libcall!"); 2150 case MVT::i8: LC = Call_I8; break; 2151 case MVT::i16: LC = Call_I16; break; 2152 case MVT::i32: LC = Call_I32; break; 2153 case MVT::i64: LC = Call_I64; break; 2154 case MVT::i128: LC = Call_I128; break; 2155 } 2156 return ExpandLibCall(LC, Node, isSigned); 2157 } 2158 2159 /// Issue libcalls to __{u}divmod to compute div / rem pairs. 2160 void 2161 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node, 2162 SmallVectorImpl<SDValue> &Results) { 2163 unsigned Opcode = Node->getOpcode(); 2164 bool isSigned = Opcode == ISD::SDIVREM; 2165 2166 RTLIB::Libcall LC; 2167 switch (Node->getSimpleValueType(0).SimpleTy) { 2168 default: llvm_unreachable("Unexpected request for libcall!"); 2169 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2170 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2171 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2172 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2173 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2174 } 2175 2176 // The input chain to this libcall is the entry node of the function. 2177 // Legalizing the call will automatically add the previous call to the 2178 // dependence. 2179 SDValue InChain = DAG.getEntryNode(); 2180 2181 EVT RetVT = Node->getValueType(0); 2182 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2183 2184 TargetLowering::ArgListTy Args; 2185 TargetLowering::ArgListEntry Entry; 2186 for (const SDValue &Op : Node->op_values()) { 2187 EVT ArgVT = Op.getValueType(); 2188 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2189 Entry.Node = Op; 2190 Entry.Ty = ArgTy; 2191 Entry.IsSExt = isSigned; 2192 Entry.IsZExt = !isSigned; 2193 Args.push_back(Entry); 2194 } 2195 2196 // Also pass the return address of the remainder. 2197 SDValue FIPtr = DAG.CreateStackTemporary(RetVT); 2198 Entry.Node = FIPtr; 2199 Entry.Ty = RetTy->getPointerTo(); 2200 Entry.IsSExt = isSigned; 2201 Entry.IsZExt = !isSigned; 2202 Args.push_back(Entry); 2203 2204 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2205 TLI.getPointerTy(DAG.getDataLayout())); 2206 2207 SDLoc dl(Node); 2208 TargetLowering::CallLoweringInfo CLI(DAG); 2209 CLI.setDebugLoc(dl) 2210 .setChain(InChain) 2211 .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, 2212 std::move(Args)) 2213 .setSExtResult(isSigned) 2214 .setZExtResult(!isSigned); 2215 2216 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2217 2218 // Remainder is loaded back from the stack frame. 2219 SDValue Rem = 2220 DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo()); 2221 Results.push_back(CallInfo.first); 2222 Results.push_back(Rem); 2223 } 2224 2225 /// Return true if sincos libcall is available. 2226 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) { 2227 RTLIB::Libcall LC; 2228 switch (Node->getSimpleValueType(0).SimpleTy) { 2229 default: llvm_unreachable("Unexpected request for libcall!"); 2230 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2231 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2232 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2233 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2234 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2235 } 2236 return TLI.getLibcallName(LC) != nullptr; 2237 } 2238 2239 /// Only issue sincos libcall if both sin and cos are needed. 2240 static bool useSinCos(SDNode *Node) { 2241 unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN 2242 ? ISD::FCOS : ISD::FSIN; 2243 2244 SDValue Op0 = Node->getOperand(0); 2245 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2246 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2247 SDNode *User = *UI; 2248 if (User == Node) 2249 continue; 2250 // The other user might have been turned into sincos already. 2251 if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS) 2252 return true; 2253 } 2254 return false; 2255 } 2256 2257 /// Issue libcalls to sincos to compute sin / cos pairs. 2258 void 2259 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node, 2260 SmallVectorImpl<SDValue> &Results) { 2261 RTLIB::Libcall LC; 2262 switch (Node->getSimpleValueType(0).SimpleTy) { 2263 default: llvm_unreachable("Unexpected request for libcall!"); 2264 case MVT::f32: LC = RTLIB::SINCOS_F32; break; 2265 case MVT::f64: LC = RTLIB::SINCOS_F64; break; 2266 case MVT::f80: LC = RTLIB::SINCOS_F80; break; 2267 case MVT::f128: LC = RTLIB::SINCOS_F128; break; 2268 case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break; 2269 } 2270 2271 // The input chain to this libcall is the entry node of the function. 2272 // Legalizing the call will automatically add the previous call to the 2273 // dependence. 2274 SDValue InChain = DAG.getEntryNode(); 2275 2276 EVT RetVT = Node->getValueType(0); 2277 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 2278 2279 TargetLowering::ArgListTy Args; 2280 TargetLowering::ArgListEntry Entry; 2281 2282 // Pass the argument. 2283 Entry.Node = Node->getOperand(0); 2284 Entry.Ty = RetTy; 2285 Entry.IsSExt = false; 2286 Entry.IsZExt = false; 2287 Args.push_back(Entry); 2288 2289 // Pass the return address of sin. 2290 SDValue SinPtr = DAG.CreateStackTemporary(RetVT); 2291 Entry.Node = SinPtr; 2292 Entry.Ty = RetTy->getPointerTo(); 2293 Entry.IsSExt = false; 2294 Entry.IsZExt = false; 2295 Args.push_back(Entry); 2296 2297 // Also pass the return address of the cos. 2298 SDValue CosPtr = DAG.CreateStackTemporary(RetVT); 2299 Entry.Node = CosPtr; 2300 Entry.Ty = RetTy->getPointerTo(); 2301 Entry.IsSExt = false; 2302 Entry.IsZExt = false; 2303 Args.push_back(Entry); 2304 2305 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC), 2306 TLI.getPointerTy(DAG.getDataLayout())); 2307 2308 SDLoc dl(Node); 2309 TargetLowering::CallLoweringInfo CLI(DAG); 2310 CLI.setDebugLoc(dl).setChain(InChain).setLibCallee( 2311 TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee, 2312 std::move(Args)); 2313 2314 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI); 2315 2316 Results.push_back( 2317 DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo())); 2318 Results.push_back( 2319 DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo())); 2320 } 2321 2322 /// This function is responsible for legalizing a 2323 /// INT_TO_FP operation of the specified operand when the target requests that 2324 /// we expand it. At this point, we know that the result and operand types are 2325 /// legal for the target. 2326 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, 2327 EVT DestVT, 2328 const SDLoc &dl) { 2329 // TODO: Should any fast-math-flags be set for the created nodes? 2330 DEBUG(dbgs() << "Legalizing INT_TO_FP\n"); 2331 if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) { 2332 DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double " 2333 "expansion\n"); 2334 2335 // Get the stack frame index of a 8 byte buffer. 2336 SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64); 2337 2338 // word offset constant for Hi/Lo address computation 2339 SDValue WordOff = DAG.getConstant(sizeof(int), dl, 2340 StackSlot.getValueType()); 2341 // set up Hi and Lo (into buffer) address based on endian 2342 SDValue Hi = StackSlot; 2343 SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(), 2344 StackSlot, WordOff); 2345 if (DAG.getDataLayout().isLittleEndian()) 2346 std::swap(Hi, Lo); 2347 2348 // if signed map to unsigned space 2349 SDValue Op0Mapped; 2350 if (isSigned) { 2351 // constant used to invert sign bit (signed to unsigned mapping) 2352 SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32); 2353 Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit); 2354 } else { 2355 Op0Mapped = Op0; 2356 } 2357 // store the lo of the constructed double - based on integer input 2358 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op0Mapped, Lo, 2359 MachinePointerInfo()); 2360 // initial hi portion of constructed double 2361 SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32); 2362 // store the hi of the constructed double - biased exponent 2363 SDValue Store2 = 2364 DAG.getStore(Store1, dl, InitialHi, Hi, MachinePointerInfo()); 2365 // load the constructed double 2366 SDValue Load = 2367 DAG.getLoad(MVT::f64, dl, Store2, StackSlot, MachinePointerInfo()); 2368 // FP constant to bias correct the final result 2369 SDValue Bias = DAG.getConstantFP(isSigned ? 2370 BitsToDouble(0x4330000080000000ULL) : 2371 BitsToDouble(0x4330000000000000ULL), 2372 dl, MVT::f64); 2373 // subtract the bias 2374 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias); 2375 // final result 2376 SDValue Result; 2377 // handle final rounding 2378 if (DestVT == MVT::f64) { 2379 // do nothing 2380 Result = Sub; 2381 } else if (DestVT.bitsLT(MVT::f64)) { 2382 Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 2383 DAG.getIntPtrConstant(0, dl)); 2384 } else if (DestVT.bitsGT(MVT::f64)) { 2385 Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 2386 } 2387 return Result; 2388 } 2389 assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet"); 2390 // Code below here assumes !isSigned without checking again. 2391 2392 // Implementation of unsigned i64 to f64 following the algorithm in 2393 // __floatundidf in compiler_rt. This implementation has the advantage 2394 // of performing rounding correctly, both in the default rounding mode 2395 // and in all alternate rounding modes. 2396 // TODO: Generalize this for use with other types. 2397 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) { 2398 DEBUG(dbgs() << "Converting unsigned i64 to f64\n"); 2399 SDValue TwoP52 = 2400 DAG.getConstant(UINT64_C(0x4330000000000000), dl, MVT::i64); 2401 SDValue TwoP84PlusTwoP52 = 2402 DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), dl, 2403 MVT::f64); 2404 SDValue TwoP84 = 2405 DAG.getConstant(UINT64_C(0x4530000000000000), dl, MVT::i64); 2406 2407 SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32); 2408 SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, 2409 DAG.getConstant(32, dl, MVT::i64)); 2410 SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52); 2411 SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84); 2412 SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr); 2413 SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr); 2414 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt, 2415 TwoP84PlusTwoP52); 2416 return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub); 2417 } 2418 2419 // TODO: Generalize this for use with other types. 2420 if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) { 2421 DEBUG(dbgs() << "Converting unsigned i64 to f32\n"); 2422 // For unsigned conversions, convert them to signed conversions using the 2423 // algorithm from the x86_64 __floatundidf in compiler_rt. 2424 if (!isSigned) { 2425 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0); 2426 2427 SDValue ShiftConst = DAG.getConstant( 2428 1, dl, TLI.getShiftAmountTy(Op0.getValueType(), DAG.getDataLayout())); 2429 SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst); 2430 SDValue AndConst = DAG.getConstant(1, dl, MVT::i64); 2431 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst); 2432 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr); 2433 2434 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or); 2435 SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt); 2436 2437 // TODO: This really should be implemented using a branch rather than a 2438 // select. We happen to get lucky and machinesink does the right 2439 // thing most of the time. This would be a good candidate for a 2440 //pseudo-op, or, even better, for whole-function isel. 2441 SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 2442 Op0, DAG.getConstant(0, dl, MVT::i64), ISD::SETLT); 2443 return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast); 2444 } 2445 2446 // Otherwise, implement the fully general conversion. 2447 2448 SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, 2449 DAG.getConstant(UINT64_C(0xfffffffffffff800), dl, MVT::i64)); 2450 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, 2451 DAG.getConstant(UINT64_C(0x800), dl, MVT::i64)); 2452 SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, 2453 DAG.getConstant(UINT64_C(0x7ff), dl, MVT::i64)); 2454 SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), And2, 2455 DAG.getConstant(UINT64_C(0), dl, MVT::i64), 2456 ISD::SETNE); 2457 SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0); 2458 SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), Op0, 2459 DAG.getConstant(UINT64_C(0x0020000000000000), dl, 2460 MVT::i64), 2461 ISD::SETUGE); 2462 SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0); 2463 EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType(), DAG.getDataLayout()); 2464 2465 SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2, 2466 DAG.getConstant(32, dl, SHVT)); 2467 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh); 2468 SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc); 2469 SDValue TwoP32 = 2470 DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), dl, 2471 MVT::f64); 2472 SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt); 2473 SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2); 2474 SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo); 2475 SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2); 2476 return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd, 2477 DAG.getIntPtrConstant(0, dl)); 2478 } 2479 2480 SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0); 2481 2482 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()), 2483 Op0, 2484 DAG.getConstant(0, dl, Op0.getValueType()), 2485 ISD::SETLT); 2486 SDValue Zero = DAG.getIntPtrConstant(0, dl), 2487 Four = DAG.getIntPtrConstant(4, dl); 2488 SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(), 2489 SignSet, Four, Zero); 2490 2491 // If the sign bit of the integer is set, the large number will be treated 2492 // as a negative number. To counteract this, the dynamic code adds an 2493 // offset depending on the data type. 2494 uint64_t FF; 2495 switch (Op0.getSimpleValueType().SimpleTy) { 2496 default: llvm_unreachable("Unsupported integer type!"); 2497 case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float) 2498 case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float) 2499 case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float) 2500 case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float) 2501 } 2502 if (DAG.getDataLayout().isLittleEndian()) 2503 FF <<= 32; 2504 Constant *FudgeFactor = ConstantInt::get( 2505 Type::getInt64Ty(*DAG.getContext()), FF); 2506 2507 SDValue CPIdx = 2508 DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout())); 2509 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 2510 CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset); 2511 Alignment = std::min(Alignment, 4u); 2512 SDValue FudgeInReg; 2513 if (DestVT == MVT::f32) 2514 FudgeInReg = DAG.getLoad( 2515 MVT::f32, dl, DAG.getEntryNode(), CPIdx, 2516 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 2517 Alignment); 2518 else { 2519 SDValue Load = DAG.getExtLoad( 2520 ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx, 2521 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32, 2522 Alignment); 2523 HandleSDNode Handle(Load); 2524 LegalizeOp(Load.getNode()); 2525 FudgeInReg = Handle.getValue(); 2526 } 2527 2528 return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg); 2529 } 2530 2531 /// This function is responsible for legalizing a 2532 /// *INT_TO_FP operation of the specified operand when the target requests that 2533 /// we promote it. At this point, we know that the result and operand types are 2534 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP 2535 /// operation that takes a larger input. 2536 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, 2537 bool isSigned, 2538 const SDLoc &dl) { 2539 // First step, figure out the appropriate *INT_TO_FP operation to use. 2540 EVT NewInTy = LegalOp.getValueType(); 2541 2542 unsigned OpToUse = 0; 2543 2544 // Scan for the appropriate larger type to use. 2545 while (true) { 2546 NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1); 2547 assert(NewInTy.isInteger() && "Ran out of possibilities!"); 2548 2549 // If the target supports SINT_TO_FP of this type, use it. 2550 if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) { 2551 OpToUse = ISD::SINT_TO_FP; 2552 break; 2553 } 2554 if (isSigned) continue; 2555 2556 // If the target supports UINT_TO_FP of this type, use it. 2557 if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) { 2558 OpToUse = ISD::UINT_TO_FP; 2559 break; 2560 } 2561 2562 // Otherwise, try a larger type. 2563 } 2564 2565 // Okay, we found the operation and type to use. Zero extend our input to the 2566 // desired type then run the operation on it. 2567 return DAG.getNode(OpToUse, dl, DestVT, 2568 DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 2569 dl, NewInTy, LegalOp)); 2570 } 2571 2572 /// This function is responsible for legalizing a 2573 /// FP_TO_*INT operation of the specified operand when the target requests that 2574 /// we promote it. At this point, we know that the result and operand types are 2575 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT 2576 /// operation that returns a larger result. 2577 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, 2578 bool isSigned, 2579 const SDLoc &dl) { 2580 // First step, figure out the appropriate FP_TO*INT operation to use. 2581 EVT NewOutTy = DestVT; 2582 2583 unsigned OpToUse = 0; 2584 2585 // Scan for the appropriate larger type to use. 2586 while (true) { 2587 NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1); 2588 assert(NewOutTy.isInteger() && "Ran out of possibilities!"); 2589 2590 // A larger signed type can hold all unsigned values of the requested type, 2591 // so using FP_TO_SINT is valid 2592 if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) { 2593 OpToUse = ISD::FP_TO_SINT; 2594 break; 2595 } 2596 2597 // However, if the value may be < 0.0, we *must* use some FP_TO_SINT. 2598 if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) { 2599 OpToUse = ISD::FP_TO_UINT; 2600 break; 2601 } 2602 2603 // Otherwise, try a larger type. 2604 } 2605 2606 // Okay, we found the operation and type to use. 2607 SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp); 2608 2609 // Truncate the result of the extended FP_TO_*INT operation to the desired 2610 // size. 2611 return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation); 2612 } 2613 2614 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts. 2615 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) { 2616 EVT VT = Op.getValueType(); 2617 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2618 unsigned Sz = VT.getScalarSizeInBits(); 2619 2620 SDValue Tmp, Tmp2, Tmp3; 2621 2622 // If we can, perform BSWAP first and then the mask+swap the i4, then i2 2623 // and finally the i1 pairs. 2624 // TODO: We can easily support i4/i2 legal types if any target ever does. 2625 if (Sz >= 8 && isPowerOf2_32(Sz)) { 2626 // Create the masks - repeating the pattern every byte. 2627 APInt MaskHi4(Sz, 0), MaskHi2(Sz, 0), MaskHi1(Sz, 0); 2628 APInt MaskLo4(Sz, 0), MaskLo2(Sz, 0), MaskLo1(Sz, 0); 2629 for (unsigned J = 0; J != Sz; J += 8) { 2630 MaskHi4 = MaskHi4 | (0xF0ull << J); 2631 MaskLo4 = MaskLo4 | (0x0Full << J); 2632 MaskHi2 = MaskHi2 | (0xCCull << J); 2633 MaskLo2 = MaskLo2 | (0x33ull << J); 2634 MaskHi1 = MaskHi1 | (0xAAull << J); 2635 MaskLo1 = MaskLo1 | (0x55ull << J); 2636 } 2637 2638 // BSWAP if the type is wider than a single byte. 2639 Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op); 2640 2641 // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4) 2642 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT)); 2643 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT)); 2644 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, VT)); 2645 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, VT)); 2646 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2647 2648 // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2) 2649 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT)); 2650 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT)); 2651 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, VT)); 2652 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, VT)); 2653 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2654 2655 // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1) 2656 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT)); 2657 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT)); 2658 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, VT)); 2659 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, VT)); 2660 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 2661 return Tmp; 2662 } 2663 2664 Tmp = DAG.getConstant(0, dl, VT); 2665 for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) { 2666 if (I < J) 2667 Tmp2 = 2668 DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT)); 2669 else 2670 Tmp2 = 2671 DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT)); 2672 2673 APInt Shift(Sz, 1); 2674 Shift <<= J; 2675 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT)); 2676 Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2); 2677 } 2678 2679 return Tmp; 2680 } 2681 2682 /// Open code the operations for BSWAP of the specified operation. 2683 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) { 2684 EVT VT = Op.getValueType(); 2685 EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2686 SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8; 2687 switch (VT.getSimpleVT().getScalarType().SimpleTy) { 2688 default: llvm_unreachable("Unhandled Expand type in BSWAP!"); 2689 case MVT::i16: 2690 Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2691 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2692 return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2); 2693 case MVT::i32: 2694 Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2695 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2696 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2697 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2698 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2699 DAG.getConstant(0xFF0000, dl, VT)); 2700 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT)); 2701 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2702 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2703 return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2704 case MVT::i64: 2705 Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2706 Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2707 Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2708 Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2709 Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT)); 2710 Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT)); 2711 Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT)); 2712 Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT)); 2713 Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, 2714 DAG.getConstant(255ULL<<48, dl, VT)); 2715 Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, 2716 DAG.getConstant(255ULL<<40, dl, VT)); 2717 Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, 2718 DAG.getConstant(255ULL<<32, dl, VT)); 2719 Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, 2720 DAG.getConstant(255ULL<<24, dl, VT)); 2721 Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, 2722 DAG.getConstant(255ULL<<16, dl, VT)); 2723 Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, 2724 DAG.getConstant(255ULL<<8 , dl, VT)); 2725 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7); 2726 Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5); 2727 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3); 2728 Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1); 2729 Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6); 2730 Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2); 2731 return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4); 2732 } 2733 } 2734 2735 /// Expand the specified bitcount instruction into operations. 2736 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op, 2737 const SDLoc &dl) { 2738 switch (Opc) { 2739 default: llvm_unreachable("Cannot expand this yet!"); 2740 case ISD::CTPOP: { 2741 EVT VT = Op.getValueType(); 2742 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2743 unsigned Len = VT.getSizeInBits(); 2744 2745 assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 && 2746 "CTPOP not implemented for this type."); 2747 2748 // This is the "best" algorithm from 2749 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 2750 2751 SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), 2752 dl, VT); 2753 SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), 2754 dl, VT); 2755 SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), 2756 dl, VT); 2757 SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), 2758 dl, VT); 2759 2760 // v = v - ((v >> 1) & 0x55555555...) 2761 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 2762 DAG.getNode(ISD::AND, dl, VT, 2763 DAG.getNode(ISD::SRL, dl, VT, Op, 2764 DAG.getConstant(1, dl, ShVT)), 2765 Mask55)); 2766 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 2767 Op = DAG.getNode(ISD::ADD, dl, VT, 2768 DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 2769 DAG.getNode(ISD::AND, dl, VT, 2770 DAG.getNode(ISD::SRL, dl, VT, Op, 2771 DAG.getConstant(2, dl, ShVT)), 2772 Mask33)); 2773 // v = (v + (v >> 4)) & 0x0F0F0F0F... 2774 Op = DAG.getNode(ISD::AND, dl, VT, 2775 DAG.getNode(ISD::ADD, dl, VT, Op, 2776 DAG.getNode(ISD::SRL, dl, VT, Op, 2777 DAG.getConstant(4, dl, ShVT))), 2778 Mask0F); 2779 // v = (v * 0x01010101...) >> (Len - 8) 2780 Op = DAG.getNode(ISD::SRL, dl, VT, 2781 DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 2782 DAG.getConstant(Len - 8, dl, ShVT)); 2783 2784 return Op; 2785 } 2786 case ISD::CTLZ_ZERO_UNDEF: 2787 // This trivially expands to CTLZ. 2788 return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op); 2789 case ISD::CTLZ: { 2790 EVT VT = Op.getValueType(); 2791 unsigned Len = VT.getSizeInBits(); 2792 2793 if (TLI.isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 2794 EVT SetCCVT = getSetCCResultType(VT); 2795 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 2796 SDValue Zero = DAG.getConstant(0, dl, VT); 2797 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 2798 return DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 2799 DAG.getConstant(Len, dl, VT), CTLZ); 2800 } 2801 2802 // for now, we do this: 2803 // x = x | (x >> 1); 2804 // x = x | (x >> 2); 2805 // ... 2806 // x = x | (x >>16); 2807 // x = x | (x >>32); // for 64-bit input 2808 // return popcount(~x); 2809 // 2810 // Ref: "Hacker's Delight" by Henry Warren 2811 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 2812 for (unsigned i = 0; (1U << i) <= (Len / 2); ++i) { 2813 SDValue Tmp3 = DAG.getConstant(1ULL << i, dl, ShVT); 2814 Op = DAG.getNode(ISD::OR, dl, VT, Op, 2815 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3)); 2816 } 2817 Op = DAG.getNOT(dl, Op, VT); 2818 return DAG.getNode(ISD::CTPOP, dl, VT, Op); 2819 } 2820 case ISD::CTTZ_ZERO_UNDEF: 2821 // This trivially expands to CTTZ. 2822 return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op); 2823 case ISD::CTTZ: { 2824 EVT VT = Op.getValueType(); 2825 unsigned Len = VT.getSizeInBits(); 2826 2827 if (TLI.isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 2828 EVT SetCCVT = getSetCCResultType(VT); 2829 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 2830 SDValue Zero = DAG.getConstant(0, dl, VT); 2831 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 2832 return DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 2833 DAG.getConstant(Len, dl, VT), CTTZ); 2834 } 2835 2836 // for now, we use: { return popcount(~x & (x - 1)); } 2837 // unless the target has ctlz but not ctpop, in which case we use: 2838 // { return 32 - nlz(~x & (x-1)); } 2839 // Ref: "Hacker's Delight" by Henry Warren 2840 SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT, 2841 DAG.getNOT(dl, Op, VT), 2842 DAG.getNode(ISD::SUB, dl, VT, Op, 2843 DAG.getConstant(1, dl, VT))); 2844 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 2845 if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) && 2846 TLI.isOperationLegalOrCustom(ISD::CTLZ, VT)) 2847 return DAG.getNode(ISD::SUB, dl, VT, 2848 DAG.getConstant(VT.getSizeInBits(), dl, VT), 2849 DAG.getNode(ISD::CTLZ, dl, VT, Tmp3)); 2850 return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3); 2851 } 2852 } 2853 } 2854 2855 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) { 2856 DEBUG(dbgs() << "Trying to expand node\n"); 2857 SmallVector<SDValue, 8> Results; 2858 SDLoc dl(Node); 2859 SDValue Tmp1, Tmp2, Tmp3, Tmp4; 2860 bool NeedInvert; 2861 switch (Node->getOpcode()) { 2862 case ISD::CTPOP: 2863 case ISD::CTLZ: 2864 case ISD::CTLZ_ZERO_UNDEF: 2865 case ISD::CTTZ: 2866 case ISD::CTTZ_ZERO_UNDEF: 2867 Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl); 2868 Results.push_back(Tmp1); 2869 break; 2870 case ISD::BITREVERSE: 2871 Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl)); 2872 break; 2873 case ISD::BSWAP: 2874 Results.push_back(ExpandBSWAP(Node->getOperand(0), dl)); 2875 break; 2876 case ISD::FRAMEADDR: 2877 case ISD::RETURNADDR: 2878 case ISD::FRAME_TO_ARGS_OFFSET: 2879 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 2880 break; 2881 case ISD::EH_DWARF_CFA: { 2882 SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl, 2883 TLI.getPointerTy(DAG.getDataLayout())); 2884 SDValue Offset = DAG.getNode(ISD::ADD, dl, 2885 CfaArg.getValueType(), 2886 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 2887 CfaArg.getValueType()), 2888 CfaArg); 2889 SDValue FA = DAG.getNode( 2890 ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()), 2891 DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()))); 2892 Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(), 2893 FA, Offset)); 2894 break; 2895 } 2896 case ISD::FLT_ROUNDS_: 2897 Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0))); 2898 break; 2899 case ISD::EH_RETURN: 2900 case ISD::EH_LABEL: 2901 case ISD::PREFETCH: 2902 case ISD::VAEND: 2903 case ISD::EH_SJLJ_LONGJMP: 2904 // If the target didn't expand these, there's nothing to do, so just 2905 // preserve the chain and be done. 2906 Results.push_back(Node->getOperand(0)); 2907 break; 2908 case ISD::READCYCLECOUNTER: 2909 // If the target didn't expand this, just return 'zero' and preserve the 2910 // chain. 2911 Results.append(Node->getNumValues() - 1, 2912 DAG.getConstant(0, dl, Node->getValueType(0))); 2913 Results.push_back(Node->getOperand(0)); 2914 break; 2915 case ISD::EH_SJLJ_SETJMP: 2916 // If the target didn't expand this, just return 'zero' and preserve the 2917 // chain. 2918 Results.push_back(DAG.getConstant(0, dl, MVT::i32)); 2919 Results.push_back(Node->getOperand(0)); 2920 break; 2921 case ISD::ATOMIC_LOAD: { 2922 // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP. 2923 SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0)); 2924 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2925 SDValue Swap = DAG.getAtomicCmpSwap( 2926 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2927 Node->getOperand(0), Node->getOperand(1), Zero, Zero, 2928 cast<AtomicSDNode>(Node)->getMemOperand()); 2929 Results.push_back(Swap.getValue(0)); 2930 Results.push_back(Swap.getValue(1)); 2931 break; 2932 } 2933 case ISD::ATOMIC_STORE: { 2934 // There is no libcall for atomic store; fake it with ATOMIC_SWAP. 2935 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 2936 cast<AtomicSDNode>(Node)->getMemoryVT(), 2937 Node->getOperand(0), 2938 Node->getOperand(1), Node->getOperand(2), 2939 cast<AtomicSDNode>(Node)->getMemOperand()); 2940 Results.push_back(Swap.getValue(1)); 2941 break; 2942 } 2943 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: { 2944 // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and 2945 // splits out the success value as a comparison. Expanding the resulting 2946 // ATOMIC_CMP_SWAP will produce a libcall. 2947 SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other); 2948 SDValue Res = DAG.getAtomicCmpSwap( 2949 ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs, 2950 Node->getOperand(0), Node->getOperand(1), Node->getOperand(2), 2951 Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand()); 2952 2953 SDValue ExtRes = Res; 2954 SDValue LHS = Res; 2955 SDValue RHS = Node->getOperand(1); 2956 2957 EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT(); 2958 EVT OuterType = Node->getValueType(0); 2959 switch (TLI.getExtendForAtomicOps()) { 2960 case ISD::SIGN_EXTEND: 2961 LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res, 2962 DAG.getValueType(AtomicType)); 2963 RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType, 2964 Node->getOperand(2), DAG.getValueType(AtomicType)); 2965 ExtRes = LHS; 2966 break; 2967 case ISD::ZERO_EXTEND: 2968 LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res, 2969 DAG.getValueType(AtomicType)); 2970 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2971 ExtRes = LHS; 2972 break; 2973 case ISD::ANY_EXTEND: 2974 LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType); 2975 RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType); 2976 break; 2977 default: 2978 llvm_unreachable("Invalid atomic op extension"); 2979 } 2980 2981 SDValue Success = 2982 DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ); 2983 2984 Results.push_back(ExtRes.getValue(0)); 2985 Results.push_back(Success); 2986 Results.push_back(Res.getValue(1)); 2987 break; 2988 } 2989 case ISD::DYNAMIC_STACKALLOC: 2990 ExpandDYNAMIC_STACKALLOC(Node, Results); 2991 break; 2992 case ISD::MERGE_VALUES: 2993 for (unsigned i = 0; i < Node->getNumValues(); i++) 2994 Results.push_back(Node->getOperand(i)); 2995 break; 2996 case ISD::UNDEF: { 2997 EVT VT = Node->getValueType(0); 2998 if (VT.isInteger()) 2999 Results.push_back(DAG.getConstant(0, dl, VT)); 3000 else { 3001 assert(VT.isFloatingPoint() && "Unknown value type!"); 3002 Results.push_back(DAG.getConstantFP(0, dl, VT)); 3003 } 3004 break; 3005 } 3006 case ISD::FP_ROUND: 3007 case ISD::BITCAST: 3008 Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0), 3009 Node->getValueType(0), dl); 3010 Results.push_back(Tmp1); 3011 break; 3012 case ISD::FP_EXTEND: 3013 Tmp1 = EmitStackConvert(Node->getOperand(0), 3014 Node->getOperand(0).getValueType(), 3015 Node->getValueType(0), dl); 3016 Results.push_back(Tmp1); 3017 break; 3018 case ISD::SIGN_EXTEND_INREG: { 3019 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 3020 EVT VT = Node->getValueType(0); 3021 3022 // An in-register sign-extend of a boolean is a negation: 3023 // 'true' (1) sign-extended is -1. 3024 // 'false' (0) sign-extended is 0. 3025 // However, we must mask the high bits of the source operand because the 3026 // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero. 3027 3028 // TODO: Do this for vectors too? 3029 if (ExtraVT.getSizeInBits() == 1) { 3030 SDValue One = DAG.getConstant(1, dl, VT); 3031 SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One); 3032 SDValue Zero = DAG.getConstant(0, dl, VT); 3033 SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And); 3034 Results.push_back(Neg); 3035 break; 3036 } 3037 3038 // NOTE: we could fall back on load/store here too for targets without 3039 // SRA. However, it is doubtful that any exist. 3040 EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 3041 unsigned BitsDiff = VT.getScalarSizeInBits() - 3042 ExtraVT.getScalarSizeInBits(); 3043 SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy); 3044 Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0), 3045 Node->getOperand(0), ShiftCst); 3046 Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst); 3047 Results.push_back(Tmp1); 3048 break; 3049 } 3050 case ISD::FP_ROUND_INREG: { 3051 // The only way we can lower this is to turn it into a TRUNCSTORE, 3052 // EXTLOAD pair, targeting a temporary location (a stack slot). 3053 3054 // NOTE: there is a choice here between constantly creating new stack 3055 // slots and always reusing the same one. We currently always create 3056 // new ones, as reuse may inhibit scheduling. 3057 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT(); 3058 Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT, 3059 Node->getValueType(0), dl); 3060 Results.push_back(Tmp1); 3061 break; 3062 } 3063 case ISD::SINT_TO_FP: 3064 case ISD::UINT_TO_FP: 3065 Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP, 3066 Node->getOperand(0), Node->getValueType(0), dl); 3067 Results.push_back(Tmp1); 3068 break; 3069 case ISD::FP_TO_SINT: 3070 if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) 3071 Results.push_back(Tmp1); 3072 break; 3073 case ISD::FP_TO_UINT: { 3074 SDValue True, False; 3075 EVT VT = Node->getOperand(0).getValueType(); 3076 EVT NVT = Node->getValueType(0); 3077 APFloat apf(DAG.EVTToAPFloatSemantics(VT), 3078 APInt::getNullValue(VT.getSizeInBits())); 3079 APInt x = APInt::getSignMask(NVT.getSizeInBits()); 3080 (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven); 3081 Tmp1 = DAG.getConstantFP(apf, dl, VT); 3082 Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT), 3083 Node->getOperand(0), 3084 Tmp1, ISD::SETLT); 3085 True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0)); 3086 // TODO: Should any fast-math-flags be set for the FSUB? 3087 False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, 3088 DAG.getNode(ISD::FSUB, dl, VT, 3089 Node->getOperand(0), Tmp1)); 3090 False = DAG.getNode(ISD::XOR, dl, NVT, False, 3091 DAG.getConstant(x, dl, NVT)); 3092 Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False); 3093 Results.push_back(Tmp1); 3094 break; 3095 } 3096 case ISD::VAARG: 3097 Results.push_back(DAG.expandVAArg(Node)); 3098 Results.push_back(Results[0].getValue(1)); 3099 break; 3100 case ISD::VACOPY: 3101 Results.push_back(DAG.expandVACopy(Node)); 3102 break; 3103 case ISD::EXTRACT_VECTOR_ELT: 3104 if (Node->getOperand(0).getValueType().getVectorNumElements() == 1) 3105 // This must be an access of the only element. Return it. 3106 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), 3107 Node->getOperand(0)); 3108 else 3109 Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0)); 3110 Results.push_back(Tmp1); 3111 break; 3112 case ISD::EXTRACT_SUBVECTOR: 3113 Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0))); 3114 break; 3115 case ISD::INSERT_SUBVECTOR: 3116 Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0))); 3117 break; 3118 case ISD::CONCAT_VECTORS: 3119 Results.push_back(ExpandVectorBuildThroughStack(Node)); 3120 break; 3121 case ISD::SCALAR_TO_VECTOR: 3122 Results.push_back(ExpandSCALAR_TO_VECTOR(Node)); 3123 break; 3124 case ISD::INSERT_VECTOR_ELT: 3125 Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0), 3126 Node->getOperand(1), 3127 Node->getOperand(2), dl)); 3128 break; 3129 case ISD::VECTOR_SHUFFLE: { 3130 SmallVector<int, 32> NewMask; 3131 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 3132 3133 EVT VT = Node->getValueType(0); 3134 EVT EltVT = VT.getVectorElementType(); 3135 SDValue Op0 = Node->getOperand(0); 3136 SDValue Op1 = Node->getOperand(1); 3137 if (!TLI.isTypeLegal(EltVT)) { 3138 EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT); 3139 3140 // BUILD_VECTOR operands are allowed to be wider than the element type. 3141 // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept 3142 // it. 3143 if (NewEltVT.bitsLT(EltVT)) { 3144 // Convert shuffle node. 3145 // If original node was v4i64 and the new EltVT is i32, 3146 // cast operands to v8i32 and re-build the mask. 3147 3148 // Calculate new VT, the size of the new VT should be equal to original. 3149 EVT NewVT = 3150 EVT::getVectorVT(*DAG.getContext(), NewEltVT, 3151 VT.getSizeInBits() / NewEltVT.getSizeInBits()); 3152 assert(NewVT.bitsEq(VT)); 3153 3154 // cast operands to new VT 3155 Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0); 3156 Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1); 3157 3158 // Convert the shuffle mask 3159 unsigned int factor = 3160 NewVT.getVectorNumElements()/VT.getVectorNumElements(); 3161 3162 // EltVT gets smaller 3163 assert(factor > 0); 3164 3165 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 3166 if (Mask[i] < 0) { 3167 for (unsigned fi = 0; fi < factor; ++fi) 3168 NewMask.push_back(Mask[i]); 3169 } 3170 else { 3171 for (unsigned fi = 0; fi < factor; ++fi) 3172 NewMask.push_back(Mask[i]*factor+fi); 3173 } 3174 } 3175 Mask = NewMask; 3176 VT = NewVT; 3177 } 3178 EltVT = NewEltVT; 3179 } 3180 unsigned NumElems = VT.getVectorNumElements(); 3181 SmallVector<SDValue, 16> Ops; 3182 for (unsigned i = 0; i != NumElems; ++i) { 3183 if (Mask[i] < 0) { 3184 Ops.push_back(DAG.getUNDEF(EltVT)); 3185 continue; 3186 } 3187 unsigned Idx = Mask[i]; 3188 if (Idx < NumElems) 3189 Ops.push_back(DAG.getNode( 3190 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0, 3191 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())))); 3192 else 3193 Ops.push_back(DAG.getNode( 3194 ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1, 3195 DAG.getConstant(Idx - NumElems, dl, 3196 TLI.getVectorIdxTy(DAG.getDataLayout())))); 3197 } 3198 3199 Tmp1 = DAG.getBuildVector(VT, dl, Ops); 3200 // We may have changed the BUILD_VECTOR type. Cast it back to the Node type. 3201 Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1); 3202 Results.push_back(Tmp1); 3203 break; 3204 } 3205 case ISD::EXTRACT_ELEMENT: { 3206 EVT OpTy = Node->getOperand(0).getValueType(); 3207 if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) { 3208 // 1 -> Hi 3209 Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0), 3210 DAG.getConstant(OpTy.getSizeInBits() / 2, dl, 3211 TLI.getShiftAmountTy( 3212 Node->getOperand(0).getValueType(), 3213 DAG.getDataLayout()))); 3214 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1); 3215 } else { 3216 // 0 -> Lo 3217 Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), 3218 Node->getOperand(0)); 3219 } 3220 Results.push_back(Tmp1); 3221 break; 3222 } 3223 case ISD::STACKSAVE: 3224 // Expand to CopyFromReg if the target set 3225 // StackPointerRegisterToSaveRestore. 3226 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3227 Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP, 3228 Node->getValueType(0))); 3229 Results.push_back(Results[0].getValue(1)); 3230 } else { 3231 Results.push_back(DAG.getUNDEF(Node->getValueType(0))); 3232 Results.push_back(Node->getOperand(0)); 3233 } 3234 break; 3235 case ISD::STACKRESTORE: 3236 // Expand to CopyToReg if the target set 3237 // StackPointerRegisterToSaveRestore. 3238 if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) { 3239 Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP, 3240 Node->getOperand(1))); 3241 } else { 3242 Results.push_back(Node->getOperand(0)); 3243 } 3244 break; 3245 case ISD::GET_DYNAMIC_AREA_OFFSET: 3246 Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0))); 3247 Results.push_back(Results[0].getValue(0)); 3248 break; 3249 case ISD::FCOPYSIGN: 3250 Results.push_back(ExpandFCOPYSIGN(Node)); 3251 break; 3252 case ISD::FNEG: 3253 // Expand Y = FNEG(X) -> Y = SUB -0.0, X 3254 Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0)); 3255 // TODO: If FNEG has fast-math-flags, propagate them to the FSUB. 3256 Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1, 3257 Node->getOperand(0)); 3258 Results.push_back(Tmp1); 3259 break; 3260 case ISD::FABS: 3261 Results.push_back(ExpandFABS(Node)); 3262 break; 3263 case ISD::SMIN: 3264 case ISD::SMAX: 3265 case ISD::UMIN: 3266 case ISD::UMAX: { 3267 // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B 3268 ISD::CondCode Pred; 3269 switch (Node->getOpcode()) { 3270 default: llvm_unreachable("How did we get here?"); 3271 case ISD::SMAX: Pred = ISD::SETGT; break; 3272 case ISD::SMIN: Pred = ISD::SETLT; break; 3273 case ISD::UMAX: Pred = ISD::SETUGT; break; 3274 case ISD::UMIN: Pred = ISD::SETULT; break; 3275 } 3276 Tmp1 = Node->getOperand(0); 3277 Tmp2 = Node->getOperand(1); 3278 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred); 3279 Results.push_back(Tmp1); 3280 break; 3281 } 3282 3283 case ISD::FSIN: 3284 case ISD::FCOS: { 3285 EVT VT = Node->getValueType(0); 3286 // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin / 3287 // fcos which share the same operand and both are used. 3288 if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) || 3289 isSinCosLibcallAvailable(Node, TLI)) 3290 && useSinCos(Node)) { 3291 SDVTList VTs = DAG.getVTList(VT, VT); 3292 Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0)); 3293 if (Node->getOpcode() == ISD::FCOS) 3294 Tmp1 = Tmp1.getValue(1); 3295 Results.push_back(Tmp1); 3296 } 3297 break; 3298 } 3299 case ISD::FMAD: 3300 llvm_unreachable("Illegal fmad should never be formed"); 3301 3302 case ISD::FP16_TO_FP: 3303 if (Node->getValueType(0) != MVT::f32) { 3304 // We can extend to types bigger than f32 in two steps without changing 3305 // the result. Since "f16 -> f32" is much more commonly available, give 3306 // CodeGen the option of emitting that before resorting to a libcall. 3307 SDValue Res = 3308 DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0)); 3309 Results.push_back( 3310 DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res)); 3311 } 3312 break; 3313 case ISD::FP_TO_FP16: 3314 DEBUG(dbgs() << "Legalizing FP_TO_FP16\n"); 3315 if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) { 3316 SDValue Op = Node->getOperand(0); 3317 MVT SVT = Op.getSimpleValueType(); 3318 if ((SVT == MVT::f64 || SVT == MVT::f80) && 3319 TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) { 3320 // Under fastmath, we can expand this node into a fround followed by 3321 // a float-half conversion. 3322 SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op, 3323 DAG.getIntPtrConstant(0, dl)); 3324 Results.push_back( 3325 DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal)); 3326 } 3327 } 3328 break; 3329 case ISD::ConstantFP: { 3330 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node); 3331 // Check to see if this FP immediate is already legal. 3332 // If this is a legal constant, turn it into a TargetConstantFP node. 3333 if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0))) 3334 Results.push_back(ExpandConstantFP(CFP, true)); 3335 break; 3336 } 3337 case ISD::Constant: { 3338 ConstantSDNode *CP = cast<ConstantSDNode>(Node); 3339 Results.push_back(ExpandConstant(CP)); 3340 break; 3341 } 3342 case ISD::FSUB: { 3343 EVT VT = Node->getValueType(0); 3344 if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) && 3345 TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) { 3346 const SDNodeFlags Flags = Node->getFlags(); 3347 Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1)); 3348 Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags); 3349 Results.push_back(Tmp1); 3350 } 3351 break; 3352 } 3353 case ISD::SUB: { 3354 EVT VT = Node->getValueType(0); 3355 assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) && 3356 TLI.isOperationLegalOrCustom(ISD::XOR, VT) && 3357 "Don't know how to expand this subtraction!"); 3358 Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1), 3359 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl, 3360 VT)); 3361 Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT)); 3362 Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1)); 3363 break; 3364 } 3365 case ISD::UREM: 3366 case ISD::SREM: { 3367 EVT VT = Node->getValueType(0); 3368 bool isSigned = Node->getOpcode() == ISD::SREM; 3369 unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV; 3370 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3371 Tmp2 = Node->getOperand(0); 3372 Tmp3 = Node->getOperand(1); 3373 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3374 SDVTList VTs = DAG.getVTList(VT, VT); 3375 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1); 3376 Results.push_back(Tmp1); 3377 } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) { 3378 // X % Y -> X-X/Y*Y 3379 Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3); 3380 Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3); 3381 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1); 3382 Results.push_back(Tmp1); 3383 } 3384 break; 3385 } 3386 case ISD::UDIV: 3387 case ISD::SDIV: { 3388 bool isSigned = Node->getOpcode() == ISD::SDIV; 3389 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3390 EVT VT = Node->getValueType(0); 3391 if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) { 3392 SDVTList VTs = DAG.getVTList(VT, VT); 3393 Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0), 3394 Node->getOperand(1)); 3395 Results.push_back(Tmp1); 3396 } 3397 break; 3398 } 3399 case ISD::MULHU: 3400 case ISD::MULHS: { 3401 unsigned ExpandOpcode = 3402 Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI; 3403 EVT VT = Node->getValueType(0); 3404 SDVTList VTs = DAG.getVTList(VT, VT); 3405 3406 Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0), 3407 Node->getOperand(1)); 3408 Results.push_back(Tmp1.getValue(1)); 3409 break; 3410 } 3411 case ISD::UMUL_LOHI: 3412 case ISD::SMUL_LOHI: { 3413 SDValue LHS = Node->getOperand(0); 3414 SDValue RHS = Node->getOperand(1); 3415 MVT VT = LHS.getSimpleValueType(); 3416 unsigned MULHOpcode = 3417 Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS; 3418 3419 if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) { 3420 Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS)); 3421 Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS)); 3422 break; 3423 } 3424 3425 SmallVector<SDValue, 4> Halves; 3426 EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext()); 3427 assert(TLI.isTypeLegal(HalfType)); 3428 if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves, 3429 HalfType, DAG, 3430 TargetLowering::MulExpansionKind::Always)) { 3431 for (unsigned i = 0; i < 2; ++i) { 3432 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]); 3433 SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]); 3434 SDValue Shift = DAG.getConstant( 3435 HalfType.getScalarSizeInBits(), dl, 3436 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3437 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3438 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3439 } 3440 break; 3441 } 3442 break; 3443 } 3444 case ISD::MUL: { 3445 EVT VT = Node->getValueType(0); 3446 SDVTList VTs = DAG.getVTList(VT, VT); 3447 // See if multiply or divide can be lowered using two-result operations. 3448 // We just need the low half of the multiply; try both the signed 3449 // and unsigned forms. If the target supports both SMUL_LOHI and 3450 // UMUL_LOHI, form a preference by checking which forms of plain 3451 // MULH it supports. 3452 bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT); 3453 bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT); 3454 bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT); 3455 bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT); 3456 unsigned OpToUse = 0; 3457 if (HasSMUL_LOHI && !HasMULHS) { 3458 OpToUse = ISD::SMUL_LOHI; 3459 } else if (HasUMUL_LOHI && !HasMULHU) { 3460 OpToUse = ISD::UMUL_LOHI; 3461 } else if (HasSMUL_LOHI) { 3462 OpToUse = ISD::SMUL_LOHI; 3463 } else if (HasUMUL_LOHI) { 3464 OpToUse = ISD::UMUL_LOHI; 3465 } 3466 if (OpToUse) { 3467 Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0), 3468 Node->getOperand(1))); 3469 break; 3470 } 3471 3472 SDValue Lo, Hi; 3473 EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext()); 3474 if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) && 3475 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) && 3476 TLI.isOperationLegalOrCustom(ISD::SHL, VT) && 3477 TLI.isOperationLegalOrCustom(ISD::OR, VT) && 3478 TLI.expandMUL(Node, Lo, Hi, HalfType, DAG, 3479 TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) { 3480 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3481 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi); 3482 SDValue Shift = 3483 DAG.getConstant(HalfType.getSizeInBits(), dl, 3484 TLI.getShiftAmountTy(HalfType, DAG.getDataLayout())); 3485 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3486 Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi)); 3487 } 3488 break; 3489 } 3490 case ISD::SADDO: 3491 case ISD::SSUBO: { 3492 SDValue LHS = Node->getOperand(0); 3493 SDValue RHS = Node->getOperand(1); 3494 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ? 3495 ISD::ADD : ISD::SUB, dl, LHS.getValueType(), 3496 LHS, RHS); 3497 Results.push_back(Sum); 3498 EVT ResultType = Node->getValueType(1); 3499 EVT OType = getSetCCResultType(Node->getValueType(0)); 3500 3501 SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType()); 3502 3503 // LHSSign -> LHS >= 0 3504 // RHSSign -> RHS >= 0 3505 // SumSign -> Sum >= 0 3506 // 3507 // Add: 3508 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign) 3509 // Sub: 3510 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign) 3511 SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE); 3512 SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE); 3513 SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign, 3514 Node->getOpcode() == ISD::SADDO ? 3515 ISD::SETEQ : ISD::SETNE); 3516 3517 SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE); 3518 SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE); 3519 3520 SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE); 3521 Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType)); 3522 break; 3523 } 3524 case ISD::UADDO: 3525 case ISD::USUBO: { 3526 SDValue LHS = Node->getOperand(0); 3527 SDValue RHS = Node->getOperand(1); 3528 SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ? 3529 ISD::ADD : ISD::SUB, dl, LHS.getValueType(), 3530 LHS, RHS); 3531 Results.push_back(Sum); 3532 3533 EVT ResultType = Node->getValueType(1); 3534 EVT SetCCType = getSetCCResultType(Node->getValueType(0)); 3535 ISD::CondCode CC 3536 = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT; 3537 SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC); 3538 3539 Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType)); 3540 break; 3541 } 3542 case ISD::UMULO: 3543 case ISD::SMULO: { 3544 EVT VT = Node->getValueType(0); 3545 EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2); 3546 SDValue LHS = Node->getOperand(0); 3547 SDValue RHS = Node->getOperand(1); 3548 SDValue BottomHalf; 3549 SDValue TopHalf; 3550 static const unsigned Ops[2][3] = 3551 { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND }, 3552 { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }}; 3553 bool isSigned = Node->getOpcode() == ISD::SMULO; 3554 if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) { 3555 BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 3556 TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS); 3557 } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) { 3558 BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS, 3559 RHS); 3560 TopHalf = BottomHalf.getValue(1); 3561 } else if (TLI.isTypeLegal(WideVT)) { 3562 LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS); 3563 RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS); 3564 Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS); 3565 BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3566 DAG.getIntPtrConstant(0, dl)); 3567 TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1, 3568 DAG.getIntPtrConstant(1, dl)); 3569 } else { 3570 // We can fall back to a libcall with an illegal type for the MUL if we 3571 // have a libcall big enough. 3572 // Also, we can fall back to a division in some cases, but that's a big 3573 // performance hit in the general case. 3574 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL; 3575 if (WideVT == MVT::i16) 3576 LC = RTLIB::MUL_I16; 3577 else if (WideVT == MVT::i32) 3578 LC = RTLIB::MUL_I32; 3579 else if (WideVT == MVT::i64) 3580 LC = RTLIB::MUL_I64; 3581 else if (WideVT == MVT::i128) 3582 LC = RTLIB::MUL_I128; 3583 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!"); 3584 3585 SDValue HiLHS; 3586 SDValue HiRHS; 3587 if (isSigned) { 3588 // The high part is obtained by SRA'ing all but one of the bits of low 3589 // part. 3590 unsigned LoSize = VT.getSizeInBits(); 3591 HiLHS = 3592 DAG.getNode(ISD::SRA, dl, VT, LHS, 3593 DAG.getConstant(LoSize - 1, dl, 3594 TLI.getPointerTy(DAG.getDataLayout()))); 3595 HiRHS = 3596 DAG.getNode(ISD::SRA, dl, VT, RHS, 3597 DAG.getConstant(LoSize - 1, dl, 3598 TLI.getPointerTy(DAG.getDataLayout()))); 3599 } else { 3600 HiLHS = DAG.getConstant(0, dl, VT); 3601 HiRHS = DAG.getConstant(0, dl, VT); 3602 } 3603 3604 // Here we're passing the 2 arguments explicitly as 4 arguments that are 3605 // pre-lowered to the correct types. This all depends upon WideVT not 3606 // being a legal type for the architecture and thus has to be split to 3607 // two arguments. 3608 SDValue Ret; 3609 if(DAG.getDataLayout().isLittleEndian()) { 3610 // Halves of WideVT are packed into registers in different order 3611 // depending on platform endianness. This is usually handled by 3612 // the C calling convention, but we can't defer to it in 3613 // the legalizer. 3614 SDValue Args[] = { LHS, HiLHS, RHS, HiRHS }; 3615 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl); 3616 } else { 3617 SDValue Args[] = { HiLHS, LHS, HiRHS, RHS }; 3618 Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl); 3619 } 3620 assert(Ret.getOpcode() == ISD::MERGE_VALUES && 3621 "Ret value is a collection of constituent nodes holding result."); 3622 BottomHalf = Ret.getOperand(0); 3623 TopHalf = Ret.getOperand(1); 3624 } 3625 3626 if (isSigned) { 3627 Tmp1 = DAG.getConstant( 3628 VT.getSizeInBits() - 1, dl, 3629 TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout())); 3630 Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1); 3631 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1, 3632 ISD::SETNE); 3633 } else { 3634 TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, 3635 DAG.getConstant(0, dl, VT), ISD::SETNE); 3636 } 3637 3638 // Truncate the result if SetCC returns a larger type than needed. 3639 EVT RType = Node->getValueType(1); 3640 if (RType.getSizeInBits() < TopHalf.getValueSizeInBits()) 3641 TopHalf = DAG.getNode(ISD::TRUNCATE, dl, RType, TopHalf); 3642 3643 assert(RType.getSizeInBits() == TopHalf.getValueSizeInBits() && 3644 "Unexpected result type for S/UMULO legalization"); 3645 3646 Results.push_back(BottomHalf); 3647 Results.push_back(TopHalf); 3648 break; 3649 } 3650 case ISD::BUILD_PAIR: { 3651 EVT PairTy = Node->getValueType(0); 3652 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0)); 3653 Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1)); 3654 Tmp2 = DAG.getNode( 3655 ISD::SHL, dl, PairTy, Tmp2, 3656 DAG.getConstant(PairTy.getSizeInBits() / 2, dl, 3657 TLI.getShiftAmountTy(PairTy, DAG.getDataLayout()))); 3658 Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2)); 3659 break; 3660 } 3661 case ISD::SELECT: 3662 Tmp1 = Node->getOperand(0); 3663 Tmp2 = Node->getOperand(1); 3664 Tmp3 = Node->getOperand(2); 3665 if (Tmp1.getOpcode() == ISD::SETCC) { 3666 Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1), 3667 Tmp2, Tmp3, 3668 cast<CondCodeSDNode>(Tmp1.getOperand(2))->get()); 3669 } else { 3670 Tmp1 = DAG.getSelectCC(dl, Tmp1, 3671 DAG.getConstant(0, dl, Tmp1.getValueType()), 3672 Tmp2, Tmp3, ISD::SETNE); 3673 } 3674 Results.push_back(Tmp1); 3675 break; 3676 case ISD::BR_JT: { 3677 SDValue Chain = Node->getOperand(0); 3678 SDValue Table = Node->getOperand(1); 3679 SDValue Index = Node->getOperand(2); 3680 3681 const DataLayout &TD = DAG.getDataLayout(); 3682 EVT PTy = TLI.getPointerTy(TD); 3683 3684 unsigned EntrySize = 3685 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD); 3686 3687 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index, 3688 DAG.getConstant(EntrySize, dl, Index.getValueType())); 3689 SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(), 3690 Index, Table); 3691 3692 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8); 3693 SDValue LD = DAG.getExtLoad( 3694 ISD::SEXTLOAD, dl, PTy, Chain, Addr, 3695 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT); 3696 Addr = LD; 3697 if (TLI.isJumpTableRelative()) { 3698 // For PIC, the sequence is: 3699 // BRIND(load(Jumptable + index) + RelocBase) 3700 // RelocBase can be JumpTable, GOT or some sort of global base. 3701 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, 3702 TLI.getPICJumpTableRelocBase(Table, DAG)); 3703 } 3704 Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr); 3705 Results.push_back(Tmp1); 3706 break; 3707 } 3708 case ISD::BRCOND: 3709 // Expand brcond's setcc into its constituent parts and create a BR_CC 3710 // Node. 3711 Tmp1 = Node->getOperand(0); 3712 Tmp2 = Node->getOperand(1); 3713 if (Tmp2.getOpcode() == ISD::SETCC) { 3714 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, 3715 Tmp1, Tmp2.getOperand(2), 3716 Tmp2.getOperand(0), Tmp2.getOperand(1), 3717 Node->getOperand(2)); 3718 } else { 3719 // We test only the i1 bit. Skip the AND if UNDEF or another AND. 3720 if (Tmp2.isUndef() || 3721 (Tmp2.getOpcode() == ISD::AND && 3722 isa<ConstantSDNode>(Tmp2.getOperand(1)) && 3723 dyn_cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1)) 3724 Tmp3 = Tmp2; 3725 else 3726 Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2, 3727 DAG.getConstant(1, dl, Tmp2.getValueType())); 3728 Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, 3729 DAG.getCondCode(ISD::SETNE), Tmp3, 3730 DAG.getConstant(0, dl, Tmp3.getValueType()), 3731 Node->getOperand(2)); 3732 } 3733 Results.push_back(Tmp1); 3734 break; 3735 case ISD::SETCC: { 3736 Tmp1 = Node->getOperand(0); 3737 Tmp2 = Node->getOperand(1); 3738 Tmp3 = Node->getOperand(2); 3739 bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, 3740 Tmp3, NeedInvert, dl); 3741 3742 if (Legalized) { 3743 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3744 // condition code, create a new SETCC node. 3745 if (Tmp3.getNode()) 3746 Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 3747 Tmp1, Tmp2, Tmp3); 3748 3749 // If we expanded the SETCC by inverting the condition code, then wrap 3750 // the existing SETCC in a NOT to restore the intended condition. 3751 if (NeedInvert) 3752 Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0)); 3753 3754 Results.push_back(Tmp1); 3755 break; 3756 } 3757 3758 // Otherwise, SETCC for the given comparison type must be completely 3759 // illegal; expand it into a SELECT_CC. 3760 EVT VT = Node->getValueType(0); 3761 int TrueValue; 3762 switch (TLI.getBooleanContents(Tmp1->getValueType(0))) { 3763 case TargetLowering::ZeroOrOneBooleanContent: 3764 case TargetLowering::UndefinedBooleanContent: 3765 TrueValue = 1; 3766 break; 3767 case TargetLowering::ZeroOrNegativeOneBooleanContent: 3768 TrueValue = -1; 3769 break; 3770 } 3771 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2, 3772 DAG.getConstant(TrueValue, dl, VT), 3773 DAG.getConstant(0, dl, VT), 3774 Tmp3); 3775 Results.push_back(Tmp1); 3776 break; 3777 } 3778 case ISD::SELECT_CC: { 3779 Tmp1 = Node->getOperand(0); // LHS 3780 Tmp2 = Node->getOperand(1); // RHS 3781 Tmp3 = Node->getOperand(2); // True 3782 Tmp4 = Node->getOperand(3); // False 3783 EVT VT = Node->getValueType(0); 3784 SDValue CC = Node->getOperand(4); 3785 ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get(); 3786 3787 if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) { 3788 // If the condition code is legal, then we need to expand this 3789 // node using SETCC and SELECT. 3790 EVT CmpVT = Tmp1.getValueType(); 3791 assert(!TLI.isOperationExpand(ISD::SELECT, VT) && 3792 "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be " 3793 "expanded."); 3794 EVT CCVT = 3795 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT); 3796 SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC); 3797 Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4)); 3798 break; 3799 } 3800 3801 // SELECT_CC is legal, so the condition code must not be. 3802 bool Legalized = false; 3803 // Try to legalize by inverting the condition. This is for targets that 3804 // might support an ordered version of a condition, but not the unordered 3805 // version (or vice versa). 3806 ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, 3807 Tmp1.getValueType().isInteger()); 3808 if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) { 3809 // Use the new condition code and swap true and false 3810 Legalized = true; 3811 Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC); 3812 } else { 3813 // If The inverse is not legal, then try to swap the arguments using 3814 // the inverse condition code. 3815 ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC); 3816 if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) { 3817 // The swapped inverse condition is legal, so swap true and false, 3818 // lhs and rhs. 3819 Legalized = true; 3820 Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC); 3821 } 3822 } 3823 3824 if (!Legalized) { 3825 Legalized = LegalizeSetCCCondCode( 3826 getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert, 3827 dl); 3828 3829 assert(Legalized && "Can't legalize SELECT_CC with legal condition!"); 3830 3831 // If we expanded the SETCC by inverting the condition code, then swap 3832 // the True/False operands to match. 3833 if (NeedInvert) 3834 std::swap(Tmp3, Tmp4); 3835 3836 // If we expanded the SETCC by swapping LHS and RHS, or by inverting the 3837 // condition code, create a new SELECT_CC node. 3838 if (CC.getNode()) { 3839 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), 3840 Tmp1, Tmp2, Tmp3, Tmp4, CC); 3841 } else { 3842 Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType()); 3843 CC = DAG.getCondCode(ISD::SETNE); 3844 Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, 3845 Tmp2, Tmp3, Tmp4, CC); 3846 } 3847 } 3848 Results.push_back(Tmp1); 3849 break; 3850 } 3851 case ISD::BR_CC: { 3852 Tmp1 = Node->getOperand(0); // Chain 3853 Tmp2 = Node->getOperand(2); // LHS 3854 Tmp3 = Node->getOperand(3); // RHS 3855 Tmp4 = Node->getOperand(1); // CC 3856 3857 bool Legalized = LegalizeSetCCCondCode(getSetCCResultType( 3858 Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl); 3859 (void)Legalized; 3860 assert(Legalized && "Can't legalize BR_CC with legal condition!"); 3861 3862 // If we expanded the SETCC by inverting the condition code, then wrap 3863 // the existing SETCC in a NOT to restore the intended condition. 3864 if (NeedInvert) 3865 Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0)); 3866 3867 // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC 3868 // node. 3869 if (Tmp4.getNode()) { 3870 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, 3871 Tmp4, Tmp2, Tmp3, Node->getOperand(4)); 3872 } else { 3873 Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType()); 3874 Tmp4 = DAG.getCondCode(ISD::SETNE); 3875 Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, 3876 Tmp2, Tmp3, Node->getOperand(4)); 3877 } 3878 Results.push_back(Tmp1); 3879 break; 3880 } 3881 case ISD::BUILD_VECTOR: 3882 Results.push_back(ExpandBUILD_VECTOR(Node)); 3883 break; 3884 case ISD::SRA: 3885 case ISD::SRL: 3886 case ISD::SHL: { 3887 // Scalarize vector SRA/SRL/SHL. 3888 EVT VT = Node->getValueType(0); 3889 assert(VT.isVector() && "Unable to legalize non-vector shift"); 3890 assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal"); 3891 unsigned NumElem = VT.getVectorNumElements(); 3892 3893 SmallVector<SDValue, 8> Scalars; 3894 for (unsigned Idx = 0; Idx < NumElem; Idx++) { 3895 SDValue Ex = DAG.getNode( 3896 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0), 3897 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3898 SDValue Sh = DAG.getNode( 3899 ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1), 3900 DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3901 Scalars.push_back(DAG.getNode(Node->getOpcode(), dl, 3902 VT.getScalarType(), Ex, Sh)); 3903 } 3904 3905 SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars); 3906 ReplaceNode(SDValue(Node, 0), Result); 3907 break; 3908 } 3909 case ISD::GLOBAL_OFFSET_TABLE: 3910 case ISD::GlobalAddress: 3911 case ISD::GlobalTLSAddress: 3912 case ISD::ExternalSymbol: 3913 case ISD::ConstantPool: 3914 case ISD::JumpTable: 3915 case ISD::INTRINSIC_W_CHAIN: 3916 case ISD::INTRINSIC_WO_CHAIN: 3917 case ISD::INTRINSIC_VOID: 3918 // FIXME: Custom lowering for these operations shouldn't return null! 3919 break; 3920 } 3921 3922 // Replace the original node with the legalized result. 3923 if (Results.empty()) { 3924 DEBUG(dbgs() << "Cannot expand node\n"); 3925 return false; 3926 } 3927 3928 DEBUG(dbgs() << "Succesfully expanded node\n"); 3929 ReplaceNode(Node, Results.data()); 3930 return true; 3931 } 3932 3933 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) { 3934 DEBUG(dbgs() << "Trying to convert node to libcall\n"); 3935 SmallVector<SDValue, 8> Results; 3936 SDLoc dl(Node); 3937 // FIXME: Check flags on the node to see if we can use a finite call. 3938 bool CanUseFiniteLibCall = TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath; 3939 unsigned Opc = Node->getOpcode(); 3940 switch (Opc) { 3941 case ISD::ATOMIC_FENCE: { 3942 // If the target didn't lower this, lower it to '__sync_synchronize()' call 3943 // FIXME: handle "fence singlethread" more efficiently. 3944 TargetLowering::ArgListTy Args; 3945 3946 TargetLowering::CallLoweringInfo CLI(DAG); 3947 CLI.setDebugLoc(dl) 3948 .setChain(Node->getOperand(0)) 3949 .setLibCallee( 3950 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3951 DAG.getExternalSymbol("__sync_synchronize", 3952 TLI.getPointerTy(DAG.getDataLayout())), 3953 std::move(Args)); 3954 3955 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3956 3957 Results.push_back(CallResult.second); 3958 break; 3959 } 3960 // By default, atomic intrinsics are marked Legal and lowered. Targets 3961 // which don't support them directly, however, may want libcalls, in which 3962 // case they mark them Expand, and we get here. 3963 case ISD::ATOMIC_SWAP: 3964 case ISD::ATOMIC_LOAD_ADD: 3965 case ISD::ATOMIC_LOAD_SUB: 3966 case ISD::ATOMIC_LOAD_AND: 3967 case ISD::ATOMIC_LOAD_OR: 3968 case ISD::ATOMIC_LOAD_XOR: 3969 case ISD::ATOMIC_LOAD_NAND: 3970 case ISD::ATOMIC_LOAD_MIN: 3971 case ISD::ATOMIC_LOAD_MAX: 3972 case ISD::ATOMIC_LOAD_UMIN: 3973 case ISD::ATOMIC_LOAD_UMAX: 3974 case ISD::ATOMIC_CMP_SWAP: { 3975 MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT(); 3976 RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT); 3977 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!"); 3978 3979 std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false); 3980 Results.push_back(Tmp.first); 3981 Results.push_back(Tmp.second); 3982 break; 3983 } 3984 case ISD::TRAP: { 3985 // If this operation is not supported, lower it to 'abort()' call 3986 TargetLowering::ArgListTy Args; 3987 TargetLowering::CallLoweringInfo CLI(DAG); 3988 CLI.setDebugLoc(dl) 3989 .setChain(Node->getOperand(0)) 3990 .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3991 DAG.getExternalSymbol( 3992 "abort", TLI.getPointerTy(DAG.getDataLayout())), 3993 std::move(Args)); 3994 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 3995 3996 Results.push_back(CallResult.second); 3997 break; 3998 } 3999 case ISD::FMINNUM: 4000 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64, 4001 RTLIB::FMIN_F80, RTLIB::FMIN_F128, 4002 RTLIB::FMIN_PPCF128)); 4003 break; 4004 case ISD::FMAXNUM: 4005 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64, 4006 RTLIB::FMAX_F80, RTLIB::FMAX_F128, 4007 RTLIB::FMAX_PPCF128)); 4008 break; 4009 case ISD::FSQRT: 4010 case ISD::STRICT_FSQRT: 4011 Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64, 4012 RTLIB::SQRT_F80, RTLIB::SQRT_F128, 4013 RTLIB::SQRT_PPCF128)); 4014 break; 4015 case ISD::FSIN: 4016 case ISD::STRICT_FSIN: 4017 Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64, 4018 RTLIB::SIN_F80, RTLIB::SIN_F128, 4019 RTLIB::SIN_PPCF128)); 4020 break; 4021 case ISD::FCOS: 4022 case ISD::STRICT_FCOS: 4023 Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64, 4024 RTLIB::COS_F80, RTLIB::COS_F128, 4025 RTLIB::COS_PPCF128)); 4026 break; 4027 case ISD::FSINCOS: 4028 // Expand into sincos libcall. 4029 ExpandSinCosLibCall(Node, Results); 4030 break; 4031 case ISD::FLOG: 4032 case ISD::STRICT_FLOG: 4033 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log_finite)) 4034 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_FINITE_F32, 4035 RTLIB::LOG_FINITE_F64, 4036 RTLIB::LOG_FINITE_F80, 4037 RTLIB::LOG_FINITE_F128, 4038 RTLIB::LOG_FINITE_PPCF128)); 4039 else 4040 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, 4041 RTLIB::LOG_F80, RTLIB::LOG_F128, 4042 RTLIB::LOG_PPCF128)); 4043 break; 4044 case ISD::FLOG2: 4045 case ISD::STRICT_FLOG2: 4046 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log2_finite)) 4047 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_FINITE_F32, 4048 RTLIB::LOG2_FINITE_F64, 4049 RTLIB::LOG2_FINITE_F80, 4050 RTLIB::LOG2_FINITE_F128, 4051 RTLIB::LOG2_FINITE_PPCF128)); 4052 else 4053 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, 4054 RTLIB::LOG2_F80, RTLIB::LOG2_F128, 4055 RTLIB::LOG2_PPCF128)); 4056 break; 4057 case ISD::FLOG10: 4058 case ISD::STRICT_FLOG10: 4059 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log10_finite)) 4060 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_FINITE_F32, 4061 RTLIB::LOG10_FINITE_F64, 4062 RTLIB::LOG10_FINITE_F80, 4063 RTLIB::LOG10_FINITE_F128, 4064 RTLIB::LOG10_FINITE_PPCF128)); 4065 else 4066 Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, 4067 RTLIB::LOG10_F80, RTLIB::LOG10_F128, 4068 RTLIB::LOG10_PPCF128)); 4069 break; 4070 case ISD::FEXP: 4071 case ISD::STRICT_FEXP: 4072 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp_finite)) 4073 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_FINITE_F32, 4074 RTLIB::EXP_FINITE_F64, 4075 RTLIB::EXP_FINITE_F80, 4076 RTLIB::EXP_FINITE_F128, 4077 RTLIB::EXP_FINITE_PPCF128)); 4078 else 4079 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, 4080 RTLIB::EXP_F80, RTLIB::EXP_F128, 4081 RTLIB::EXP_PPCF128)); 4082 break; 4083 case ISD::FEXP2: 4084 case ISD::STRICT_FEXP2: 4085 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp2_finite)) 4086 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_FINITE_F32, 4087 RTLIB::EXP2_FINITE_F64, 4088 RTLIB::EXP2_FINITE_F80, 4089 RTLIB::EXP2_FINITE_F128, 4090 RTLIB::EXP2_FINITE_PPCF128)); 4091 else 4092 Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, 4093 RTLIB::EXP2_F80, RTLIB::EXP2_F128, 4094 RTLIB::EXP2_PPCF128)); 4095 break; 4096 case ISD::FTRUNC: 4097 Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64, 4098 RTLIB::TRUNC_F80, RTLIB::TRUNC_F128, 4099 RTLIB::TRUNC_PPCF128)); 4100 break; 4101 case ISD::FFLOOR: 4102 Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64, 4103 RTLIB::FLOOR_F80, RTLIB::FLOOR_F128, 4104 RTLIB::FLOOR_PPCF128)); 4105 break; 4106 case ISD::FCEIL: 4107 Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64, 4108 RTLIB::CEIL_F80, RTLIB::CEIL_F128, 4109 RTLIB::CEIL_PPCF128)); 4110 break; 4111 case ISD::FRINT: 4112 case ISD::STRICT_FRINT: 4113 Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64, 4114 RTLIB::RINT_F80, RTLIB::RINT_F128, 4115 RTLIB::RINT_PPCF128)); 4116 break; 4117 case ISD::FNEARBYINT: 4118 case ISD::STRICT_FNEARBYINT: 4119 Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32, 4120 RTLIB::NEARBYINT_F64, 4121 RTLIB::NEARBYINT_F80, 4122 RTLIB::NEARBYINT_F128, 4123 RTLIB::NEARBYINT_PPCF128)); 4124 break; 4125 case ISD::FROUND: 4126 Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32, 4127 RTLIB::ROUND_F64, 4128 RTLIB::ROUND_F80, 4129 RTLIB::ROUND_F128, 4130 RTLIB::ROUND_PPCF128)); 4131 break; 4132 case ISD::FPOWI: 4133 case ISD::STRICT_FPOWI: 4134 Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64, 4135 RTLIB::POWI_F80, RTLIB::POWI_F128, 4136 RTLIB::POWI_PPCF128)); 4137 break; 4138 case ISD::FPOW: 4139 case ISD::STRICT_FPOW: 4140 if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_pow_finite)) 4141 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_FINITE_F32, 4142 RTLIB::POW_FINITE_F64, 4143 RTLIB::POW_FINITE_F80, 4144 RTLIB::POW_FINITE_F128, 4145 RTLIB::POW_FINITE_PPCF128)); 4146 else 4147 Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, 4148 RTLIB::POW_F80, RTLIB::POW_F128, 4149 RTLIB::POW_PPCF128)); 4150 break; 4151 case ISD::FDIV: 4152 Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64, 4153 RTLIB::DIV_F80, RTLIB::DIV_F128, 4154 RTLIB::DIV_PPCF128)); 4155 break; 4156 case ISD::FREM: 4157 Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64, 4158 RTLIB::REM_F80, RTLIB::REM_F128, 4159 RTLIB::REM_PPCF128)); 4160 break; 4161 case ISD::FMA: 4162 case ISD::STRICT_FMA: 4163 Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64, 4164 RTLIB::FMA_F80, RTLIB::FMA_F128, 4165 RTLIB::FMA_PPCF128)); 4166 break; 4167 case ISD::FADD: 4168 Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64, 4169 RTLIB::ADD_F80, RTLIB::ADD_F128, 4170 RTLIB::ADD_PPCF128)); 4171 break; 4172 case ISD::FMUL: 4173 Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64, 4174 RTLIB::MUL_F80, RTLIB::MUL_F128, 4175 RTLIB::MUL_PPCF128)); 4176 break; 4177 case ISD::FP16_TO_FP: 4178 if (Node->getValueType(0) == MVT::f32) { 4179 Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false)); 4180 } 4181 break; 4182 case ISD::FP_TO_FP16: { 4183 RTLIB::Libcall LC = 4184 RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16); 4185 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16"); 4186 Results.push_back(ExpandLibCall(LC, Node, false)); 4187 break; 4188 } 4189 case ISD::FSUB: 4190 Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64, 4191 RTLIB::SUB_F80, RTLIB::SUB_F128, 4192 RTLIB::SUB_PPCF128)); 4193 break; 4194 case ISD::SREM: 4195 Results.push_back(ExpandIntLibCall(Node, true, 4196 RTLIB::SREM_I8, 4197 RTLIB::SREM_I16, RTLIB::SREM_I32, 4198 RTLIB::SREM_I64, RTLIB::SREM_I128)); 4199 break; 4200 case ISD::UREM: 4201 Results.push_back(ExpandIntLibCall(Node, false, 4202 RTLIB::UREM_I8, 4203 RTLIB::UREM_I16, RTLIB::UREM_I32, 4204 RTLIB::UREM_I64, RTLIB::UREM_I128)); 4205 break; 4206 case ISD::SDIV: 4207 Results.push_back(ExpandIntLibCall(Node, true, 4208 RTLIB::SDIV_I8, 4209 RTLIB::SDIV_I16, RTLIB::SDIV_I32, 4210 RTLIB::SDIV_I64, RTLIB::SDIV_I128)); 4211 break; 4212 case ISD::UDIV: 4213 Results.push_back(ExpandIntLibCall(Node, false, 4214 RTLIB::UDIV_I8, 4215 RTLIB::UDIV_I16, RTLIB::UDIV_I32, 4216 RTLIB::UDIV_I64, RTLIB::UDIV_I128)); 4217 break; 4218 case ISD::SDIVREM: 4219 case ISD::UDIVREM: 4220 // Expand into divrem libcall 4221 ExpandDivRemLibCall(Node, Results); 4222 break; 4223 case ISD::MUL: 4224 Results.push_back(ExpandIntLibCall(Node, false, 4225 RTLIB::MUL_I8, 4226 RTLIB::MUL_I16, RTLIB::MUL_I32, 4227 RTLIB::MUL_I64, RTLIB::MUL_I128)); 4228 break; 4229 } 4230 4231 // Replace the original node with the legalized result. 4232 if (!Results.empty()) { 4233 DEBUG(dbgs() << "Successfully converted node to libcall\n"); 4234 ReplaceNode(Node, Results.data()); 4235 } else 4236 DEBUG(dbgs() << "Could not convert node to libcall\n"); 4237 } 4238 4239 // Determine the vector type to use in place of an original scalar element when 4240 // promoting equally sized vectors. 4241 static MVT getPromotedVectorElementType(const TargetLowering &TLI, 4242 MVT EltVT, MVT NewEltVT) { 4243 unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits(); 4244 MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt); 4245 assert(TLI.isTypeLegal(MidVT) && "unexpected"); 4246 return MidVT; 4247 } 4248 4249 void SelectionDAGLegalize::PromoteNode(SDNode *Node) { 4250 DEBUG(dbgs() << "Trying to promote node\n"); 4251 SmallVector<SDValue, 8> Results; 4252 MVT OVT = Node->getSimpleValueType(0); 4253 if (Node->getOpcode() == ISD::UINT_TO_FP || 4254 Node->getOpcode() == ISD::SINT_TO_FP || 4255 Node->getOpcode() == ISD::SETCC || 4256 Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT || 4257 Node->getOpcode() == ISD::INSERT_VECTOR_ELT) { 4258 OVT = Node->getOperand(0).getSimpleValueType(); 4259 } 4260 if (Node->getOpcode() == ISD::BR_CC) 4261 OVT = Node->getOperand(2).getSimpleValueType(); 4262 MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT); 4263 SDLoc dl(Node); 4264 SDValue Tmp1, Tmp2, Tmp3; 4265 switch (Node->getOpcode()) { 4266 case ISD::CTTZ: 4267 case ISD::CTTZ_ZERO_UNDEF: 4268 case ISD::CTLZ: 4269 case ISD::CTLZ_ZERO_UNDEF: 4270 case ISD::CTPOP: 4271 // Zero extend the argument. 4272 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4273 if (Node->getOpcode() == ISD::CTTZ) { 4274 // The count is the same in the promoted type except if the original 4275 // value was zero. This can be handled by setting the bit just off 4276 // the top of the original type. 4277 auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(), 4278 OVT.getSizeInBits()); 4279 Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1, 4280 DAG.getConstant(TopBit, dl, NVT)); 4281 } 4282 // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is 4283 // already the correct result. 4284 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4285 if (Node->getOpcode() == ISD::CTLZ || 4286 Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) { 4287 // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT)) 4288 Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1, 4289 DAG.getConstant(NVT.getSizeInBits() - 4290 OVT.getSizeInBits(), dl, NVT)); 4291 } 4292 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4293 break; 4294 case ISD::BITREVERSE: 4295 case ISD::BSWAP: { 4296 unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits(); 4297 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0)); 4298 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4299 Tmp1 = DAG.getNode( 4300 ISD::SRL, dl, NVT, Tmp1, 4301 DAG.getConstant(DiffBits, dl, 4302 TLI.getShiftAmountTy(NVT, DAG.getDataLayout()))); 4303 Results.push_back(Tmp1); 4304 break; 4305 } 4306 case ISD::FP_TO_UINT: 4307 case ISD::FP_TO_SINT: 4308 Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0), 4309 Node->getOpcode() == ISD::FP_TO_SINT, dl); 4310 Results.push_back(Tmp1); 4311 break; 4312 case ISD::UINT_TO_FP: 4313 case ISD::SINT_TO_FP: 4314 Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0), 4315 Node->getOpcode() == ISD::SINT_TO_FP, dl); 4316 Results.push_back(Tmp1); 4317 break; 4318 case ISD::VAARG: { 4319 SDValue Chain = Node->getOperand(0); // Get the chain. 4320 SDValue Ptr = Node->getOperand(1); // Get the pointer. 4321 4322 unsigned TruncOp; 4323 if (OVT.isVector()) { 4324 TruncOp = ISD::BITCAST; 4325 } else { 4326 assert(OVT.isInteger() 4327 && "VAARG promotion is supported only for vectors or integer types"); 4328 TruncOp = ISD::TRUNCATE; 4329 } 4330 4331 // Perform the larger operation, then convert back 4332 Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2), 4333 Node->getConstantOperandVal(3)); 4334 Chain = Tmp1.getValue(1); 4335 4336 Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1); 4337 4338 // Modified the chain result - switch anything that used the old chain to 4339 // use the new one. 4340 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2); 4341 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain); 4342 if (UpdatedNodes) { 4343 UpdatedNodes->insert(Tmp2.getNode()); 4344 UpdatedNodes->insert(Chain.getNode()); 4345 } 4346 ReplacedNode(Node); 4347 break; 4348 } 4349 case ISD::MUL: 4350 case ISD::SDIV: 4351 case ISD::SREM: 4352 case ISD::UDIV: 4353 case ISD::UREM: 4354 case ISD::AND: 4355 case ISD::OR: 4356 case ISD::XOR: { 4357 unsigned ExtOp, TruncOp; 4358 if (OVT.isVector()) { 4359 ExtOp = ISD::BITCAST; 4360 TruncOp = ISD::BITCAST; 4361 } else { 4362 assert(OVT.isInteger() && "Cannot promote logic operation"); 4363 4364 switch (Node->getOpcode()) { 4365 default: 4366 ExtOp = ISD::ANY_EXTEND; 4367 break; 4368 case ISD::SDIV: 4369 case ISD::SREM: 4370 ExtOp = ISD::SIGN_EXTEND; 4371 break; 4372 case ISD::UDIV: 4373 case ISD::UREM: 4374 ExtOp = ISD::ZERO_EXTEND; 4375 break; 4376 } 4377 TruncOp = ISD::TRUNCATE; 4378 } 4379 // Promote each of the values to the new type. 4380 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4381 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4382 // Perform the larger operation, then convert back 4383 Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4384 Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1)); 4385 break; 4386 } 4387 case ISD::UMUL_LOHI: 4388 case ISD::SMUL_LOHI: { 4389 // Promote to a multiply in a wider integer type. 4390 unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND 4391 : ISD::SIGN_EXTEND; 4392 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4393 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4394 Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2); 4395 4396 auto &DL = DAG.getDataLayout(); 4397 unsigned OriginalSize = OVT.getScalarSizeInBits(); 4398 Tmp2 = DAG.getNode( 4399 ISD::SRL, dl, NVT, Tmp1, 4400 DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT))); 4401 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1)); 4402 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2)); 4403 break; 4404 } 4405 case ISD::SELECT: { 4406 unsigned ExtOp, TruncOp; 4407 if (Node->getValueType(0).isVector() || 4408 Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) { 4409 ExtOp = ISD::BITCAST; 4410 TruncOp = ISD::BITCAST; 4411 } else if (Node->getValueType(0).isInteger()) { 4412 ExtOp = ISD::ANY_EXTEND; 4413 TruncOp = ISD::TRUNCATE; 4414 } else { 4415 ExtOp = ISD::FP_EXTEND; 4416 TruncOp = ISD::FP_ROUND; 4417 } 4418 Tmp1 = Node->getOperand(0); 4419 // Promote each of the values to the new type. 4420 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4421 Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4422 // Perform the larger operation, then round down. 4423 Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3); 4424 if (TruncOp != ISD::FP_ROUND) 4425 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1); 4426 else 4427 Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1, 4428 DAG.getIntPtrConstant(0, dl)); 4429 Results.push_back(Tmp1); 4430 break; 4431 } 4432 case ISD::VECTOR_SHUFFLE: { 4433 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask(); 4434 4435 // Cast the two input vectors. 4436 Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0)); 4437 Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1)); 4438 4439 // Convert the shuffle mask to the right # elements. 4440 Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask); 4441 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1); 4442 Results.push_back(Tmp1); 4443 break; 4444 } 4445 case ISD::SETCC: { 4446 unsigned ExtOp = ISD::FP_EXTEND; 4447 if (NVT.isInteger()) { 4448 ISD::CondCode CCCode = 4449 cast<CondCodeSDNode>(Node->getOperand(2))->get(); 4450 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4451 } 4452 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0)); 4453 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1)); 4454 Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), 4455 Tmp1, Tmp2, Node->getOperand(2))); 4456 break; 4457 } 4458 case ISD::BR_CC: { 4459 unsigned ExtOp = ISD::FP_EXTEND; 4460 if (NVT.isInteger()) { 4461 ISD::CondCode CCCode = 4462 cast<CondCodeSDNode>(Node->getOperand(1))->get(); 4463 ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4464 } 4465 Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2)); 4466 Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3)); 4467 Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), 4468 Node->getOperand(0), Node->getOperand(1), 4469 Tmp1, Tmp2, Node->getOperand(4))); 4470 break; 4471 } 4472 case ISD::FADD: 4473 case ISD::FSUB: 4474 case ISD::FMUL: 4475 case ISD::FDIV: 4476 case ISD::FREM: 4477 case ISD::FMINNUM: 4478 case ISD::FMAXNUM: 4479 case ISD::FPOW: 4480 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4481 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4482 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, 4483 Node->getFlags()); 4484 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4485 Tmp3, DAG.getIntPtrConstant(0, dl))); 4486 break; 4487 case ISD::FMA: 4488 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4489 Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1)); 4490 Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2)); 4491 Results.push_back( 4492 DAG.getNode(ISD::FP_ROUND, dl, OVT, 4493 DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3), 4494 DAG.getIntPtrConstant(0, dl))); 4495 break; 4496 case ISD::FCOPYSIGN: 4497 case ISD::FPOWI: { 4498 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4499 Tmp2 = Node->getOperand(1); 4500 Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2); 4501 4502 // fcopysign doesn't change anything but the sign bit, so 4503 // (fp_round (fcopysign (fpext a), b)) 4504 // is as precise as 4505 // (fp_round (fpext a)) 4506 // which is a no-op. Mark it as a TRUNCating FP_ROUND. 4507 const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN); 4508 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4509 Tmp3, DAG.getIntPtrConstant(isTrunc, dl))); 4510 break; 4511 } 4512 case ISD::FFLOOR: 4513 case ISD::FCEIL: 4514 case ISD::FRINT: 4515 case ISD::FNEARBYINT: 4516 case ISD::FROUND: 4517 case ISD::FTRUNC: 4518 case ISD::FNEG: 4519 case ISD::FSQRT: 4520 case ISD::FSIN: 4521 case ISD::FCOS: 4522 case ISD::FLOG: 4523 case ISD::FLOG2: 4524 case ISD::FLOG10: 4525 case ISD::FABS: 4526 case ISD::FEXP: 4527 case ISD::FEXP2: 4528 Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0)); 4529 Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1); 4530 Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT, 4531 Tmp2, DAG.getIntPtrConstant(0, dl))); 4532 break; 4533 case ISD::BUILD_VECTOR: { 4534 MVT EltVT = OVT.getVectorElementType(); 4535 MVT NewEltVT = NVT.getVectorElementType(); 4536 4537 // Handle bitcasts to a different vector type with the same total bit size 4538 // 4539 // e.g. v2i64 = build_vector i64:x, i64:y => v4i32 4540 // => 4541 // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y)) 4542 4543 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4544 "Invalid promote type for build_vector"); 4545 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4546 4547 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4548 4549 SmallVector<SDValue, 8> NewOps; 4550 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) { 4551 SDValue Op = Node->getOperand(I); 4552 NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op)); 4553 } 4554 4555 SDLoc SL(Node); 4556 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps); 4557 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4558 Results.push_back(CvtVec); 4559 break; 4560 } 4561 case ISD::EXTRACT_VECTOR_ELT: { 4562 MVT EltVT = OVT.getVectorElementType(); 4563 MVT NewEltVT = NVT.getVectorElementType(); 4564 4565 // Handle bitcasts to a different vector type with the same total bit size. 4566 // 4567 // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32 4568 // => 4569 // v4i32:castx = bitcast x:v2i64 4570 // 4571 // i64 = bitcast 4572 // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))), 4573 // (i32 (extract_vector_elt castx, (2 * y + 1))) 4574 // 4575 4576 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4577 "Invalid promote type for extract_vector_elt"); 4578 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4579 4580 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4581 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4582 4583 SDValue Idx = Node->getOperand(1); 4584 EVT IdxVT = Idx.getValueType(); 4585 SDLoc SL(Node); 4586 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT); 4587 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4588 4589 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4590 4591 SmallVector<SDValue, 8> NewOps; 4592 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4593 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4594 SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4595 4596 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4597 CastVec, TmpIdx); 4598 NewOps.push_back(Elt); 4599 } 4600 4601 SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps); 4602 Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec)); 4603 break; 4604 } 4605 case ISD::INSERT_VECTOR_ELT: { 4606 MVT EltVT = OVT.getVectorElementType(); 4607 MVT NewEltVT = NVT.getVectorElementType(); 4608 4609 // Handle bitcasts to a different vector type with the same total bit size 4610 // 4611 // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32 4612 // => 4613 // v4i32:castx = bitcast x:v2i64 4614 // v2i32:casty = bitcast y:i64 4615 // 4616 // v2i64 = bitcast 4617 // (v4i32 insert_vector_elt 4618 // (v4i32 insert_vector_elt v4i32:castx, 4619 // (extract_vector_elt casty, 0), 2 * z), 4620 // (extract_vector_elt casty, 1), (2 * z + 1)) 4621 4622 assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() && 4623 "Invalid promote type for insert_vector_elt"); 4624 assert(NewEltVT.bitsLT(EltVT) && "not handled"); 4625 4626 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4627 unsigned NewEltsPerOldElt = MidVT.getVectorNumElements(); 4628 4629 SDValue Val = Node->getOperand(1); 4630 SDValue Idx = Node->getOperand(2); 4631 EVT IdxVT = Idx.getValueType(); 4632 SDLoc SL(Node); 4633 4634 SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT); 4635 SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor); 4636 4637 SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0)); 4638 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4639 4640 SDValue NewVec = CastVec; 4641 for (unsigned I = 0; I < NewEltsPerOldElt; ++I) { 4642 SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT); 4643 SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset); 4644 4645 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT, 4646 CastVal, IdxOffset); 4647 4648 NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT, 4649 NewVec, Elt, InEltIdx); 4650 } 4651 4652 Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec)); 4653 break; 4654 } 4655 case ISD::SCALAR_TO_VECTOR: { 4656 MVT EltVT = OVT.getVectorElementType(); 4657 MVT NewEltVT = NVT.getVectorElementType(); 4658 4659 // Handle bitcasts to different vector type with the same total bit size. 4660 // 4661 // e.g. v2i64 = scalar_to_vector x:i64 4662 // => 4663 // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef) 4664 // 4665 4666 MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT); 4667 SDValue Val = Node->getOperand(0); 4668 SDLoc SL(Node); 4669 4670 SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val); 4671 SDValue Undef = DAG.getUNDEF(MidVT); 4672 4673 SmallVector<SDValue, 8> NewElts; 4674 NewElts.push_back(CastVal); 4675 for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I) 4676 NewElts.push_back(Undef); 4677 4678 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts); 4679 SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat); 4680 Results.push_back(CvtVec); 4681 break; 4682 } 4683 } 4684 4685 // Replace the original node with the legalized result. 4686 if (!Results.empty()) { 4687 DEBUG(dbgs() << "Successfully promoted node\n"); 4688 ReplaceNode(Node, Results.data()); 4689 } else 4690 DEBUG(dbgs() << "Could not promote node\n"); 4691 } 4692 4693 /// This is the entry point for the file. 4694 void SelectionDAG::Legalize() { 4695 AssignTopologicalOrder(); 4696 4697 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4698 // Use a delete listener to remove nodes which were deleted during 4699 // legalization from LegalizeNodes. This is needed to handle the situation 4700 // where a new node is allocated by the object pool to the same address of a 4701 // previously deleted node. 4702 DAGNodeDeletedListener DeleteListener( 4703 *this, 4704 [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); }); 4705 4706 SelectionDAGLegalize Legalizer(*this, LegalizedNodes); 4707 4708 // Visit all the nodes. We start in topological order, so that we see 4709 // nodes with their original operands intact. Legalization can produce 4710 // new nodes which may themselves need to be legalized. Iterate until all 4711 // nodes have been legalized. 4712 while (true) { 4713 bool AnyLegalized = false; 4714 for (auto NI = allnodes_end(); NI != allnodes_begin();) { 4715 --NI; 4716 4717 SDNode *N = &*NI; 4718 if (N->use_empty() && N != getRoot().getNode()) { 4719 ++NI; 4720 DeleteNode(N); 4721 continue; 4722 } 4723 4724 if (LegalizedNodes.insert(N).second) { 4725 AnyLegalized = true; 4726 Legalizer.LegalizeOp(N); 4727 4728 if (N->use_empty() && N != getRoot().getNode()) { 4729 ++NI; 4730 DeleteNode(N); 4731 } 4732 } 4733 } 4734 if (!AnyLegalized) 4735 break; 4736 4737 } 4738 4739 // Remove dead nodes now. 4740 RemoveDeadNodes(); 4741 } 4742 4743 bool SelectionDAG::LegalizeOp(SDNode *N, 4744 SmallSetVector<SDNode *, 16> &UpdatedNodes) { 4745 SmallPtrSet<SDNode *, 16> LegalizedNodes; 4746 SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes); 4747 4748 // Directly insert the node in question, and legalize it. This will recurse 4749 // as needed through operands. 4750 LegalizedNodes.insert(N); 4751 Legalizer.LegalizeOp(N); 4752 4753 return LegalizedNodes.count(N); 4754 } 4755