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