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