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