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