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