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