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