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