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