1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "isel" 15 #include "SDNodeDbgValue.h" 16 #include "SelectionDAGBuilder.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/PostOrderIterator.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/ConstantFolding.h" 22 #include "llvm/Constants.h" 23 #include "llvm/CallingConv.h" 24 #include "llvm/DerivedTypes.h" 25 #include "llvm/Function.h" 26 #include "llvm/GlobalVariable.h" 27 #include "llvm/InlineAsm.h" 28 #include "llvm/Instructions.h" 29 #include "llvm/Intrinsics.h" 30 #include "llvm/IntrinsicInst.h" 31 #include "llvm/LLVMContext.h" 32 #include "llvm/Module.h" 33 #include "llvm/CodeGen/Analysis.h" 34 #include "llvm/CodeGen/FastISel.h" 35 #include "llvm/CodeGen/FunctionLoweringInfo.h" 36 #include "llvm/CodeGen/GCStrategy.h" 37 #include "llvm/CodeGen/GCMetadata.h" 38 #include "llvm/CodeGen/MachineFunction.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineInstrBuilder.h" 41 #include "llvm/CodeGen/MachineJumpTableInfo.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineRegisterInfo.h" 44 #include "llvm/CodeGen/PseudoSourceValue.h" 45 #include "llvm/CodeGen/SelectionDAG.h" 46 #include "llvm/Analysis/DebugInfo.h" 47 #include "llvm/Target/TargetRegisterInfo.h" 48 #include "llvm/Target/TargetData.h" 49 #include "llvm/Target/TargetFrameInfo.h" 50 #include "llvm/Target/TargetInstrInfo.h" 51 #include "llvm/Target/TargetIntrinsicInfo.h" 52 #include "llvm/Target/TargetLowering.h" 53 #include "llvm/Target/TargetOptions.h" 54 #include "llvm/Support/Compiler.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/MathExtras.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include <algorithm> 61 using namespace llvm; 62 63 /// LimitFloatPrecision - Generate low-precision inline sequences for 64 /// some float libcalls (6, 8 or 12 bits). 65 static unsigned LimitFloatPrecision; 66 67 static cl::opt<unsigned, true> 68 LimitFPPrecision("limit-float-precision", 69 cl::desc("Generate low-precision inline sequences " 70 "for some float libcalls"), 71 cl::location(LimitFloatPrecision), 72 cl::init(0)); 73 74 // Limit the width of DAG chains. This is important in general to prevent 75 // prevent DAG-based analysis from blowing up. For example, alias analysis and 76 // load clustering may not complete in reasonable time. It is difficult to 77 // recognize and avoid this situation within each individual analysis, and 78 // future analyses are likely to have the same behavior. Limiting DAG width is 79 // the safe approach, and will be especially important with global DAGs. 80 // 81 // MaxParallelChains default is arbitrarily high to avoid affecting 82 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 83 // sequence over this should have been converted to llvm.memcpy by the 84 // frontend. It easy to induce this behavior with .ll code such as: 85 // %buffer = alloca [4096 x i8] 86 // %data = load [4096 x i8]* %argPtr 87 // store [4096 x i8] %data, [4096 x i8]* %buffer 88 static cl::opt<unsigned> 89 MaxParallelChains("dag-chain-limit", cl::desc("Max parallel isel dag chains"), 90 cl::init(64), cl::Hidden); 91 92 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, 93 const SDValue *Parts, unsigned NumParts, 94 EVT PartVT, EVT ValueVT); 95 96 /// getCopyFromParts - Create a value that contains the specified legal parts 97 /// combined into the value they represent. If the parts combine to a type 98 /// larger then ValueVT then AssertOp can be used to specify whether the extra 99 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 100 /// (ISD::AssertSext). 101 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL, 102 const SDValue *Parts, 103 unsigned NumParts, EVT PartVT, EVT ValueVT, 104 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 105 if (ValueVT.isVector()) 106 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT); 107 108 assert(NumParts > 0 && "No parts to assemble!"); 109 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 110 SDValue Val = Parts[0]; 111 112 if (NumParts > 1) { 113 // Assemble the value from multiple parts. 114 if (ValueVT.isInteger()) { 115 unsigned PartBits = PartVT.getSizeInBits(); 116 unsigned ValueBits = ValueVT.getSizeInBits(); 117 118 // Assemble the power of 2 part. 119 unsigned RoundParts = NumParts & (NumParts - 1) ? 120 1 << Log2_32(NumParts) : NumParts; 121 unsigned RoundBits = PartBits * RoundParts; 122 EVT RoundVT = RoundBits == ValueBits ? 123 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 124 SDValue Lo, Hi; 125 126 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 127 128 if (RoundParts > 2) { 129 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 130 PartVT, HalfVT); 131 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 132 RoundParts / 2, PartVT, HalfVT); 133 } else { 134 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 135 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 136 } 137 138 if (TLI.isBigEndian()) 139 std::swap(Lo, Hi); 140 141 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 142 143 if (RoundParts < NumParts) { 144 // Assemble the trailing non-power-of-2 part. 145 unsigned OddParts = NumParts - RoundParts; 146 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 147 Hi = getCopyFromParts(DAG, DL, 148 Parts + RoundParts, OddParts, PartVT, OddVT); 149 150 // Combine the round and odd parts. 151 Lo = Val; 152 if (TLI.isBigEndian()) 153 std::swap(Lo, Hi); 154 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 155 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 156 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 157 DAG.getConstant(Lo.getValueType().getSizeInBits(), 158 TLI.getPointerTy())); 159 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 160 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 161 } 162 } else if (PartVT.isFloatingPoint()) { 163 // FP split into multiple FP parts (for ppcf128) 164 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) && 165 "Unexpected split"); 166 SDValue Lo, Hi; 167 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 168 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 169 if (TLI.isBigEndian()) 170 std::swap(Lo, Hi); 171 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 172 } else { 173 // FP split into integer parts (soft fp) 174 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 175 !PartVT.isVector() && "Unexpected split"); 176 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 177 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT); 178 } 179 } 180 181 // There is now one part, held in Val. Correct it to match ValueVT. 182 PartVT = Val.getValueType(); 183 184 if (PartVT == ValueVT) 185 return Val; 186 187 if (PartVT.isInteger() && ValueVT.isInteger()) { 188 if (ValueVT.bitsLT(PartVT)) { 189 // For a truncate, see if we have any information to 190 // indicate whether the truncated bits will always be 191 // zero or sign-extension. 192 if (AssertOp != ISD::DELETED_NODE) 193 Val = DAG.getNode(AssertOp, DL, PartVT, Val, 194 DAG.getValueType(ValueVT)); 195 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 196 } 197 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 198 } 199 200 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 201 // FP_ROUND's are always exact here. 202 if (ValueVT.bitsLT(Val.getValueType())) 203 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, 204 DAG.getIntPtrConstant(1)); 205 206 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 207 } 208 209 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) 210 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 211 212 llvm_unreachable("Unknown mismatch!"); 213 return SDValue(); 214 } 215 216 /// getCopyFromParts - Create a value that contains the specified legal parts 217 /// combined into the value they represent. If the parts combine to a type 218 /// larger then ValueVT then AssertOp can be used to specify whether the extra 219 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 220 /// (ISD::AssertSext). 221 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL, 222 const SDValue *Parts, unsigned NumParts, 223 EVT PartVT, EVT ValueVT) { 224 assert(ValueVT.isVector() && "Not a vector value"); 225 assert(NumParts > 0 && "No parts to assemble!"); 226 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 227 SDValue Val = Parts[0]; 228 229 // Handle a multi-element vector. 230 if (NumParts > 1) { 231 EVT IntermediateVT, RegisterVT; 232 unsigned NumIntermediates; 233 unsigned NumRegs = 234 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 235 NumIntermediates, RegisterVT); 236 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 237 NumParts = NumRegs; // Silence a compiler warning. 238 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 239 assert(RegisterVT == Parts[0].getValueType() && 240 "Part type doesn't match part!"); 241 242 // Assemble the parts into intermediate operands. 243 SmallVector<SDValue, 8> Ops(NumIntermediates); 244 if (NumIntermediates == NumParts) { 245 // If the register was not expanded, truncate or copy the value, 246 // as appropriate. 247 for (unsigned i = 0; i != NumParts; ++i) 248 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 249 PartVT, IntermediateVT); 250 } else if (NumParts > 0) { 251 // If the intermediate type was expanded, build the intermediate 252 // operands from the parts. 253 assert(NumParts % NumIntermediates == 0 && 254 "Must expand into a divisible number of parts!"); 255 unsigned Factor = NumParts / NumIntermediates; 256 for (unsigned i = 0; i != NumIntermediates; ++i) 257 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 258 PartVT, IntermediateVT); 259 } 260 261 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 262 // intermediate operands. 263 Val = DAG.getNode(IntermediateVT.isVector() ? 264 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL, 265 ValueVT, &Ops[0], NumIntermediates); 266 } 267 268 // There is now one part, held in Val. Correct it to match ValueVT. 269 PartVT = Val.getValueType(); 270 271 if (PartVT == ValueVT) 272 return Val; 273 274 if (PartVT.isVector()) { 275 // If the element type of the source/dest vectors are the same, but the 276 // parts vector has more elements than the value vector, then we have a 277 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 278 // elements we want. 279 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 280 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 281 "Cannot narrow, it would be a lossy transformation"); 282 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 283 DAG.getIntPtrConstant(0)); 284 } 285 286 // Vector/Vector bitcast. 287 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 288 } 289 290 assert(ValueVT.getVectorElementType() == PartVT && 291 ValueVT.getVectorNumElements() == 1 && 292 "Only trivial scalar-to-vector conversions should get here!"); 293 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 294 } 295 296 297 298 299 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl, 300 SDValue Val, SDValue *Parts, unsigned NumParts, 301 EVT PartVT); 302 303 /// getCopyToParts - Create a series of nodes that contain the specified value 304 /// split into legal parts. If the parts contain more bits than Val, then, for 305 /// integers, ExtendKind can be used to specify how to generate the extra bits. 306 static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL, 307 SDValue Val, SDValue *Parts, unsigned NumParts, 308 EVT PartVT, 309 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 310 EVT ValueVT = Val.getValueType(); 311 312 // Handle the vector case separately. 313 if (ValueVT.isVector()) 314 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT); 315 316 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 317 unsigned PartBits = PartVT.getSizeInBits(); 318 unsigned OrigNumParts = NumParts; 319 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 320 321 if (NumParts == 0) 322 return; 323 324 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 325 if (PartVT == ValueVT) { 326 assert(NumParts == 1 && "No-op copy with multiple parts!"); 327 Parts[0] = Val; 328 return; 329 } 330 331 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 332 // If the parts cover more bits than the value has, promote the value. 333 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 334 assert(NumParts == 1 && "Do not know what to promote to!"); 335 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 336 } else { 337 assert(PartVT.isInteger() && ValueVT.isInteger() && 338 "Unknown mismatch!"); 339 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 340 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 341 } 342 } else if (PartBits == ValueVT.getSizeInBits()) { 343 // Different types of the same size. 344 assert(NumParts == 1 && PartVT != ValueVT); 345 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 346 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 347 // If the parts cover less bits than value has, truncate the value. 348 assert(PartVT.isInteger() && ValueVT.isInteger() && 349 "Unknown mismatch!"); 350 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 351 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 352 } 353 354 // The value may have changed - recompute ValueVT. 355 ValueVT = Val.getValueType(); 356 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 357 "Failed to tile the value with PartVT!"); 358 359 if (NumParts == 1) { 360 assert(PartVT == ValueVT && "Type conversion failed!"); 361 Parts[0] = Val; 362 return; 363 } 364 365 // Expand the value into multiple parts. 366 if (NumParts & (NumParts - 1)) { 367 // The number of parts is not a power of 2. Split off and copy the tail. 368 assert(PartVT.isInteger() && ValueVT.isInteger() && 369 "Do not know what to expand to!"); 370 unsigned RoundParts = 1 << Log2_32(NumParts); 371 unsigned RoundBits = RoundParts * PartBits; 372 unsigned OddParts = NumParts - RoundParts; 373 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 374 DAG.getIntPtrConstant(RoundBits)); 375 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT); 376 377 if (TLI.isBigEndian()) 378 // The odd parts were reversed by getCopyToParts - unreverse them. 379 std::reverse(Parts + RoundParts, Parts + NumParts); 380 381 NumParts = RoundParts; 382 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 383 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 384 } 385 386 // The number of parts is a power of 2. Repeatedly bisect the value using 387 // EXTRACT_ELEMENT. 388 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 389 EVT::getIntegerVT(*DAG.getContext(), 390 ValueVT.getSizeInBits()), 391 Val); 392 393 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 394 for (unsigned i = 0; i < NumParts; i += StepSize) { 395 unsigned ThisBits = StepSize * PartBits / 2; 396 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 397 SDValue &Part0 = Parts[i]; 398 SDValue &Part1 = Parts[i+StepSize/2]; 399 400 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 401 ThisVT, Part0, DAG.getIntPtrConstant(1)); 402 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 403 ThisVT, Part0, DAG.getIntPtrConstant(0)); 404 405 if (ThisBits == PartBits && ThisVT != PartVT) { 406 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 407 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 408 } 409 } 410 } 411 412 if (TLI.isBigEndian()) 413 std::reverse(Parts, Parts + OrigNumParts); 414 } 415 416 417 /// getCopyToPartsVector - Create a series of nodes that contain the specified 418 /// value split into legal parts. 419 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL, 420 SDValue Val, SDValue *Parts, unsigned NumParts, 421 EVT PartVT) { 422 EVT ValueVT = Val.getValueType(); 423 assert(ValueVT.isVector() && "Not a vector"); 424 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 425 426 if (NumParts == 1) { 427 if (PartVT == ValueVT) { 428 // Nothing to do. 429 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 430 // Bitconvert vector->vector case. 431 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 432 } else if (PartVT.isVector() && 433 PartVT.getVectorElementType() == ValueVT.getVectorElementType()&& 434 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 435 EVT ElementVT = PartVT.getVectorElementType(); 436 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 437 // undef elements. 438 SmallVector<SDValue, 16> Ops; 439 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 440 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 441 ElementVT, Val, DAG.getIntPtrConstant(i))); 442 443 for (unsigned i = ValueVT.getVectorNumElements(), 444 e = PartVT.getVectorNumElements(); i != e; ++i) 445 Ops.push_back(DAG.getUNDEF(ElementVT)); 446 447 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size()); 448 449 // FIXME: Use CONCAT for 2x -> 4x. 450 451 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 452 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 453 } else { 454 // Vector -> scalar conversion. 455 assert(ValueVT.getVectorElementType() == PartVT && 456 ValueVT.getVectorNumElements() == 1 && 457 "Only trivial vector-to-scalar conversions should get here!"); 458 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 459 PartVT, Val, DAG.getIntPtrConstant(0)); 460 } 461 462 Parts[0] = Val; 463 return; 464 } 465 466 // Handle a multi-element vector. 467 EVT IntermediateVT, RegisterVT; 468 unsigned NumIntermediates; 469 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 470 IntermediateVT, 471 NumIntermediates, RegisterVT); 472 unsigned NumElements = ValueVT.getVectorNumElements(); 473 474 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 475 NumParts = NumRegs; // Silence a compiler warning. 476 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 477 478 // Split the vector into intermediate operands. 479 SmallVector<SDValue, 8> Ops(NumIntermediates); 480 for (unsigned i = 0; i != NumIntermediates; ++i) { 481 if (IntermediateVT.isVector()) 482 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 483 IntermediateVT, Val, 484 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates))); 485 else 486 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 487 IntermediateVT, Val, DAG.getIntPtrConstant(i)); 488 } 489 490 // Split the intermediate operands into legal parts. 491 if (NumParts == NumIntermediates) { 492 // If the register was not expanded, promote or copy the value, 493 // as appropriate. 494 for (unsigned i = 0; i != NumParts; ++i) 495 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT); 496 } else if (NumParts > 0) { 497 // If the intermediate type was expanded, split each the value into 498 // legal parts. 499 assert(NumParts % NumIntermediates == 0 && 500 "Must expand into a divisible number of parts!"); 501 unsigned Factor = NumParts / NumIntermediates; 502 for (unsigned i = 0; i != NumIntermediates; ++i) 503 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT); 504 } 505 } 506 507 508 509 510 namespace { 511 /// RegsForValue - This struct represents the registers (physical or virtual) 512 /// that a particular set of values is assigned, and the type information 513 /// about the value. The most common situation is to represent one value at a 514 /// time, but struct or array values are handled element-wise as multiple 515 /// values. The splitting of aggregates is performed recursively, so that we 516 /// never have aggregate-typed registers. The values at this point do not 517 /// necessarily have legal types, so each value may require one or more 518 /// registers of some legal type. 519 /// 520 struct RegsForValue { 521 /// ValueVTs - The value types of the values, which may not be legal, and 522 /// may need be promoted or synthesized from one or more registers. 523 /// 524 SmallVector<EVT, 4> ValueVTs; 525 526 /// RegVTs - The value types of the registers. This is the same size as 527 /// ValueVTs and it records, for each value, what the type of the assigned 528 /// register or registers are. (Individual values are never synthesized 529 /// from more than one type of register.) 530 /// 531 /// With virtual registers, the contents of RegVTs is redundant with TLI's 532 /// getRegisterType member function, however when with physical registers 533 /// it is necessary to have a separate record of the types. 534 /// 535 SmallVector<EVT, 4> RegVTs; 536 537 /// Regs - This list holds the registers assigned to the values. 538 /// Each legal or promoted value requires one register, and each 539 /// expanded value requires multiple registers. 540 /// 541 SmallVector<unsigned, 4> Regs; 542 543 RegsForValue() {} 544 545 RegsForValue(const SmallVector<unsigned, 4> ®s, 546 EVT regvt, EVT valuevt) 547 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 548 549 RegsForValue(LLVMContext &Context, const TargetLowering &tli, 550 unsigned Reg, const Type *Ty) { 551 ComputeValueVTs(tli, Ty, ValueVTs); 552 553 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 554 EVT ValueVT = ValueVTs[Value]; 555 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT); 556 EVT RegisterVT = tli.getRegisterType(Context, ValueVT); 557 for (unsigned i = 0; i != NumRegs; ++i) 558 Regs.push_back(Reg + i); 559 RegVTs.push_back(RegisterVT); 560 Reg += NumRegs; 561 } 562 } 563 564 /// areValueTypesLegal - Return true if types of all the values are legal. 565 bool areValueTypesLegal(const TargetLowering &TLI) { 566 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 567 EVT RegisterVT = RegVTs[Value]; 568 if (!TLI.isTypeLegal(RegisterVT)) 569 return false; 570 } 571 return true; 572 } 573 574 /// append - Add the specified values to this one. 575 void append(const RegsForValue &RHS) { 576 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 577 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 578 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 579 } 580 581 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 582 /// this value and returns the result as a ValueVTs value. This uses 583 /// Chain/Flag as the input and updates them for the output Chain/Flag. 584 /// If the Flag pointer is NULL, no flag is used. 585 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 586 DebugLoc dl, 587 SDValue &Chain, SDValue *Flag) const; 588 589 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 590 /// specified value into the registers specified by this object. This uses 591 /// Chain/Flag as the input and updates them for the output Chain/Flag. 592 /// If the Flag pointer is NULL, no flag is used. 593 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 594 SDValue &Chain, SDValue *Flag) const; 595 596 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 597 /// operand list. This adds the code marker, matching input operand index 598 /// (if applicable), and includes the number of values added into it. 599 void AddInlineAsmOperands(unsigned Kind, 600 bool HasMatching, unsigned MatchingIdx, 601 SelectionDAG &DAG, 602 std::vector<SDValue> &Ops) const; 603 }; 604 } 605 606 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 607 /// this value and returns the result as a ValueVT value. This uses 608 /// Chain/Flag as the input and updates them for the output Chain/Flag. 609 /// If the Flag pointer is NULL, no flag is used. 610 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 611 FunctionLoweringInfo &FuncInfo, 612 DebugLoc dl, 613 SDValue &Chain, SDValue *Flag) const { 614 // A Value with type {} or [0 x %t] needs no registers. 615 if (ValueVTs.empty()) 616 return SDValue(); 617 618 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 619 620 // Assemble the legal parts into the final values. 621 SmallVector<SDValue, 4> Values(ValueVTs.size()); 622 SmallVector<SDValue, 8> Parts; 623 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 624 // Copy the legal parts from the registers. 625 EVT ValueVT = ValueVTs[Value]; 626 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 627 EVT RegisterVT = RegVTs[Value]; 628 629 Parts.resize(NumRegs); 630 for (unsigned i = 0; i != NumRegs; ++i) { 631 SDValue P; 632 if (Flag == 0) { 633 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 634 } else { 635 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 636 *Flag = P.getValue(2); 637 } 638 639 Chain = P.getValue(1); 640 641 // If the source register was virtual and if we know something about it, 642 // add an assert node. 643 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) && 644 RegisterVT.isInteger() && !RegisterVT.isVector()) { 645 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister; 646 if (FuncInfo.LiveOutRegInfo.size() > SlotNo) { 647 const FunctionLoweringInfo::LiveOutInfo &LOI = 648 FuncInfo.LiveOutRegInfo[SlotNo]; 649 650 unsigned RegSize = RegisterVT.getSizeInBits(); 651 unsigned NumSignBits = LOI.NumSignBits; 652 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes(); 653 654 // FIXME: We capture more information than the dag can represent. For 655 // now, just use the tightest assertzext/assertsext possible. 656 bool isSExt = true; 657 EVT FromVT(MVT::Other); 658 if (NumSignBits == RegSize) 659 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 660 else if (NumZeroBits >= RegSize-1) 661 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 662 else if (NumSignBits > RegSize-8) 663 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 664 else if (NumZeroBits >= RegSize-8) 665 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 666 else if (NumSignBits > RegSize-16) 667 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 668 else if (NumZeroBits >= RegSize-16) 669 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 670 else if (NumSignBits > RegSize-32) 671 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 672 else if (NumZeroBits >= RegSize-32) 673 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 674 675 if (FromVT != MVT::Other) 676 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 677 RegisterVT, P, DAG.getValueType(FromVT)); 678 } 679 } 680 681 Parts[i] = P; 682 } 683 684 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 685 NumRegs, RegisterVT, ValueVT); 686 Part += NumRegs; 687 Parts.clear(); 688 } 689 690 return DAG.getNode(ISD::MERGE_VALUES, dl, 691 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 692 &Values[0], ValueVTs.size()); 693 } 694 695 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 696 /// specified value into the registers specified by this object. This uses 697 /// Chain/Flag as the input and updates them for the output Chain/Flag. 698 /// If the Flag pointer is NULL, no flag is used. 699 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 700 SDValue &Chain, SDValue *Flag) const { 701 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 702 703 // Get the list of the values's legal parts. 704 unsigned NumRegs = Regs.size(); 705 SmallVector<SDValue, 8> Parts(NumRegs); 706 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 707 EVT ValueVT = ValueVTs[Value]; 708 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 709 EVT RegisterVT = RegVTs[Value]; 710 711 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 712 &Parts[Part], NumParts, RegisterVT); 713 Part += NumParts; 714 } 715 716 // Copy the parts into the registers. 717 SmallVector<SDValue, 8> Chains(NumRegs); 718 for (unsigned i = 0; i != NumRegs; ++i) { 719 SDValue Part; 720 if (Flag == 0) { 721 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 722 } else { 723 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 724 *Flag = Part.getValue(1); 725 } 726 727 Chains[i] = Part.getValue(0); 728 } 729 730 if (NumRegs == 1 || Flag) 731 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 732 // flagged to it. That is the CopyToReg nodes and the user are considered 733 // a single scheduling unit. If we create a TokenFactor and return it as 734 // chain, then the TokenFactor is both a predecessor (operand) of the 735 // user as well as a successor (the TF operands are flagged to the user). 736 // c1, f1 = CopyToReg 737 // c2, f2 = CopyToReg 738 // c3 = TokenFactor c1, c2 739 // ... 740 // = op c3, ..., f2 741 Chain = Chains[NumRegs-1]; 742 else 743 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 744 } 745 746 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 747 /// operand list. This adds the code marker and includes the number of 748 /// values added into it. 749 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 750 unsigned MatchingIdx, 751 SelectionDAG &DAG, 752 std::vector<SDValue> &Ops) const { 753 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 754 755 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 756 if (HasMatching) 757 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 758 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); 759 Ops.push_back(Res); 760 761 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 762 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 763 EVT RegisterVT = RegVTs[Value]; 764 for (unsigned i = 0; i != NumRegs; ++i) { 765 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 766 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); 767 } 768 } 769 } 770 771 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) { 772 AA = &aa; 773 GFI = gfi; 774 TD = DAG.getTarget().getTargetData(); 775 } 776 777 /// clear - Clear out the current SelectionDAG and the associated 778 /// state and prepare this SelectionDAGBuilder object to be used 779 /// for a new block. This doesn't clear out information about 780 /// additional blocks that are needed to complete switch lowering 781 /// or PHI node updating; that information is cleared out as it is 782 /// consumed. 783 void SelectionDAGBuilder::clear() { 784 NodeMap.clear(); 785 UnusedArgNodeMap.clear(); 786 PendingLoads.clear(); 787 PendingExports.clear(); 788 DanglingDebugInfoMap.clear(); 789 CurDebugLoc = DebugLoc(); 790 HasTailCall = false; 791 } 792 793 /// getRoot - Return the current virtual root of the Selection DAG, 794 /// flushing any PendingLoad items. This must be done before emitting 795 /// a store or any other node that may need to be ordered after any 796 /// prior load instructions. 797 /// 798 SDValue SelectionDAGBuilder::getRoot() { 799 if (PendingLoads.empty()) 800 return DAG.getRoot(); 801 802 if (PendingLoads.size() == 1) { 803 SDValue Root = PendingLoads[0]; 804 DAG.setRoot(Root); 805 PendingLoads.clear(); 806 return Root; 807 } 808 809 // Otherwise, we have to make a token factor node. 810 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 811 &PendingLoads[0], PendingLoads.size()); 812 PendingLoads.clear(); 813 DAG.setRoot(Root); 814 return Root; 815 } 816 817 /// getControlRoot - Similar to getRoot, but instead of flushing all the 818 /// PendingLoad items, flush all the PendingExports items. It is necessary 819 /// to do this before emitting a terminator instruction. 820 /// 821 SDValue SelectionDAGBuilder::getControlRoot() { 822 SDValue Root = DAG.getRoot(); 823 824 if (PendingExports.empty()) 825 return Root; 826 827 // Turn all of the CopyToReg chains into one factored node. 828 if (Root.getOpcode() != ISD::EntryToken) { 829 unsigned i = 0, e = PendingExports.size(); 830 for (; i != e; ++i) { 831 assert(PendingExports[i].getNode()->getNumOperands() > 1); 832 if (PendingExports[i].getNode()->getOperand(0) == Root) 833 break; // Don't add the root if we already indirectly depend on it. 834 } 835 836 if (i == e) 837 PendingExports.push_back(Root); 838 } 839 840 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 841 &PendingExports[0], 842 PendingExports.size()); 843 PendingExports.clear(); 844 DAG.setRoot(Root); 845 return Root; 846 } 847 848 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) { 849 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering. 850 DAG.AssignOrdering(Node, SDNodeOrder); 851 852 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) 853 AssignOrderingToNode(Node->getOperand(I).getNode()); 854 } 855 856 void SelectionDAGBuilder::visit(const Instruction &I) { 857 // Set up outgoing PHI node register values before emitting the terminator. 858 if (isa<TerminatorInst>(&I)) 859 HandlePHINodesInSuccessorBlocks(I.getParent()); 860 861 CurDebugLoc = I.getDebugLoc(); 862 863 visit(I.getOpcode(), I); 864 865 if (!isa<TerminatorInst>(&I) && !HasTailCall) 866 CopyToExportRegsIfNeeded(&I); 867 868 CurDebugLoc = DebugLoc(); 869 } 870 871 void SelectionDAGBuilder::visitPHI(const PHINode &) { 872 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 873 } 874 875 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 876 // Note: this doesn't use InstVisitor, because it has to work with 877 // ConstantExpr's in addition to instructions. 878 switch (Opcode) { 879 default: llvm_unreachable("Unknown instruction type encountered!"); 880 // Build the switch statement using the Instruction.def file. 881 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 882 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break; 883 #include "llvm/Instruction.def" 884 } 885 886 // Assign the ordering to the freshly created DAG nodes. 887 if (NodeMap.count(&I)) { 888 ++SDNodeOrder; 889 AssignOrderingToNode(getValue(&I).getNode()); 890 } 891 } 892 893 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 894 // generate the debug data structures now that we've seen its definition. 895 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 896 SDValue Val) { 897 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 898 if (DDI.getDI()) { 899 const DbgValueInst *DI = DDI.getDI(); 900 DebugLoc dl = DDI.getdl(); 901 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 902 MDNode *Variable = DI->getVariable(); 903 uint64_t Offset = DI->getOffset(); 904 SDDbgValue *SDV; 905 if (Val.getNode()) { 906 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) { 907 SDV = DAG.getDbgValue(Variable, Val.getNode(), 908 Val.getResNo(), Offset, dl, DbgSDNodeOrder); 909 DAG.AddDbgValue(SDV, Val.getNode(), false); 910 } 911 } else 912 DEBUG(dbgs() << "Dropping debug info for " << DI); 913 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 914 } 915 } 916 917 // getValue - Return an SDValue for the given Value. 918 SDValue SelectionDAGBuilder::getValue(const Value *V) { 919 // If we already have an SDValue for this value, use it. It's important 920 // to do this first, so that we don't create a CopyFromReg if we already 921 // have a regular SDValue. 922 SDValue &N = NodeMap[V]; 923 if (N.getNode()) return N; 924 925 // If there's a virtual register allocated and initialized for this 926 // value, use it. 927 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 928 if (It != FuncInfo.ValueMap.end()) { 929 unsigned InReg = It->second; 930 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType()); 931 SDValue Chain = DAG.getEntryNode(); 932 return N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL); 933 } 934 935 // Otherwise create a new SDValue and remember it. 936 SDValue Val = getValueImpl(V); 937 NodeMap[V] = Val; 938 resolveDanglingDebugInfo(V, Val); 939 return Val; 940 } 941 942 /// getNonRegisterValue - Return an SDValue for the given Value, but 943 /// don't look in FuncInfo.ValueMap for a virtual register. 944 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 945 // If we already have an SDValue for this value, use it. 946 SDValue &N = NodeMap[V]; 947 if (N.getNode()) return N; 948 949 // Otherwise create a new SDValue and remember it. 950 SDValue Val = getValueImpl(V); 951 NodeMap[V] = Val; 952 resolveDanglingDebugInfo(V, Val); 953 return Val; 954 } 955 956 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 957 /// Create an SDValue for the given value. 958 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 959 if (const Constant *C = dyn_cast<Constant>(V)) { 960 EVT VT = TLI.getValueType(V->getType(), true); 961 962 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 963 return DAG.getConstant(*CI, VT); 964 965 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 966 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT); 967 968 if (isa<ConstantPointerNull>(C)) 969 return DAG.getConstant(0, TLI.getPointerTy()); 970 971 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 972 return DAG.getConstantFP(*CFP, VT); 973 974 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 975 return DAG.getUNDEF(VT); 976 977 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 978 visit(CE->getOpcode(), *CE); 979 SDValue N1 = NodeMap[V]; 980 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 981 return N1; 982 } 983 984 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 985 SmallVector<SDValue, 4> Constants; 986 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 987 OI != OE; ++OI) { 988 SDNode *Val = getValue(*OI).getNode(); 989 // If the operand is an empty aggregate, there are no values. 990 if (!Val) continue; 991 // Add each leaf value from the operand to the Constants list 992 // to form a flattened list of all the values. 993 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 994 Constants.push_back(SDValue(Val, i)); 995 } 996 997 return DAG.getMergeValues(&Constants[0], Constants.size(), 998 getCurDebugLoc()); 999 } 1000 1001 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1002 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1003 "Unknown struct or array constant!"); 1004 1005 SmallVector<EVT, 4> ValueVTs; 1006 ComputeValueVTs(TLI, C->getType(), ValueVTs); 1007 unsigned NumElts = ValueVTs.size(); 1008 if (NumElts == 0) 1009 return SDValue(); // empty struct 1010 SmallVector<SDValue, 4> Constants(NumElts); 1011 for (unsigned i = 0; i != NumElts; ++i) { 1012 EVT EltVT = ValueVTs[i]; 1013 if (isa<UndefValue>(C)) 1014 Constants[i] = DAG.getUNDEF(EltVT); 1015 else if (EltVT.isFloatingPoint()) 1016 Constants[i] = DAG.getConstantFP(0, EltVT); 1017 else 1018 Constants[i] = DAG.getConstant(0, EltVT); 1019 } 1020 1021 return DAG.getMergeValues(&Constants[0], NumElts, 1022 getCurDebugLoc()); 1023 } 1024 1025 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1026 return DAG.getBlockAddress(BA, VT); 1027 1028 const VectorType *VecTy = cast<VectorType>(V->getType()); 1029 unsigned NumElements = VecTy->getNumElements(); 1030 1031 // Now that we know the number and type of the elements, get that number of 1032 // elements into the Ops array based on what kind of constant it is. 1033 SmallVector<SDValue, 16> Ops; 1034 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 1035 for (unsigned i = 0; i != NumElements; ++i) 1036 Ops.push_back(getValue(CP->getOperand(i))); 1037 } else { 1038 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1039 EVT EltVT = TLI.getValueType(VecTy->getElementType()); 1040 1041 SDValue Op; 1042 if (EltVT.isFloatingPoint()) 1043 Op = DAG.getConstantFP(0, EltVT); 1044 else 1045 Op = DAG.getConstant(0, EltVT); 1046 Ops.assign(NumElements, Op); 1047 } 1048 1049 // Create a BUILD_VECTOR node. 1050 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 1051 VT, &Ops[0], Ops.size()); 1052 } 1053 1054 // If this is a static alloca, generate it as the frameindex instead of 1055 // computation. 1056 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1057 DenseMap<const AllocaInst*, int>::iterator SI = 1058 FuncInfo.StaticAllocaMap.find(AI); 1059 if (SI != FuncInfo.StaticAllocaMap.end()) 1060 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 1061 } 1062 1063 // If this is an instruction which fast-isel has deferred, select it now. 1064 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1065 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1066 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType()); 1067 SDValue Chain = DAG.getEntryNode(); 1068 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL); 1069 } 1070 1071 llvm_unreachable("Can't get register for value!"); 1072 return SDValue(); 1073 } 1074 1075 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1076 SDValue Chain = getControlRoot(); 1077 SmallVector<ISD::OutputArg, 8> Outs; 1078 SmallVector<SDValue, 8> OutVals; 1079 1080 if (!FuncInfo.CanLowerReturn) { 1081 unsigned DemoteReg = FuncInfo.DemoteRegister; 1082 const Function *F = I.getParent()->getParent(); 1083 1084 // Emit a store of the return value through the virtual register. 1085 // Leave Outs empty so that LowerReturn won't try to load return 1086 // registers the usual way. 1087 SmallVector<EVT, 1> PtrValueVTs; 1088 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), 1089 PtrValueVTs); 1090 1091 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 1092 SDValue RetOp = getValue(I.getOperand(0)); 1093 1094 SmallVector<EVT, 4> ValueVTs; 1095 SmallVector<uint64_t, 4> Offsets; 1096 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1097 unsigned NumValues = ValueVTs.size(); 1098 1099 SmallVector<SDValue, 4> Chains(NumValues); 1100 for (unsigned i = 0; i != NumValues; ++i) { 1101 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), 1102 RetPtr.getValueType(), RetPtr, 1103 DAG.getIntPtrConstant(Offsets[i])); 1104 Chains[i] = 1105 DAG.getStore(Chain, getCurDebugLoc(), 1106 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1107 // FIXME: better loc info would be nice. 1108 Add, MachinePointerInfo(), false, false, 0); 1109 } 1110 1111 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 1112 MVT::Other, &Chains[0], NumValues); 1113 } else if (I.getNumOperands() != 0) { 1114 SmallVector<EVT, 4> ValueVTs; 1115 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs); 1116 unsigned NumValues = ValueVTs.size(); 1117 if (NumValues) { 1118 SDValue RetOp = getValue(I.getOperand(0)); 1119 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1120 EVT VT = ValueVTs[j]; 1121 1122 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1123 1124 const Function *F = I.getParent()->getParent(); 1125 if (F->paramHasAttr(0, Attribute::SExt)) 1126 ExtendKind = ISD::SIGN_EXTEND; 1127 else if (F->paramHasAttr(0, Attribute::ZExt)) 1128 ExtendKind = ISD::ZERO_EXTEND; 1129 1130 // FIXME: C calling convention requires the return type to be promoted 1131 // to at least 32-bit. But this is not necessary for non-C calling 1132 // conventions. The frontend should mark functions whose return values 1133 // require promoting with signext or zeroext attributes. 1134 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 1135 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32); 1136 if (VT.bitsLT(MinVT)) 1137 VT = MinVT; 1138 } 1139 1140 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT); 1141 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT); 1142 SmallVector<SDValue, 4> Parts(NumParts); 1143 getCopyToParts(DAG, getCurDebugLoc(), 1144 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1145 &Parts[0], NumParts, PartVT, ExtendKind); 1146 1147 // 'inreg' on function refers to return value 1148 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1149 if (F->paramHasAttr(0, Attribute::InReg)) 1150 Flags.setInReg(); 1151 1152 // Propagate extension type if any 1153 if (F->paramHasAttr(0, Attribute::SExt)) 1154 Flags.setSExt(); 1155 else if (F->paramHasAttr(0, Attribute::ZExt)) 1156 Flags.setZExt(); 1157 1158 for (unsigned i = 0; i < NumParts; ++i) { 1159 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1160 /*isfixed=*/true)); 1161 OutVals.push_back(Parts[i]); 1162 } 1163 } 1164 } 1165 } 1166 1167 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1168 CallingConv::ID CallConv = 1169 DAG.getMachineFunction().getFunction()->getCallingConv(); 1170 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg, 1171 Outs, OutVals, getCurDebugLoc(), DAG); 1172 1173 // Verify that the target's LowerReturn behaved as expected. 1174 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1175 "LowerReturn didn't return a valid chain!"); 1176 1177 // Update the DAG with the new chain value resulting from return lowering. 1178 DAG.setRoot(Chain); 1179 } 1180 1181 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1182 /// created for it, emit nodes to copy the value into the virtual 1183 /// registers. 1184 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1185 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1186 if (VMI != FuncInfo.ValueMap.end()) { 1187 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1188 CopyValueToVirtualRegister(V, VMI->second); 1189 } 1190 } 1191 1192 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1193 /// the current basic block, add it to ValueMap now so that we'll get a 1194 /// CopyTo/FromReg. 1195 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1196 // No need to export constants. 1197 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1198 1199 // Already exported? 1200 if (FuncInfo.isExportedInst(V)) return; 1201 1202 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1203 CopyValueToVirtualRegister(V, Reg); 1204 } 1205 1206 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1207 const BasicBlock *FromBB) { 1208 // The operands of the setcc have to be in this block. We don't know 1209 // how to export them from some other block. 1210 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1211 // Can export from current BB. 1212 if (VI->getParent() == FromBB) 1213 return true; 1214 1215 // Is already exported, noop. 1216 return FuncInfo.isExportedInst(V); 1217 } 1218 1219 // If this is an argument, we can export it if the BB is the entry block or 1220 // if it is already exported. 1221 if (isa<Argument>(V)) { 1222 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1223 return true; 1224 1225 // Otherwise, can only export this if it is already exported. 1226 return FuncInfo.isExportedInst(V); 1227 } 1228 1229 // Otherwise, constants can always be exported. 1230 return true; 1231 } 1232 1233 static bool InBlock(const Value *V, const BasicBlock *BB) { 1234 if (const Instruction *I = dyn_cast<Instruction>(V)) 1235 return I->getParent() == BB; 1236 return true; 1237 } 1238 1239 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1240 /// This function emits a branch and is used at the leaves of an OR or an 1241 /// AND operator tree. 1242 /// 1243 void 1244 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1245 MachineBasicBlock *TBB, 1246 MachineBasicBlock *FBB, 1247 MachineBasicBlock *CurBB, 1248 MachineBasicBlock *SwitchBB) { 1249 const BasicBlock *BB = CurBB->getBasicBlock(); 1250 1251 // If the leaf of the tree is a comparison, merge the condition into 1252 // the caseblock. 1253 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1254 // The operands of the cmp have to be in this block. We don't know 1255 // how to export them from some other block. If this is the first block 1256 // of the sequence, no exporting is needed. 1257 if (CurBB == SwitchBB || 1258 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1259 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1260 ISD::CondCode Condition; 1261 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1262 Condition = getICmpCondCode(IC->getPredicate()); 1263 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1264 Condition = getFCmpCondCode(FC->getPredicate()); 1265 } else { 1266 Condition = ISD::SETEQ; // silence warning. 1267 llvm_unreachable("Unknown compare instruction"); 1268 } 1269 1270 CaseBlock CB(Condition, BOp->getOperand(0), 1271 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1272 SwitchCases.push_back(CB); 1273 return; 1274 } 1275 } 1276 1277 // Create a CaseBlock record representing this branch. 1278 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1279 NULL, TBB, FBB, CurBB); 1280 SwitchCases.push_back(CB); 1281 } 1282 1283 /// FindMergedConditions - If Cond is an expression like 1284 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1285 MachineBasicBlock *TBB, 1286 MachineBasicBlock *FBB, 1287 MachineBasicBlock *CurBB, 1288 MachineBasicBlock *SwitchBB, 1289 unsigned Opc) { 1290 // If this node is not part of the or/and tree, emit it as a branch. 1291 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1292 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1293 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1294 BOp->getParent() != CurBB->getBasicBlock() || 1295 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1296 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1297 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB); 1298 return; 1299 } 1300 1301 // Create TmpBB after CurBB. 1302 MachineFunction::iterator BBI = CurBB; 1303 MachineFunction &MF = DAG.getMachineFunction(); 1304 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1305 CurBB->getParent()->insert(++BBI, TmpBB); 1306 1307 if (Opc == Instruction::Or) { 1308 // Codegen X | Y as: 1309 // jmp_if_X TBB 1310 // jmp TmpBB 1311 // TmpBB: 1312 // jmp_if_Y TBB 1313 // jmp FBB 1314 // 1315 1316 // Emit the LHS condition. 1317 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc); 1318 1319 // Emit the RHS condition into TmpBB. 1320 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1321 } else { 1322 assert(Opc == Instruction::And && "Unknown merge op!"); 1323 // Codegen X & Y as: 1324 // jmp_if_X TmpBB 1325 // jmp FBB 1326 // TmpBB: 1327 // jmp_if_Y TBB 1328 // jmp FBB 1329 // 1330 // This requires creation of TmpBB after CurBB. 1331 1332 // Emit the LHS condition. 1333 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc); 1334 1335 // Emit the RHS condition into TmpBB. 1336 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1337 } 1338 } 1339 1340 /// If the set of cases should be emitted as a series of branches, return true. 1341 /// If we should emit this as a bunch of and/or'd together conditions, return 1342 /// false. 1343 bool 1344 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){ 1345 if (Cases.size() != 2) return true; 1346 1347 // If this is two comparisons of the same values or'd or and'd together, they 1348 // will get folded into a single comparison, so don't emit two blocks. 1349 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1350 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1351 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1352 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1353 return false; 1354 } 1355 1356 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1357 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1358 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1359 Cases[0].CC == Cases[1].CC && 1360 isa<Constant>(Cases[0].CmpRHS) && 1361 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1362 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1363 return false; 1364 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1365 return false; 1366 } 1367 1368 return true; 1369 } 1370 1371 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1372 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1373 1374 // Update machine-CFG edges. 1375 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1376 1377 // Figure out which block is immediately after the current one. 1378 MachineBasicBlock *NextBlock = 0; 1379 MachineFunction::iterator BBI = BrMBB; 1380 if (++BBI != FuncInfo.MF->end()) 1381 NextBlock = BBI; 1382 1383 if (I.isUnconditional()) { 1384 // Update machine-CFG edges. 1385 BrMBB->addSuccessor(Succ0MBB); 1386 1387 // If this is not a fall-through branch, emit the branch. 1388 if (Succ0MBB != NextBlock) 1389 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1390 MVT::Other, getControlRoot(), 1391 DAG.getBasicBlock(Succ0MBB))); 1392 1393 return; 1394 } 1395 1396 // If this condition is one of the special cases we handle, do special stuff 1397 // now. 1398 const Value *CondVal = I.getCondition(); 1399 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1400 1401 // If this is a series of conditions that are or'd or and'd together, emit 1402 // this as a sequence of branches instead of setcc's with and/or operations. 1403 // As long as jumps are not expensive, this should improve performance. 1404 // For example, instead of something like: 1405 // cmp A, B 1406 // C = seteq 1407 // cmp D, E 1408 // F = setle 1409 // or C, F 1410 // jnz foo 1411 // Emit: 1412 // cmp A, B 1413 // je foo 1414 // cmp D, E 1415 // jle foo 1416 // 1417 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1418 if (!TLI.isJumpExpensive() && 1419 BOp->hasOneUse() && 1420 (BOp->getOpcode() == Instruction::And || 1421 BOp->getOpcode() == Instruction::Or)) { 1422 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1423 BOp->getOpcode()); 1424 // If the compares in later blocks need to use values not currently 1425 // exported from this block, export them now. This block should always 1426 // be the first entry. 1427 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1428 1429 // Allow some cases to be rejected. 1430 if (ShouldEmitAsBranches(SwitchCases)) { 1431 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1432 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1433 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1434 } 1435 1436 // Emit the branch for this block. 1437 visitSwitchCase(SwitchCases[0], BrMBB); 1438 SwitchCases.erase(SwitchCases.begin()); 1439 return; 1440 } 1441 1442 // Okay, we decided not to do this, remove any inserted MBB's and clear 1443 // SwitchCases. 1444 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1445 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1446 1447 SwitchCases.clear(); 1448 } 1449 } 1450 1451 // Create a CaseBlock record representing this branch. 1452 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1453 NULL, Succ0MBB, Succ1MBB, BrMBB); 1454 1455 // Use visitSwitchCase to actually insert the fast branch sequence for this 1456 // cond branch. 1457 visitSwitchCase(CB, BrMBB); 1458 } 1459 1460 /// visitSwitchCase - Emits the necessary code to represent a single node in 1461 /// the binary search tree resulting from lowering a switch instruction. 1462 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1463 MachineBasicBlock *SwitchBB) { 1464 SDValue Cond; 1465 SDValue CondLHS = getValue(CB.CmpLHS); 1466 DebugLoc dl = getCurDebugLoc(); 1467 1468 // Build the setcc now. 1469 if (CB.CmpMHS == NULL) { 1470 // Fold "(X == true)" to X and "(X == false)" to !X to 1471 // handle common cases produced by branch lowering. 1472 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1473 CB.CC == ISD::SETEQ) 1474 Cond = CondLHS; 1475 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1476 CB.CC == ISD::SETEQ) { 1477 SDValue True = DAG.getConstant(1, CondLHS.getValueType()); 1478 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1479 } else 1480 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1481 } else { 1482 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1483 1484 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1485 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1486 1487 SDValue CmpOp = getValue(CB.CmpMHS); 1488 EVT VT = CmpOp.getValueType(); 1489 1490 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1491 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), 1492 ISD::SETLE); 1493 } else { 1494 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1495 VT, CmpOp, DAG.getConstant(Low, VT)); 1496 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1497 DAG.getConstant(High-Low, VT), ISD::SETULE); 1498 } 1499 } 1500 1501 // Update successor info 1502 SwitchBB->addSuccessor(CB.TrueBB); 1503 SwitchBB->addSuccessor(CB.FalseBB); 1504 1505 // Set NextBlock to be the MBB immediately after the current one, if any. 1506 // This is used to avoid emitting unnecessary branches to the next block. 1507 MachineBasicBlock *NextBlock = 0; 1508 MachineFunction::iterator BBI = SwitchBB; 1509 if (++BBI != FuncInfo.MF->end()) 1510 NextBlock = BBI; 1511 1512 // If the lhs block is the next block, invert the condition so that we can 1513 // fall through to the lhs instead of the rhs block. 1514 if (CB.TrueBB == NextBlock) { 1515 std::swap(CB.TrueBB, CB.FalseBB); 1516 SDValue True = DAG.getConstant(1, Cond.getValueType()); 1517 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1518 } 1519 1520 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1521 MVT::Other, getControlRoot(), Cond, 1522 DAG.getBasicBlock(CB.TrueBB)); 1523 1524 // Insert the false branch. Do this even if it's a fall through branch, 1525 // this makes it easier to do DAG optimizations which require inverting 1526 // the branch condition. 1527 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1528 DAG.getBasicBlock(CB.FalseBB)); 1529 1530 DAG.setRoot(BrCond); 1531 } 1532 1533 /// visitJumpTable - Emit JumpTable node in the current MBB 1534 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1535 // Emit the code for the jump table 1536 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1537 EVT PTy = TLI.getPointerTy(); 1538 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), 1539 JT.Reg, PTy); 1540 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1541 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(), 1542 MVT::Other, Index.getValue(1), 1543 Table, Index); 1544 DAG.setRoot(BrJumpTable); 1545 } 1546 1547 /// visitJumpTableHeader - This function emits necessary code to produce index 1548 /// in the JumpTable from switch case. 1549 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1550 JumpTableHeader &JTH, 1551 MachineBasicBlock *SwitchBB) { 1552 // Subtract the lowest switch case value from the value being switched on and 1553 // conditional branch to default mbb if the result is greater than the 1554 // difference between smallest and largest cases. 1555 SDValue SwitchOp = getValue(JTH.SValue); 1556 EVT VT = SwitchOp.getValueType(); 1557 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1558 DAG.getConstant(JTH.First, VT)); 1559 1560 // The SDNode we just created, which holds the value being switched on minus 1561 // the smallest case value, needs to be copied to a virtual register so it 1562 // can be used as an index into the jump table in a subsequent basic block. 1563 // This value may be smaller or larger than the target's pointer type, and 1564 // therefore require extension or truncating. 1565 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy()); 1566 1567 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy()); 1568 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1569 JumpTableReg, SwitchOp); 1570 JT.Reg = JumpTableReg; 1571 1572 // Emit the range check for the jump table, and branch to the default block 1573 // for the switch statement if the value being switched on exceeds the largest 1574 // case in the switch. 1575 SDValue CMP = DAG.getSetCC(getCurDebugLoc(), 1576 TLI.getSetCCResultType(Sub.getValueType()), Sub, 1577 DAG.getConstant(JTH.Last-JTH.First,VT), 1578 ISD::SETUGT); 1579 1580 // Set NextBlock to be the MBB immediately after the current one, if any. 1581 // This is used to avoid emitting unnecessary branches to the next block. 1582 MachineBasicBlock *NextBlock = 0; 1583 MachineFunction::iterator BBI = SwitchBB; 1584 1585 if (++BBI != FuncInfo.MF->end()) 1586 NextBlock = BBI; 1587 1588 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1589 MVT::Other, CopyTo, CMP, 1590 DAG.getBasicBlock(JT.Default)); 1591 1592 if (JT.MBB != NextBlock) 1593 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond, 1594 DAG.getBasicBlock(JT.MBB)); 1595 1596 DAG.setRoot(BrCond); 1597 } 1598 1599 /// visitBitTestHeader - This function emits necessary code to produce value 1600 /// suitable for "bit tests" 1601 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1602 MachineBasicBlock *SwitchBB) { 1603 // Subtract the minimum value 1604 SDValue SwitchOp = getValue(B.SValue); 1605 EVT VT = SwitchOp.getValueType(); 1606 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1607 DAG.getConstant(B.First, VT)); 1608 1609 // Check range 1610 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(), 1611 TLI.getSetCCResultType(Sub.getValueType()), 1612 Sub, DAG.getConstant(B.Range, VT), 1613 ISD::SETUGT); 1614 1615 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), 1616 TLI.getPointerTy()); 1617 1618 B.Reg = FuncInfo.CreateReg(TLI.getPointerTy()); 1619 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1620 B.Reg, ShiftOp); 1621 1622 // Set NextBlock to be the MBB immediately after the current one, if any. 1623 // This is used to avoid emitting unnecessary branches to the next block. 1624 MachineBasicBlock *NextBlock = 0; 1625 MachineFunction::iterator BBI = SwitchBB; 1626 if (++BBI != FuncInfo.MF->end()) 1627 NextBlock = BBI; 1628 1629 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1630 1631 SwitchBB->addSuccessor(B.Default); 1632 SwitchBB->addSuccessor(MBB); 1633 1634 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1635 MVT::Other, CopyTo, RangeCmp, 1636 DAG.getBasicBlock(B.Default)); 1637 1638 if (MBB != NextBlock) 1639 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo, 1640 DAG.getBasicBlock(MBB)); 1641 1642 DAG.setRoot(BrRange); 1643 } 1644 1645 /// visitBitTestCase - this function produces one "bit test" 1646 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB, 1647 unsigned Reg, 1648 BitTestCase &B, 1649 MachineBasicBlock *SwitchBB) { 1650 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg, 1651 TLI.getPointerTy()); 1652 SDValue Cmp; 1653 if (CountPopulation_64(B.Mask) == 1) { 1654 // Testing for a single bit; just compare the shift count with what it 1655 // would need to be to shift a 1 bit in that position. 1656 Cmp = DAG.getSetCC(getCurDebugLoc(), 1657 TLI.getSetCCResultType(ShiftOp.getValueType()), 1658 ShiftOp, 1659 DAG.getConstant(CountTrailingZeros_64(B.Mask), 1660 TLI.getPointerTy()), 1661 ISD::SETEQ); 1662 } else { 1663 // Make desired shift 1664 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), 1665 TLI.getPointerTy(), 1666 DAG.getConstant(1, TLI.getPointerTy()), 1667 ShiftOp); 1668 1669 // Emit bit tests and jumps 1670 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), 1671 TLI.getPointerTy(), SwitchVal, 1672 DAG.getConstant(B.Mask, TLI.getPointerTy())); 1673 Cmp = DAG.getSetCC(getCurDebugLoc(), 1674 TLI.getSetCCResultType(AndOp.getValueType()), 1675 AndOp, DAG.getConstant(0, TLI.getPointerTy()), 1676 ISD::SETNE); 1677 } 1678 1679 SwitchBB->addSuccessor(B.TargetBB); 1680 SwitchBB->addSuccessor(NextMBB); 1681 1682 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1683 MVT::Other, getControlRoot(), 1684 Cmp, DAG.getBasicBlock(B.TargetBB)); 1685 1686 // Set NextBlock to be the MBB immediately after the current one, if any. 1687 // This is used to avoid emitting unnecessary branches to the next block. 1688 MachineBasicBlock *NextBlock = 0; 1689 MachineFunction::iterator BBI = SwitchBB; 1690 if (++BBI != FuncInfo.MF->end()) 1691 NextBlock = BBI; 1692 1693 if (NextMBB != NextBlock) 1694 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd, 1695 DAG.getBasicBlock(NextMBB)); 1696 1697 DAG.setRoot(BrAnd); 1698 } 1699 1700 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1701 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 1702 1703 // Retrieve successors. 1704 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1705 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1706 1707 const Value *Callee(I.getCalledValue()); 1708 if (isa<InlineAsm>(Callee)) 1709 visitInlineAsm(&I); 1710 else 1711 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1712 1713 // If the value of the invoke is used outside of its defining block, make it 1714 // available as a virtual register. 1715 CopyToExportRegsIfNeeded(&I); 1716 1717 // Update successor info 1718 InvokeMBB->addSuccessor(Return); 1719 InvokeMBB->addSuccessor(LandingPad); 1720 1721 // Drop into normal successor. 1722 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1723 MVT::Other, getControlRoot(), 1724 DAG.getBasicBlock(Return))); 1725 } 1726 1727 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) { 1728 } 1729 1730 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1731 /// small case ranges). 1732 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, 1733 CaseRecVector& WorkList, 1734 const Value* SV, 1735 MachineBasicBlock *Default, 1736 MachineBasicBlock *SwitchBB) { 1737 Case& BackCase = *(CR.Range.second-1); 1738 1739 // Size is the number of Cases represented by this range. 1740 size_t Size = CR.Range.second - CR.Range.first; 1741 if (Size > 3) 1742 return false; 1743 1744 // Get the MachineFunction which holds the current MBB. This is used when 1745 // inserting any additional MBBs necessary to represent the switch. 1746 MachineFunction *CurMF = FuncInfo.MF; 1747 1748 // Figure out which block is immediately after the current one. 1749 MachineBasicBlock *NextBlock = 0; 1750 MachineFunction::iterator BBI = CR.CaseBB; 1751 1752 if (++BBI != FuncInfo.MF->end()) 1753 NextBlock = BBI; 1754 1755 // If any two of the cases has the same destination, and if one value 1756 // is the same as the other, but has one bit unset that the other has set, 1757 // use bit manipulation to do two compares at once. For example: 1758 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1759 // TODO: This could be extended to merge any 2 cases in switches with 3 cases. 1760 // TODO: Handle cases where CR.CaseBB != SwitchBB. 1761 if (Size == 2 && CR.CaseBB == SwitchBB) { 1762 Case &Small = *CR.Range.first; 1763 Case &Big = *(CR.Range.second-1); 1764 1765 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) { 1766 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue(); 1767 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue(); 1768 1769 // Check that there is only one bit different. 1770 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 && 1771 (SmallValue | BigValue) == BigValue) { 1772 // Isolate the common bit. 1773 APInt CommonBit = BigValue & ~SmallValue; 1774 assert((SmallValue | CommonBit) == BigValue && 1775 CommonBit.countPopulation() == 1 && "Not a common bit?"); 1776 1777 SDValue CondLHS = getValue(SV); 1778 EVT VT = CondLHS.getValueType(); 1779 DebugLoc DL = getCurDebugLoc(); 1780 1781 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 1782 DAG.getConstant(CommonBit, VT)); 1783 SDValue Cond = DAG.getSetCC(DL, MVT::i1, 1784 Or, DAG.getConstant(BigValue, VT), 1785 ISD::SETEQ); 1786 1787 // Update successor info. 1788 SwitchBB->addSuccessor(Small.BB); 1789 SwitchBB->addSuccessor(Default); 1790 1791 // Insert the true branch. 1792 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other, 1793 getControlRoot(), Cond, 1794 DAG.getBasicBlock(Small.BB)); 1795 1796 // Insert the false branch. 1797 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 1798 DAG.getBasicBlock(Default)); 1799 1800 DAG.setRoot(BrCond); 1801 return true; 1802 } 1803 } 1804 } 1805 1806 // Rearrange the case blocks so that the last one falls through if possible. 1807 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1808 // The last case block won't fall through into 'NextBlock' if we emit the 1809 // branches in this order. See if rearranging a case value would help. 1810 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1811 if (I->BB == NextBlock) { 1812 std::swap(*I, BackCase); 1813 break; 1814 } 1815 } 1816 } 1817 1818 // Create a CaseBlock record representing a conditional branch to 1819 // the Case's target mbb if the value being switched on SV is equal 1820 // to C. 1821 MachineBasicBlock *CurBlock = CR.CaseBB; 1822 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1823 MachineBasicBlock *FallThrough; 1824 if (I != E-1) { 1825 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); 1826 CurMF->insert(BBI, FallThrough); 1827 1828 // Put SV in a virtual register to make it available from the new blocks. 1829 ExportFromCurrentBlock(SV); 1830 } else { 1831 // If the last case doesn't match, go to the default block. 1832 FallThrough = Default; 1833 } 1834 1835 const Value *RHS, *LHS, *MHS; 1836 ISD::CondCode CC; 1837 if (I->High == I->Low) { 1838 // This is just small small case range :) containing exactly 1 case 1839 CC = ISD::SETEQ; 1840 LHS = SV; RHS = I->High; MHS = NULL; 1841 } else { 1842 CC = ISD::SETLE; 1843 LHS = I->Low; MHS = SV; RHS = I->High; 1844 } 1845 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock); 1846 1847 // If emitting the first comparison, just call visitSwitchCase to emit the 1848 // code into the current block. Otherwise, push the CaseBlock onto the 1849 // vector to be later processed by SDISel, and insert the node's MBB 1850 // before the next MBB. 1851 if (CurBlock == SwitchBB) 1852 visitSwitchCase(CB, SwitchBB); 1853 else 1854 SwitchCases.push_back(CB); 1855 1856 CurBlock = FallThrough; 1857 } 1858 1859 return true; 1860 } 1861 1862 static inline bool areJTsAllowed(const TargetLowering &TLI) { 1863 return !DisableJumpTables && 1864 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 1865 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); 1866 } 1867 1868 static APInt ComputeRange(const APInt &First, const APInt &Last) { 1869 APInt LastExt(Last), FirstExt(First); 1870 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; 1871 LastExt.sext(BitWidth); FirstExt.sext(BitWidth); 1872 return (LastExt - FirstExt + 1ULL); 1873 } 1874 1875 /// handleJTSwitchCase - Emit jumptable for current switch case range 1876 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR, 1877 CaseRecVector& WorkList, 1878 const Value* SV, 1879 MachineBasicBlock* Default, 1880 MachineBasicBlock *SwitchBB) { 1881 Case& FrontCase = *CR.Range.first; 1882 Case& BackCase = *(CR.Range.second-1); 1883 1884 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1885 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1886 1887 APInt TSize(First.getBitWidth(), 0); 1888 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1889 I!=E; ++I) 1890 TSize += I->size(); 1891 1892 if (!areJTsAllowed(TLI) || TSize.ult(4)) 1893 return false; 1894 1895 APInt Range = ComputeRange(First, Last); 1896 double Density = TSize.roundToDouble() / Range.roundToDouble(); 1897 if (Density < 0.4) 1898 return false; 1899 1900 DEBUG(dbgs() << "Lowering jump table\n" 1901 << "First entry: " << First << ". Last entry: " << Last << '\n' 1902 << "Range: " << Range 1903 << "Size: " << TSize << ". Density: " << Density << "\n\n"); 1904 1905 // Get the MachineFunction which holds the current MBB. This is used when 1906 // inserting any additional MBBs necessary to represent the switch. 1907 MachineFunction *CurMF = FuncInfo.MF; 1908 1909 // Figure out which block is immediately after the current one. 1910 MachineFunction::iterator BBI = CR.CaseBB; 1911 ++BBI; 1912 1913 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1914 1915 // Create a new basic block to hold the code for loading the address 1916 // of the jump table, and jumping to it. Update successor information; 1917 // we will either branch to the default case for the switch, or the jump 1918 // table. 1919 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1920 CurMF->insert(BBI, JumpTableBB); 1921 CR.CaseBB->addSuccessor(Default); 1922 CR.CaseBB->addSuccessor(JumpTableBB); 1923 1924 // Build a vector of destination BBs, corresponding to each target 1925 // of the jump table. If the value of the jump table slot corresponds to 1926 // a case statement, push the case's BB onto the vector, otherwise, push 1927 // the default BB. 1928 std::vector<MachineBasicBlock*> DestBBs; 1929 APInt TEI = First; 1930 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 1931 const APInt &Low = cast<ConstantInt>(I->Low)->getValue(); 1932 const APInt &High = cast<ConstantInt>(I->High)->getValue(); 1933 1934 if (Low.sle(TEI) && TEI.sle(High)) { 1935 DestBBs.push_back(I->BB); 1936 if (TEI==High) 1937 ++I; 1938 } else { 1939 DestBBs.push_back(Default); 1940 } 1941 } 1942 1943 // Update successor info. Add one edge to each unique successor. 1944 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 1945 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 1946 E = DestBBs.end(); I != E; ++I) { 1947 if (!SuccsHandled[(*I)->getNumber()]) { 1948 SuccsHandled[(*I)->getNumber()] = true; 1949 JumpTableBB->addSuccessor(*I); 1950 } 1951 } 1952 1953 // Create a jump table index for this jump table. 1954 unsigned JTEncoding = TLI.getJumpTableEncoding(); 1955 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) 1956 ->createJumpTableIndex(DestBBs); 1957 1958 // Set the jump table information so that we can codegen it as a second 1959 // MachineBasicBlock 1960 JumpTable JT(-1U, JTI, JumpTableBB, Default); 1961 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB)); 1962 if (CR.CaseBB == SwitchBB) 1963 visitJumpTableHeader(JT, JTH, SwitchBB); 1964 1965 JTCases.push_back(JumpTableBlock(JTH, JT)); 1966 1967 return true; 1968 } 1969 1970 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1971 /// 2 subtrees. 1972 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 1973 CaseRecVector& WorkList, 1974 const Value* SV, 1975 MachineBasicBlock *Default, 1976 MachineBasicBlock *SwitchBB) { 1977 // Get the MachineFunction which holds the current MBB. This is used when 1978 // inserting any additional MBBs necessary to represent the switch. 1979 MachineFunction *CurMF = FuncInfo.MF; 1980 1981 // Figure out which block is immediately after the current one. 1982 MachineFunction::iterator BBI = CR.CaseBB; 1983 ++BBI; 1984 1985 Case& FrontCase = *CR.Range.first; 1986 Case& BackCase = *(CR.Range.second-1); 1987 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1988 1989 // Size is the number of Cases represented by this range. 1990 unsigned Size = CR.Range.second - CR.Range.first; 1991 1992 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1993 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1994 double FMetric = 0; 1995 CaseItr Pivot = CR.Range.first + Size/2; 1996 1997 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1998 // (heuristically) allow us to emit JumpTable's later. 1999 APInt TSize(First.getBitWidth(), 0); 2000 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2001 I!=E; ++I) 2002 TSize += I->size(); 2003 2004 APInt LSize = FrontCase.size(); 2005 APInt RSize = TSize-LSize; 2006 DEBUG(dbgs() << "Selecting best pivot: \n" 2007 << "First: " << First << ", Last: " << Last <<'\n' 2008 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 2009 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 2010 J!=E; ++I, ++J) { 2011 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 2012 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 2013 APInt Range = ComputeRange(LEnd, RBegin); 2014 assert((Range - 2ULL).isNonNegative() && 2015 "Invalid case distance"); 2016 double LDensity = (double)LSize.roundToDouble() / 2017 (LEnd - First + 1ULL).roundToDouble(); 2018 double RDensity = (double)RSize.roundToDouble() / 2019 (Last - RBegin + 1ULL).roundToDouble(); 2020 double Metric = Range.logBase2()*(LDensity+RDensity); 2021 // Should always split in some non-trivial place 2022 DEBUG(dbgs() <<"=>Step\n" 2023 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 2024 << "LDensity: " << LDensity 2025 << ", RDensity: " << RDensity << '\n' 2026 << "Metric: " << Metric << '\n'); 2027 if (FMetric < Metric) { 2028 Pivot = J; 2029 FMetric = Metric; 2030 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); 2031 } 2032 2033 LSize += J->size(); 2034 RSize -= J->size(); 2035 } 2036 if (areJTsAllowed(TLI)) { 2037 // If our case is dense we *really* should handle it earlier! 2038 assert((FMetric > 0) && "Should handle dense range earlier!"); 2039 } else { 2040 Pivot = CR.Range.first + Size/2; 2041 } 2042 2043 CaseRange LHSR(CR.Range.first, Pivot); 2044 CaseRange RHSR(Pivot, CR.Range.second); 2045 Constant *C = Pivot->Low; 2046 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 2047 2048 // We know that we branch to the LHS if the Value being switched on is 2049 // less than the Pivot value, C. We use this to optimize our binary 2050 // tree a bit, by recognizing that if SV is greater than or equal to the 2051 // LHS's Case Value, and that Case Value is exactly one less than the 2052 // Pivot's Value, then we can branch directly to the LHS's Target, 2053 // rather than creating a leaf node for it. 2054 if ((LHSR.second - LHSR.first) == 1 && 2055 LHSR.first->High == CR.GE && 2056 cast<ConstantInt>(C)->getValue() == 2057 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 2058 TrueBB = LHSR.first->BB; 2059 } else { 2060 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2061 CurMF->insert(BBI, TrueBB); 2062 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 2063 2064 // Put SV in a virtual register to make it available from the new blocks. 2065 ExportFromCurrentBlock(SV); 2066 } 2067 2068 // Similar to the optimization above, if the Value being switched on is 2069 // known to be less than the Constant CR.LT, and the current Case Value 2070 // is CR.LT - 1, then we can branch directly to the target block for 2071 // the current Case Value, rather than emitting a RHS leaf node for it. 2072 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 2073 cast<ConstantInt>(RHSR.first->Low)->getValue() == 2074 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 2075 FalseBB = RHSR.first->BB; 2076 } else { 2077 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2078 CurMF->insert(BBI, FalseBB); 2079 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 2080 2081 // Put SV in a virtual register to make it available from the new blocks. 2082 ExportFromCurrentBlock(SV); 2083 } 2084 2085 // Create a CaseBlock record representing a conditional branch to 2086 // the LHS node if the value being switched on SV is less than C. 2087 // Otherwise, branch to LHS. 2088 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 2089 2090 if (CR.CaseBB == SwitchBB) 2091 visitSwitchCase(CB, SwitchBB); 2092 else 2093 SwitchCases.push_back(CB); 2094 2095 return true; 2096 } 2097 2098 /// handleBitTestsSwitchCase - if current case range has few destination and 2099 /// range span less, than machine word bitwidth, encode case range into series 2100 /// of masks and emit bit tests with these masks. 2101 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 2102 CaseRecVector& WorkList, 2103 const Value* SV, 2104 MachineBasicBlock* Default, 2105 MachineBasicBlock *SwitchBB){ 2106 EVT PTy = TLI.getPointerTy(); 2107 unsigned IntPtrBits = PTy.getSizeInBits(); 2108 2109 Case& FrontCase = *CR.Range.first; 2110 Case& BackCase = *(CR.Range.second-1); 2111 2112 // Get the MachineFunction which holds the current MBB. This is used when 2113 // inserting any additional MBBs necessary to represent the switch. 2114 MachineFunction *CurMF = FuncInfo.MF; 2115 2116 // If target does not have legal shift left, do not emit bit tests at all. 2117 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) 2118 return false; 2119 2120 size_t numCmps = 0; 2121 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2122 I!=E; ++I) { 2123 // Single case counts one, case range - two. 2124 numCmps += (I->Low == I->High ? 1 : 2); 2125 } 2126 2127 // Count unique destinations 2128 SmallSet<MachineBasicBlock*, 4> Dests; 2129 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2130 Dests.insert(I->BB); 2131 if (Dests.size() > 3) 2132 // Don't bother the code below, if there are too much unique destinations 2133 return false; 2134 } 2135 DEBUG(dbgs() << "Total number of unique destinations: " 2136 << Dests.size() << '\n' 2137 << "Total number of comparisons: " << numCmps << '\n'); 2138 2139 // Compute span of values. 2140 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 2141 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 2142 APInt cmpRange = maxValue - minValue; 2143 2144 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n' 2145 << "Low bound: " << minValue << '\n' 2146 << "High bound: " << maxValue << '\n'); 2147 2148 if (cmpRange.uge(IntPtrBits) || 2149 (!(Dests.size() == 1 && numCmps >= 3) && 2150 !(Dests.size() == 2 && numCmps >= 5) && 2151 !(Dests.size() >= 3 && numCmps >= 6))) 2152 return false; 2153 2154 DEBUG(dbgs() << "Emitting bit tests\n"); 2155 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 2156 2157 // Optimize the case where all the case values fit in a 2158 // word without having to subtract minValue. In this case, 2159 // we can optimize away the subtraction. 2160 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) { 2161 cmpRange = maxValue; 2162 } else { 2163 lowBound = minValue; 2164 } 2165 2166 CaseBitsVector CasesBits; 2167 unsigned i, count = 0; 2168 2169 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2170 MachineBasicBlock* Dest = I->BB; 2171 for (i = 0; i < count; ++i) 2172 if (Dest == CasesBits[i].BB) 2173 break; 2174 2175 if (i == count) { 2176 assert((count < 3) && "Too much destinations to test!"); 2177 CasesBits.push_back(CaseBits(0, Dest, 0)); 2178 count++; 2179 } 2180 2181 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 2182 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 2183 2184 uint64_t lo = (lowValue - lowBound).getZExtValue(); 2185 uint64_t hi = (highValue - lowBound).getZExtValue(); 2186 2187 for (uint64_t j = lo; j <= hi; j++) { 2188 CasesBits[i].Mask |= 1ULL << j; 2189 CasesBits[i].Bits++; 2190 } 2191 2192 } 2193 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 2194 2195 BitTestInfo BTC; 2196 2197 // Figure out which block is immediately after the current one. 2198 MachineFunction::iterator BBI = CR.CaseBB; 2199 ++BBI; 2200 2201 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2202 2203 DEBUG(dbgs() << "Cases:\n"); 2204 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 2205 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask 2206 << ", Bits: " << CasesBits[i].Bits 2207 << ", BB: " << CasesBits[i].BB << '\n'); 2208 2209 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2210 CurMF->insert(BBI, CaseBB); 2211 BTC.push_back(BitTestCase(CasesBits[i].Mask, 2212 CaseBB, 2213 CasesBits[i].BB)); 2214 2215 // Put SV in a virtual register to make it available from the new blocks. 2216 ExportFromCurrentBlock(SV); 2217 } 2218 2219 BitTestBlock BTB(lowBound, cmpRange, SV, 2220 -1U, (CR.CaseBB == SwitchBB), 2221 CR.CaseBB, Default, BTC); 2222 2223 if (CR.CaseBB == SwitchBB) 2224 visitBitTestHeader(BTB, SwitchBB); 2225 2226 BitTestCases.push_back(BTB); 2227 2228 return true; 2229 } 2230 2231 /// Clusterify - Transform simple list of Cases into list of CaseRange's 2232 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 2233 const SwitchInst& SI) { 2234 size_t numCmps = 0; 2235 2236 // Start with "simple" cases 2237 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) { 2238 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 2239 Cases.push_back(Case(SI.getSuccessorValue(i), 2240 SI.getSuccessorValue(i), 2241 SMBB)); 2242 } 2243 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 2244 2245 // Merge case into clusters 2246 if (Cases.size() >= 2) 2247 // Must recompute end() each iteration because it may be 2248 // invalidated by erase if we hold on to it 2249 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) { 2250 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue(); 2251 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue(); 2252 MachineBasicBlock* nextBB = J->BB; 2253 MachineBasicBlock* currentBB = I->BB; 2254 2255 // If the two neighboring cases go to the same destination, merge them 2256 // into a single case. 2257 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) { 2258 I->High = J->High; 2259 J = Cases.erase(J); 2260 } else { 2261 I = J++; 2262 } 2263 } 2264 2265 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 2266 if (I->Low != I->High) 2267 // A range counts double, since it requires two compares. 2268 ++numCmps; 2269 } 2270 2271 return numCmps; 2272 } 2273 2274 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2275 MachineBasicBlock *Last) { 2276 // Update JTCases. 2277 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2278 if (JTCases[i].first.HeaderBB == First) 2279 JTCases[i].first.HeaderBB = Last; 2280 2281 // Update BitTestCases. 2282 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2283 if (BitTestCases[i].Parent == First) 2284 BitTestCases[i].Parent = Last; 2285 } 2286 2287 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 2288 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 2289 2290 // Figure out which block is immediately after the current one. 2291 MachineBasicBlock *NextBlock = 0; 2292 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2293 2294 // If there is only the default destination, branch to it if it is not the 2295 // next basic block. Otherwise, just fall through. 2296 if (SI.getNumOperands() == 2) { 2297 // Update machine-CFG edges. 2298 2299 // If this is not a fall-through branch, emit the branch. 2300 SwitchMBB->addSuccessor(Default); 2301 if (Default != NextBlock) 2302 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 2303 MVT::Other, getControlRoot(), 2304 DAG.getBasicBlock(Default))); 2305 2306 return; 2307 } 2308 2309 // If there are any non-default case statements, create a vector of Cases 2310 // representing each one, and sort the vector so that we can efficiently 2311 // create a binary search tree from them. 2312 CaseVector Cases; 2313 size_t numCmps = Clusterify(Cases, SI); 2314 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 2315 << ". Total compares: " << numCmps << '\n'); 2316 numCmps = 0; 2317 2318 // Get the Value to be switched on and default basic blocks, which will be 2319 // inserted into CaseBlock records, representing basic blocks in the binary 2320 // search tree. 2321 const Value *SV = SI.getOperand(0); 2322 2323 // Push the initial CaseRec onto the worklist 2324 CaseRecVector WorkList; 2325 WorkList.push_back(CaseRec(SwitchMBB,0,0, 2326 CaseRange(Cases.begin(),Cases.end()))); 2327 2328 while (!WorkList.empty()) { 2329 // Grab a record representing a case range to process off the worklist 2330 CaseRec CR = WorkList.back(); 2331 WorkList.pop_back(); 2332 2333 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2334 continue; 2335 2336 // If the range has few cases (two or less) emit a series of specific 2337 // tests. 2338 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB)) 2339 continue; 2340 2341 // If the switch has more than 5 blocks, and at least 40% dense, and the 2342 // target supports indirect branches, then emit a jump table rather than 2343 // lowering the switch to a binary tree of conditional branches. 2344 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2345 continue; 2346 2347 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2348 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2349 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB); 2350 } 2351 } 2352 2353 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2354 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2355 2356 // Update machine-CFG edges with unique successors. 2357 SmallVector<BasicBlock*, 32> succs; 2358 succs.reserve(I.getNumSuccessors()); 2359 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) 2360 succs.push_back(I.getSuccessor(i)); 2361 array_pod_sort(succs.begin(), succs.end()); 2362 succs.erase(std::unique(succs.begin(), succs.end()), succs.end()); 2363 for (unsigned i = 0, e = succs.size(); i != e; ++i) 2364 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]); 2365 2366 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(), 2367 MVT::Other, getControlRoot(), 2368 getValue(I.getAddress()))); 2369 } 2370 2371 void SelectionDAGBuilder::visitFSub(const User &I) { 2372 // -0.0 - X --> fneg 2373 const Type *Ty = I.getType(); 2374 if (Ty->isVectorTy()) { 2375 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) { 2376 const VectorType *DestTy = cast<VectorType>(I.getType()); 2377 const Type *ElTy = DestTy->getElementType(); 2378 unsigned VL = DestTy->getNumElements(); 2379 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy)); 2380 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size()); 2381 if (CV == CNZ) { 2382 SDValue Op2 = getValue(I.getOperand(1)); 2383 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2384 Op2.getValueType(), Op2)); 2385 return; 2386 } 2387 } 2388 } 2389 2390 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 2391 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) { 2392 SDValue Op2 = getValue(I.getOperand(1)); 2393 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2394 Op2.getValueType(), Op2)); 2395 return; 2396 } 2397 2398 visitBinary(I, ISD::FSUB); 2399 } 2400 2401 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2402 SDValue Op1 = getValue(I.getOperand(0)); 2403 SDValue Op2 = getValue(I.getOperand(1)); 2404 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(), 2405 Op1.getValueType(), Op1, Op2)); 2406 } 2407 2408 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2409 SDValue Op1 = getValue(I.getOperand(0)); 2410 SDValue Op2 = getValue(I.getOperand(1)); 2411 if (!I.getType()->isVectorTy() && 2412 Op2.getValueType() != TLI.getShiftAmountTy()) { 2413 // If the operand is smaller than the shift count type, promote it. 2414 EVT PTy = TLI.getPointerTy(); 2415 EVT STy = TLI.getShiftAmountTy(); 2416 if (STy.bitsGT(Op2.getValueType())) 2417 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2418 TLI.getShiftAmountTy(), Op2); 2419 // If the operand is larger than the shift count type but the shift 2420 // count type has enough bits to represent any shift value, truncate 2421 // it now. This is a common case and it exposes the truncate to 2422 // optimization early. 2423 else if (STy.getSizeInBits() >= 2424 Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2425 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2426 TLI.getShiftAmountTy(), Op2); 2427 // Otherwise we'll need to temporarily settle for some other 2428 // convenient type; type legalization will make adjustments as 2429 // needed. 2430 else if (PTy.bitsLT(Op2.getValueType())) 2431 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2432 TLI.getPointerTy(), Op2); 2433 else if (PTy.bitsGT(Op2.getValueType())) 2434 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2435 TLI.getPointerTy(), Op2); 2436 } 2437 2438 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), 2439 Op1.getValueType(), Op1, Op2)); 2440 } 2441 2442 void SelectionDAGBuilder::visitICmp(const User &I) { 2443 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2444 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2445 predicate = IC->getPredicate(); 2446 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2447 predicate = ICmpInst::Predicate(IC->getPredicate()); 2448 SDValue Op1 = getValue(I.getOperand(0)); 2449 SDValue Op2 = getValue(I.getOperand(1)); 2450 ISD::CondCode Opcode = getICmpCondCode(predicate); 2451 2452 EVT DestVT = TLI.getValueType(I.getType()); 2453 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode)); 2454 } 2455 2456 void SelectionDAGBuilder::visitFCmp(const User &I) { 2457 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2458 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2459 predicate = FC->getPredicate(); 2460 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2461 predicate = FCmpInst::Predicate(FC->getPredicate()); 2462 SDValue Op1 = getValue(I.getOperand(0)); 2463 SDValue Op2 = getValue(I.getOperand(1)); 2464 ISD::CondCode Condition = getFCmpCondCode(predicate); 2465 EVT DestVT = TLI.getValueType(I.getType()); 2466 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition)); 2467 } 2468 2469 void SelectionDAGBuilder::visitSelect(const User &I) { 2470 SmallVector<EVT, 4> ValueVTs; 2471 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2472 unsigned NumValues = ValueVTs.size(); 2473 if (NumValues == 0) return; 2474 2475 SmallVector<SDValue, 4> Values(NumValues); 2476 SDValue Cond = getValue(I.getOperand(0)); 2477 SDValue TrueVal = getValue(I.getOperand(1)); 2478 SDValue FalseVal = getValue(I.getOperand(2)); 2479 2480 for (unsigned i = 0; i != NumValues; ++i) 2481 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 2482 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i), 2483 Cond, 2484 SDValue(TrueVal.getNode(), 2485 TrueVal.getResNo() + i), 2486 SDValue(FalseVal.getNode(), 2487 FalseVal.getResNo() + i)); 2488 2489 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2490 DAG.getVTList(&ValueVTs[0], NumValues), 2491 &Values[0], NumValues)); 2492 } 2493 2494 void SelectionDAGBuilder::visitTrunc(const User &I) { 2495 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2496 SDValue N = getValue(I.getOperand(0)); 2497 EVT DestVT = TLI.getValueType(I.getType()); 2498 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N)); 2499 } 2500 2501 void SelectionDAGBuilder::visitZExt(const User &I) { 2502 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2503 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2504 SDValue N = getValue(I.getOperand(0)); 2505 EVT DestVT = TLI.getValueType(I.getType()); 2506 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N)); 2507 } 2508 2509 void SelectionDAGBuilder::visitSExt(const User &I) { 2510 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2511 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2512 SDValue N = getValue(I.getOperand(0)); 2513 EVT DestVT = TLI.getValueType(I.getType()); 2514 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N)); 2515 } 2516 2517 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2518 // FPTrunc is never a no-op cast, no need to check 2519 SDValue N = getValue(I.getOperand(0)); 2520 EVT DestVT = TLI.getValueType(I.getType()); 2521 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 2522 DestVT, N, DAG.getIntPtrConstant(0))); 2523 } 2524 2525 void SelectionDAGBuilder::visitFPExt(const User &I){ 2526 // FPTrunc is never a no-op cast, no need to check 2527 SDValue N = getValue(I.getOperand(0)); 2528 EVT DestVT = TLI.getValueType(I.getType()); 2529 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N)); 2530 } 2531 2532 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2533 // FPToUI is never a no-op cast, no need to check 2534 SDValue N = getValue(I.getOperand(0)); 2535 EVT DestVT = TLI.getValueType(I.getType()); 2536 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N)); 2537 } 2538 2539 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2540 // FPToSI is never a no-op cast, no need to check 2541 SDValue N = getValue(I.getOperand(0)); 2542 EVT DestVT = TLI.getValueType(I.getType()); 2543 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N)); 2544 } 2545 2546 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2547 // UIToFP is never a no-op cast, no need to check 2548 SDValue N = getValue(I.getOperand(0)); 2549 EVT DestVT = TLI.getValueType(I.getType()); 2550 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2551 } 2552 2553 void SelectionDAGBuilder::visitSIToFP(const User &I){ 2554 // SIToFP is never a no-op cast, no need to check 2555 SDValue N = getValue(I.getOperand(0)); 2556 EVT DestVT = TLI.getValueType(I.getType()); 2557 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2558 } 2559 2560 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2561 // What to do depends on the size of the integer and the size of the pointer. 2562 // We can either truncate, zero extend, or no-op, accordingly. 2563 SDValue N = getValue(I.getOperand(0)); 2564 EVT DestVT = TLI.getValueType(I.getType()); 2565 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2566 } 2567 2568 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2569 // What to do depends on the size of the integer and the size of the pointer. 2570 // We can either truncate, zero extend, or no-op, accordingly. 2571 SDValue N = getValue(I.getOperand(0)); 2572 EVT DestVT = TLI.getValueType(I.getType()); 2573 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2574 } 2575 2576 void SelectionDAGBuilder::visitBitCast(const User &I) { 2577 SDValue N = getValue(I.getOperand(0)); 2578 EVT DestVT = TLI.getValueType(I.getType()); 2579 2580 // BitCast assures us that source and destination are the same size so this is 2581 // either a BITCAST or a no-op. 2582 if (DestVT != N.getValueType()) 2583 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 2584 DestVT, N)); // convert types. 2585 else 2586 setValue(&I, N); // noop cast. 2587 } 2588 2589 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2590 SDValue InVec = getValue(I.getOperand(0)); 2591 SDValue InVal = getValue(I.getOperand(1)); 2592 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2593 TLI.getPointerTy(), 2594 getValue(I.getOperand(2))); 2595 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 2596 TLI.getValueType(I.getType()), 2597 InVec, InVal, InIdx)); 2598 } 2599 2600 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2601 SDValue InVec = getValue(I.getOperand(0)); 2602 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2603 TLI.getPointerTy(), 2604 getValue(I.getOperand(1))); 2605 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2606 TLI.getValueType(I.getType()), InVec, InIdx)); 2607 } 2608 2609 // Utility for visitShuffleVector - Returns true if the mask is mask starting 2610 // from SIndx and increasing to the element length (undefs are allowed). 2611 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) { 2612 unsigned MaskNumElts = Mask.size(); 2613 for (unsigned i = 0; i != MaskNumElts; ++i) 2614 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx))) 2615 return false; 2616 return true; 2617 } 2618 2619 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2620 SmallVector<int, 8> Mask; 2621 SDValue Src1 = getValue(I.getOperand(0)); 2622 SDValue Src2 = getValue(I.getOperand(1)); 2623 2624 // Convert the ConstantVector mask operand into an array of ints, with -1 2625 // representing undef values. 2626 SmallVector<Constant*, 8> MaskElts; 2627 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts); 2628 unsigned MaskNumElts = MaskElts.size(); 2629 for (unsigned i = 0; i != MaskNumElts; ++i) { 2630 if (isa<UndefValue>(MaskElts[i])) 2631 Mask.push_back(-1); 2632 else 2633 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue()); 2634 } 2635 2636 EVT VT = TLI.getValueType(I.getType()); 2637 EVT SrcVT = Src1.getValueType(); 2638 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2639 2640 if (SrcNumElts == MaskNumElts) { 2641 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2642 &Mask[0])); 2643 return; 2644 } 2645 2646 // Normalize the shuffle vector since mask and vector length don't match. 2647 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2648 // Mask is longer than the source vectors and is a multiple of the source 2649 // vectors. We can use concatenate vector to make the mask and vectors 2650 // lengths match. 2651 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) { 2652 // The shuffle is concatenating two vectors together. 2653 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 2654 VT, Src1, Src2)); 2655 return; 2656 } 2657 2658 // Pad both vectors with undefs to make them the same length as the mask. 2659 unsigned NumConcat = MaskNumElts / SrcNumElts; 2660 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2661 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2662 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2663 2664 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2665 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2666 MOps1[0] = Src1; 2667 MOps2[0] = Src2; 2668 2669 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2670 getCurDebugLoc(), VT, 2671 &MOps1[0], NumConcat); 2672 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2673 getCurDebugLoc(), VT, 2674 &MOps2[0], NumConcat); 2675 2676 // Readjust mask for new input vector length. 2677 SmallVector<int, 8> MappedOps; 2678 for (unsigned i = 0; i != MaskNumElts; ++i) { 2679 int Idx = Mask[i]; 2680 if (Idx < (int)SrcNumElts) 2681 MappedOps.push_back(Idx); 2682 else 2683 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); 2684 } 2685 2686 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2687 &MappedOps[0])); 2688 return; 2689 } 2690 2691 if (SrcNumElts > MaskNumElts) { 2692 // Analyze the access pattern of the vector to see if we can extract 2693 // two subvectors and do the shuffle. The analysis is done by calculating 2694 // the range of elements the mask access on both vectors. 2695 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1}; 2696 int MaxRange[2] = {-1, -1}; 2697 2698 for (unsigned i = 0; i != MaskNumElts; ++i) { 2699 int Idx = Mask[i]; 2700 int Input = 0; 2701 if (Idx < 0) 2702 continue; 2703 2704 if (Idx >= (int)SrcNumElts) { 2705 Input = 1; 2706 Idx -= SrcNumElts; 2707 } 2708 if (Idx > MaxRange[Input]) 2709 MaxRange[Input] = Idx; 2710 if (Idx < MinRange[Input]) 2711 MinRange[Input] = Idx; 2712 } 2713 2714 // Check if the access is smaller than the vector size and can we find 2715 // a reasonable extract index. 2716 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not 2717 // Extract. 2718 int StartIdx[2]; // StartIdx to extract from 2719 for (int Input=0; Input < 2; ++Input) { 2720 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { 2721 RangeUse[Input] = 0; // Unused 2722 StartIdx[Input] = 0; 2723 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) { 2724 // Fits within range but we should see if we can find a good 2725 // start index that is a multiple of the mask length. 2726 if (MaxRange[Input] < (int)MaskNumElts) { 2727 RangeUse[Input] = 1; // Extract from beginning of the vector 2728 StartIdx[Input] = 0; 2729 } else { 2730 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2731 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2732 StartIdx[Input] + MaskNumElts < SrcNumElts) 2733 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2734 } 2735 } 2736 } 2737 2738 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2739 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 2740 return; 2741 } 2742 else if (RangeUse[0] < 2 && RangeUse[1] < 2) { 2743 // Extract appropriate subvector and generate a vector shuffle 2744 for (int Input=0; Input < 2; ++Input) { 2745 SDValue &Src = Input == 0 ? Src1 : Src2; 2746 if (RangeUse[Input] == 0) 2747 Src = DAG.getUNDEF(VT); 2748 else 2749 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT, 2750 Src, DAG.getIntPtrConstant(StartIdx[Input])); 2751 } 2752 2753 // Calculate new mask. 2754 SmallVector<int, 8> MappedOps; 2755 for (unsigned i = 0; i != MaskNumElts; ++i) { 2756 int Idx = Mask[i]; 2757 if (Idx < 0) 2758 MappedOps.push_back(Idx); 2759 else if (Idx < (int)SrcNumElts) 2760 MappedOps.push_back(Idx - StartIdx[0]); 2761 else 2762 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts); 2763 } 2764 2765 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2766 &MappedOps[0])); 2767 return; 2768 } 2769 } 2770 2771 // We can't use either concat vectors or extract subvectors so fall back to 2772 // replacing the shuffle with extract and build vector. 2773 // to insert and build vector. 2774 EVT EltVT = VT.getVectorElementType(); 2775 EVT PtrVT = TLI.getPointerTy(); 2776 SmallVector<SDValue,8> Ops; 2777 for (unsigned i = 0; i != MaskNumElts; ++i) { 2778 if (Mask[i] < 0) { 2779 Ops.push_back(DAG.getUNDEF(EltVT)); 2780 } else { 2781 int Idx = Mask[i]; 2782 SDValue Res; 2783 2784 if (Idx < (int)SrcNumElts) 2785 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2786 EltVT, Src1, DAG.getConstant(Idx, PtrVT)); 2787 else 2788 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2789 EltVT, Src2, 2790 DAG.getConstant(Idx - SrcNumElts, PtrVT)); 2791 2792 Ops.push_back(Res); 2793 } 2794 } 2795 2796 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 2797 VT, &Ops[0], Ops.size())); 2798 } 2799 2800 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 2801 const Value *Op0 = I.getOperand(0); 2802 const Value *Op1 = I.getOperand(1); 2803 const Type *AggTy = I.getType(); 2804 const Type *ValTy = Op1->getType(); 2805 bool IntoUndef = isa<UndefValue>(Op0); 2806 bool FromUndef = isa<UndefValue>(Op1); 2807 2808 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end()); 2809 2810 SmallVector<EVT, 4> AggValueVTs; 2811 ComputeValueVTs(TLI, AggTy, AggValueVTs); 2812 SmallVector<EVT, 4> ValValueVTs; 2813 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2814 2815 unsigned NumAggValues = AggValueVTs.size(); 2816 unsigned NumValValues = ValValueVTs.size(); 2817 SmallVector<SDValue, 4> Values(NumAggValues); 2818 2819 SDValue Agg = getValue(Op0); 2820 SDValue Val = getValue(Op1); 2821 unsigned i = 0; 2822 // Copy the beginning value(s) from the original aggregate. 2823 for (; i != LinearIndex; ++i) 2824 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2825 SDValue(Agg.getNode(), Agg.getResNo() + i); 2826 // Copy values from the inserted value(s). 2827 for (; i != LinearIndex + NumValValues; ++i) 2828 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2829 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2830 // Copy remaining value(s) from the original aggregate. 2831 for (; i != NumAggValues; ++i) 2832 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2833 SDValue(Agg.getNode(), Agg.getResNo() + i); 2834 2835 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2836 DAG.getVTList(&AggValueVTs[0], NumAggValues), 2837 &Values[0], NumAggValues)); 2838 } 2839 2840 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 2841 const Value *Op0 = I.getOperand(0); 2842 const Type *AggTy = Op0->getType(); 2843 const Type *ValTy = I.getType(); 2844 bool OutOfUndef = isa<UndefValue>(Op0); 2845 2846 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end()); 2847 2848 SmallVector<EVT, 4> ValValueVTs; 2849 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2850 2851 unsigned NumValValues = ValValueVTs.size(); 2852 SmallVector<SDValue, 4> Values(NumValValues); 2853 2854 SDValue Agg = getValue(Op0); 2855 // Copy out the selected value(s). 2856 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2857 Values[i - LinearIndex] = 2858 OutOfUndef ? 2859 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2860 SDValue(Agg.getNode(), Agg.getResNo() + i); 2861 2862 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2863 DAG.getVTList(&ValValueVTs[0], NumValValues), 2864 &Values[0], NumValValues)); 2865 } 2866 2867 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 2868 SDValue N = getValue(I.getOperand(0)); 2869 const Type *Ty = I.getOperand(0)->getType(); 2870 2871 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 2872 OI != E; ++OI) { 2873 const Value *Idx = *OI; 2874 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2875 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2876 if (Field) { 2877 // N = N + Offset 2878 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2879 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2880 DAG.getIntPtrConstant(Offset)); 2881 } 2882 2883 Ty = StTy->getElementType(Field); 2884 } else { 2885 Ty = cast<SequentialType>(Ty)->getElementType(); 2886 2887 // If this is a constant subscript, handle it quickly. 2888 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2889 if (CI->isZero()) continue; 2890 uint64_t Offs = 2891 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2892 SDValue OffsVal; 2893 EVT PTy = TLI.getPointerTy(); 2894 unsigned PtrBits = PTy.getSizeInBits(); 2895 if (PtrBits < 64) 2896 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2897 TLI.getPointerTy(), 2898 DAG.getConstant(Offs, MVT::i64)); 2899 else 2900 OffsVal = DAG.getIntPtrConstant(Offs); 2901 2902 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2903 OffsVal); 2904 continue; 2905 } 2906 2907 // N = N + Idx * ElementSize; 2908 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(), 2909 TD->getTypeAllocSize(Ty)); 2910 SDValue IdxN = getValue(Idx); 2911 2912 // If the index is smaller or larger than intptr_t, truncate or extend 2913 // it. 2914 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType()); 2915 2916 // If this is a multiply by a power of two, turn it into a shl 2917 // immediately. This is a very common case. 2918 if (ElementSize != 1) { 2919 if (ElementSize.isPowerOf2()) { 2920 unsigned Amt = ElementSize.logBase2(); 2921 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 2922 N.getValueType(), IdxN, 2923 DAG.getConstant(Amt, TLI.getPointerTy())); 2924 } else { 2925 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy()); 2926 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 2927 N.getValueType(), IdxN, Scale); 2928 } 2929 } 2930 2931 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2932 N.getValueType(), N, IdxN); 2933 } 2934 } 2935 2936 setValue(&I, N); 2937 } 2938 2939 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 2940 // If this is a fixed sized alloca in the entry block of the function, 2941 // allocate it statically on the stack. 2942 if (FuncInfo.StaticAllocaMap.count(&I)) 2943 return; // getValue will auto-populate this. 2944 2945 const Type *Ty = I.getAllocatedType(); 2946 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 2947 unsigned Align = 2948 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2949 I.getAlignment()); 2950 2951 SDValue AllocSize = getValue(I.getArraySize()); 2952 2953 EVT IntPtr = TLI.getPointerTy(); 2954 if (AllocSize.getValueType() != IntPtr) 2955 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); 2956 2957 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, 2958 AllocSize, 2959 DAG.getConstant(TySize, IntPtr)); 2960 2961 // Handle alignment. If the requested alignment is less than or equal to 2962 // the stack alignment, ignore it. If the size is greater than or equal to 2963 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2964 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment(); 2965 if (Align <= StackAlign) 2966 Align = 0; 2967 2968 // Round the size of the allocation up to the stack alignment size 2969 // by add SA-1 to the size. 2970 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2971 AllocSize.getValueType(), AllocSize, 2972 DAG.getIntPtrConstant(StackAlign-1)); 2973 2974 // Mask out the low bits for alignment purposes. 2975 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 2976 AllocSize.getValueType(), AllocSize, 2977 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2978 2979 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 2980 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2981 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 2982 VTs, Ops, 3); 2983 setValue(&I, DSA); 2984 DAG.setRoot(DSA.getValue(1)); 2985 2986 // Inform the Frame Information that we have just allocated a variable-sized 2987 // object. 2988 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1); 2989 } 2990 2991 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 2992 const Value *SV = I.getOperand(0); 2993 SDValue Ptr = getValue(SV); 2994 2995 const Type *Ty = I.getType(); 2996 2997 bool isVolatile = I.isVolatile(); 2998 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 2999 unsigned Alignment = I.getAlignment(); 3000 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3001 3002 SmallVector<EVT, 4> ValueVTs; 3003 SmallVector<uint64_t, 4> Offsets; 3004 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets); 3005 unsigned NumValues = ValueVTs.size(); 3006 if (NumValues == 0) 3007 return; 3008 3009 SDValue Root; 3010 bool ConstantMemory = false; 3011 if (I.isVolatile() || NumValues > MaxParallelChains) 3012 // Serialize volatile loads with other side effects. 3013 Root = getRoot(); 3014 else if (AA->pointsToConstantMemory( 3015 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) { 3016 // Do not serialize (non-volatile) loads of constant memory with anything. 3017 Root = DAG.getEntryNode(); 3018 ConstantMemory = true; 3019 } else { 3020 // Do not serialize non-volatile loads against each other. 3021 Root = DAG.getRoot(); 3022 } 3023 3024 SmallVector<SDValue, 4> Values(NumValues); 3025 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3026 NumValues)); 3027 EVT PtrVT = Ptr.getValueType(); 3028 unsigned ChainI = 0; 3029 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3030 // Serializing loads here may result in excessive register pressure, and 3031 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3032 // could recover a bit by hoisting nodes upward in the chain by recognizing 3033 // they are side-effect free or do not alias. The optimizer should really 3034 // avoid this case by converting large object/array copies to llvm.memcpy 3035 // (MaxParallelChains should always remain as failsafe). 3036 if (ChainI == MaxParallelChains) { 3037 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3038 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3039 MVT::Other, &Chains[0], ChainI); 3040 Root = Chain; 3041 ChainI = 0; 3042 } 3043 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(), 3044 PtrVT, Ptr, 3045 DAG.getConstant(Offsets[i], PtrVT)); 3046 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root, 3047 A, MachinePointerInfo(SV, Offsets[i]), isVolatile, 3048 isNonTemporal, Alignment, TBAAInfo); 3049 3050 Values[i] = L; 3051 Chains[ChainI] = L.getValue(1); 3052 } 3053 3054 if (!ConstantMemory) { 3055 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3056 MVT::Other, &Chains[0], ChainI); 3057 if (isVolatile) 3058 DAG.setRoot(Chain); 3059 else 3060 PendingLoads.push_back(Chain); 3061 } 3062 3063 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 3064 DAG.getVTList(&ValueVTs[0], NumValues), 3065 &Values[0], NumValues)); 3066 } 3067 3068 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3069 const Value *SrcV = I.getOperand(0); 3070 const Value *PtrV = I.getOperand(1); 3071 3072 SmallVector<EVT, 4> ValueVTs; 3073 SmallVector<uint64_t, 4> Offsets; 3074 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets); 3075 unsigned NumValues = ValueVTs.size(); 3076 if (NumValues == 0) 3077 return; 3078 3079 // Get the lowered operands. Note that we do this after 3080 // checking if NumResults is zero, because with zero results 3081 // the operands won't have values in the map. 3082 SDValue Src = getValue(SrcV); 3083 SDValue Ptr = getValue(PtrV); 3084 3085 SDValue Root = getRoot(); 3086 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3087 NumValues)); 3088 EVT PtrVT = Ptr.getValueType(); 3089 bool isVolatile = I.isVolatile(); 3090 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 3091 unsigned Alignment = I.getAlignment(); 3092 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3093 3094 unsigned ChainI = 0; 3095 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3096 // See visitLoad comments. 3097 if (ChainI == MaxParallelChains) { 3098 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3099 MVT::Other, &Chains[0], ChainI); 3100 Root = Chain; 3101 ChainI = 0; 3102 } 3103 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr, 3104 DAG.getConstant(Offsets[i], PtrVT)); 3105 SDValue St = DAG.getStore(Root, getCurDebugLoc(), 3106 SDValue(Src.getNode(), Src.getResNo() + i), 3107 Add, MachinePointerInfo(PtrV, Offsets[i]), 3108 isVolatile, isNonTemporal, Alignment, TBAAInfo); 3109 Chains[ChainI] = St; 3110 } 3111 3112 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 3113 MVT::Other, &Chains[0], ChainI); 3114 ++SDNodeOrder; 3115 AssignOrderingToNode(StoreNode.getNode()); 3116 DAG.setRoot(StoreNode); 3117 } 3118 3119 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 3120 /// node. 3121 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 3122 unsigned Intrinsic) { 3123 bool HasChain = !I.doesNotAccessMemory(); 3124 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 3125 3126 // Build the operand list. 3127 SmallVector<SDValue, 8> Ops; 3128 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3129 if (OnlyLoad) { 3130 // We don't need to serialize loads against other loads. 3131 Ops.push_back(DAG.getRoot()); 3132 } else { 3133 Ops.push_back(getRoot()); 3134 } 3135 } 3136 3137 // Info is set by getTgtMemInstrinsic 3138 TargetLowering::IntrinsicInfo Info; 3139 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 3140 3141 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3142 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 3143 Info.opc == ISD::INTRINSIC_W_CHAIN) 3144 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 3145 3146 // Add all operands of the call to the operand list. 3147 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 3148 SDValue Op = getValue(I.getArgOperand(i)); 3149 assert(TLI.isTypeLegal(Op.getValueType()) && 3150 "Intrinsic uses a non-legal type?"); 3151 Ops.push_back(Op); 3152 } 3153 3154 SmallVector<EVT, 4> ValueVTs; 3155 ComputeValueVTs(TLI, I.getType(), ValueVTs); 3156 #ifndef NDEBUG 3157 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) { 3158 assert(TLI.isTypeLegal(ValueVTs[Val]) && 3159 "Intrinsic uses a non-legal type?"); 3160 } 3161 #endif // NDEBUG 3162 3163 if (HasChain) 3164 ValueVTs.push_back(MVT::Other); 3165 3166 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 3167 3168 // Create the node. 3169 SDValue Result; 3170 if (IsTgtIntrinsic) { 3171 // This is target intrinsic that touches memory 3172 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(), 3173 VTs, &Ops[0], Ops.size(), 3174 Info.memVT, 3175 MachinePointerInfo(Info.ptrVal, Info.offset), 3176 Info.align, Info.vol, 3177 Info.readMem, Info.writeMem); 3178 } else if (!HasChain) { 3179 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 3180 VTs, &Ops[0], Ops.size()); 3181 } else if (!I.getType()->isVoidTy()) { 3182 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 3183 VTs, &Ops[0], Ops.size()); 3184 } else { 3185 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 3186 VTs, &Ops[0], Ops.size()); 3187 } 3188 3189 if (HasChain) { 3190 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3191 if (OnlyLoad) 3192 PendingLoads.push_back(Chain); 3193 else 3194 DAG.setRoot(Chain); 3195 } 3196 3197 if (!I.getType()->isVoidTy()) { 3198 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3199 EVT VT = TLI.getValueType(PTy); 3200 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result); 3201 } 3202 3203 setValue(&I, Result); 3204 } 3205 } 3206 3207 /// GetSignificand - Get the significand and build it into a floating-point 3208 /// number with exponent of 1: 3209 /// 3210 /// Op = (Op & 0x007fffff) | 0x3f800000; 3211 /// 3212 /// where Op is the hexidecimal representation of floating point value. 3213 static SDValue 3214 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) { 3215 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3216 DAG.getConstant(0x007fffff, MVT::i32)); 3217 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3218 DAG.getConstant(0x3f800000, MVT::i32)); 3219 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 3220 } 3221 3222 /// GetExponent - Get the exponent: 3223 /// 3224 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3225 /// 3226 /// where Op is the hexidecimal representation of floating point value. 3227 static SDValue 3228 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3229 DebugLoc dl) { 3230 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3231 DAG.getConstant(0x7f800000, MVT::i32)); 3232 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 3233 DAG.getConstant(23, TLI.getPointerTy())); 3234 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3235 DAG.getConstant(127, MVT::i32)); 3236 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3237 } 3238 3239 /// getF32Constant - Get 32-bit floating point constant. 3240 static SDValue 3241 getF32Constant(SelectionDAG &DAG, unsigned Flt) { 3242 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32); 3243 } 3244 3245 /// Inlined utility function to implement binary input atomic intrinsics for 3246 /// visitIntrinsicCall: I is a call instruction 3247 /// Op is the associated NodeType for I 3248 const char * 3249 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I, 3250 ISD::NodeType Op) { 3251 SDValue Root = getRoot(); 3252 SDValue L = 3253 DAG.getAtomic(Op, getCurDebugLoc(), 3254 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(), 3255 Root, 3256 getValue(I.getArgOperand(0)), 3257 getValue(I.getArgOperand(1)), 3258 I.getArgOperand(0)); 3259 setValue(&I, L); 3260 DAG.setRoot(L.getValue(1)); 3261 return 0; 3262 } 3263 3264 // implVisitAluOverflow - Lower arithmetic overflow instrinsics. 3265 const char * 3266 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) { 3267 SDValue Op1 = getValue(I.getArgOperand(0)); 3268 SDValue Op2 = getValue(I.getArgOperand(1)); 3269 3270 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 3271 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2)); 3272 return 0; 3273 } 3274 3275 /// visitExp - Lower an exp intrinsic. Handles the special sequences for 3276 /// limited-precision mode. 3277 void 3278 SelectionDAGBuilder::visitExp(const CallInst &I) { 3279 SDValue result; 3280 DebugLoc dl = getCurDebugLoc(); 3281 3282 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3283 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3284 SDValue Op = getValue(I.getArgOperand(0)); 3285 3286 // Put the exponent in the right bit position for later addition to the 3287 // final result: 3288 // 3289 // #define LOG2OFe 1.4426950f 3290 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 3291 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3292 getF32Constant(DAG, 0x3fb8aa3b)); 3293 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3294 3295 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 3296 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3297 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3298 3299 // IntegerPartOfX <<= 23; 3300 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3301 DAG.getConstant(23, TLI.getPointerTy())); 3302 3303 if (LimitFloatPrecision <= 6) { 3304 // For floating-point precision of 6: 3305 // 3306 // TwoToFractionalPartOfX = 3307 // 0.997535578f + 3308 // (0.735607626f + 0.252464424f * x) * x; 3309 // 3310 // error 0.0144103317, which is 6 bits 3311 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3312 getF32Constant(DAG, 0x3e814304)); 3313 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3314 getF32Constant(DAG, 0x3f3c50c8)); 3315 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3316 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3317 getF32Constant(DAG, 0x3f7f5e7e)); 3318 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5); 3319 3320 // Add the exponent into the result in integer domain. 3321 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3322 TwoToFracPartOfX, IntegerPartOfX); 3323 3324 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6); 3325 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3326 // For floating-point precision of 12: 3327 // 3328 // TwoToFractionalPartOfX = 3329 // 0.999892986f + 3330 // (0.696457318f + 3331 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3332 // 3333 // 0.000107046256 error, which is 13 to 14 bits 3334 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3335 getF32Constant(DAG, 0x3da235e3)); 3336 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3337 getF32Constant(DAG, 0x3e65b8f3)); 3338 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3339 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3340 getF32Constant(DAG, 0x3f324b07)); 3341 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3342 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3343 getF32Constant(DAG, 0x3f7ff8fd)); 3344 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7); 3345 3346 // Add the exponent into the result in integer domain. 3347 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3348 TwoToFracPartOfX, IntegerPartOfX); 3349 3350 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8); 3351 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3352 // For floating-point precision of 18: 3353 // 3354 // TwoToFractionalPartOfX = 3355 // 0.999999982f + 3356 // (0.693148872f + 3357 // (0.240227044f + 3358 // (0.554906021e-1f + 3359 // (0.961591928e-2f + 3360 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3361 // 3362 // error 2.47208000*10^(-7), which is better than 18 bits 3363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3364 getF32Constant(DAG, 0x3924b03e)); 3365 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3366 getF32Constant(DAG, 0x3ab24b87)); 3367 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3368 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3369 getF32Constant(DAG, 0x3c1d8c17)); 3370 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3371 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3372 getF32Constant(DAG, 0x3d634a1d)); 3373 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3374 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3375 getF32Constant(DAG, 0x3e75fe14)); 3376 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3377 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3378 getF32Constant(DAG, 0x3f317234)); 3379 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3380 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3381 getF32Constant(DAG, 0x3f800000)); 3382 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl, 3383 MVT::i32, t13); 3384 3385 // Add the exponent into the result in integer domain. 3386 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3387 TwoToFracPartOfX, IntegerPartOfX); 3388 3389 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14); 3390 } 3391 } else { 3392 // No special expansion. 3393 result = DAG.getNode(ISD::FEXP, dl, 3394 getValue(I.getArgOperand(0)).getValueType(), 3395 getValue(I.getArgOperand(0))); 3396 } 3397 3398 setValue(&I, result); 3399 } 3400 3401 /// visitLog - Lower a log intrinsic. Handles the special sequences for 3402 /// limited-precision mode. 3403 void 3404 SelectionDAGBuilder::visitLog(const CallInst &I) { 3405 SDValue result; 3406 DebugLoc dl = getCurDebugLoc(); 3407 3408 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3409 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3410 SDValue Op = getValue(I.getArgOperand(0)); 3411 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3412 3413 // Scale the exponent by log(2) [0.69314718f]. 3414 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3415 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3416 getF32Constant(DAG, 0x3f317218)); 3417 3418 // Get the significand and build it into a floating-point number with 3419 // exponent of 1. 3420 SDValue X = GetSignificand(DAG, Op1, dl); 3421 3422 if (LimitFloatPrecision <= 6) { 3423 // For floating-point precision of 6: 3424 // 3425 // LogofMantissa = 3426 // -1.1609546f + 3427 // (1.4034025f - 0.23903021f * x) * x; 3428 // 3429 // error 0.0034276066, which is better than 8 bits 3430 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3431 getF32Constant(DAG, 0xbe74c456)); 3432 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3433 getF32Constant(DAG, 0x3fb3a2b1)); 3434 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3435 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3436 getF32Constant(DAG, 0x3f949a29)); 3437 3438 result = DAG.getNode(ISD::FADD, dl, 3439 MVT::f32, LogOfExponent, LogOfMantissa); 3440 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3441 // For floating-point precision of 12: 3442 // 3443 // LogOfMantissa = 3444 // -1.7417939f + 3445 // (2.8212026f + 3446 // (-1.4699568f + 3447 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3448 // 3449 // error 0.000061011436, which is 14 bits 3450 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3451 getF32Constant(DAG, 0xbd67b6d6)); 3452 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3453 getF32Constant(DAG, 0x3ee4f4b8)); 3454 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3455 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3456 getF32Constant(DAG, 0x3fbc278b)); 3457 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3458 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3459 getF32Constant(DAG, 0x40348e95)); 3460 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3461 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3462 getF32Constant(DAG, 0x3fdef31a)); 3463 3464 result = DAG.getNode(ISD::FADD, dl, 3465 MVT::f32, LogOfExponent, LogOfMantissa); 3466 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3467 // For floating-point precision of 18: 3468 // 3469 // LogOfMantissa = 3470 // -2.1072184f + 3471 // (4.2372794f + 3472 // (-3.7029485f + 3473 // (2.2781945f + 3474 // (-0.87823314f + 3475 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3476 // 3477 // error 0.0000023660568, which is better than 18 bits 3478 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3479 getF32Constant(DAG, 0xbc91e5ac)); 3480 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3481 getF32Constant(DAG, 0x3e4350aa)); 3482 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3483 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3484 getF32Constant(DAG, 0x3f60d3e3)); 3485 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3486 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3487 getF32Constant(DAG, 0x4011cdf0)); 3488 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3489 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3490 getF32Constant(DAG, 0x406cfd1c)); 3491 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3492 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3493 getF32Constant(DAG, 0x408797cb)); 3494 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3495 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3496 getF32Constant(DAG, 0x4006dcab)); 3497 3498 result = DAG.getNode(ISD::FADD, dl, 3499 MVT::f32, LogOfExponent, LogOfMantissa); 3500 } 3501 } else { 3502 // No special expansion. 3503 result = DAG.getNode(ISD::FLOG, dl, 3504 getValue(I.getArgOperand(0)).getValueType(), 3505 getValue(I.getArgOperand(0))); 3506 } 3507 3508 setValue(&I, result); 3509 } 3510 3511 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for 3512 /// limited-precision mode. 3513 void 3514 SelectionDAGBuilder::visitLog2(const CallInst &I) { 3515 SDValue result; 3516 DebugLoc dl = getCurDebugLoc(); 3517 3518 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3519 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3520 SDValue Op = getValue(I.getArgOperand(0)); 3521 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3522 3523 // Get the exponent. 3524 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3525 3526 // Get the significand and build it into a floating-point number with 3527 // exponent of 1. 3528 SDValue X = GetSignificand(DAG, Op1, dl); 3529 3530 // Different possible minimax approximations of significand in 3531 // floating-point for various degrees of accuracy over [1,2]. 3532 if (LimitFloatPrecision <= 6) { 3533 // For floating-point precision of 6: 3534 // 3535 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3536 // 3537 // error 0.0049451742, which is more than 7 bits 3538 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3539 getF32Constant(DAG, 0xbeb08fe0)); 3540 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3541 getF32Constant(DAG, 0x40019463)); 3542 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3543 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3544 getF32Constant(DAG, 0x3fd6633d)); 3545 3546 result = DAG.getNode(ISD::FADD, dl, 3547 MVT::f32, LogOfExponent, Log2ofMantissa); 3548 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3549 // For floating-point precision of 12: 3550 // 3551 // Log2ofMantissa = 3552 // -2.51285454f + 3553 // (4.07009056f + 3554 // (-2.12067489f + 3555 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3556 // 3557 // error 0.0000876136000, which is better than 13 bits 3558 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3559 getF32Constant(DAG, 0xbda7262e)); 3560 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3561 getF32Constant(DAG, 0x3f25280b)); 3562 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3563 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3564 getF32Constant(DAG, 0x4007b923)); 3565 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3566 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3567 getF32Constant(DAG, 0x40823e2f)); 3568 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3569 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3570 getF32Constant(DAG, 0x4020d29c)); 3571 3572 result = DAG.getNode(ISD::FADD, dl, 3573 MVT::f32, LogOfExponent, Log2ofMantissa); 3574 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3575 // For floating-point precision of 18: 3576 // 3577 // Log2ofMantissa = 3578 // -3.0400495f + 3579 // (6.1129976f + 3580 // (-5.3420409f + 3581 // (3.2865683f + 3582 // (-1.2669343f + 3583 // (0.27515199f - 3584 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3585 // 3586 // error 0.0000018516, which is better than 18 bits 3587 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3588 getF32Constant(DAG, 0xbcd2769e)); 3589 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3590 getF32Constant(DAG, 0x3e8ce0b9)); 3591 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3592 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3593 getF32Constant(DAG, 0x3fa22ae7)); 3594 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3595 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3596 getF32Constant(DAG, 0x40525723)); 3597 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3598 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3599 getF32Constant(DAG, 0x40aaf200)); 3600 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3601 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3602 getF32Constant(DAG, 0x40c39dad)); 3603 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3604 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3605 getF32Constant(DAG, 0x4042902c)); 3606 3607 result = DAG.getNode(ISD::FADD, dl, 3608 MVT::f32, LogOfExponent, Log2ofMantissa); 3609 } 3610 } else { 3611 // No special expansion. 3612 result = DAG.getNode(ISD::FLOG2, dl, 3613 getValue(I.getArgOperand(0)).getValueType(), 3614 getValue(I.getArgOperand(0))); 3615 } 3616 3617 setValue(&I, result); 3618 } 3619 3620 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for 3621 /// limited-precision mode. 3622 void 3623 SelectionDAGBuilder::visitLog10(const CallInst &I) { 3624 SDValue result; 3625 DebugLoc dl = getCurDebugLoc(); 3626 3627 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3628 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3629 SDValue Op = getValue(I.getArgOperand(0)); 3630 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3631 3632 // Scale the exponent by log10(2) [0.30102999f]. 3633 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3634 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3635 getF32Constant(DAG, 0x3e9a209a)); 3636 3637 // Get the significand and build it into a floating-point number with 3638 // exponent of 1. 3639 SDValue X = GetSignificand(DAG, Op1, dl); 3640 3641 if (LimitFloatPrecision <= 6) { 3642 // For floating-point precision of 6: 3643 // 3644 // Log10ofMantissa = 3645 // -0.50419619f + 3646 // (0.60948995f - 0.10380950f * x) * x; 3647 // 3648 // error 0.0014886165, which is 6 bits 3649 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3650 getF32Constant(DAG, 0xbdd49a13)); 3651 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3652 getF32Constant(DAG, 0x3f1c0789)); 3653 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3654 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3655 getF32Constant(DAG, 0x3f011300)); 3656 3657 result = DAG.getNode(ISD::FADD, dl, 3658 MVT::f32, LogOfExponent, Log10ofMantissa); 3659 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3660 // For floating-point precision of 12: 3661 // 3662 // Log10ofMantissa = 3663 // -0.64831180f + 3664 // (0.91751397f + 3665 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3666 // 3667 // error 0.00019228036, which is better than 12 bits 3668 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3669 getF32Constant(DAG, 0x3d431f31)); 3670 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3671 getF32Constant(DAG, 0x3ea21fb2)); 3672 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3673 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3674 getF32Constant(DAG, 0x3f6ae232)); 3675 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3676 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3677 getF32Constant(DAG, 0x3f25f7c3)); 3678 3679 result = DAG.getNode(ISD::FADD, dl, 3680 MVT::f32, LogOfExponent, Log10ofMantissa); 3681 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3682 // For floating-point precision of 18: 3683 // 3684 // Log10ofMantissa = 3685 // -0.84299375f + 3686 // (1.5327582f + 3687 // (-1.0688956f + 3688 // (0.49102474f + 3689 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3690 // 3691 // error 0.0000037995730, which is better than 18 bits 3692 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3693 getF32Constant(DAG, 0x3c5d51ce)); 3694 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3695 getF32Constant(DAG, 0x3e00685a)); 3696 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3697 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3698 getF32Constant(DAG, 0x3efb6798)); 3699 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3700 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3701 getF32Constant(DAG, 0x3f88d192)); 3702 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3703 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3704 getF32Constant(DAG, 0x3fc4316c)); 3705 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3706 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3707 getF32Constant(DAG, 0x3f57ce70)); 3708 3709 result = DAG.getNode(ISD::FADD, dl, 3710 MVT::f32, LogOfExponent, Log10ofMantissa); 3711 } 3712 } else { 3713 // No special expansion. 3714 result = DAG.getNode(ISD::FLOG10, dl, 3715 getValue(I.getArgOperand(0)).getValueType(), 3716 getValue(I.getArgOperand(0))); 3717 } 3718 3719 setValue(&I, result); 3720 } 3721 3722 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3723 /// limited-precision mode. 3724 void 3725 SelectionDAGBuilder::visitExp2(const CallInst &I) { 3726 SDValue result; 3727 DebugLoc dl = getCurDebugLoc(); 3728 3729 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 && 3730 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3731 SDValue Op = getValue(I.getArgOperand(0)); 3732 3733 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 3734 3735 // FractionalPartOfX = x - (float)IntegerPartOfX; 3736 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3737 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 3738 3739 // IntegerPartOfX <<= 23; 3740 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3741 DAG.getConstant(23, TLI.getPointerTy())); 3742 3743 if (LimitFloatPrecision <= 6) { 3744 // For floating-point precision of 6: 3745 // 3746 // TwoToFractionalPartOfX = 3747 // 0.997535578f + 3748 // (0.735607626f + 0.252464424f * x) * x; 3749 // 3750 // error 0.0144103317, which is 6 bits 3751 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3752 getF32Constant(DAG, 0x3e814304)); 3753 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3754 getF32Constant(DAG, 0x3f3c50c8)); 3755 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3756 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3757 getF32Constant(DAG, 0x3f7f5e7e)); 3758 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5); 3759 SDValue TwoToFractionalPartOfX = 3760 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3761 3762 result = DAG.getNode(ISD::BITCAST, dl, 3763 MVT::f32, TwoToFractionalPartOfX); 3764 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3765 // For floating-point precision of 12: 3766 // 3767 // TwoToFractionalPartOfX = 3768 // 0.999892986f + 3769 // (0.696457318f + 3770 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3771 // 3772 // error 0.000107046256, which is 13 to 14 bits 3773 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3774 getF32Constant(DAG, 0x3da235e3)); 3775 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3776 getF32Constant(DAG, 0x3e65b8f3)); 3777 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3778 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3779 getF32Constant(DAG, 0x3f324b07)); 3780 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3781 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3782 getF32Constant(DAG, 0x3f7ff8fd)); 3783 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7); 3784 SDValue TwoToFractionalPartOfX = 3785 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3786 3787 result = DAG.getNode(ISD::BITCAST, dl, 3788 MVT::f32, TwoToFractionalPartOfX); 3789 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3790 // For floating-point precision of 18: 3791 // 3792 // TwoToFractionalPartOfX = 3793 // 0.999999982f + 3794 // (0.693148872f + 3795 // (0.240227044f + 3796 // (0.554906021e-1f + 3797 // (0.961591928e-2f + 3798 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3799 // error 2.47208000*10^(-7), which is better than 18 bits 3800 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3801 getF32Constant(DAG, 0x3924b03e)); 3802 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3803 getF32Constant(DAG, 0x3ab24b87)); 3804 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3805 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3806 getF32Constant(DAG, 0x3c1d8c17)); 3807 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3808 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3809 getF32Constant(DAG, 0x3d634a1d)); 3810 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3811 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3812 getF32Constant(DAG, 0x3e75fe14)); 3813 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3814 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3815 getF32Constant(DAG, 0x3f317234)); 3816 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3817 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3818 getF32Constant(DAG, 0x3f800000)); 3819 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13); 3820 SDValue TwoToFractionalPartOfX = 3821 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3822 3823 result = DAG.getNode(ISD::BITCAST, dl, 3824 MVT::f32, TwoToFractionalPartOfX); 3825 } 3826 } else { 3827 // No special expansion. 3828 result = DAG.getNode(ISD::FEXP2, dl, 3829 getValue(I.getArgOperand(0)).getValueType(), 3830 getValue(I.getArgOperand(0))); 3831 } 3832 3833 setValue(&I, result); 3834 } 3835 3836 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3837 /// limited-precision mode with x == 10.0f. 3838 void 3839 SelectionDAGBuilder::visitPow(const CallInst &I) { 3840 SDValue result; 3841 const Value *Val = I.getArgOperand(0); 3842 DebugLoc dl = getCurDebugLoc(); 3843 bool IsExp10 = false; 3844 3845 if (getValue(Val).getValueType() == MVT::f32 && 3846 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 && 3847 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3848 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) { 3849 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 3850 APFloat Ten(10.0f); 3851 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten); 3852 } 3853 } 3854 } 3855 3856 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3857 SDValue Op = getValue(I.getArgOperand(1)); 3858 3859 // Put the exponent in the right bit position for later addition to the 3860 // final result: 3861 // 3862 // #define LOG2OF10 3.3219281f 3863 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 3864 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3865 getF32Constant(DAG, 0x40549a78)); 3866 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3867 3868 // FractionalPartOfX = x - (float)IntegerPartOfX; 3869 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3870 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3871 3872 // IntegerPartOfX <<= 23; 3873 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3874 DAG.getConstant(23, TLI.getPointerTy())); 3875 3876 if (LimitFloatPrecision <= 6) { 3877 // For floating-point precision of 6: 3878 // 3879 // twoToFractionalPartOfX = 3880 // 0.997535578f + 3881 // (0.735607626f + 0.252464424f * x) * x; 3882 // 3883 // error 0.0144103317, which is 6 bits 3884 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3885 getF32Constant(DAG, 0x3e814304)); 3886 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3887 getF32Constant(DAG, 0x3f3c50c8)); 3888 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3889 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3890 getF32Constant(DAG, 0x3f7f5e7e)); 3891 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5); 3892 SDValue TwoToFractionalPartOfX = 3893 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3894 3895 result = DAG.getNode(ISD::BITCAST, dl, 3896 MVT::f32, TwoToFractionalPartOfX); 3897 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3898 // For floating-point precision of 12: 3899 // 3900 // TwoToFractionalPartOfX = 3901 // 0.999892986f + 3902 // (0.696457318f + 3903 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3904 // 3905 // error 0.000107046256, which is 13 to 14 bits 3906 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3907 getF32Constant(DAG, 0x3da235e3)); 3908 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3909 getF32Constant(DAG, 0x3e65b8f3)); 3910 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3911 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3912 getF32Constant(DAG, 0x3f324b07)); 3913 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3914 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3915 getF32Constant(DAG, 0x3f7ff8fd)); 3916 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7); 3917 SDValue TwoToFractionalPartOfX = 3918 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3919 3920 result = DAG.getNode(ISD::BITCAST, dl, 3921 MVT::f32, TwoToFractionalPartOfX); 3922 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3923 // For floating-point precision of 18: 3924 // 3925 // TwoToFractionalPartOfX = 3926 // 0.999999982f + 3927 // (0.693148872f + 3928 // (0.240227044f + 3929 // (0.554906021e-1f + 3930 // (0.961591928e-2f + 3931 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3932 // error 2.47208000*10^(-7), which is better than 18 bits 3933 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3934 getF32Constant(DAG, 0x3924b03e)); 3935 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3936 getF32Constant(DAG, 0x3ab24b87)); 3937 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3938 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3939 getF32Constant(DAG, 0x3c1d8c17)); 3940 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3941 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3942 getF32Constant(DAG, 0x3d634a1d)); 3943 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3944 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3945 getF32Constant(DAG, 0x3e75fe14)); 3946 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3947 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3948 getF32Constant(DAG, 0x3f317234)); 3949 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3950 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3951 getF32Constant(DAG, 0x3f800000)); 3952 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13); 3953 SDValue TwoToFractionalPartOfX = 3954 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3955 3956 result = DAG.getNode(ISD::BITCAST, dl, 3957 MVT::f32, TwoToFractionalPartOfX); 3958 } 3959 } else { 3960 // No special expansion. 3961 result = DAG.getNode(ISD::FPOW, dl, 3962 getValue(I.getArgOperand(0)).getValueType(), 3963 getValue(I.getArgOperand(0)), 3964 getValue(I.getArgOperand(1))); 3965 } 3966 3967 setValue(&I, result); 3968 } 3969 3970 3971 /// ExpandPowI - Expand a llvm.powi intrinsic. 3972 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS, 3973 SelectionDAG &DAG) { 3974 // If RHS is a constant, we can expand this out to a multiplication tree, 3975 // otherwise we end up lowering to a call to __powidf2 (for example). When 3976 // optimizing for size, we only want to do this if the expansion would produce 3977 // a small number of multiplies, otherwise we do the full expansion. 3978 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3979 // Get the exponent as a positive value. 3980 unsigned Val = RHSC->getSExtValue(); 3981 if ((int)Val < 0) Val = -Val; 3982 3983 // powi(x, 0) -> 1.0 3984 if (Val == 0) 3985 return DAG.getConstantFP(1.0, LHS.getValueType()); 3986 3987 const Function *F = DAG.getMachineFunction().getFunction(); 3988 if (!F->hasFnAttr(Attribute::OptimizeForSize) || 3989 // If optimizing for size, don't insert too many multiplies. This 3990 // inserts up to 5 multiplies. 3991 CountPopulation_32(Val)+Log2_32(Val) < 7) { 3992 // We use the simple binary decomposition method to generate the multiply 3993 // sequence. There are more optimal ways to do this (for example, 3994 // powi(x,15) generates one more multiply than it should), but this has 3995 // the benefit of being both really simple and much better than a libcall. 3996 SDValue Res; // Logically starts equal to 1.0 3997 SDValue CurSquare = LHS; 3998 while (Val) { 3999 if (Val & 1) { 4000 if (Res.getNode()) 4001 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4002 else 4003 Res = CurSquare; // 1.0*CurSquare. 4004 } 4005 4006 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4007 CurSquare, CurSquare); 4008 Val >>= 1; 4009 } 4010 4011 // If the original was negative, invert the result, producing 1/(x*x*x). 4012 if (RHSC->getSExtValue() < 0) 4013 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4014 DAG.getConstantFP(1.0, LHS.getValueType()), Res); 4015 return Res; 4016 } 4017 } 4018 4019 // Otherwise, expand to a libcall. 4020 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4021 } 4022 4023 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4024 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4025 /// At the end of instruction selection, they will be inserted to the entry BB. 4026 bool 4027 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable, 4028 int64_t Offset, 4029 const SDValue &N) { 4030 const Argument *Arg = dyn_cast<Argument>(V); 4031 if (!Arg) 4032 return false; 4033 4034 MachineFunction &MF = DAG.getMachineFunction(); 4035 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo(); 4036 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 4037 4038 // Ignore inlined function arguments here. 4039 DIVariable DV(Variable); 4040 if (DV.isInlinedFnArgument(MF.getFunction())) 4041 return false; 4042 4043 MachineBasicBlock *MBB = FuncInfo.MBB; 4044 if (MBB != &MF.front()) 4045 return false; 4046 4047 unsigned Reg = 0; 4048 if (Arg->hasByValAttr()) { 4049 // Byval arguments' frame index is recorded during argument lowering. 4050 // Use this info directly. 4051 Reg = TRI->getFrameRegister(MF); 4052 Offset = FuncInfo.getByValArgumentFrameIndex(Arg); 4053 // If byval argument ofset is not recorded then ignore this. 4054 if (!Offset) 4055 Reg = 0; 4056 } 4057 4058 if (N.getNode() && N.getOpcode() == ISD::CopyFromReg) { 4059 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4060 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4061 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4062 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4063 if (PR) 4064 Reg = PR; 4065 } 4066 } 4067 4068 if (!Reg) { 4069 // Check if ValueMap has reg number. 4070 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4071 if (VMI != FuncInfo.ValueMap.end()) 4072 Reg = VMI->second; 4073 } 4074 4075 if (!Reg && N.getNode()) { 4076 // Check if frame index is available. 4077 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4078 if (FrameIndexSDNode *FINode = 4079 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) { 4080 Reg = TRI->getFrameRegister(MF); 4081 Offset = FINode->getIndex(); 4082 } 4083 } 4084 4085 if (!Reg) 4086 return false; 4087 4088 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(), 4089 TII->get(TargetOpcode::DBG_VALUE)) 4090 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable); 4091 FuncInfo.ArgDbgValues.push_back(&*MIB); 4092 return true; 4093 } 4094 4095 // VisualStudio defines setjmp as _setjmp 4096 #if defined(_MSC_VER) && defined(setjmp) && \ 4097 !defined(setjmp_undefined_for_msvc) 4098 # pragma push_macro("setjmp") 4099 # undef setjmp 4100 # define setjmp_undefined_for_msvc 4101 #endif 4102 4103 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4104 /// we want to emit this as a call to a named external function, return the name 4105 /// otherwise lower it and return null. 4106 const char * 4107 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4108 DebugLoc dl = getCurDebugLoc(); 4109 SDValue Res; 4110 4111 switch (Intrinsic) { 4112 default: 4113 // By default, turn this into a target intrinsic node. 4114 visitTargetIntrinsic(I, Intrinsic); 4115 return 0; 4116 case Intrinsic::vastart: visitVAStart(I); return 0; 4117 case Intrinsic::vaend: visitVAEnd(I); return 0; 4118 case Intrinsic::vacopy: visitVACopy(I); return 0; 4119 case Intrinsic::returnaddress: 4120 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(), 4121 getValue(I.getArgOperand(0)))); 4122 return 0; 4123 case Intrinsic::frameaddress: 4124 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(), 4125 getValue(I.getArgOperand(0)))); 4126 return 0; 4127 case Intrinsic::setjmp: 4128 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 4129 case Intrinsic::longjmp: 4130 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 4131 case Intrinsic::memcpy: { 4132 // Assert for address < 256 since we support only user defined address 4133 // spaces. 4134 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4135 < 256 && 4136 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4137 < 256 && 4138 "Unknown address space"); 4139 SDValue Op1 = getValue(I.getArgOperand(0)); 4140 SDValue Op2 = getValue(I.getArgOperand(1)); 4141 SDValue Op3 = getValue(I.getArgOperand(2)); 4142 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4143 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4144 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false, 4145 MachinePointerInfo(I.getArgOperand(0)), 4146 MachinePointerInfo(I.getArgOperand(1)))); 4147 return 0; 4148 } 4149 case Intrinsic::memset: { 4150 // Assert for address < 256 since we support only user defined address 4151 // spaces. 4152 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4153 < 256 && 4154 "Unknown address space"); 4155 SDValue Op1 = getValue(I.getArgOperand(0)); 4156 SDValue Op2 = getValue(I.getArgOperand(1)); 4157 SDValue Op3 = getValue(I.getArgOperand(2)); 4158 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4159 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4160 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 4161 MachinePointerInfo(I.getArgOperand(0)))); 4162 return 0; 4163 } 4164 case Intrinsic::memmove: { 4165 // Assert for address < 256 since we support only user defined address 4166 // spaces. 4167 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4168 < 256 && 4169 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4170 < 256 && 4171 "Unknown address space"); 4172 SDValue Op1 = getValue(I.getArgOperand(0)); 4173 SDValue Op2 = getValue(I.getArgOperand(1)); 4174 SDValue Op3 = getValue(I.getArgOperand(2)); 4175 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4176 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4177 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 4178 MachinePointerInfo(I.getArgOperand(0)), 4179 MachinePointerInfo(I.getArgOperand(1)))); 4180 return 0; 4181 } 4182 case Intrinsic::dbg_declare: { 4183 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4184 MDNode *Variable = DI.getVariable(); 4185 const Value *Address = DI.getAddress(); 4186 if (!Address || !DIVariable(DI.getVariable()).Verify()) 4187 return 0; 4188 4189 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 4190 // but do not always have a corresponding SDNode built. The SDNodeOrder 4191 // absolute, but not relative, values are different depending on whether 4192 // debug info exists. 4193 ++SDNodeOrder; 4194 4195 // Check if address has undef value. 4196 if (isa<UndefValue>(Address) || 4197 (Address->use_empty() && !isa<Argument>(Address))) { 4198 DEBUG(dbgs() << "Dropping debug info for " << DI); 4199 return 0; 4200 } 4201 4202 SDValue &N = NodeMap[Address]; 4203 if (!N.getNode() && isa<Argument>(Address)) 4204 // Check unused arguments map. 4205 N = UnusedArgNodeMap[Address]; 4206 SDDbgValue *SDV; 4207 if (N.getNode()) { 4208 // Parameters are handled specially. 4209 bool isParameter = 4210 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable; 4211 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4212 Address = BCI->getOperand(0); 4213 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4214 4215 if (isParameter && !AI) { 4216 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4217 if (FINode) 4218 // Byval parameter. We have a frame index at this point. 4219 SDV = DAG.getDbgValue(Variable, FINode->getIndex(), 4220 0, dl, SDNodeOrder); 4221 else { 4222 // Can't do anything with other non-AI cases yet. This might be a 4223 // parameter of a callee function that got inlined, for example. 4224 DEBUG(dbgs() << "Dropping debug info for " << DI); 4225 return 0; 4226 } 4227 } else if (AI) 4228 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(), 4229 0, dl, SDNodeOrder); 4230 else { 4231 // Can't do anything with other non-AI cases yet. 4232 DEBUG(dbgs() << "Dropping debug info for " << DI); 4233 return 0; 4234 } 4235 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4236 } else { 4237 // If Address is an argument then try to emit its dbg value using 4238 // virtual register info from the FuncInfo.ValueMap. 4239 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) { 4240 // If variable is pinned by a alloca in dominating bb then 4241 // use StaticAllocaMap. 4242 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4243 if (AI->getParent() != DI.getParent()) { 4244 DenseMap<const AllocaInst*, int>::iterator SI = 4245 FuncInfo.StaticAllocaMap.find(AI); 4246 if (SI != FuncInfo.StaticAllocaMap.end()) { 4247 SDV = DAG.getDbgValue(Variable, SI->second, 4248 0, dl, SDNodeOrder); 4249 DAG.AddDbgValue(SDV, 0, false); 4250 return 0; 4251 } 4252 } 4253 } 4254 DEBUG(dbgs() << "Dropping debug info for " << DI); 4255 } 4256 } 4257 return 0; 4258 } 4259 case Intrinsic::dbg_value: { 4260 const DbgValueInst &DI = cast<DbgValueInst>(I); 4261 if (!DIVariable(DI.getVariable()).Verify()) 4262 return 0; 4263 4264 MDNode *Variable = DI.getVariable(); 4265 uint64_t Offset = DI.getOffset(); 4266 const Value *V = DI.getValue(); 4267 if (!V) 4268 return 0; 4269 4270 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 4271 // but do not always have a corresponding SDNode built. The SDNodeOrder 4272 // absolute, but not relative, values are different depending on whether 4273 // debug info exists. 4274 ++SDNodeOrder; 4275 SDDbgValue *SDV; 4276 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) { 4277 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder); 4278 DAG.AddDbgValue(SDV, 0, false); 4279 } else { 4280 // Do not use getValue() in here; we don't want to generate code at 4281 // this point if it hasn't been done yet. 4282 SDValue N = NodeMap[V]; 4283 if (!N.getNode() && isa<Argument>(V)) 4284 // Check unused arguments map. 4285 N = UnusedArgNodeMap[V]; 4286 if (N.getNode()) { 4287 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) { 4288 SDV = DAG.getDbgValue(Variable, N.getNode(), 4289 N.getResNo(), Offset, dl, SDNodeOrder); 4290 DAG.AddDbgValue(SDV, N.getNode(), false); 4291 } 4292 } else if (isa<PHINode>(V) && !V->use_empty() ) { 4293 // Do not call getValue(V) yet, as we don't want to generate code. 4294 // Remember it for later. 4295 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4296 DanglingDebugInfoMap[V] = DDI; 4297 } else { 4298 // We may expand this to cover more cases. One case where we have no 4299 // data available is an unreferenced parameter. 4300 DEBUG(dbgs() << "Dropping debug info for " << DI); 4301 } 4302 } 4303 4304 // Build a debug info table entry. 4305 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4306 V = BCI->getOperand(0); 4307 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4308 // Don't handle byval struct arguments or VLAs, for example. 4309 if (!AI) 4310 return 0; 4311 DenseMap<const AllocaInst*, int>::iterator SI = 4312 FuncInfo.StaticAllocaMap.find(AI); 4313 if (SI == FuncInfo.StaticAllocaMap.end()) 4314 return 0; // VLAs. 4315 int FI = SI->second; 4316 4317 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4318 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo()) 4319 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc()); 4320 return 0; 4321 } 4322 case Intrinsic::eh_exception: { 4323 // Insert the EXCEPTIONADDR instruction. 4324 assert(FuncInfo.MBB->isLandingPad() && 4325 "Call to eh.exception not in landing pad!"); 4326 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4327 SDValue Ops[1]; 4328 Ops[0] = DAG.getRoot(); 4329 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1); 4330 setValue(&I, Op); 4331 DAG.setRoot(Op.getValue(1)); 4332 return 0; 4333 } 4334 4335 case Intrinsic::eh_selector: { 4336 MachineBasicBlock *CallMBB = FuncInfo.MBB; 4337 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4338 if (CallMBB->isLandingPad()) 4339 AddCatchInfo(I, &MMI, CallMBB); 4340 else { 4341 #ifndef NDEBUG 4342 FuncInfo.CatchInfoLost.insert(&I); 4343 #endif 4344 // FIXME: Mark exception selector register as live in. Hack for PR1508. 4345 unsigned Reg = TLI.getExceptionSelectorRegister(); 4346 if (Reg) FuncInfo.MBB->addLiveIn(Reg); 4347 } 4348 4349 // Insert the EHSELECTION instruction. 4350 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 4351 SDValue Ops[2]; 4352 Ops[0] = getValue(I.getArgOperand(0)); 4353 Ops[1] = getRoot(); 4354 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2); 4355 DAG.setRoot(Op.getValue(1)); 4356 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32)); 4357 return 0; 4358 } 4359 4360 case Intrinsic::eh_typeid_for: { 4361 // Find the type id for the given typeinfo. 4362 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0)); 4363 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4364 Res = DAG.getConstant(TypeID, MVT::i32); 4365 setValue(&I, Res); 4366 return 0; 4367 } 4368 4369 case Intrinsic::eh_return_i32: 4370 case Intrinsic::eh_return_i64: 4371 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4372 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl, 4373 MVT::Other, 4374 getControlRoot(), 4375 getValue(I.getArgOperand(0)), 4376 getValue(I.getArgOperand(1)))); 4377 return 0; 4378 case Intrinsic::eh_unwind_init: 4379 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4380 return 0; 4381 case Intrinsic::eh_dwarf_cfa: { 4382 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl, 4383 TLI.getPointerTy()); 4384 SDValue Offset = DAG.getNode(ISD::ADD, dl, 4385 TLI.getPointerTy(), 4386 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 4387 TLI.getPointerTy()), 4388 CfaArg); 4389 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl, 4390 TLI.getPointerTy(), 4391 DAG.getConstant(0, TLI.getPointerTy())); 4392 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 4393 FA, Offset)); 4394 return 0; 4395 } 4396 case Intrinsic::eh_sjlj_callsite: { 4397 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4398 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 4399 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4400 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4401 4402 MMI.setCurrentCallSite(CI->getZExtValue()); 4403 return 0; 4404 } 4405 case Intrinsic::eh_sjlj_setjmp: { 4406 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(), 4407 getValue(I.getArgOperand(0)))); 4408 return 0; 4409 } 4410 case Intrinsic::eh_sjlj_longjmp: { 4411 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other, 4412 getRoot(), getValue(I.getArgOperand(0)))); 4413 return 0; 4414 } 4415 case Intrinsic::eh_sjlj_dispatch_setup: { 4416 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other, 4417 getRoot(), getValue(I.getArgOperand(0)))); 4418 return 0; 4419 } 4420 4421 case Intrinsic::x86_mmx_pslli_w: 4422 case Intrinsic::x86_mmx_pslli_d: 4423 case Intrinsic::x86_mmx_pslli_q: 4424 case Intrinsic::x86_mmx_psrli_w: 4425 case Intrinsic::x86_mmx_psrli_d: 4426 case Intrinsic::x86_mmx_psrli_q: 4427 case Intrinsic::x86_mmx_psrai_w: 4428 case Intrinsic::x86_mmx_psrai_d: { 4429 SDValue ShAmt = getValue(I.getArgOperand(1)); 4430 if (isa<ConstantSDNode>(ShAmt)) { 4431 visitTargetIntrinsic(I, Intrinsic); 4432 return 0; 4433 } 4434 unsigned NewIntrinsic = 0; 4435 EVT ShAmtVT = MVT::v2i32; 4436 switch (Intrinsic) { 4437 case Intrinsic::x86_mmx_pslli_w: 4438 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 4439 break; 4440 case Intrinsic::x86_mmx_pslli_d: 4441 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 4442 break; 4443 case Intrinsic::x86_mmx_pslli_q: 4444 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 4445 break; 4446 case Intrinsic::x86_mmx_psrli_w: 4447 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 4448 break; 4449 case Intrinsic::x86_mmx_psrli_d: 4450 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 4451 break; 4452 case Intrinsic::x86_mmx_psrli_q: 4453 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 4454 break; 4455 case Intrinsic::x86_mmx_psrai_w: 4456 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 4457 break; 4458 case Intrinsic::x86_mmx_psrai_d: 4459 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 4460 break; 4461 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4462 } 4463 4464 // The vector shift intrinsics with scalars uses 32b shift amounts but 4465 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 4466 // to be zero. 4467 // We must do this early because v2i32 is not a legal type. 4468 DebugLoc dl = getCurDebugLoc(); 4469 SDValue ShOps[2]; 4470 ShOps[0] = ShAmt; 4471 ShOps[1] = DAG.getConstant(0, MVT::i32); 4472 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 4473 EVT DestVT = TLI.getValueType(I.getType()); 4474 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt); 4475 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 4476 DAG.getConstant(NewIntrinsic, MVT::i32), 4477 getValue(I.getArgOperand(0)), ShAmt); 4478 setValue(&I, Res); 4479 return 0; 4480 } 4481 case Intrinsic::convertff: 4482 case Intrinsic::convertfsi: 4483 case Intrinsic::convertfui: 4484 case Intrinsic::convertsif: 4485 case Intrinsic::convertuif: 4486 case Intrinsic::convertss: 4487 case Intrinsic::convertsu: 4488 case Intrinsic::convertus: 4489 case Intrinsic::convertuu: { 4490 ISD::CvtCode Code = ISD::CVT_INVALID; 4491 switch (Intrinsic) { 4492 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4493 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4494 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4495 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4496 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4497 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4498 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4499 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4500 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4501 } 4502 EVT DestVT = TLI.getValueType(I.getType()); 4503 const Value *Op1 = I.getArgOperand(0); 4504 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1), 4505 DAG.getValueType(DestVT), 4506 DAG.getValueType(getValue(Op1).getValueType()), 4507 getValue(I.getArgOperand(1)), 4508 getValue(I.getArgOperand(2)), 4509 Code); 4510 setValue(&I, Res); 4511 return 0; 4512 } 4513 case Intrinsic::sqrt: 4514 setValue(&I, DAG.getNode(ISD::FSQRT, dl, 4515 getValue(I.getArgOperand(0)).getValueType(), 4516 getValue(I.getArgOperand(0)))); 4517 return 0; 4518 case Intrinsic::powi: 4519 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)), 4520 getValue(I.getArgOperand(1)), DAG)); 4521 return 0; 4522 case Intrinsic::sin: 4523 setValue(&I, DAG.getNode(ISD::FSIN, dl, 4524 getValue(I.getArgOperand(0)).getValueType(), 4525 getValue(I.getArgOperand(0)))); 4526 return 0; 4527 case Intrinsic::cos: 4528 setValue(&I, DAG.getNode(ISD::FCOS, dl, 4529 getValue(I.getArgOperand(0)).getValueType(), 4530 getValue(I.getArgOperand(0)))); 4531 return 0; 4532 case Intrinsic::log: 4533 visitLog(I); 4534 return 0; 4535 case Intrinsic::log2: 4536 visitLog2(I); 4537 return 0; 4538 case Intrinsic::log10: 4539 visitLog10(I); 4540 return 0; 4541 case Intrinsic::exp: 4542 visitExp(I); 4543 return 0; 4544 case Intrinsic::exp2: 4545 visitExp2(I); 4546 return 0; 4547 case Intrinsic::pow: 4548 visitPow(I); 4549 return 0; 4550 case Intrinsic::convert_to_fp16: 4551 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl, 4552 MVT::i16, getValue(I.getArgOperand(0)))); 4553 return 0; 4554 case Intrinsic::convert_from_fp16: 4555 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl, 4556 MVT::f32, getValue(I.getArgOperand(0)))); 4557 return 0; 4558 case Intrinsic::pcmarker: { 4559 SDValue Tmp = getValue(I.getArgOperand(0)); 4560 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp)); 4561 return 0; 4562 } 4563 case Intrinsic::readcyclecounter: { 4564 SDValue Op = getRoot(); 4565 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl, 4566 DAG.getVTList(MVT::i64, MVT::Other), 4567 &Op, 1); 4568 setValue(&I, Res); 4569 DAG.setRoot(Res.getValue(1)); 4570 return 0; 4571 } 4572 case Intrinsic::bswap: 4573 setValue(&I, DAG.getNode(ISD::BSWAP, dl, 4574 getValue(I.getArgOperand(0)).getValueType(), 4575 getValue(I.getArgOperand(0)))); 4576 return 0; 4577 case Intrinsic::cttz: { 4578 SDValue Arg = getValue(I.getArgOperand(0)); 4579 EVT Ty = Arg.getValueType(); 4580 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg)); 4581 return 0; 4582 } 4583 case Intrinsic::ctlz: { 4584 SDValue Arg = getValue(I.getArgOperand(0)); 4585 EVT Ty = Arg.getValueType(); 4586 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg)); 4587 return 0; 4588 } 4589 case Intrinsic::ctpop: { 4590 SDValue Arg = getValue(I.getArgOperand(0)); 4591 EVT Ty = Arg.getValueType(); 4592 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg)); 4593 return 0; 4594 } 4595 case Intrinsic::stacksave: { 4596 SDValue Op = getRoot(); 4597 Res = DAG.getNode(ISD::STACKSAVE, dl, 4598 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1); 4599 setValue(&I, Res); 4600 DAG.setRoot(Res.getValue(1)); 4601 return 0; 4602 } 4603 case Intrinsic::stackrestore: { 4604 Res = getValue(I.getArgOperand(0)); 4605 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res)); 4606 return 0; 4607 } 4608 case Intrinsic::stackprotector: { 4609 // Emit code into the DAG to store the stack guard onto the stack. 4610 MachineFunction &MF = DAG.getMachineFunction(); 4611 MachineFrameInfo *MFI = MF.getFrameInfo(); 4612 EVT PtrTy = TLI.getPointerTy(); 4613 4614 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value. 4615 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 4616 4617 int FI = FuncInfo.StaticAllocaMap[Slot]; 4618 MFI->setStackProtectorIndex(FI); 4619 4620 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4621 4622 // Store the stack protector onto the stack. 4623 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN, 4624 MachinePointerInfo::getFixedStack(FI), 4625 true, false, 0); 4626 setValue(&I, Res); 4627 DAG.setRoot(Res); 4628 return 0; 4629 } 4630 case Intrinsic::objectsize: { 4631 // If we don't know by now, we're never going to know. 4632 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 4633 4634 assert(CI && "Non-constant type in __builtin_object_size?"); 4635 4636 SDValue Arg = getValue(I.getCalledValue()); 4637 EVT Ty = Arg.getValueType(); 4638 4639 if (CI->isZero()) 4640 Res = DAG.getConstant(-1ULL, Ty); 4641 else 4642 Res = DAG.getConstant(0, Ty); 4643 4644 setValue(&I, Res); 4645 return 0; 4646 } 4647 case Intrinsic::var_annotation: 4648 // Discard annotate attributes 4649 return 0; 4650 4651 case Intrinsic::init_trampoline: { 4652 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 4653 4654 SDValue Ops[6]; 4655 Ops[0] = getRoot(); 4656 Ops[1] = getValue(I.getArgOperand(0)); 4657 Ops[2] = getValue(I.getArgOperand(1)); 4658 Ops[3] = getValue(I.getArgOperand(2)); 4659 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 4660 Ops[5] = DAG.getSrcValue(F); 4661 4662 Res = DAG.getNode(ISD::TRAMPOLINE, dl, 4663 DAG.getVTList(TLI.getPointerTy(), MVT::Other), 4664 Ops, 6); 4665 4666 setValue(&I, Res); 4667 DAG.setRoot(Res.getValue(1)); 4668 return 0; 4669 } 4670 case Intrinsic::gcroot: 4671 if (GFI) { 4672 const Value *Alloca = I.getArgOperand(0); 4673 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 4674 4675 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4676 GFI->addStackRoot(FI->getIndex(), TypeMap); 4677 } 4678 return 0; 4679 case Intrinsic::gcread: 4680 case Intrinsic::gcwrite: 4681 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4682 return 0; 4683 case Intrinsic::flt_rounds: 4684 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32)); 4685 return 0; 4686 case Intrinsic::trap: 4687 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot())); 4688 return 0; 4689 case Intrinsic::uadd_with_overflow: 4690 return implVisitAluOverflow(I, ISD::UADDO); 4691 case Intrinsic::sadd_with_overflow: 4692 return implVisitAluOverflow(I, ISD::SADDO); 4693 case Intrinsic::usub_with_overflow: 4694 return implVisitAluOverflow(I, ISD::USUBO); 4695 case Intrinsic::ssub_with_overflow: 4696 return implVisitAluOverflow(I, ISD::SSUBO); 4697 case Intrinsic::umul_with_overflow: 4698 return implVisitAluOverflow(I, ISD::UMULO); 4699 case Intrinsic::smul_with_overflow: 4700 return implVisitAluOverflow(I, ISD::SMULO); 4701 4702 case Intrinsic::prefetch: { 4703 SDValue Ops[4]; 4704 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4705 Ops[0] = getRoot(); 4706 Ops[1] = getValue(I.getArgOperand(0)); 4707 Ops[2] = getValue(I.getArgOperand(1)); 4708 Ops[3] = getValue(I.getArgOperand(2)); 4709 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl, 4710 DAG.getVTList(MVT::Other), 4711 &Ops[0], 4, 4712 EVT::getIntegerVT(*Context, 8), 4713 MachinePointerInfo(I.getArgOperand(0)), 4714 0, /* align */ 4715 false, /* volatile */ 4716 rw==0, /* read */ 4717 rw==1)); /* write */ 4718 return 0; 4719 } 4720 case Intrinsic::memory_barrier: { 4721 SDValue Ops[6]; 4722 Ops[0] = getRoot(); 4723 for (int x = 1; x < 6; ++x) 4724 Ops[x] = getValue(I.getArgOperand(x - 1)); 4725 4726 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6)); 4727 return 0; 4728 } 4729 case Intrinsic::atomic_cmp_swap: { 4730 SDValue Root = getRoot(); 4731 SDValue L = 4732 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 4733 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(), 4734 Root, 4735 getValue(I.getArgOperand(0)), 4736 getValue(I.getArgOperand(1)), 4737 getValue(I.getArgOperand(2)), 4738 MachinePointerInfo(I.getArgOperand(0))); 4739 setValue(&I, L); 4740 DAG.setRoot(L.getValue(1)); 4741 return 0; 4742 } 4743 case Intrinsic::atomic_load_add: 4744 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD); 4745 case Intrinsic::atomic_load_sub: 4746 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB); 4747 case Intrinsic::atomic_load_or: 4748 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR); 4749 case Intrinsic::atomic_load_xor: 4750 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR); 4751 case Intrinsic::atomic_load_and: 4752 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND); 4753 case Intrinsic::atomic_load_nand: 4754 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND); 4755 case Intrinsic::atomic_load_max: 4756 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX); 4757 case Intrinsic::atomic_load_min: 4758 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN); 4759 case Intrinsic::atomic_load_umin: 4760 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN); 4761 case Intrinsic::atomic_load_umax: 4762 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX); 4763 case Intrinsic::atomic_swap: 4764 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP); 4765 4766 case Intrinsic::invariant_start: 4767 case Intrinsic::lifetime_start: 4768 // Discard region information. 4769 setValue(&I, DAG.getUNDEF(TLI.getPointerTy())); 4770 return 0; 4771 case Intrinsic::invariant_end: 4772 case Intrinsic::lifetime_end: 4773 // Discard region information. 4774 return 0; 4775 } 4776 } 4777 4778 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 4779 bool isTailCall, 4780 MachineBasicBlock *LandingPad) { 4781 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 4782 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 4783 const Type *RetTy = FTy->getReturnType(); 4784 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4785 MCSymbol *BeginLabel = 0; 4786 4787 TargetLowering::ArgListTy Args; 4788 TargetLowering::ArgListEntry Entry; 4789 Args.reserve(CS.arg_size()); 4790 4791 // Check whether the function can return without sret-demotion. 4792 SmallVector<ISD::OutputArg, 4> Outs; 4793 SmallVector<uint64_t, 4> Offsets; 4794 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), 4795 Outs, TLI, &Offsets); 4796 4797 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 4798 FTy->isVarArg(), Outs, FTy->getContext()); 4799 4800 SDValue DemoteStackSlot; 4801 int DemoteStackIdx = -100; 4802 4803 if (!CanLowerReturn) { 4804 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize( 4805 FTy->getReturnType()); 4806 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment( 4807 FTy->getReturnType()); 4808 MachineFunction &MF = DAG.getMachineFunction(); 4809 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 4810 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 4811 4812 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy()); 4813 Entry.Node = DemoteStackSlot; 4814 Entry.Ty = StackSlotPtrType; 4815 Entry.isSExt = false; 4816 Entry.isZExt = false; 4817 Entry.isInReg = false; 4818 Entry.isSRet = true; 4819 Entry.isNest = false; 4820 Entry.isByVal = false; 4821 Entry.Alignment = Align; 4822 Args.push_back(Entry); 4823 RetTy = Type::getVoidTy(FTy->getContext()); 4824 } 4825 4826 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 4827 i != e; ++i) { 4828 SDValue ArgNode = getValue(*i); 4829 Entry.Node = ArgNode; Entry.Ty = (*i)->getType(); 4830 4831 unsigned attrInd = i - CS.arg_begin() + 1; 4832 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 4833 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 4834 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 4835 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 4836 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 4837 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 4838 Entry.Alignment = CS.getParamAlignment(attrInd); 4839 Args.push_back(Entry); 4840 } 4841 4842 if (LandingPad) { 4843 // Insert a label before the invoke call to mark the try range. This can be 4844 // used to detect deletion of the invoke via the MachineModuleInfo. 4845 BeginLabel = MMI.getContext().CreateTempSymbol(); 4846 4847 // For SjLj, keep track of which landing pads go with which invokes 4848 // so as to maintain the ordering of pads in the LSDA. 4849 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 4850 if (CallSiteIndex) { 4851 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 4852 // Now that the call site is handled, stop tracking it. 4853 MMI.setCurrentCallSite(0); 4854 } 4855 4856 // Both PendingLoads and PendingExports must be flushed here; 4857 // this call might not return. 4858 (void)getRoot(); 4859 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel)); 4860 } 4861 4862 // Check if target-independent constraints permit a tail call here. 4863 // Target-dependent constraints are checked within TLI.LowerCallTo. 4864 if (isTailCall && 4865 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI)) 4866 isTailCall = false; 4867 4868 // If there's a possibility that fast-isel has already selected some amount 4869 // of the current basic block, don't emit a tail call. 4870 if (isTailCall && EnableFastISel) 4871 isTailCall = false; 4872 4873 std::pair<SDValue,SDValue> Result = 4874 TLI.LowerCallTo(getRoot(), RetTy, 4875 CS.paramHasAttr(0, Attribute::SExt), 4876 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(), 4877 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(), 4878 CS.getCallingConv(), 4879 isTailCall, 4880 !CS.getInstruction()->use_empty(), 4881 Callee, Args, DAG, getCurDebugLoc()); 4882 assert((isTailCall || Result.second.getNode()) && 4883 "Non-null chain expected with non-tail call!"); 4884 assert((Result.second.getNode() || !Result.first.getNode()) && 4885 "Null value expected with tail call!"); 4886 if (Result.first.getNode()) { 4887 setValue(CS.getInstruction(), Result.first); 4888 } else if (!CanLowerReturn && Result.second.getNode()) { 4889 // The instruction result is the result of loading from the 4890 // hidden sret parameter. 4891 SmallVector<EVT, 1> PVTs; 4892 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 4893 4894 ComputeValueVTs(TLI, PtrRetTy, PVTs); 4895 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 4896 EVT PtrVT = PVTs[0]; 4897 unsigned NumValues = Outs.size(); 4898 SmallVector<SDValue, 4> Values(NumValues); 4899 SmallVector<SDValue, 4> Chains(NumValues); 4900 4901 for (unsigned i = 0; i < NumValues; ++i) { 4902 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, 4903 DemoteStackSlot, 4904 DAG.getConstant(Offsets[i], PtrVT)); 4905 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second, 4906 Add, 4907 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), 4908 false, false, 1); 4909 Values[i] = L; 4910 Chains[i] = L.getValue(1); 4911 } 4912 4913 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 4914 MVT::Other, &Chains[0], NumValues); 4915 PendingLoads.push_back(Chain); 4916 4917 // Collect the legal value parts into potentially illegal values 4918 // that correspond to the original function's return values. 4919 SmallVector<EVT, 4> RetTys; 4920 RetTy = FTy->getReturnType(); 4921 ComputeValueVTs(TLI, RetTy, RetTys); 4922 ISD::NodeType AssertOp = ISD::DELETED_NODE; 4923 SmallVector<SDValue, 4> ReturnValues; 4924 unsigned CurReg = 0; 4925 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 4926 EVT VT = RetTys[I]; 4927 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT); 4928 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT); 4929 4930 SDValue ReturnValue = 4931 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs, 4932 RegisterVT, VT, AssertOp); 4933 ReturnValues.push_back(ReturnValue); 4934 CurReg += NumRegs; 4935 } 4936 4937 setValue(CS.getInstruction(), 4938 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 4939 DAG.getVTList(&RetTys[0], RetTys.size()), 4940 &ReturnValues[0], ReturnValues.size())); 4941 4942 } 4943 4944 // As a special case, a null chain means that a tail call has been emitted and 4945 // the DAG root is already updated. 4946 if (Result.second.getNode()) 4947 DAG.setRoot(Result.second); 4948 else 4949 HasTailCall = true; 4950 4951 if (LandingPad) { 4952 // Insert a label at the end of the invoke call to mark the try range. This 4953 // can be used to detect deletion of the invoke via the MachineModuleInfo. 4954 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol(); 4955 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel)); 4956 4957 // Inform MachineModuleInfo of range. 4958 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 4959 } 4960 } 4961 4962 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 4963 /// value is equal or not-equal to zero. 4964 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 4965 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 4966 UI != E; ++UI) { 4967 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 4968 if (IC->isEquality()) 4969 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 4970 if (C->isNullValue()) 4971 continue; 4972 // Unknown instruction. 4973 return false; 4974 } 4975 return true; 4976 } 4977 4978 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 4979 const Type *LoadTy, 4980 SelectionDAGBuilder &Builder) { 4981 4982 // Check to see if this load can be trivially constant folded, e.g. if the 4983 // input is from a string literal. 4984 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 4985 // Cast pointer to the type we really want to load. 4986 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 4987 PointerType::getUnqual(LoadTy)); 4988 4989 if (const Constant *LoadCst = 4990 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 4991 Builder.TD)) 4992 return Builder.getValue(LoadCst); 4993 } 4994 4995 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 4996 // still constant memory, the input chain can be the entry node. 4997 SDValue Root; 4998 bool ConstantMemory = false; 4999 5000 // Do not serialize (non-volatile) loads of constant memory with anything. 5001 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5002 Root = Builder.DAG.getEntryNode(); 5003 ConstantMemory = true; 5004 } else { 5005 // Do not serialize non-volatile loads against each other. 5006 Root = Builder.DAG.getRoot(); 5007 } 5008 5009 SDValue Ptr = Builder.getValue(PtrVal); 5010 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root, 5011 Ptr, MachinePointerInfo(PtrVal), 5012 false /*volatile*/, 5013 false /*nontemporal*/, 1 /* align=1 */); 5014 5015 if (!ConstantMemory) 5016 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5017 return LoadVal; 5018 } 5019 5020 5021 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5022 /// If so, return true and lower it, otherwise return false and it will be 5023 /// lowered like a normal call. 5024 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5025 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5026 if (I.getNumArgOperands() != 3) 5027 return false; 5028 5029 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5030 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5031 !I.getArgOperand(2)->getType()->isIntegerTy() || 5032 !I.getType()->isIntegerTy()) 5033 return false; 5034 5035 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2)); 5036 5037 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5038 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5039 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) { 5040 bool ActuallyDoIt = true; 5041 MVT LoadVT; 5042 const Type *LoadTy; 5043 switch (Size->getZExtValue()) { 5044 default: 5045 LoadVT = MVT::Other; 5046 LoadTy = 0; 5047 ActuallyDoIt = false; 5048 break; 5049 case 2: 5050 LoadVT = MVT::i16; 5051 LoadTy = Type::getInt16Ty(Size->getContext()); 5052 break; 5053 case 4: 5054 LoadVT = MVT::i32; 5055 LoadTy = Type::getInt32Ty(Size->getContext()); 5056 break; 5057 case 8: 5058 LoadVT = MVT::i64; 5059 LoadTy = Type::getInt64Ty(Size->getContext()); 5060 break; 5061 /* 5062 case 16: 5063 LoadVT = MVT::v4i32; 5064 LoadTy = Type::getInt32Ty(Size->getContext()); 5065 LoadTy = VectorType::get(LoadTy, 4); 5066 break; 5067 */ 5068 } 5069 5070 // This turns into unaligned loads. We only do this if the target natively 5071 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5072 // we'll only produce a small number of byte loads. 5073 5074 // Require that we can find a legal MVT, and only do this if the target 5075 // supports unaligned loads of that type. Expanding into byte loads would 5076 // bloat the code. 5077 if (ActuallyDoIt && Size->getZExtValue() > 4) { 5078 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5079 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5080 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT)) 5081 ActuallyDoIt = false; 5082 } 5083 5084 if (ActuallyDoIt) { 5085 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5086 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5087 5088 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal, 5089 ISD::SETNE); 5090 EVT CallVT = TLI.getValueType(I.getType(), true); 5091 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT)); 5092 return true; 5093 } 5094 } 5095 5096 5097 return false; 5098 } 5099 5100 5101 void SelectionDAGBuilder::visitCall(const CallInst &I) { 5102 // Handle inline assembly differently. 5103 if (isa<InlineAsm>(I.getCalledValue())) { 5104 visitInlineAsm(&I); 5105 return; 5106 } 5107 5108 // See if any floating point values are being passed to this function. This is 5109 // used to emit an undefined reference to fltused on Windows. 5110 const FunctionType *FT = 5111 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0)); 5112 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5113 if (FT->isVarArg() && 5114 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) { 5115 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 5116 const Type* T = I.getArgOperand(i)->getType(); 5117 for (po_iterator<const Type*> i = po_begin(T), e = po_end(T); 5118 i != e; ++i) { 5119 if (!i->isFloatingPointTy()) continue; 5120 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true); 5121 break; 5122 } 5123 } 5124 } 5125 5126 const char *RenameFn = 0; 5127 if (Function *F = I.getCalledFunction()) { 5128 if (F->isDeclaration()) { 5129 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 5130 if (unsigned IID = II->getIntrinsicID(F)) { 5131 RenameFn = visitIntrinsicCall(I, IID); 5132 if (!RenameFn) 5133 return; 5134 } 5135 } 5136 if (unsigned IID = F->getIntrinsicID()) { 5137 RenameFn = visitIntrinsicCall(I, IID); 5138 if (!RenameFn) 5139 return; 5140 } 5141 } 5142 5143 // Check for well-known libc/libm calls. If the function is internal, it 5144 // can't be a library call. 5145 if (!F->hasLocalLinkage() && F->hasName()) { 5146 StringRef Name = F->getName(); 5147 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") { 5148 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 5149 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5150 I.getType() == I.getArgOperand(0)->getType() && 5151 I.getType() == I.getArgOperand(1)->getType()) { 5152 SDValue LHS = getValue(I.getArgOperand(0)); 5153 SDValue RHS = getValue(I.getArgOperand(1)); 5154 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 5155 LHS.getValueType(), LHS, RHS)); 5156 return; 5157 } 5158 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") { 5159 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5160 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5161 I.getType() == I.getArgOperand(0)->getType()) { 5162 SDValue Tmp = getValue(I.getArgOperand(0)); 5163 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 5164 Tmp.getValueType(), Tmp)); 5165 return; 5166 } 5167 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") { 5168 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5169 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5170 I.getType() == I.getArgOperand(0)->getType() && 5171 I.onlyReadsMemory()) { 5172 SDValue Tmp = getValue(I.getArgOperand(0)); 5173 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 5174 Tmp.getValueType(), Tmp)); 5175 return; 5176 } 5177 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") { 5178 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5179 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5180 I.getType() == I.getArgOperand(0)->getType() && 5181 I.onlyReadsMemory()) { 5182 SDValue Tmp = getValue(I.getArgOperand(0)); 5183 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 5184 Tmp.getValueType(), Tmp)); 5185 return; 5186 } 5187 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") { 5188 if (I.getNumArgOperands() == 1 && // Basic sanity checks. 5189 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5190 I.getType() == I.getArgOperand(0)->getType() && 5191 I.onlyReadsMemory()) { 5192 SDValue Tmp = getValue(I.getArgOperand(0)); 5193 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(), 5194 Tmp.getValueType(), Tmp)); 5195 return; 5196 } 5197 } else if (Name == "memcmp") { 5198 if (visitMemCmpCall(I)) 5199 return; 5200 } 5201 } 5202 } 5203 5204 SDValue Callee; 5205 if (!RenameFn) 5206 Callee = getValue(I.getCalledValue()); 5207 else 5208 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 5209 5210 // Check if we can potentially perform a tail call. More detailed checking is 5211 // be done within LowerCallTo, after more information about the call is known. 5212 LowerCallTo(&I, Callee, I.isTailCall()); 5213 } 5214 5215 namespace llvm { 5216 5217 /// AsmOperandInfo - This contains information for each constraint that we are 5218 /// lowering. 5219 class LLVM_LIBRARY_VISIBILITY SDISelAsmOperandInfo : 5220 public TargetLowering::AsmOperandInfo { 5221 public: 5222 /// CallOperand - If this is the result output operand or a clobber 5223 /// this is null, otherwise it is the incoming operand to the CallInst. 5224 /// This gets modified as the asm is processed. 5225 SDValue CallOperand; 5226 5227 /// AssignedRegs - If this is a register or register class operand, this 5228 /// contains the set of register corresponding to the operand. 5229 RegsForValue AssignedRegs; 5230 5231 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 5232 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 5233 } 5234 5235 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 5236 /// busy in OutputRegs/InputRegs. 5237 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 5238 std::set<unsigned> &OutputRegs, 5239 std::set<unsigned> &InputRegs, 5240 const TargetRegisterInfo &TRI) const { 5241 if (isOutReg) { 5242 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5243 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 5244 } 5245 if (isInReg) { 5246 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 5247 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 5248 } 5249 } 5250 5251 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 5252 /// corresponds to. If there is no Value* for this operand, it returns 5253 /// MVT::Other. 5254 EVT getCallOperandValEVT(LLVMContext &Context, 5255 const TargetLowering &TLI, 5256 const TargetData *TD) const { 5257 if (CallOperandVal == 0) return MVT::Other; 5258 5259 if (isa<BasicBlock>(CallOperandVal)) 5260 return TLI.getPointerTy(); 5261 5262 const llvm::Type *OpTy = CallOperandVal->getType(); 5263 5264 // If this is an indirect operand, the operand is a pointer to the 5265 // accessed type. 5266 if (isIndirect) { 5267 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5268 if (!PtrTy) 5269 report_fatal_error("Indirect operand for inline asm not a pointer!"); 5270 OpTy = PtrTy->getElementType(); 5271 } 5272 5273 // If OpTy is not a single value, it may be a struct/union that we 5274 // can tile with integers. 5275 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5276 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 5277 switch (BitSize) { 5278 default: break; 5279 case 1: 5280 case 8: 5281 case 16: 5282 case 32: 5283 case 64: 5284 case 128: 5285 OpTy = IntegerType::get(Context, BitSize); 5286 break; 5287 } 5288 } 5289 5290 return TLI.getValueType(OpTy, true); 5291 } 5292 5293 private: 5294 /// MarkRegAndAliases - Mark the specified register and all aliases in the 5295 /// specified set. 5296 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 5297 const TargetRegisterInfo &TRI) { 5298 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 5299 Regs.insert(Reg); 5300 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 5301 for (; *Aliases; ++Aliases) 5302 Regs.insert(*Aliases); 5303 } 5304 }; 5305 5306 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 5307 5308 } // end llvm namespace. 5309 5310 /// isAllocatableRegister - If the specified register is safe to allocate, 5311 /// i.e. it isn't a stack pointer or some other special register, return the 5312 /// register class for the register. Otherwise, return null. 5313 static const TargetRegisterClass * 5314 isAllocatableRegister(unsigned Reg, MachineFunction &MF, 5315 const TargetLowering &TLI, 5316 const TargetRegisterInfo *TRI) { 5317 EVT FoundVT = MVT::Other; 5318 const TargetRegisterClass *FoundRC = 0; 5319 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(), 5320 E = TRI->regclass_end(); RCI != E; ++RCI) { 5321 EVT ThisVT = MVT::Other; 5322 5323 const TargetRegisterClass *RC = *RCI; 5324 // If none of the value types for this register class are valid, we 5325 // can't use it. For example, 64-bit reg classes on 32-bit targets. 5326 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 5327 I != E; ++I) { 5328 if (TLI.isTypeLegal(*I)) { 5329 // If we have already found this register in a different register class, 5330 // choose the one with the largest VT specified. For example, on 5331 // PowerPC, we favor f64 register classes over f32. 5332 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) { 5333 ThisVT = *I; 5334 break; 5335 } 5336 } 5337 } 5338 5339 if (ThisVT == MVT::Other) continue; 5340 5341 // NOTE: This isn't ideal. In particular, this might allocate the 5342 // frame pointer in functions that need it (due to them not being taken 5343 // out of allocation, because a variable sized allocation hasn't been seen 5344 // yet). This is a slight code pessimization, but should still work. 5345 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 5346 E = RC->allocation_order_end(MF); I != E; ++I) 5347 if (*I == Reg) { 5348 // We found a matching register class. Keep looking at others in case 5349 // we find one with larger registers that this physreg is also in. 5350 FoundRC = RC; 5351 FoundVT = ThisVT; 5352 break; 5353 } 5354 } 5355 return FoundRC; 5356 } 5357 5358 /// GetRegistersForValue - Assign registers (virtual or physical) for the 5359 /// specified operand. We prefer to assign virtual registers, to allow the 5360 /// register allocator to handle the assignment process. However, if the asm 5361 /// uses features that we can't model on machineinstrs, we have SDISel do the 5362 /// allocation. This produces generally horrible, but correct, code. 5363 /// 5364 /// OpInfo describes the operand. 5365 /// Input and OutputRegs are the set of already allocated physical registers. 5366 /// 5367 void SelectionDAGBuilder:: 5368 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, 5369 std::set<unsigned> &OutputRegs, 5370 std::set<unsigned> &InputRegs) { 5371 LLVMContext &Context = FuncInfo.Fn->getContext(); 5372 5373 // Compute whether this value requires an input register, an output register, 5374 // or both. 5375 bool isOutReg = false; 5376 bool isInReg = false; 5377 switch (OpInfo.Type) { 5378 case InlineAsm::isOutput: 5379 isOutReg = true; 5380 5381 // If there is an input constraint that matches this, we need to reserve 5382 // the input register so no other inputs allocate to it. 5383 isInReg = OpInfo.hasMatchingInput(); 5384 break; 5385 case InlineAsm::isInput: 5386 isInReg = true; 5387 isOutReg = false; 5388 break; 5389 case InlineAsm::isClobber: 5390 isOutReg = true; 5391 isInReg = true; 5392 break; 5393 } 5394 5395 5396 MachineFunction &MF = DAG.getMachineFunction(); 5397 SmallVector<unsigned, 4> Regs; 5398 5399 // If this is a constraint for a single physreg, or a constraint for a 5400 // register class, find it. 5401 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 5402 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 5403 OpInfo.ConstraintVT); 5404 5405 unsigned NumRegs = 1; 5406 if (OpInfo.ConstraintVT != MVT::Other) { 5407 // If this is a FP input in an integer register (or visa versa) insert a bit 5408 // cast of the input value. More generally, handle any case where the input 5409 // value disagrees with the register class we plan to stick this in. 5410 if (OpInfo.Type == InlineAsm::isInput && 5411 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5412 // Try to convert to the first EVT that the reg class contains. If the 5413 // types are identical size, use a bitcast to convert (e.g. two differing 5414 // vector types). 5415 EVT RegVT = *PhysReg.second->vt_begin(); 5416 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 5417 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 5418 RegVT, OpInfo.CallOperand); 5419 OpInfo.ConstraintVT = RegVT; 5420 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5421 // If the input is a FP value and we want it in FP registers, do a 5422 // bitcast to the corresponding integer type. This turns an f64 value 5423 // into i64, which can be passed with two i32 values on a 32-bit 5424 // machine. 5425 RegVT = EVT::getIntegerVT(Context, 5426 OpInfo.ConstraintVT.getSizeInBits()); 5427 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 5428 RegVT, OpInfo.CallOperand); 5429 OpInfo.ConstraintVT = RegVT; 5430 } 5431 } 5432 5433 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5434 } 5435 5436 EVT RegVT; 5437 EVT ValueVT = OpInfo.ConstraintVT; 5438 5439 // If this is a constraint for a specific physical register, like {r17}, 5440 // assign it now. 5441 if (unsigned AssignedReg = PhysReg.first) { 5442 const TargetRegisterClass *RC = PhysReg.second; 5443 if (OpInfo.ConstraintVT == MVT::Other) 5444 ValueVT = *RC->vt_begin(); 5445 5446 // Get the actual register value type. This is important, because the user 5447 // may have asked for (e.g.) the AX register in i32 type. We need to 5448 // remember that AX is actually i16 to get the right extension. 5449 RegVT = *RC->vt_begin(); 5450 5451 // This is a explicit reference to a physical register. 5452 Regs.push_back(AssignedReg); 5453 5454 // If this is an expanded reference, add the rest of the regs to Regs. 5455 if (NumRegs != 1) { 5456 TargetRegisterClass::iterator I = RC->begin(); 5457 for (; *I != AssignedReg; ++I) 5458 assert(I != RC->end() && "Didn't find reg!"); 5459 5460 // Already added the first reg. 5461 --NumRegs; ++I; 5462 for (; NumRegs; --NumRegs, ++I) { 5463 assert(I != RC->end() && "Ran out of registers to allocate!"); 5464 Regs.push_back(*I); 5465 } 5466 } 5467 5468 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5469 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5470 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5471 return; 5472 } 5473 5474 // Otherwise, if this was a reference to an LLVM register class, create vregs 5475 // for this reference. 5476 if (const TargetRegisterClass *RC = PhysReg.second) { 5477 RegVT = *RC->vt_begin(); 5478 if (OpInfo.ConstraintVT == MVT::Other) 5479 ValueVT = RegVT; 5480 5481 // Create the appropriate number of virtual registers. 5482 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5483 for (; NumRegs; --NumRegs) 5484 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5485 5486 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5487 return; 5488 } 5489 5490 // This is a reference to a register class that doesn't directly correspond 5491 // to an LLVM register class. Allocate NumRegs consecutive, available, 5492 // registers from the class. 5493 std::vector<unsigned> RegClassRegs 5494 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 5495 OpInfo.ConstraintVT); 5496 5497 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5498 unsigned NumAllocated = 0; 5499 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 5500 unsigned Reg = RegClassRegs[i]; 5501 // See if this register is available. 5502 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 5503 (isInReg && InputRegs.count(Reg))) { // Already used. 5504 // Make sure we find consecutive registers. 5505 NumAllocated = 0; 5506 continue; 5507 } 5508 5509 // Check to see if this register is allocatable (i.e. don't give out the 5510 // stack pointer). 5511 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI); 5512 if (!RC) { // Couldn't allocate this register. 5513 // Reset NumAllocated to make sure we return consecutive registers. 5514 NumAllocated = 0; 5515 continue; 5516 } 5517 5518 // Okay, this register is good, we can use it. 5519 ++NumAllocated; 5520 5521 // If we allocated enough consecutive registers, succeed. 5522 if (NumAllocated == NumRegs) { 5523 unsigned RegStart = (i-NumAllocated)+1; 5524 unsigned RegEnd = i+1; 5525 // Mark all of the allocated registers used. 5526 for (unsigned i = RegStart; i != RegEnd; ++i) 5527 Regs.push_back(RegClassRegs[i]); 5528 5529 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(), 5530 OpInfo.ConstraintVT); 5531 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5532 return; 5533 } 5534 } 5535 5536 // Otherwise, we couldn't allocate enough registers for this. 5537 } 5538 5539 /// visitInlineAsm - Handle a call to an InlineAsm object. 5540 /// 5541 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 5542 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5543 5544 /// ConstraintOperands - Information about all of the constraints. 5545 SDISelAsmOperandInfoVector ConstraintOperands; 5546 5547 std::set<unsigned> OutputRegs, InputRegs; 5548 5549 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(CS); 5550 bool hasMemory = false; 5551 5552 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5553 unsigned ResNo = 0; // ResNo - The result number of the next output. 5554 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 5555 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 5556 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5557 5558 EVT OpVT = MVT::Other; 5559 5560 // Compute the value type for each operand. 5561 switch (OpInfo.Type) { 5562 case InlineAsm::isOutput: 5563 // Indirect outputs just consume an argument. 5564 if (OpInfo.isIndirect) { 5565 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5566 break; 5567 } 5568 5569 // The return value of the call is this value. As such, there is no 5570 // corresponding argument. 5571 assert(!CS.getType()->isVoidTy() && 5572 "Bad inline asm!"); 5573 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) { 5574 OpVT = TLI.getValueType(STy->getElementType(ResNo)); 5575 } else { 5576 assert(ResNo == 0 && "Asm only has one result!"); 5577 OpVT = TLI.getValueType(CS.getType()); 5578 } 5579 ++ResNo; 5580 break; 5581 case InlineAsm::isInput: 5582 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5583 break; 5584 case InlineAsm::isClobber: 5585 // Nothing to do. 5586 break; 5587 } 5588 5589 // If this is an input or an indirect output, process the call argument. 5590 // BasicBlocks are labels, currently appearing only in asm's. 5591 if (OpInfo.CallOperandVal) { 5592 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5593 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5594 } else { 5595 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5596 } 5597 5598 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD); 5599 } 5600 5601 OpInfo.ConstraintVT = OpVT; 5602 5603 // Indirect operand accesses access memory. 5604 if (OpInfo.isIndirect) 5605 hasMemory = true; 5606 else { 5607 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 5608 TargetLowering::ConstraintType CType = TLI.getConstraintType(OpInfo.Codes[j]); 5609 if (CType == TargetLowering::C_Memory) { 5610 hasMemory = true; 5611 break; 5612 } 5613 } 5614 } 5615 } 5616 5617 SDValue Chain, Flag; 5618 5619 // We won't need to flush pending loads if this asm doesn't touch 5620 // memory and is nonvolatile. 5621 if (hasMemory || IA->hasSideEffects()) 5622 Chain = getRoot(); 5623 else 5624 Chain = DAG.getRoot(); 5625 5626 // Second pass over the constraints: compute which constraint option to use 5627 // and assign registers to constraints that want a specific physreg. 5628 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5629 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5630 5631 // If this is an output operand with a matching input operand, look up the 5632 // matching input. If their types mismatch, e.g. one is an integer, the 5633 // other is floating point, or their sizes are different, flag it as an 5634 // error. 5635 if (OpInfo.hasMatchingInput()) { 5636 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5637 5638 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5639 if ((OpInfo.ConstraintVT.isInteger() != 5640 Input.ConstraintVT.isInteger()) || 5641 (OpInfo.ConstraintVT.getSizeInBits() != 5642 Input.ConstraintVT.getSizeInBits())) { 5643 report_fatal_error("Unsupported asm: input constraint" 5644 " with a matching output constraint of" 5645 " incompatible type!"); 5646 } 5647 Input.ConstraintVT = OpInfo.ConstraintVT; 5648 } 5649 } 5650 5651 // Compute the constraint code and ConstraintType to use. 5652 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 5653 5654 // If this is a memory input, and if the operand is not indirect, do what we 5655 // need to to provide an address for the memory input. 5656 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5657 !OpInfo.isIndirect) { 5658 assert((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) && 5659 "Can only indirectify direct input operands!"); 5660 5661 // Memory operands really want the address of the value. If we don't have 5662 // an indirect input, put it in the constpool if we can, otherwise spill 5663 // it to a stack slot. 5664 5665 // If the operand is a float, integer, or vector constant, spill to a 5666 // constant pool entry to get its address. 5667 const Value *OpVal = OpInfo.CallOperandVal; 5668 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 5669 isa<ConstantVector>(OpVal)) { 5670 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 5671 TLI.getPointerTy()); 5672 } else { 5673 // Otherwise, create a stack slot and emit a store to it before the 5674 // asm. 5675 const Type *Ty = OpVal->getType(); 5676 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 5677 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 5678 MachineFunction &MF = DAG.getMachineFunction(); 5679 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5680 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 5681 Chain = DAG.getStore(Chain, getCurDebugLoc(), 5682 OpInfo.CallOperand, StackSlot, 5683 MachinePointerInfo::getFixedStack(SSFI), 5684 false, false, 0); 5685 OpInfo.CallOperand = StackSlot; 5686 } 5687 5688 // There is no longer a Value* corresponding to this operand. 5689 OpInfo.CallOperandVal = 0; 5690 5691 // It is now an indirect operand. 5692 OpInfo.isIndirect = true; 5693 } 5694 5695 // If this constraint is for a specific register, allocate it before 5696 // anything else. 5697 if (OpInfo.ConstraintType == TargetLowering::C_Register) 5698 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5699 } 5700 5701 // Second pass - Loop over all of the operands, assigning virtual or physregs 5702 // to register class operands. 5703 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5704 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5705 5706 // C_Register operands have already been allocated, Other/Memory don't need 5707 // to be. 5708 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 5709 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5710 } 5711 5712 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 5713 std::vector<SDValue> AsmNodeOperands; 5714 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 5715 AsmNodeOperands.push_back( 5716 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 5717 TLI.getPointerTy())); 5718 5719 // If we have a !srcloc metadata node associated with it, we want to attach 5720 // this to the ultimately generated inline asm machineinstr. To do this, we 5721 // pass in the third operand as this (potentially null) inline asm MDNode. 5722 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 5723 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 5724 5725 // Remember the AlignStack bit as operand 3. 5726 AsmNodeOperands.push_back(DAG.getTargetConstant(IA->isAlignStack() ? 1 : 0, 5727 MVT::i1)); 5728 5729 // Loop over all of the inputs, copying the operand values into the 5730 // appropriate registers and processing the output regs. 5731 RegsForValue RetValRegs; 5732 5733 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 5734 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 5735 5736 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5737 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5738 5739 switch (OpInfo.Type) { 5740 case InlineAsm::isOutput: { 5741 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 5742 OpInfo.ConstraintType != TargetLowering::C_Register) { 5743 // Memory output, or 'other' output (e.g. 'X' constraint). 5744 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 5745 5746 // Add information to the INLINEASM node to know about this output. 5747 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 5748 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, 5749 TLI.getPointerTy())); 5750 AsmNodeOperands.push_back(OpInfo.CallOperand); 5751 break; 5752 } 5753 5754 // Otherwise, this is a register or register class output. 5755 5756 // Copy the output from the appropriate register. Find a register that 5757 // we can use. 5758 if (OpInfo.AssignedRegs.Regs.empty()) 5759 report_fatal_error("Couldn't allocate output reg for constraint '" + 5760 Twine(OpInfo.ConstraintCode) + "'!"); 5761 5762 // If this is an indirect operand, store through the pointer after the 5763 // asm. 5764 if (OpInfo.isIndirect) { 5765 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 5766 OpInfo.CallOperandVal)); 5767 } else { 5768 // This is the result value of the call. 5769 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5770 // Concatenate this output onto the outputs list. 5771 RetValRegs.append(OpInfo.AssignedRegs); 5772 } 5773 5774 // Add information to the INLINEASM node to know that this register is 5775 // set. 5776 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ? 5777 InlineAsm::Kind_RegDefEarlyClobber : 5778 InlineAsm::Kind_RegDef, 5779 false, 5780 0, 5781 DAG, 5782 AsmNodeOperands); 5783 break; 5784 } 5785 case InlineAsm::isInput: { 5786 SDValue InOperandVal = OpInfo.CallOperand; 5787 5788 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 5789 // If this is required to match an output register we have already set, 5790 // just use its register. 5791 unsigned OperandNo = OpInfo.getMatchedOperand(); 5792 5793 // Scan until we find the definition we already emitted of this operand. 5794 // When we find it, create a RegsForValue operand. 5795 unsigned CurOp = InlineAsm::Op_FirstOperand; 5796 for (; OperandNo; --OperandNo) { 5797 // Advance to the next operand. 5798 unsigned OpFlag = 5799 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5800 assert((InlineAsm::isRegDefKind(OpFlag) || 5801 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 5802 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 5803 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 5804 } 5805 5806 unsigned OpFlag = 5807 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5808 if (InlineAsm::isRegDefKind(OpFlag) || 5809 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 5810 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 5811 if (OpInfo.isIndirect) { 5812 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 5813 LLVMContext &Ctx = *DAG.getContext(); 5814 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 5815 " don't know how to handle tied " 5816 "indirect register inputs"); 5817 } 5818 5819 RegsForValue MatchedRegs; 5820 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 5821 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType(); 5822 MatchedRegs.RegVTs.push_back(RegVT); 5823 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 5824 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 5825 i != e; ++i) 5826 MatchedRegs.Regs.push_back 5827 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); 5828 5829 // Use the produced MatchedRegs object to 5830 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5831 Chain, &Flag); 5832 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 5833 true, OpInfo.getMatchedOperand(), 5834 DAG, AsmNodeOperands); 5835 break; 5836 } 5837 5838 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 5839 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 5840 "Unexpected number of operands"); 5841 // Add information to the INLINEASM node to know about this input. 5842 // See InlineAsm.h isUseOperandTiedToDef. 5843 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 5844 OpInfo.getMatchedOperand()); 5845 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 5846 TLI.getPointerTy())); 5847 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 5848 break; 5849 } 5850 5851 // Treat indirect 'X' constraint as memory. 5852 if (OpInfo.ConstraintType == TargetLowering::C_Other && 5853 OpInfo.isIndirect) 5854 OpInfo.ConstraintType = TargetLowering::C_Memory; 5855 5856 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 5857 std::vector<SDValue> Ops; 5858 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0], 5859 Ops, DAG); 5860 if (Ops.empty()) 5861 report_fatal_error("Invalid operand for inline asm constraint '" + 5862 Twine(OpInfo.ConstraintCode) + "'!"); 5863 5864 // Add information to the INLINEASM node to know about this input. 5865 unsigned ResOpType = 5866 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 5867 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5868 TLI.getPointerTy())); 5869 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 5870 break; 5871 } 5872 5873 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 5874 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 5875 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 5876 "Memory operands expect pointer values"); 5877 5878 // Add information to the INLINEASM node to know about this input. 5879 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 5880 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5881 TLI.getPointerTy())); 5882 AsmNodeOperands.push_back(InOperandVal); 5883 break; 5884 } 5885 5886 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 5887 OpInfo.ConstraintType == TargetLowering::C_Register) && 5888 "Unknown constraint type!"); 5889 assert(!OpInfo.isIndirect && 5890 "Don't know how to handle indirect register inputs yet!"); 5891 5892 // Copy the input into the appropriate registers. 5893 if (OpInfo.AssignedRegs.Regs.empty() || 5894 !OpInfo.AssignedRegs.areValueTypesLegal(TLI)) 5895 report_fatal_error("Couldn't allocate input reg for constraint '" + 5896 Twine(OpInfo.ConstraintCode) + "'!"); 5897 5898 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5899 Chain, &Flag); 5900 5901 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 5902 DAG, AsmNodeOperands); 5903 break; 5904 } 5905 case InlineAsm::isClobber: { 5906 // Add the clobbered value to the operand list, so that the register 5907 // allocator is aware that the physreg got clobbered. 5908 if (!OpInfo.AssignedRegs.Regs.empty()) 5909 OpInfo.AssignedRegs.AddInlineAsmOperands( 5910 InlineAsm::Kind_RegDefEarlyClobber, 5911 false, 0, DAG, 5912 AsmNodeOperands); 5913 break; 5914 } 5915 } 5916 } 5917 5918 // Finish up input operands. Set the input chain and add the flag last. 5919 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 5920 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 5921 5922 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(), 5923 DAG.getVTList(MVT::Other, MVT::Flag), 5924 &AsmNodeOperands[0], AsmNodeOperands.size()); 5925 Flag = Chain.getValue(1); 5926 5927 // If this asm returns a register value, copy the result from that register 5928 // and set it as the value of the call. 5929 if (!RetValRegs.Regs.empty()) { 5930 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 5931 Chain, &Flag); 5932 5933 // FIXME: Why don't we do this for inline asms with MRVs? 5934 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 5935 EVT ResultType = TLI.getValueType(CS.getType()); 5936 5937 // If any of the results of the inline asm is a vector, it may have the 5938 // wrong width/num elts. This can happen for register classes that can 5939 // contain multiple different value types. The preg or vreg allocated may 5940 // not have the same VT as was expected. Convert it to the right type 5941 // with bit_convert. 5942 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 5943 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), 5944 ResultType, Val); 5945 5946 } else if (ResultType != Val.getValueType() && 5947 ResultType.isInteger() && Val.getValueType().isInteger()) { 5948 // If a result value was tied to an input value, the computed result may 5949 // have a wider width than the expected result. Extract the relevant 5950 // portion. 5951 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val); 5952 } 5953 5954 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 5955 } 5956 5957 setValue(CS.getInstruction(), Val); 5958 // Don't need to use this as a chain in this case. 5959 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 5960 return; 5961 } 5962 5963 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 5964 5965 // Process indirect outputs, first output all of the flagged copies out of 5966 // physregs. 5967 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 5968 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 5969 const Value *Ptr = IndirectStoresToEmit[i].second; 5970 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 5971 Chain, &Flag); 5972 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 5973 } 5974 5975 // Emit the non-flagged stores from the physregs. 5976 SmallVector<SDValue, 8> OutChains; 5977 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 5978 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(), 5979 StoresToEmit[i].first, 5980 getValue(StoresToEmit[i].second), 5981 MachinePointerInfo(StoresToEmit[i].second), 5982 false, false, 0); 5983 OutChains.push_back(Val); 5984 } 5985 5986 if (!OutChains.empty()) 5987 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 5988 &OutChains[0], OutChains.size()); 5989 5990 DAG.setRoot(Chain); 5991 } 5992 5993 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 5994 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(), 5995 MVT::Other, getRoot(), 5996 getValue(I.getArgOperand(0)), 5997 DAG.getSrcValue(I.getArgOperand(0)))); 5998 } 5999 6000 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 6001 const TargetData &TD = *TLI.getTargetData(); 6002 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(), 6003 getRoot(), getValue(I.getOperand(0)), 6004 DAG.getSrcValue(I.getOperand(0)), 6005 TD.getABITypeAlignment(I.getType())); 6006 setValue(&I, V); 6007 DAG.setRoot(V.getValue(1)); 6008 } 6009 6010 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 6011 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(), 6012 MVT::Other, getRoot(), 6013 getValue(I.getArgOperand(0)), 6014 DAG.getSrcValue(I.getArgOperand(0)))); 6015 } 6016 6017 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 6018 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(), 6019 MVT::Other, getRoot(), 6020 getValue(I.getArgOperand(0)), 6021 getValue(I.getArgOperand(1)), 6022 DAG.getSrcValue(I.getArgOperand(0)), 6023 DAG.getSrcValue(I.getArgOperand(1)))); 6024 } 6025 6026 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 6027 /// implementation, which just calls LowerCall. 6028 /// FIXME: When all targets are 6029 /// migrated to using LowerCall, this hook should be integrated into SDISel. 6030 std::pair<SDValue, SDValue> 6031 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy, 6032 bool RetSExt, bool RetZExt, bool isVarArg, 6033 bool isInreg, unsigned NumFixedArgs, 6034 CallingConv::ID CallConv, bool isTailCall, 6035 bool isReturnValueUsed, 6036 SDValue Callee, 6037 ArgListTy &Args, SelectionDAG &DAG, 6038 DebugLoc dl) const { 6039 // Handle all of the outgoing arguments. 6040 SmallVector<ISD::OutputArg, 32> Outs; 6041 SmallVector<SDValue, 32> OutVals; 6042 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6043 SmallVector<EVT, 4> ValueVTs; 6044 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 6045 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6046 Value != NumValues; ++Value) { 6047 EVT VT = ValueVTs[Value]; 6048 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext()); 6049 SDValue Op = SDValue(Args[i].Node.getNode(), 6050 Args[i].Node.getResNo() + Value); 6051 ISD::ArgFlagsTy Flags; 6052 unsigned OriginalAlignment = 6053 getTargetData()->getABITypeAlignment(ArgTy); 6054 6055 if (Args[i].isZExt) 6056 Flags.setZExt(); 6057 if (Args[i].isSExt) 6058 Flags.setSExt(); 6059 if (Args[i].isInReg) 6060 Flags.setInReg(); 6061 if (Args[i].isSRet) 6062 Flags.setSRet(); 6063 if (Args[i].isByVal) { 6064 Flags.setByVal(); 6065 const PointerType *Ty = cast<PointerType>(Args[i].Ty); 6066 const Type *ElementTy = Ty->getElementType(); 6067 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 6068 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy); 6069 // For ByVal, alignment should come from FE. BE will guess if this 6070 // info is not there but there are cases it cannot get right. 6071 if (Args[i].Alignment) 6072 FrameAlign = Args[i].Alignment; 6073 Flags.setByValAlign(FrameAlign); 6074 Flags.setByValSize(FrameSize); 6075 } 6076 if (Args[i].isNest) 6077 Flags.setNest(); 6078 Flags.setOrigAlign(OriginalAlignment); 6079 6080 EVT PartVT = getRegisterType(RetTy->getContext(), VT); 6081 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT); 6082 SmallVector<SDValue, 4> Parts(NumParts); 6083 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6084 6085 if (Args[i].isSExt) 6086 ExtendKind = ISD::SIGN_EXTEND; 6087 else if (Args[i].isZExt) 6088 ExtendKind = ISD::ZERO_EXTEND; 6089 6090 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, 6091 PartVT, ExtendKind); 6092 6093 for (unsigned j = 0; j != NumParts; ++j) { 6094 // if it isn't first piece, alignment must be 1 6095 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), 6096 i < NumFixedArgs); 6097 if (NumParts > 1 && j == 0) 6098 MyFlags.Flags.setSplit(); 6099 else if (j != 0) 6100 MyFlags.Flags.setOrigAlign(1); 6101 6102 Outs.push_back(MyFlags); 6103 OutVals.push_back(Parts[j]); 6104 } 6105 } 6106 } 6107 6108 // Handle the incoming return values from the call. 6109 SmallVector<ISD::InputArg, 32> Ins; 6110 SmallVector<EVT, 4> RetTys; 6111 ComputeValueVTs(*this, RetTy, RetTys); 6112 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6113 EVT VT = RetTys[I]; 6114 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6115 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6116 for (unsigned i = 0; i != NumRegs; ++i) { 6117 ISD::InputArg MyFlags; 6118 MyFlags.VT = RegisterVT.getSimpleVT(); 6119 MyFlags.Used = isReturnValueUsed; 6120 if (RetSExt) 6121 MyFlags.Flags.setSExt(); 6122 if (RetZExt) 6123 MyFlags.Flags.setZExt(); 6124 if (isInreg) 6125 MyFlags.Flags.setInReg(); 6126 Ins.push_back(MyFlags); 6127 } 6128 } 6129 6130 SmallVector<SDValue, 4> InVals; 6131 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall, 6132 Outs, OutVals, Ins, dl, DAG, InVals); 6133 6134 // Verify that the target's LowerCall behaved as expected. 6135 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 6136 "LowerCall didn't return a valid chain!"); 6137 assert((!isTailCall || InVals.empty()) && 6138 "LowerCall emitted a return value for a tail call!"); 6139 assert((isTailCall || InVals.size() == Ins.size()) && 6140 "LowerCall didn't emit the correct number of values!"); 6141 6142 // For a tail call, the return value is merely live-out and there aren't 6143 // any nodes in the DAG representing it. Return a special value to 6144 // indicate that a tail call has been emitted and no more Instructions 6145 // should be processed in the current block. 6146 if (isTailCall) { 6147 DAG.setRoot(Chain); 6148 return std::make_pair(SDValue(), SDValue()); 6149 } 6150 6151 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6152 assert(InVals[i].getNode() && 6153 "LowerCall emitted a null value!"); 6154 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 6155 "LowerCall emitted a value with the wrong type!"); 6156 }); 6157 6158 // Collect the legal value parts into potentially illegal values 6159 // that correspond to the original function's return values. 6160 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6161 if (RetSExt) 6162 AssertOp = ISD::AssertSext; 6163 else if (RetZExt) 6164 AssertOp = ISD::AssertZext; 6165 SmallVector<SDValue, 4> ReturnValues; 6166 unsigned CurReg = 0; 6167 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6168 EVT VT = RetTys[I]; 6169 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 6170 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 6171 6172 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg], 6173 NumRegs, RegisterVT, VT, 6174 AssertOp)); 6175 CurReg += NumRegs; 6176 } 6177 6178 // For a function returning void, there is no return value. We can't create 6179 // such a node, so we just return a null return value in that case. In 6180 // that case, nothing will actualy look at the value. 6181 if (ReturnValues.empty()) 6182 return std::make_pair(SDValue(), Chain); 6183 6184 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 6185 DAG.getVTList(&RetTys[0], RetTys.size()), 6186 &ReturnValues[0], ReturnValues.size()); 6187 return std::make_pair(Res, Chain); 6188 } 6189 6190 void TargetLowering::LowerOperationWrapper(SDNode *N, 6191 SmallVectorImpl<SDValue> &Results, 6192 SelectionDAG &DAG) const { 6193 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 6194 if (Res.getNode()) 6195 Results.push_back(Res); 6196 } 6197 6198 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6199 llvm_unreachable("LowerOperation not implemented for this target!"); 6200 return SDValue(); 6201 } 6202 6203 void 6204 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 6205 SDValue Op = getNonRegisterValue(V); 6206 assert((Op.getOpcode() != ISD::CopyFromReg || 6207 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 6208 "Copy from a reg to the same reg!"); 6209 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 6210 6211 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType()); 6212 SDValue Chain = DAG.getEntryNode(); 6213 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0); 6214 PendingExports.push_back(Chain); 6215 } 6216 6217 #include "llvm/CodeGen/SelectionDAGISel.h" 6218 6219 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) { 6220 // If this is the entry block, emit arguments. 6221 const Function &F = *LLVMBB->getParent(); 6222 SelectionDAG &DAG = SDB->DAG; 6223 DebugLoc dl = SDB->getCurDebugLoc(); 6224 const TargetData *TD = TLI.getTargetData(); 6225 SmallVector<ISD::InputArg, 16> Ins; 6226 6227 // Check whether the function can return without sret-demotion. 6228 SmallVector<ISD::OutputArg, 4> Outs; 6229 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), 6230 Outs, TLI); 6231 6232 if (!FuncInfo->CanLowerReturn) { 6233 // Put in an sret pointer parameter before all the other parameters. 6234 SmallVector<EVT, 1> ValueVTs; 6235 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6236 6237 // NOTE: Assuming that a pointer will never break down to more than one VT 6238 // or one register. 6239 ISD::ArgFlagsTy Flags; 6240 Flags.setSRet(); 6241 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]); 6242 ISD::InputArg RetArg(Flags, RegisterVT, true); 6243 Ins.push_back(RetArg); 6244 } 6245 6246 // Set up the incoming argument description vector. 6247 unsigned Idx = 1; 6248 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 6249 I != E; ++I, ++Idx) { 6250 SmallVector<EVT, 4> ValueVTs; 6251 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6252 bool isArgValueUsed = !I->use_empty(); 6253 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6254 Value != NumValues; ++Value) { 6255 EVT VT = ValueVTs[Value]; 6256 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 6257 ISD::ArgFlagsTy Flags; 6258 unsigned OriginalAlignment = 6259 TD->getABITypeAlignment(ArgTy); 6260 6261 if (F.paramHasAttr(Idx, Attribute::ZExt)) 6262 Flags.setZExt(); 6263 if (F.paramHasAttr(Idx, Attribute::SExt)) 6264 Flags.setSExt(); 6265 if (F.paramHasAttr(Idx, Attribute::InReg)) 6266 Flags.setInReg(); 6267 if (F.paramHasAttr(Idx, Attribute::StructRet)) 6268 Flags.setSRet(); 6269 if (F.paramHasAttr(Idx, Attribute::ByVal)) { 6270 Flags.setByVal(); 6271 const PointerType *Ty = cast<PointerType>(I->getType()); 6272 const Type *ElementTy = Ty->getElementType(); 6273 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy); 6274 unsigned FrameSize = TD->getTypeAllocSize(ElementTy); 6275 // For ByVal, alignment should be passed from FE. BE will guess if 6276 // this info is not there but there are cases it cannot get right. 6277 if (F.getParamAlignment(Idx)) 6278 FrameAlign = F.getParamAlignment(Idx); 6279 Flags.setByValAlign(FrameAlign); 6280 Flags.setByValSize(FrameSize); 6281 } 6282 if (F.paramHasAttr(Idx, Attribute::Nest)) 6283 Flags.setNest(); 6284 Flags.setOrigAlign(OriginalAlignment); 6285 6286 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6287 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6288 for (unsigned i = 0; i != NumRegs; ++i) { 6289 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed); 6290 if (NumRegs > 1 && i == 0) 6291 MyFlags.Flags.setSplit(); 6292 // if it isn't first piece, alignment must be 1 6293 else if (i > 0) 6294 MyFlags.Flags.setOrigAlign(1); 6295 Ins.push_back(MyFlags); 6296 } 6297 } 6298 } 6299 6300 // Call the target to set up the argument values. 6301 SmallVector<SDValue, 8> InVals; 6302 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 6303 F.isVarArg(), Ins, 6304 dl, DAG, InVals); 6305 6306 // Verify that the target's LowerFormalArguments behaved as expected. 6307 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 6308 "LowerFormalArguments didn't return a valid chain!"); 6309 assert(InVals.size() == Ins.size() && 6310 "LowerFormalArguments didn't emit the correct number of values!"); 6311 DEBUG({ 6312 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 6313 assert(InVals[i].getNode() && 6314 "LowerFormalArguments emitted a null value!"); 6315 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 6316 "LowerFormalArguments emitted a value with the wrong type!"); 6317 } 6318 }); 6319 6320 // Update the DAG with the new chain value resulting from argument lowering. 6321 DAG.setRoot(NewRoot); 6322 6323 // Set up the argument values. 6324 unsigned i = 0; 6325 Idx = 1; 6326 if (!FuncInfo->CanLowerReturn) { 6327 // Create a virtual register for the sret pointer, and put in a copy 6328 // from the sret argument into it. 6329 SmallVector<EVT, 1> ValueVTs; 6330 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6331 EVT VT = ValueVTs[0]; 6332 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6333 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6334 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 6335 RegVT, VT, AssertOp); 6336 6337 MachineFunction& MF = SDB->DAG.getMachineFunction(); 6338 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 6339 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); 6340 FuncInfo->DemoteRegister = SRetReg; 6341 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), 6342 SRetReg, ArgValue); 6343 DAG.setRoot(NewRoot); 6344 6345 // i indexes lowered arguments. Bump it past the hidden sret argument. 6346 // Idx indexes LLVM arguments. Don't touch it. 6347 ++i; 6348 } 6349 6350 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 6351 ++I, ++Idx) { 6352 SmallVector<SDValue, 4> ArgValues; 6353 SmallVector<EVT, 4> ValueVTs; 6354 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6355 unsigned NumValues = ValueVTs.size(); 6356 6357 // If this argument is unused then remember its value. It is used to generate 6358 // debugging information. 6359 if (I->use_empty() && NumValues) 6360 SDB->setUnusedArgValue(I, InVals[i]); 6361 6362 for (unsigned Value = 0; Value != NumValues; ++Value) { 6363 EVT VT = ValueVTs[Value]; 6364 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6365 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6366 6367 if (!I->use_empty()) { 6368 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6369 if (F.paramHasAttr(Idx, Attribute::SExt)) 6370 AssertOp = ISD::AssertSext; 6371 else if (F.paramHasAttr(Idx, Attribute::ZExt)) 6372 AssertOp = ISD::AssertZext; 6373 6374 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 6375 NumParts, PartVT, VT, 6376 AssertOp)); 6377 } 6378 6379 i += NumParts; 6380 } 6381 6382 // Note down frame index for byval arguments. 6383 if (I->hasByValAttr() && !ArgValues.empty()) 6384 if (FrameIndexSDNode *FI = 6385 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 6386 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex()); 6387 6388 if (!I->use_empty()) { 6389 SDValue Res; 6390 if (!ArgValues.empty()) 6391 Res = DAG.getMergeValues(&ArgValues[0], NumValues, 6392 SDB->getCurDebugLoc()); 6393 SDB->setValue(I, Res); 6394 6395 // If this argument is live outside of the entry block, insert a copy from 6396 // whereever we got it to the vreg that other BB's will reference it as. 6397 SDB->CopyToExportRegsIfNeeded(I); 6398 } 6399 } 6400 6401 assert(i == InVals.size() && "Argument register count mismatch!"); 6402 6403 // Finally, if the target has anything special to do, allow it to do so. 6404 // FIXME: this should insert code into the DAG! 6405 EmitFunctionEntryCode(); 6406 } 6407 6408 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 6409 /// ensure constants are generated when needed. Remember the virtual registers 6410 /// that need to be added to the Machine PHI nodes as input. We cannot just 6411 /// directly add them, because expansion might result in multiple MBB's for one 6412 /// BB. As such, the start of the BB might correspond to a different MBB than 6413 /// the end. 6414 /// 6415 void 6416 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 6417 const TerminatorInst *TI = LLVMBB->getTerminator(); 6418 6419 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6420 6421 // Check successor nodes' PHI nodes that expect a constant to be available 6422 // from this block. 6423 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6424 const BasicBlock *SuccBB = TI->getSuccessor(succ); 6425 if (!isa<PHINode>(SuccBB->begin())) continue; 6426 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 6427 6428 // If this terminator has multiple identical successors (common for 6429 // switches), only handle each succ once. 6430 if (!SuccsHandled.insert(SuccMBB)) continue; 6431 6432 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6433 6434 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6435 // nodes and Machine PHI nodes, but the incoming operands have not been 6436 // emitted yet. 6437 for (BasicBlock::const_iterator I = SuccBB->begin(); 6438 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 6439 // Ignore dead phi's. 6440 if (PN->use_empty()) continue; 6441 6442 unsigned Reg; 6443 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6444 6445 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 6446 unsigned &RegOut = ConstantsOut[C]; 6447 if (RegOut == 0) { 6448 RegOut = FuncInfo.CreateRegs(C->getType()); 6449 CopyValueToVirtualRegister(C, RegOut); 6450 } 6451 Reg = RegOut; 6452 } else { 6453 DenseMap<const Value *, unsigned>::iterator I = 6454 FuncInfo.ValueMap.find(PHIOp); 6455 if (I != FuncInfo.ValueMap.end()) 6456 Reg = I->second; 6457 else { 6458 assert(isa<AllocaInst>(PHIOp) && 6459 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 6460 "Didn't codegen value into a register!??"); 6461 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 6462 CopyValueToVirtualRegister(PHIOp, Reg); 6463 } 6464 } 6465 6466 // Remember that this register needs to added to the machine PHI node as 6467 // the input for this MBB. 6468 SmallVector<EVT, 4> ValueVTs; 6469 ComputeValueVTs(TLI, PN->getType(), ValueVTs); 6470 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 6471 EVT VT = ValueVTs[vti]; 6472 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 6473 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 6474 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 6475 Reg += NumRegisters; 6476 } 6477 } 6478 } 6479 ConstantsOut.clear(); 6480 } 6481