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