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