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