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