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