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 SDValue InChain = DAG.getRoot(); 3835 if (AA->pointsToConstantMemory(MemoryLocation( 3836 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), 3837 AAInfo))) { 3838 // Do not serialize (non-volatile) loads of constant memory with anything. 3839 InChain = DAG.getEntryNode(); 3840 } 3841 3842 MachineMemOperand *MMO = 3843 DAG.getMachineFunction(). 3844 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3845 MachineMemOperand::MOLoad, VT.getStoreSize(), 3846 Alignment, AAInfo, Ranges); 3847 3848 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 3849 ISD::NON_EXTLOAD); 3850 SDValue OutChain = Load.getValue(1); 3851 DAG.setRoot(OutChain); 3852 setValue(&I, Load); 3853 } 3854 3855 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 3856 SDLoc sdl = getCurSDLoc(); 3857 3858 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 3859 const Value *Ptr = I.getArgOperand(0); 3860 SDValue Src0 = getValue(I.getArgOperand(3)); 3861 SDValue Mask = getValue(I.getArgOperand(2)); 3862 3863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3864 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3865 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 3866 if (!Alignment) 3867 Alignment = DAG.getEVTAlignment(VT); 3868 3869 AAMDNodes AAInfo; 3870 I.getAAMetadata(AAInfo); 3871 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3872 3873 SDValue Root = DAG.getRoot(); 3874 SDValue Base; 3875 SDValue Index; 3876 const Value *BasePtr = Ptr; 3877 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3878 bool ConstantMemory = false; 3879 if (UniformBase && 3880 AA->pointsToConstantMemory(MemoryLocation( 3881 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 3882 AAInfo))) { 3883 // Do not serialize (non-volatile) loads of constant memory with anything. 3884 Root = DAG.getEntryNode(); 3885 ConstantMemory = true; 3886 } 3887 3888 MachineMemOperand *MMO = 3889 DAG.getMachineFunction(). 3890 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 3891 MachineMemOperand::MOLoad, VT.getStoreSize(), 3892 Alignment, AAInfo, Ranges); 3893 3894 if (!UniformBase) { 3895 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3896 Index = getValue(Ptr); 3897 } 3898 SDValue Ops[] = { Root, Src0, Mask, Base, Index }; 3899 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 3900 Ops, MMO); 3901 3902 SDValue OutChain = Gather.getValue(1); 3903 if (!ConstantMemory) 3904 PendingLoads.push_back(OutChain); 3905 setValue(&I, Gather); 3906 } 3907 3908 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3909 SDLoc dl = getCurSDLoc(); 3910 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 3911 AtomicOrdering FailureOrder = I.getFailureOrdering(); 3912 SynchronizationScope Scope = I.getSynchScope(); 3913 3914 SDValue InChain = getRoot(); 3915 3916 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 3917 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 3918 SDValue L = DAG.getAtomicCmpSwap( 3919 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 3920 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 3921 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 3922 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope); 3923 3924 SDValue OutChain = L.getValue(2); 3925 3926 setValue(&I, L); 3927 DAG.setRoot(OutChain); 3928 } 3929 3930 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3931 SDLoc dl = getCurSDLoc(); 3932 ISD::NodeType NT; 3933 switch (I.getOperation()) { 3934 default: llvm_unreachable("Unknown atomicrmw operation"); 3935 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3936 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3937 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3938 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3939 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3940 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3941 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3942 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3943 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3944 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3945 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3946 } 3947 AtomicOrdering Order = I.getOrdering(); 3948 SynchronizationScope Scope = I.getSynchScope(); 3949 3950 SDValue InChain = getRoot(); 3951 3952 SDValue L = 3953 DAG.getAtomic(NT, dl, 3954 getValue(I.getValOperand()).getSimpleValueType(), 3955 InChain, 3956 getValue(I.getPointerOperand()), 3957 getValue(I.getValOperand()), 3958 I.getPointerOperand(), 3959 /* Alignment=*/ 0, Order, Scope); 3960 3961 SDValue OutChain = L.getValue(1); 3962 3963 setValue(&I, L); 3964 DAG.setRoot(OutChain); 3965 } 3966 3967 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3968 SDLoc dl = getCurSDLoc(); 3969 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3970 SDValue Ops[3]; 3971 Ops[0] = getRoot(); 3972 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 3973 TLI.getPointerTy(DAG.getDataLayout())); 3974 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, 3975 TLI.getPointerTy(DAG.getDataLayout())); 3976 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 3977 } 3978 3979 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 3980 SDLoc dl = getCurSDLoc(); 3981 AtomicOrdering Order = I.getOrdering(); 3982 SynchronizationScope Scope = I.getSynchScope(); 3983 3984 SDValue InChain = getRoot(); 3985 3986 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3987 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3988 3989 if (I.getAlignment() < VT.getSizeInBits() / 8) 3990 report_fatal_error("Cannot generate unaligned atomic load"); 3991 3992 MachineMemOperand *MMO = 3993 DAG.getMachineFunction(). 3994 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 3995 MachineMemOperand::MOVolatile | 3996 MachineMemOperand::MOLoad, 3997 VT.getStoreSize(), 3998 I.getAlignment() ? I.getAlignment() : 3999 DAG.getEVTAlignment(VT)); 4000 4001 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4002 SDValue L = 4003 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4004 getValue(I.getPointerOperand()), MMO, 4005 Order, Scope); 4006 4007 SDValue OutChain = L.getValue(1); 4008 4009 setValue(&I, L); 4010 DAG.setRoot(OutChain); 4011 } 4012 4013 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4014 SDLoc dl = getCurSDLoc(); 4015 4016 AtomicOrdering Order = I.getOrdering(); 4017 SynchronizationScope Scope = I.getSynchScope(); 4018 4019 SDValue InChain = getRoot(); 4020 4021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4022 EVT VT = 4023 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4024 4025 if (I.getAlignment() < VT.getSizeInBits() / 8) 4026 report_fatal_error("Cannot generate unaligned atomic store"); 4027 4028 SDValue OutChain = 4029 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4030 InChain, 4031 getValue(I.getPointerOperand()), 4032 getValue(I.getValueOperand()), 4033 I.getPointerOperand(), I.getAlignment(), 4034 Order, Scope); 4035 4036 DAG.setRoot(OutChain); 4037 } 4038 4039 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4040 /// node. 4041 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4042 unsigned Intrinsic) { 4043 bool HasChain = !I.doesNotAccessMemory(); 4044 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 4045 4046 // Build the operand list. 4047 SmallVector<SDValue, 8> Ops; 4048 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4049 if (OnlyLoad) { 4050 // We don't need to serialize loads against other loads. 4051 Ops.push_back(DAG.getRoot()); 4052 } else { 4053 Ops.push_back(getRoot()); 4054 } 4055 } 4056 4057 // Info is set by getTgtMemInstrinsic 4058 TargetLowering::IntrinsicInfo Info; 4059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4060 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 4061 4062 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4063 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4064 Info.opc == ISD::INTRINSIC_W_CHAIN) 4065 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4066 TLI.getPointerTy(DAG.getDataLayout()))); 4067 4068 // Add all operands of the call to the operand list. 4069 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4070 SDValue Op = getValue(I.getArgOperand(i)); 4071 Ops.push_back(Op); 4072 } 4073 4074 SmallVector<EVT, 4> ValueVTs; 4075 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4076 4077 if (HasChain) 4078 ValueVTs.push_back(MVT::Other); 4079 4080 SDVTList VTs = DAG.getVTList(ValueVTs); 4081 4082 // Create the node. 4083 SDValue Result; 4084 if (IsTgtIntrinsic) { 4085 // This is target intrinsic that touches memory 4086 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 4087 VTs, Ops, Info.memVT, 4088 MachinePointerInfo(Info.ptrVal, Info.offset), 4089 Info.align, Info.vol, 4090 Info.readMem, Info.writeMem, Info.size); 4091 } else if (!HasChain) { 4092 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4093 } else if (!I.getType()->isVoidTy()) { 4094 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4095 } else { 4096 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4097 } 4098 4099 if (HasChain) { 4100 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4101 if (OnlyLoad) 4102 PendingLoads.push_back(Chain); 4103 else 4104 DAG.setRoot(Chain); 4105 } 4106 4107 if (!I.getType()->isVoidTy()) { 4108 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4109 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4110 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4111 } else 4112 Result = lowerRangeToAssertZExt(DAG, I, Result); 4113 4114 setValue(&I, Result); 4115 } 4116 } 4117 4118 /// GetSignificand - Get the significand and build it into a floating-point 4119 /// number with exponent of 1: 4120 /// 4121 /// Op = (Op & 0x007fffff) | 0x3f800000; 4122 /// 4123 /// where Op is the hexadecimal representation of floating point value. 4124 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4125 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4126 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4127 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4128 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4129 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4130 } 4131 4132 /// GetExponent - Get the exponent: 4133 /// 4134 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4135 /// 4136 /// where Op is the hexadecimal representation of floating point value. 4137 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4138 const TargetLowering &TLI, const SDLoc &dl) { 4139 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4140 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4141 SDValue t1 = DAG.getNode( 4142 ISD::SRL, dl, MVT::i32, t0, 4143 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4144 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4145 DAG.getConstant(127, dl, MVT::i32)); 4146 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4147 } 4148 4149 /// getF32Constant - Get 32-bit floating point constant. 4150 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4151 const SDLoc &dl) { 4152 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl, 4153 MVT::f32); 4154 } 4155 4156 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4157 SelectionDAG &DAG) { 4158 // TODO: What fast-math-flags should be set on the floating-point nodes? 4159 4160 // IntegerPartOfX = ((int32_t)(t0); 4161 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4162 4163 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4164 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4165 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4166 4167 // IntegerPartOfX <<= 23; 4168 IntegerPartOfX = DAG.getNode( 4169 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4170 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4171 DAG.getDataLayout()))); 4172 4173 SDValue TwoToFractionalPartOfX; 4174 if (LimitFloatPrecision <= 6) { 4175 // For floating-point precision of 6: 4176 // 4177 // TwoToFractionalPartOfX = 4178 // 0.997535578f + 4179 // (0.735607626f + 0.252464424f * x) * x; 4180 // 4181 // error 0.0144103317, which is 6 bits 4182 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4183 getF32Constant(DAG, 0x3e814304, dl)); 4184 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4185 getF32Constant(DAG, 0x3f3c50c8, dl)); 4186 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4187 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4188 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4189 } else if (LimitFloatPrecision <= 12) { 4190 // For floating-point precision of 12: 4191 // 4192 // TwoToFractionalPartOfX = 4193 // 0.999892986f + 4194 // (0.696457318f + 4195 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4196 // 4197 // error 0.000107046256, which is 13 to 14 bits 4198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4199 getF32Constant(DAG, 0x3da235e3, dl)); 4200 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4201 getF32Constant(DAG, 0x3e65b8f3, dl)); 4202 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4203 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4204 getF32Constant(DAG, 0x3f324b07, dl)); 4205 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4206 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4207 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4208 } else { // LimitFloatPrecision <= 18 4209 // For floating-point precision of 18: 4210 // 4211 // TwoToFractionalPartOfX = 4212 // 0.999999982f + 4213 // (0.693148872f + 4214 // (0.240227044f + 4215 // (0.554906021e-1f + 4216 // (0.961591928e-2f + 4217 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4218 // error 2.47208000*10^(-7), which is better than 18 bits 4219 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4220 getF32Constant(DAG, 0x3924b03e, dl)); 4221 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4222 getF32Constant(DAG, 0x3ab24b87, dl)); 4223 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4224 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4225 getF32Constant(DAG, 0x3c1d8c17, dl)); 4226 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4227 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4228 getF32Constant(DAG, 0x3d634a1d, dl)); 4229 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4230 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4231 getF32Constant(DAG, 0x3e75fe14, dl)); 4232 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4233 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4234 getF32Constant(DAG, 0x3f317234, dl)); 4235 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4236 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4237 getF32Constant(DAG, 0x3f800000, dl)); 4238 } 4239 4240 // Add the exponent into the result in integer domain. 4241 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4242 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4243 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4244 } 4245 4246 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4247 /// limited-precision mode. 4248 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4249 const TargetLowering &TLI) { 4250 if (Op.getValueType() == MVT::f32 && 4251 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4252 4253 // Put the exponent in the right bit position for later addition to the 4254 // final result: 4255 // 4256 // #define LOG2OFe 1.4426950f 4257 // t0 = Op * LOG2OFe 4258 4259 // TODO: What fast-math-flags should be set here? 4260 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4261 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4262 return getLimitedPrecisionExp2(t0, dl, DAG); 4263 } 4264 4265 // No special expansion. 4266 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4267 } 4268 4269 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4270 /// limited-precision mode. 4271 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4272 const TargetLowering &TLI) { 4273 4274 // TODO: What fast-math-flags should be set on the floating-point nodes? 4275 4276 if (Op.getValueType() == MVT::f32 && 4277 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4278 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4279 4280 // Scale the exponent by log(2) [0.69314718f]. 4281 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4282 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4283 getF32Constant(DAG, 0x3f317218, dl)); 4284 4285 // Get the significand and build it into a floating-point number with 4286 // exponent of 1. 4287 SDValue X = GetSignificand(DAG, Op1, dl); 4288 4289 SDValue LogOfMantissa; 4290 if (LimitFloatPrecision <= 6) { 4291 // For floating-point precision of 6: 4292 // 4293 // LogofMantissa = 4294 // -1.1609546f + 4295 // (1.4034025f - 0.23903021f * x) * x; 4296 // 4297 // error 0.0034276066, which is better than 8 bits 4298 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4299 getF32Constant(DAG, 0xbe74c456, dl)); 4300 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4301 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4302 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4303 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4304 getF32Constant(DAG, 0x3f949a29, dl)); 4305 } else if (LimitFloatPrecision <= 12) { 4306 // For floating-point precision of 12: 4307 // 4308 // LogOfMantissa = 4309 // -1.7417939f + 4310 // (2.8212026f + 4311 // (-1.4699568f + 4312 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4313 // 4314 // error 0.000061011436, which is 14 bits 4315 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4316 getF32Constant(DAG, 0xbd67b6d6, dl)); 4317 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4318 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4319 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4320 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4321 getF32Constant(DAG, 0x3fbc278b, dl)); 4322 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4323 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4324 getF32Constant(DAG, 0x40348e95, dl)); 4325 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4326 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4327 getF32Constant(DAG, 0x3fdef31a, dl)); 4328 } else { // LimitFloatPrecision <= 18 4329 // For floating-point precision of 18: 4330 // 4331 // LogOfMantissa = 4332 // -2.1072184f + 4333 // (4.2372794f + 4334 // (-3.7029485f + 4335 // (2.2781945f + 4336 // (-0.87823314f + 4337 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4338 // 4339 // error 0.0000023660568, which is better than 18 bits 4340 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4341 getF32Constant(DAG, 0xbc91e5ac, dl)); 4342 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4343 getF32Constant(DAG, 0x3e4350aa, dl)); 4344 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4345 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4346 getF32Constant(DAG, 0x3f60d3e3, dl)); 4347 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4348 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4349 getF32Constant(DAG, 0x4011cdf0, dl)); 4350 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4351 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4352 getF32Constant(DAG, 0x406cfd1c, dl)); 4353 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4354 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4355 getF32Constant(DAG, 0x408797cb, dl)); 4356 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4357 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4358 getF32Constant(DAG, 0x4006dcab, dl)); 4359 } 4360 4361 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4362 } 4363 4364 // No special expansion. 4365 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4366 } 4367 4368 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4369 /// limited-precision mode. 4370 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4371 const TargetLowering &TLI) { 4372 4373 // TODO: What fast-math-flags should be set on the floating-point nodes? 4374 4375 if (Op.getValueType() == MVT::f32 && 4376 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4377 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4378 4379 // Get the exponent. 4380 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4381 4382 // Get the significand and build it into a floating-point number with 4383 // exponent of 1. 4384 SDValue X = GetSignificand(DAG, Op1, dl); 4385 4386 // Different possible minimax approximations of significand in 4387 // floating-point for various degrees of accuracy over [1,2]. 4388 SDValue Log2ofMantissa; 4389 if (LimitFloatPrecision <= 6) { 4390 // For floating-point precision of 6: 4391 // 4392 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4393 // 4394 // error 0.0049451742, which is more than 7 bits 4395 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4396 getF32Constant(DAG, 0xbeb08fe0, dl)); 4397 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4398 getF32Constant(DAG, 0x40019463, dl)); 4399 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4400 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4401 getF32Constant(DAG, 0x3fd6633d, dl)); 4402 } else if (LimitFloatPrecision <= 12) { 4403 // For floating-point precision of 12: 4404 // 4405 // Log2ofMantissa = 4406 // -2.51285454f + 4407 // (4.07009056f + 4408 // (-2.12067489f + 4409 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4410 // 4411 // error 0.0000876136000, which is better than 13 bits 4412 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4413 getF32Constant(DAG, 0xbda7262e, dl)); 4414 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4415 getF32Constant(DAG, 0x3f25280b, dl)); 4416 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4417 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4418 getF32Constant(DAG, 0x4007b923, dl)); 4419 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4420 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4421 getF32Constant(DAG, 0x40823e2f, dl)); 4422 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4423 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4424 getF32Constant(DAG, 0x4020d29c, dl)); 4425 } else { // LimitFloatPrecision <= 18 4426 // For floating-point precision of 18: 4427 // 4428 // Log2ofMantissa = 4429 // -3.0400495f + 4430 // (6.1129976f + 4431 // (-5.3420409f + 4432 // (3.2865683f + 4433 // (-1.2669343f + 4434 // (0.27515199f - 4435 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4436 // 4437 // error 0.0000018516, which is better than 18 bits 4438 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4439 getF32Constant(DAG, 0xbcd2769e, dl)); 4440 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4441 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4442 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4443 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4444 getF32Constant(DAG, 0x3fa22ae7, dl)); 4445 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4446 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4447 getF32Constant(DAG, 0x40525723, dl)); 4448 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4449 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4450 getF32Constant(DAG, 0x40aaf200, dl)); 4451 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4452 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4453 getF32Constant(DAG, 0x40c39dad, dl)); 4454 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4455 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4456 getF32Constant(DAG, 0x4042902c, dl)); 4457 } 4458 4459 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4460 } 4461 4462 // No special expansion. 4463 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4464 } 4465 4466 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4467 /// limited-precision mode. 4468 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4469 const TargetLowering &TLI) { 4470 4471 // TODO: What fast-math-flags should be set on the floating-point nodes? 4472 4473 if (Op.getValueType() == MVT::f32 && 4474 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4475 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4476 4477 // Scale the exponent by log10(2) [0.30102999f]. 4478 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4479 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4480 getF32Constant(DAG, 0x3e9a209a, dl)); 4481 4482 // Get the significand and build it into a floating-point number with 4483 // exponent of 1. 4484 SDValue X = GetSignificand(DAG, Op1, dl); 4485 4486 SDValue Log10ofMantissa; 4487 if (LimitFloatPrecision <= 6) { 4488 // For floating-point precision of 6: 4489 // 4490 // Log10ofMantissa = 4491 // -0.50419619f + 4492 // (0.60948995f - 0.10380950f * x) * x; 4493 // 4494 // error 0.0014886165, which is 6 bits 4495 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4496 getF32Constant(DAG, 0xbdd49a13, dl)); 4497 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4498 getF32Constant(DAG, 0x3f1c0789, dl)); 4499 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4500 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4501 getF32Constant(DAG, 0x3f011300, dl)); 4502 } else if (LimitFloatPrecision <= 12) { 4503 // For floating-point precision of 12: 4504 // 4505 // Log10ofMantissa = 4506 // -0.64831180f + 4507 // (0.91751397f + 4508 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4509 // 4510 // error 0.00019228036, which is better than 12 bits 4511 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4512 getF32Constant(DAG, 0x3d431f31, dl)); 4513 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4514 getF32Constant(DAG, 0x3ea21fb2, dl)); 4515 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4516 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4517 getF32Constant(DAG, 0x3f6ae232, dl)); 4518 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4519 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4520 getF32Constant(DAG, 0x3f25f7c3, dl)); 4521 } else { // LimitFloatPrecision <= 18 4522 // For floating-point precision of 18: 4523 // 4524 // Log10ofMantissa = 4525 // -0.84299375f + 4526 // (1.5327582f + 4527 // (-1.0688956f + 4528 // (0.49102474f + 4529 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4530 // 4531 // error 0.0000037995730, which is better than 18 bits 4532 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4533 getF32Constant(DAG, 0x3c5d51ce, dl)); 4534 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4535 getF32Constant(DAG, 0x3e00685a, dl)); 4536 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4537 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4538 getF32Constant(DAG, 0x3efb6798, dl)); 4539 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4540 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4541 getF32Constant(DAG, 0x3f88d192, dl)); 4542 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4543 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4544 getF32Constant(DAG, 0x3fc4316c, dl)); 4545 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4546 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4547 getF32Constant(DAG, 0x3f57ce70, dl)); 4548 } 4549 4550 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4551 } 4552 4553 // No special expansion. 4554 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4555 } 4556 4557 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4558 /// limited-precision mode. 4559 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4560 const TargetLowering &TLI) { 4561 if (Op.getValueType() == MVT::f32 && 4562 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4563 return getLimitedPrecisionExp2(Op, dl, DAG); 4564 4565 // No special expansion. 4566 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4567 } 4568 4569 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4570 /// limited-precision mode with x == 10.0f. 4571 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4572 SelectionDAG &DAG, const TargetLowering &TLI) { 4573 bool IsExp10 = false; 4574 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4575 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4576 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4577 APFloat Ten(10.0f); 4578 IsExp10 = LHSC->isExactlyValue(Ten); 4579 } 4580 } 4581 4582 // TODO: What fast-math-flags should be set on the FMUL node? 4583 if (IsExp10) { 4584 // Put the exponent in the right bit position for later addition to the 4585 // final result: 4586 // 4587 // #define LOG2OF10 3.3219281f 4588 // t0 = Op * LOG2OF10; 4589 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4590 getF32Constant(DAG, 0x40549a78, dl)); 4591 return getLimitedPrecisionExp2(t0, dl, DAG); 4592 } 4593 4594 // No special expansion. 4595 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4596 } 4597 4598 4599 /// ExpandPowI - Expand a llvm.powi intrinsic. 4600 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4601 SelectionDAG &DAG) { 4602 // If RHS is a constant, we can expand this out to a multiplication tree, 4603 // otherwise we end up lowering to a call to __powidf2 (for example). When 4604 // optimizing for size, we only want to do this if the expansion would produce 4605 // a small number of multiplies, otherwise we do the full expansion. 4606 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4607 // Get the exponent as a positive value. 4608 unsigned Val = RHSC->getSExtValue(); 4609 if ((int)Val < 0) Val = -Val; 4610 4611 // powi(x, 0) -> 1.0 4612 if (Val == 0) 4613 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4614 4615 const Function *F = DAG.getMachineFunction().getFunction(); 4616 if (!F->optForSize() || 4617 // If optimizing for size, don't insert too many multiplies. 4618 // This inserts up to 5 multiplies. 4619 countPopulation(Val) + Log2_32(Val) < 7) { 4620 // We use the simple binary decomposition method to generate the multiply 4621 // sequence. There are more optimal ways to do this (for example, 4622 // powi(x,15) generates one more multiply than it should), but this has 4623 // the benefit of being both really simple and much better than a libcall. 4624 SDValue Res; // Logically starts equal to 1.0 4625 SDValue CurSquare = LHS; 4626 // TODO: Intrinsics should have fast-math-flags that propagate to these 4627 // nodes. 4628 while (Val) { 4629 if (Val & 1) { 4630 if (Res.getNode()) 4631 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4632 else 4633 Res = CurSquare; // 1.0*CurSquare. 4634 } 4635 4636 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4637 CurSquare, CurSquare); 4638 Val >>= 1; 4639 } 4640 4641 // If the original was negative, invert the result, producing 1/(x*x*x). 4642 if (RHSC->getSExtValue() < 0) 4643 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4644 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4645 return Res; 4646 } 4647 } 4648 4649 // Otherwise, expand to a libcall. 4650 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4651 } 4652 4653 // getUnderlyingArgReg - Find underlying register used for a truncated or 4654 // bitcasted argument. 4655 static unsigned getUnderlyingArgReg(const SDValue &N) { 4656 switch (N.getOpcode()) { 4657 case ISD::CopyFromReg: 4658 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4659 case ISD::BITCAST: 4660 case ISD::AssertZext: 4661 case ISD::AssertSext: 4662 case ISD::TRUNCATE: 4663 return getUnderlyingArgReg(N.getOperand(0)); 4664 default: 4665 return 0; 4666 } 4667 } 4668 4669 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4670 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4671 /// At the end of instruction selection, they will be inserted to the entry BB. 4672 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4673 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4674 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) { 4675 const Argument *Arg = dyn_cast<Argument>(V); 4676 if (!Arg) 4677 return false; 4678 4679 MachineFunction &MF = DAG.getMachineFunction(); 4680 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4681 4682 // Ignore inlined function arguments here. 4683 // 4684 // FIXME: Should we be checking DL->inlinedAt() to determine this? 4685 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction())) 4686 return false; 4687 4688 Optional<MachineOperand> Op; 4689 // Some arguments' frame index is recorded during argument lowering. 4690 if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) 4691 Op = MachineOperand::CreateFI(FI); 4692 4693 if (!Op && N.getNode()) { 4694 unsigned Reg = getUnderlyingArgReg(N); 4695 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4696 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4697 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4698 if (PR) 4699 Reg = PR; 4700 } 4701 if (Reg) 4702 Op = MachineOperand::CreateReg(Reg, false); 4703 } 4704 4705 if (!Op) { 4706 // Check if ValueMap has reg number. 4707 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4708 if (VMI != FuncInfo.ValueMap.end()) 4709 Op = MachineOperand::CreateReg(VMI->second, false); 4710 } 4711 4712 if (!Op && N.getNode()) 4713 // Check if frame index is available. 4714 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4715 if (FrameIndexSDNode *FINode = 4716 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4717 Op = MachineOperand::CreateFI(FINode->getIndex()); 4718 4719 if (!Op) 4720 return false; 4721 4722 assert(Variable->isValidLocationForIntrinsic(DL) && 4723 "Expected inlined-at fields to agree"); 4724 if (Op->isReg()) 4725 FuncInfo.ArgDbgValues.push_back( 4726 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4727 Op->getReg(), Offset, Variable, Expr)); 4728 else 4729 FuncInfo.ArgDbgValues.push_back( 4730 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4731 .addOperand(*Op) 4732 .addImm(Offset) 4733 .addMetadata(Variable) 4734 .addMetadata(Expr)); 4735 4736 return true; 4737 } 4738 4739 // VisualStudio defines setjmp as _setjmp 4740 #if defined(_MSC_VER) && defined(setjmp) && \ 4741 !defined(setjmp_undefined_for_msvc) 4742 # pragma push_macro("setjmp") 4743 # undef setjmp 4744 # define setjmp_undefined_for_msvc 4745 #endif 4746 4747 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4748 /// we want to emit this as a call to a named external function, return the name 4749 /// otherwise lower it and return null. 4750 const char * 4751 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4752 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4753 SDLoc sdl = getCurSDLoc(); 4754 DebugLoc dl = getCurDebugLoc(); 4755 SDValue Res; 4756 4757 switch (Intrinsic) { 4758 default: 4759 // By default, turn this into a target intrinsic node. 4760 visitTargetIntrinsic(I, Intrinsic); 4761 return nullptr; 4762 case Intrinsic::vastart: visitVAStart(I); return nullptr; 4763 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 4764 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 4765 case Intrinsic::returnaddress: 4766 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 4767 TLI.getPointerTy(DAG.getDataLayout()), 4768 getValue(I.getArgOperand(0)))); 4769 return nullptr; 4770 case Intrinsic::frameaddress: 4771 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 4772 TLI.getPointerTy(DAG.getDataLayout()), 4773 getValue(I.getArgOperand(0)))); 4774 return nullptr; 4775 case Intrinsic::read_register: { 4776 Value *Reg = I.getArgOperand(0); 4777 SDValue Chain = getRoot(); 4778 SDValue RegName = 4779 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4780 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4781 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 4782 DAG.getVTList(VT, MVT::Other), Chain, RegName); 4783 setValue(&I, Res); 4784 DAG.setRoot(Res.getValue(1)); 4785 return nullptr; 4786 } 4787 case Intrinsic::write_register: { 4788 Value *Reg = I.getArgOperand(0); 4789 Value *RegValue = I.getArgOperand(1); 4790 SDValue Chain = getRoot(); 4791 SDValue RegName = 4792 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4793 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 4794 RegName, getValue(RegValue))); 4795 return nullptr; 4796 } 4797 case Intrinsic::setjmp: 4798 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 4799 case Intrinsic::longjmp: 4800 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 4801 case Intrinsic::memcpy: { 4802 SDValue Op1 = getValue(I.getArgOperand(0)); 4803 SDValue Op2 = getValue(I.getArgOperand(1)); 4804 SDValue Op3 = getValue(I.getArgOperand(2)); 4805 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4806 if (!Align) 4807 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 4808 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4809 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4810 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4811 false, isTC, 4812 MachinePointerInfo(I.getArgOperand(0)), 4813 MachinePointerInfo(I.getArgOperand(1))); 4814 updateDAGForMaybeTailCall(MC); 4815 return nullptr; 4816 } 4817 case Intrinsic::memset: { 4818 SDValue Op1 = getValue(I.getArgOperand(0)); 4819 SDValue Op2 = getValue(I.getArgOperand(1)); 4820 SDValue Op3 = getValue(I.getArgOperand(2)); 4821 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4822 if (!Align) 4823 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 4824 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4825 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4826 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4827 isTC, MachinePointerInfo(I.getArgOperand(0))); 4828 updateDAGForMaybeTailCall(MS); 4829 return nullptr; 4830 } 4831 case Intrinsic::memmove: { 4832 SDValue Op1 = getValue(I.getArgOperand(0)); 4833 SDValue Op2 = getValue(I.getArgOperand(1)); 4834 SDValue Op3 = getValue(I.getArgOperand(2)); 4835 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4836 if (!Align) 4837 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 4838 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4839 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 4840 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4841 isTC, MachinePointerInfo(I.getArgOperand(0)), 4842 MachinePointerInfo(I.getArgOperand(1))); 4843 updateDAGForMaybeTailCall(MM); 4844 return nullptr; 4845 } 4846 case Intrinsic::dbg_declare: { 4847 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4848 DILocalVariable *Variable = DI.getVariable(); 4849 DIExpression *Expression = DI.getExpression(); 4850 const Value *Address = DI.getAddress(); 4851 assert(Variable && "Missing variable"); 4852 if (!Address) { 4853 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4854 return nullptr; 4855 } 4856 4857 // Check if address has undef value. 4858 if (isa<UndefValue>(Address) || 4859 (Address->use_empty() && !isa<Argument>(Address))) { 4860 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4861 return nullptr; 4862 } 4863 4864 SDValue &N = NodeMap[Address]; 4865 if (!N.getNode() && isa<Argument>(Address)) 4866 // Check unused arguments map. 4867 N = UnusedArgNodeMap[Address]; 4868 SDDbgValue *SDV; 4869 if (N.getNode()) { 4870 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4871 Address = BCI->getOperand(0); 4872 // Parameters are handled specially. 4873 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 4874 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4875 if (isParameter && FINode) { 4876 // Byval parameter. We have a frame index at this point. 4877 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 4878 FINode->getIndex(), 0, dl, SDNodeOrder); 4879 } else if (isa<Argument>(Address)) { 4880 // Address is an argument, so try to emit its dbg value using 4881 // virtual register info from the FuncInfo.ValueMap. 4882 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4883 N); 4884 return nullptr; 4885 } else { 4886 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4887 true, 0, dl, SDNodeOrder); 4888 } 4889 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4890 } else { 4891 // If Address is an argument then try to emit its dbg value using 4892 // virtual register info from the FuncInfo.ValueMap. 4893 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false, 4894 N)) { 4895 // If variable is pinned by a alloca in dominating bb then 4896 // use StaticAllocaMap. 4897 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4898 if (AI->getParent() != DI.getParent()) { 4899 DenseMap<const AllocaInst*, int>::iterator SI = 4900 FuncInfo.StaticAllocaMap.find(AI); 4901 if (SI != FuncInfo.StaticAllocaMap.end()) { 4902 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 4903 0, dl, SDNodeOrder); 4904 DAG.AddDbgValue(SDV, nullptr, false); 4905 return nullptr; 4906 } 4907 } 4908 } 4909 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4910 } 4911 } 4912 return nullptr; 4913 } 4914 case Intrinsic::dbg_value: { 4915 const DbgValueInst &DI = cast<DbgValueInst>(I); 4916 assert(DI.getVariable() && "Missing variable"); 4917 4918 DILocalVariable *Variable = DI.getVariable(); 4919 DIExpression *Expression = DI.getExpression(); 4920 uint64_t Offset = DI.getOffset(); 4921 const Value *V = DI.getValue(); 4922 if (!V) 4923 return nullptr; 4924 4925 SDDbgValue *SDV; 4926 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 4927 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl, 4928 SDNodeOrder); 4929 DAG.AddDbgValue(SDV, nullptr, false); 4930 } else { 4931 // Do not use getValue() in here; we don't want to generate code at 4932 // this point if it hasn't been done yet. 4933 SDValue N = NodeMap[V]; 4934 if (!N.getNode() && isa<Argument>(V)) 4935 // Check unused arguments map. 4936 N = UnusedArgNodeMap[V]; 4937 if (N.getNode()) { 4938 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset, 4939 false, N)) { 4940 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 4941 false, Offset, dl, SDNodeOrder); 4942 DAG.AddDbgValue(SDV, N.getNode(), false); 4943 } 4944 } else if (!V->use_empty() ) { 4945 // Do not call getValue(V) yet, as we don't want to generate code. 4946 // Remember it for later. 4947 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4948 DanglingDebugInfoMap[V] = DDI; 4949 } else { 4950 // We may expand this to cover more cases. One case where we have no 4951 // data available is an unreferenced parameter. 4952 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4953 } 4954 } 4955 4956 // Build a debug info table entry. 4957 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4958 V = BCI->getOperand(0); 4959 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4960 // Don't handle byval struct arguments or VLAs, for example. 4961 if (!AI) { 4962 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 4963 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 4964 return nullptr; 4965 } 4966 DenseMap<const AllocaInst*, int>::iterator SI = 4967 FuncInfo.StaticAllocaMap.find(AI); 4968 if (SI == FuncInfo.StaticAllocaMap.end()) 4969 return nullptr; // VLAs. 4970 return nullptr; 4971 } 4972 4973 case Intrinsic::eh_typeid_for: { 4974 // Find the type id for the given typeinfo. 4975 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 4976 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4977 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 4978 setValue(&I, Res); 4979 return nullptr; 4980 } 4981 4982 case Intrinsic::eh_return_i32: 4983 case Intrinsic::eh_return_i64: 4984 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4985 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 4986 MVT::Other, 4987 getControlRoot(), 4988 getValue(I.getArgOperand(0)), 4989 getValue(I.getArgOperand(1)))); 4990 return nullptr; 4991 case Intrinsic::eh_unwind_init: 4992 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4993 return nullptr; 4994 case Intrinsic::eh_dwarf_cfa: { 4995 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl, 4996 TLI.getPointerTy(DAG.getDataLayout())); 4997 SDValue Offset = DAG.getNode(ISD::ADD, sdl, 4998 CfaArg.getValueType(), 4999 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl, 5000 CfaArg.getValueType()), 5001 CfaArg); 5002 SDValue FA = DAG.getNode( 5003 ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()), 5004 DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 5005 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(), 5006 FA, Offset)); 5007 return nullptr; 5008 } 5009 case Intrinsic::eh_sjlj_callsite: { 5010 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5011 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5012 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5013 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5014 5015 MMI.setCurrentCallSite(CI->getZExtValue()); 5016 return nullptr; 5017 } 5018 case Intrinsic::eh_sjlj_functioncontext: { 5019 // Get and store the index of the function context. 5020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 5021 AllocaInst *FnCtx = 5022 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5023 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5024 MFI->setFunctionContextIndex(FI); 5025 return nullptr; 5026 } 5027 case Intrinsic::eh_sjlj_setjmp: { 5028 SDValue Ops[2]; 5029 Ops[0] = getRoot(); 5030 Ops[1] = getValue(I.getArgOperand(0)); 5031 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5032 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5033 setValue(&I, Op.getValue(0)); 5034 DAG.setRoot(Op.getValue(1)); 5035 return nullptr; 5036 } 5037 case Intrinsic::eh_sjlj_longjmp: { 5038 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5039 getRoot(), getValue(I.getArgOperand(0)))); 5040 return nullptr; 5041 } 5042 case Intrinsic::eh_sjlj_setup_dispatch: { 5043 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5044 getRoot())); 5045 return nullptr; 5046 } 5047 5048 case Intrinsic::masked_gather: 5049 visitMaskedGather(I); 5050 return nullptr; 5051 case Intrinsic::masked_load: 5052 visitMaskedLoad(I); 5053 return nullptr; 5054 case Intrinsic::masked_scatter: 5055 visitMaskedScatter(I); 5056 return nullptr; 5057 case Intrinsic::masked_store: 5058 visitMaskedStore(I); 5059 return nullptr; 5060 case Intrinsic::x86_mmx_pslli_w: 5061 case Intrinsic::x86_mmx_pslli_d: 5062 case Intrinsic::x86_mmx_pslli_q: 5063 case Intrinsic::x86_mmx_psrli_w: 5064 case Intrinsic::x86_mmx_psrli_d: 5065 case Intrinsic::x86_mmx_psrli_q: 5066 case Intrinsic::x86_mmx_psrai_w: 5067 case Intrinsic::x86_mmx_psrai_d: { 5068 SDValue ShAmt = getValue(I.getArgOperand(1)); 5069 if (isa<ConstantSDNode>(ShAmt)) { 5070 visitTargetIntrinsic(I, Intrinsic); 5071 return nullptr; 5072 } 5073 unsigned NewIntrinsic = 0; 5074 EVT ShAmtVT = MVT::v2i32; 5075 switch (Intrinsic) { 5076 case Intrinsic::x86_mmx_pslli_w: 5077 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5078 break; 5079 case Intrinsic::x86_mmx_pslli_d: 5080 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5081 break; 5082 case Intrinsic::x86_mmx_pslli_q: 5083 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5084 break; 5085 case Intrinsic::x86_mmx_psrli_w: 5086 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5087 break; 5088 case Intrinsic::x86_mmx_psrli_d: 5089 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5090 break; 5091 case Intrinsic::x86_mmx_psrli_q: 5092 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5093 break; 5094 case Intrinsic::x86_mmx_psrai_w: 5095 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5096 break; 5097 case Intrinsic::x86_mmx_psrai_d: 5098 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5099 break; 5100 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5101 } 5102 5103 // The vector shift intrinsics with scalars uses 32b shift amounts but 5104 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5105 // to be zero. 5106 // We must do this early because v2i32 is not a legal type. 5107 SDValue ShOps[2]; 5108 ShOps[0] = ShAmt; 5109 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5110 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps); 5111 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5112 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5113 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5114 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5115 getValue(I.getArgOperand(0)), ShAmt); 5116 setValue(&I, Res); 5117 return nullptr; 5118 } 5119 case Intrinsic::convertff: 5120 case Intrinsic::convertfsi: 5121 case Intrinsic::convertfui: 5122 case Intrinsic::convertsif: 5123 case Intrinsic::convertuif: 5124 case Intrinsic::convertss: 5125 case Intrinsic::convertsu: 5126 case Intrinsic::convertus: 5127 case Intrinsic::convertuu: { 5128 ISD::CvtCode Code = ISD::CVT_INVALID; 5129 switch (Intrinsic) { 5130 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5131 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 5132 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 5133 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 5134 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 5135 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 5136 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 5137 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 5138 case Intrinsic::convertus: Code = ISD::CVT_US; break; 5139 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 5140 } 5141 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5142 const Value *Op1 = I.getArgOperand(0); 5143 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1), 5144 DAG.getValueType(DestVT), 5145 DAG.getValueType(getValue(Op1).getValueType()), 5146 getValue(I.getArgOperand(1)), 5147 getValue(I.getArgOperand(2)), 5148 Code); 5149 setValue(&I, Res); 5150 return nullptr; 5151 } 5152 case Intrinsic::powi: 5153 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5154 getValue(I.getArgOperand(1)), DAG)); 5155 return nullptr; 5156 case Intrinsic::log: 5157 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5158 return nullptr; 5159 case Intrinsic::log2: 5160 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5161 return nullptr; 5162 case Intrinsic::log10: 5163 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5164 return nullptr; 5165 case Intrinsic::exp: 5166 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5167 return nullptr; 5168 case Intrinsic::exp2: 5169 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5170 return nullptr; 5171 case Intrinsic::pow: 5172 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5173 getValue(I.getArgOperand(1)), DAG, TLI)); 5174 return nullptr; 5175 case Intrinsic::sqrt: 5176 case Intrinsic::fabs: 5177 case Intrinsic::sin: 5178 case Intrinsic::cos: 5179 case Intrinsic::floor: 5180 case Intrinsic::ceil: 5181 case Intrinsic::trunc: 5182 case Intrinsic::rint: 5183 case Intrinsic::nearbyint: 5184 case Intrinsic::round: 5185 case Intrinsic::canonicalize: { 5186 unsigned Opcode; 5187 switch (Intrinsic) { 5188 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5189 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5190 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5191 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5192 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5193 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5194 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5195 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5196 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5197 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5198 case Intrinsic::round: Opcode = ISD::FROUND; break; 5199 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5200 } 5201 5202 setValue(&I, DAG.getNode(Opcode, sdl, 5203 getValue(I.getArgOperand(0)).getValueType(), 5204 getValue(I.getArgOperand(0)))); 5205 return nullptr; 5206 } 5207 case Intrinsic::minnum: { 5208 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5209 unsigned Opc = 5210 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5211 ? ISD::FMINNAN 5212 : ISD::FMINNUM; 5213 setValue(&I, DAG.getNode(Opc, sdl, VT, 5214 getValue(I.getArgOperand(0)), 5215 getValue(I.getArgOperand(1)))); 5216 return nullptr; 5217 } 5218 case Intrinsic::maxnum: { 5219 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5220 unsigned Opc = 5221 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5222 ? ISD::FMAXNAN 5223 : ISD::FMAXNUM; 5224 setValue(&I, DAG.getNode(Opc, sdl, VT, 5225 getValue(I.getArgOperand(0)), 5226 getValue(I.getArgOperand(1)))); 5227 return nullptr; 5228 } 5229 case Intrinsic::copysign: 5230 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5231 getValue(I.getArgOperand(0)).getValueType(), 5232 getValue(I.getArgOperand(0)), 5233 getValue(I.getArgOperand(1)))); 5234 return nullptr; 5235 case Intrinsic::fma: 5236 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5237 getValue(I.getArgOperand(0)).getValueType(), 5238 getValue(I.getArgOperand(0)), 5239 getValue(I.getArgOperand(1)), 5240 getValue(I.getArgOperand(2)))); 5241 return nullptr; 5242 case Intrinsic::fmuladd: { 5243 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5244 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5245 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5246 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5247 getValue(I.getArgOperand(0)).getValueType(), 5248 getValue(I.getArgOperand(0)), 5249 getValue(I.getArgOperand(1)), 5250 getValue(I.getArgOperand(2)))); 5251 } else { 5252 // TODO: Intrinsic calls should have fast-math-flags. 5253 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5254 getValue(I.getArgOperand(0)).getValueType(), 5255 getValue(I.getArgOperand(0)), 5256 getValue(I.getArgOperand(1))); 5257 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5258 getValue(I.getArgOperand(0)).getValueType(), 5259 Mul, 5260 getValue(I.getArgOperand(2))); 5261 setValue(&I, Add); 5262 } 5263 return nullptr; 5264 } 5265 case Intrinsic::convert_to_fp16: 5266 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5267 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5268 getValue(I.getArgOperand(0)), 5269 DAG.getTargetConstant(0, sdl, 5270 MVT::i32)))); 5271 return nullptr; 5272 case Intrinsic::convert_from_fp16: 5273 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5274 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5275 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5276 getValue(I.getArgOperand(0))))); 5277 return nullptr; 5278 case Intrinsic::pcmarker: { 5279 SDValue Tmp = getValue(I.getArgOperand(0)); 5280 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5281 return nullptr; 5282 } 5283 case Intrinsic::readcyclecounter: { 5284 SDValue Op = getRoot(); 5285 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5286 DAG.getVTList(MVT::i64, MVT::Other), Op); 5287 setValue(&I, Res); 5288 DAG.setRoot(Res.getValue(1)); 5289 return nullptr; 5290 } 5291 case Intrinsic::bitreverse: 5292 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5293 getValue(I.getArgOperand(0)).getValueType(), 5294 getValue(I.getArgOperand(0)))); 5295 return nullptr; 5296 case Intrinsic::bswap: 5297 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5298 getValue(I.getArgOperand(0)).getValueType(), 5299 getValue(I.getArgOperand(0)))); 5300 return nullptr; 5301 case Intrinsic::cttz: { 5302 SDValue Arg = getValue(I.getArgOperand(0)); 5303 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5304 EVT Ty = Arg.getValueType(); 5305 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5306 sdl, Ty, Arg)); 5307 return nullptr; 5308 } 5309 case Intrinsic::ctlz: { 5310 SDValue Arg = getValue(I.getArgOperand(0)); 5311 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5312 EVT Ty = Arg.getValueType(); 5313 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5314 sdl, Ty, Arg)); 5315 return nullptr; 5316 } 5317 case Intrinsic::ctpop: { 5318 SDValue Arg = getValue(I.getArgOperand(0)); 5319 EVT Ty = Arg.getValueType(); 5320 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5321 return nullptr; 5322 } 5323 case Intrinsic::stacksave: { 5324 SDValue Op = getRoot(); 5325 Res = DAG.getNode( 5326 ISD::STACKSAVE, sdl, 5327 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5328 setValue(&I, Res); 5329 DAG.setRoot(Res.getValue(1)); 5330 return nullptr; 5331 } 5332 case Intrinsic::stackrestore: { 5333 Res = getValue(I.getArgOperand(0)); 5334 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5335 return nullptr; 5336 } 5337 case Intrinsic::get_dynamic_area_offset: { 5338 SDValue Op = getRoot(); 5339 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5340 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5341 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5342 // target. 5343 if (PtrTy != ResTy) 5344 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5345 " intrinsic!"); 5346 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5347 Op); 5348 DAG.setRoot(Op); 5349 setValue(&I, Res); 5350 return nullptr; 5351 } 5352 case Intrinsic::stackguard: { 5353 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5354 MachineFunction &MF = DAG.getMachineFunction(); 5355 const Module &M = *MF.getFunction()->getParent(); 5356 SDValue Chain = getRoot(); 5357 if (TLI.useLoadStackGuardNode()) { 5358 Res = getLoadStackGuard(DAG, sdl, Chain); 5359 } else { 5360 const Value *Global = TLI.getSDagStackGuard(M); 5361 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5362 Res = 5363 DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5364 MachinePointerInfo(Global, 0), true, false, false, Align); 5365 } 5366 DAG.setRoot(Chain); 5367 setValue(&I, Res); 5368 return nullptr; 5369 } 5370 case Intrinsic::stackprotector: { 5371 // Emit code into the DAG to store the stack guard onto the stack. 5372 MachineFunction &MF = DAG.getMachineFunction(); 5373 MachineFrameInfo *MFI = MF.getFrameInfo(); 5374 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5375 SDValue Src, Chain = getRoot(); 5376 5377 if (TLI.useLoadStackGuardNode()) 5378 Src = getLoadStackGuard(DAG, sdl, Chain); 5379 else 5380 Src = getValue(I.getArgOperand(0)); // The guard's value. 5381 5382 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5383 5384 int FI = FuncInfo.StaticAllocaMap[Slot]; 5385 MFI->setStackProtectorIndex(FI); 5386 5387 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5388 5389 // Store the stack protector onto the stack. 5390 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5391 DAG.getMachineFunction(), FI), 5392 true, false, 0); 5393 setValue(&I, Res); 5394 DAG.setRoot(Res); 5395 return nullptr; 5396 } 5397 case Intrinsic::objectsize: { 5398 // If we don't know by now, we're never going to know. 5399 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5400 5401 assert(CI && "Non-constant type in __builtin_object_size?"); 5402 5403 SDValue Arg = getValue(I.getCalledValue()); 5404 EVT Ty = Arg.getValueType(); 5405 5406 if (CI->isZero()) 5407 Res = DAG.getConstant(-1ULL, sdl, Ty); 5408 else 5409 Res = DAG.getConstant(0, sdl, Ty); 5410 5411 setValue(&I, Res); 5412 return nullptr; 5413 } 5414 case Intrinsic::annotation: 5415 case Intrinsic::ptr_annotation: 5416 // Drop the intrinsic, but forward the value 5417 setValue(&I, getValue(I.getOperand(0))); 5418 return nullptr; 5419 case Intrinsic::assume: 5420 case Intrinsic::var_annotation: 5421 // Discard annotate attributes and assumptions 5422 return nullptr; 5423 5424 case Intrinsic::init_trampoline: { 5425 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5426 5427 SDValue Ops[6]; 5428 Ops[0] = getRoot(); 5429 Ops[1] = getValue(I.getArgOperand(0)); 5430 Ops[2] = getValue(I.getArgOperand(1)); 5431 Ops[3] = getValue(I.getArgOperand(2)); 5432 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5433 Ops[5] = DAG.getSrcValue(F); 5434 5435 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5436 5437 DAG.setRoot(Res); 5438 return nullptr; 5439 } 5440 case Intrinsic::adjust_trampoline: { 5441 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5442 TLI.getPointerTy(DAG.getDataLayout()), 5443 getValue(I.getArgOperand(0)))); 5444 return nullptr; 5445 } 5446 case Intrinsic::gcroot: { 5447 MachineFunction &MF = DAG.getMachineFunction(); 5448 const Function *F = MF.getFunction(); 5449 (void)F; 5450 assert(F->hasGC() && 5451 "only valid in functions with gc specified, enforced by Verifier"); 5452 assert(GFI && "implied by previous"); 5453 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5454 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5455 5456 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5457 GFI->addStackRoot(FI->getIndex(), TypeMap); 5458 return nullptr; 5459 } 5460 case Intrinsic::gcread: 5461 case Intrinsic::gcwrite: 5462 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5463 case Intrinsic::flt_rounds: 5464 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5465 return nullptr; 5466 5467 case Intrinsic::expect: { 5468 // Just replace __builtin_expect(exp, c) with EXP. 5469 setValue(&I, getValue(I.getArgOperand(0))); 5470 return nullptr; 5471 } 5472 5473 case Intrinsic::debugtrap: 5474 case Intrinsic::trap: { 5475 StringRef TrapFuncName = 5476 I.getAttributes() 5477 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name") 5478 .getValueAsString(); 5479 if (TrapFuncName.empty()) { 5480 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5481 ISD::TRAP : ISD::DEBUGTRAP; 5482 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5483 return nullptr; 5484 } 5485 TargetLowering::ArgListTy Args; 5486 5487 TargetLowering::CallLoweringInfo CLI(DAG); 5488 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee( 5489 CallingConv::C, I.getType(), 5490 DAG.getExternalSymbol(TrapFuncName.data(), 5491 TLI.getPointerTy(DAG.getDataLayout())), 5492 std::move(Args)); 5493 5494 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5495 DAG.setRoot(Result.second); 5496 return nullptr; 5497 } 5498 5499 case Intrinsic::uadd_with_overflow: 5500 case Intrinsic::sadd_with_overflow: 5501 case Intrinsic::usub_with_overflow: 5502 case Intrinsic::ssub_with_overflow: 5503 case Intrinsic::umul_with_overflow: 5504 case Intrinsic::smul_with_overflow: { 5505 ISD::NodeType Op; 5506 switch (Intrinsic) { 5507 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5508 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5509 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5510 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5511 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5512 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5513 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5514 } 5515 SDValue Op1 = getValue(I.getArgOperand(0)); 5516 SDValue Op2 = getValue(I.getArgOperand(1)); 5517 5518 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5519 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5520 return nullptr; 5521 } 5522 case Intrinsic::prefetch: { 5523 SDValue Ops[5]; 5524 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5525 Ops[0] = getRoot(); 5526 Ops[1] = getValue(I.getArgOperand(0)); 5527 Ops[2] = getValue(I.getArgOperand(1)); 5528 Ops[3] = getValue(I.getArgOperand(2)); 5529 Ops[4] = getValue(I.getArgOperand(3)); 5530 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5531 DAG.getVTList(MVT::Other), Ops, 5532 EVT::getIntegerVT(*Context, 8), 5533 MachinePointerInfo(I.getArgOperand(0)), 5534 0, /* align */ 5535 false, /* volatile */ 5536 rw==0, /* read */ 5537 rw==1)); /* write */ 5538 return nullptr; 5539 } 5540 case Intrinsic::lifetime_start: 5541 case Intrinsic::lifetime_end: { 5542 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5543 // Stack coloring is not enabled in O0, discard region information. 5544 if (TM.getOptLevel() == CodeGenOpt::None) 5545 return nullptr; 5546 5547 SmallVector<Value *, 4> Allocas; 5548 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5549 5550 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5551 E = Allocas.end(); Object != E; ++Object) { 5552 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5553 5554 // Could not find an Alloca. 5555 if (!LifetimeObject) 5556 continue; 5557 5558 // First check that the Alloca is static, otherwise it won't have a 5559 // valid frame index. 5560 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5561 if (SI == FuncInfo.StaticAllocaMap.end()) 5562 return nullptr; 5563 5564 int FI = SI->second; 5565 5566 SDValue Ops[2]; 5567 Ops[0] = getRoot(); 5568 Ops[1] = 5569 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true); 5570 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5571 5572 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5573 DAG.setRoot(Res); 5574 } 5575 return nullptr; 5576 } 5577 case Intrinsic::invariant_start: 5578 // Discard region information. 5579 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5580 return nullptr; 5581 case Intrinsic::invariant_end: 5582 // Discard region information. 5583 return nullptr; 5584 case Intrinsic::clear_cache: 5585 return TLI.getClearCacheBuiltinName(); 5586 case Intrinsic::donothing: 5587 // ignore 5588 return nullptr; 5589 case Intrinsic::experimental_stackmap: { 5590 visitStackmap(I); 5591 return nullptr; 5592 } 5593 case Intrinsic::experimental_patchpoint_void: 5594 case Intrinsic::experimental_patchpoint_i64: { 5595 visitPatchpoint(&I); 5596 return nullptr; 5597 } 5598 case Intrinsic::experimental_gc_statepoint: { 5599 LowerStatepoint(ImmutableStatepoint(&I)); 5600 return nullptr; 5601 } 5602 case Intrinsic::experimental_gc_result: { 5603 visitGCResult(cast<GCResultInst>(I)); 5604 return nullptr; 5605 } 5606 case Intrinsic::experimental_gc_relocate: { 5607 visitGCRelocate(cast<GCRelocateInst>(I)); 5608 return nullptr; 5609 } 5610 case Intrinsic::instrprof_increment: 5611 llvm_unreachable("instrprof failed to lower an increment"); 5612 case Intrinsic::instrprof_value_profile: 5613 llvm_unreachable("instrprof failed to lower a value profiling call"); 5614 case Intrinsic::localescape: { 5615 MachineFunction &MF = DAG.getMachineFunction(); 5616 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5617 5618 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5619 // is the same on all targets. 5620 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5621 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5622 if (isa<ConstantPointerNull>(Arg)) 5623 continue; // Skip null pointers. They represent a hole in index space. 5624 AllocaInst *Slot = cast<AllocaInst>(Arg); 5625 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5626 "can only escape static allocas"); 5627 int FI = FuncInfo.StaticAllocaMap[Slot]; 5628 MCSymbol *FrameAllocSym = 5629 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5630 GlobalValue::getRealLinkageName(MF.getName()), Idx); 5631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5632 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5633 .addSym(FrameAllocSym) 5634 .addFrameIndex(FI); 5635 } 5636 5637 return nullptr; 5638 } 5639 5640 case Intrinsic::localrecover: { 5641 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 5642 MachineFunction &MF = DAG.getMachineFunction(); 5643 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 5644 5645 // Get the symbol that defines the frame offset. 5646 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 5647 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 5648 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX)); 5649 MCSymbol *FrameAllocSym = 5650 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5651 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal); 5652 5653 // Create a MCSymbol for the label to avoid any target lowering 5654 // that would make this PC relative. 5655 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 5656 SDValue OffsetVal = 5657 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 5658 5659 // Add the offset to the FP. 5660 Value *FP = I.getArgOperand(1); 5661 SDValue FPVal = getValue(FP); 5662 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 5663 setValue(&I, Add); 5664 5665 return nullptr; 5666 } 5667 5668 case Intrinsic::eh_exceptionpointer: 5669 case Intrinsic::eh_exceptioncode: { 5670 // Get the exception pointer vreg, copy from it, and resize it to fit. 5671 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 5672 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 5673 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 5674 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 5675 SDValue N = 5676 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 5677 if (Intrinsic == Intrinsic::eh_exceptioncode) 5678 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 5679 setValue(&I, N); 5680 return nullptr; 5681 } 5682 5683 case Intrinsic::experimental_deoptimize: 5684 LowerDeoptimizeCall(&I); 5685 return nullptr; 5686 } 5687 } 5688 5689 std::pair<SDValue, SDValue> 5690 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 5691 const BasicBlock *EHPadBB) { 5692 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5693 MCSymbol *BeginLabel = nullptr; 5694 5695 if (EHPadBB) { 5696 // Insert a label before the invoke call to mark the try range. This can be 5697 // used to detect deletion of the invoke via the MachineModuleInfo. 5698 BeginLabel = MMI.getContext().createTempSymbol(); 5699 5700 // For SjLj, keep track of which landing pads go with which invokes 5701 // so as to maintain the ordering of pads in the LSDA. 5702 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5703 if (CallSiteIndex) { 5704 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5705 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 5706 5707 // Now that the call site is handled, stop tracking it. 5708 MMI.setCurrentCallSite(0); 5709 } 5710 5711 // Both PendingLoads and PendingExports must be flushed here; 5712 // this call might not return. 5713 (void)getRoot(); 5714 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 5715 5716 CLI.setChain(getRoot()); 5717 } 5718 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5719 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5720 5721 assert((CLI.IsTailCall || Result.second.getNode()) && 5722 "Non-null chain expected with non-tail call!"); 5723 assert((Result.second.getNode() || !Result.first.getNode()) && 5724 "Null value expected with tail call!"); 5725 5726 if (!Result.second.getNode()) { 5727 // As a special case, a null chain means that a tail call has been emitted 5728 // and the DAG root is already updated. 5729 HasTailCall = true; 5730 5731 // Since there's no actual continuation from this block, nothing can be 5732 // relying on us setting vregs for them. 5733 PendingExports.clear(); 5734 } else { 5735 DAG.setRoot(Result.second); 5736 } 5737 5738 if (EHPadBB) { 5739 // Insert a label at the end of the invoke call to mark the try range. This 5740 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5741 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 5742 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 5743 5744 // Inform MachineModuleInfo of range. 5745 if (MMI.hasEHFunclets()) { 5746 assert(CLI.CS); 5747 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 5748 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS->getInstruction()), 5749 BeginLabel, EndLabel); 5750 } else { 5751 MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 5752 } 5753 } 5754 5755 return Result; 5756 } 5757 5758 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 5759 bool isTailCall, 5760 const BasicBlock *EHPadBB) { 5761 auto &DL = DAG.getDataLayout(); 5762 FunctionType *FTy = CS.getFunctionType(); 5763 Type *RetTy = CS.getType(); 5764 5765 TargetLowering::ArgListTy Args; 5766 TargetLowering::ArgListEntry Entry; 5767 Args.reserve(CS.arg_size()); 5768 5769 const Value *SwiftErrorVal = nullptr; 5770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5771 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5772 i != e; ++i) { 5773 const Value *V = *i; 5774 5775 // Skip empty types 5776 if (V->getType()->isEmptyTy()) 5777 continue; 5778 5779 SDValue ArgNode = getValue(V); 5780 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5781 5782 // Skip the first return-type Attribute to get to params. 5783 Entry.setAttributes(&CS, i - CS.arg_begin() + 1); 5784 5785 // Use swifterror virtual register as input to the call. 5786 if (Entry.isSwiftError && TLI.supportSwiftError()) { 5787 SwiftErrorVal = V; 5788 // We find the virtual register for the actual swifterror argument. 5789 // Instead of using the Value, we use the virtual register instead. 5790 Entry.Node = DAG.getRegister( 5791 FuncInfo.findSwiftErrorVReg(FuncInfo.MBB, V), 5792 EVT(TLI.getPointerTy(DL))); 5793 } 5794 5795 Args.push_back(Entry); 5796 5797 // If we have an explicit sret argument that is an Instruction, (i.e., it 5798 // might point to function-local memory), we can't meaningfully tail-call. 5799 if (Entry.isSRet && isa<Instruction>(V)) 5800 isTailCall = false; 5801 } 5802 5803 // Check if target-independent constraints permit a tail call here. 5804 // Target-dependent constraints are checked within TLI->LowerCallTo. 5805 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 5806 isTailCall = false; 5807 5808 TargetLowering::CallLoweringInfo CLI(DAG); 5809 CLI.setDebugLoc(getCurSDLoc()) 5810 .setChain(getRoot()) 5811 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 5812 .setTailCall(isTailCall) 5813 .setConvergent(CS.isConvergent()); 5814 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 5815 5816 if (Result.first.getNode()) { 5817 const Instruction *Inst = CS.getInstruction(); 5818 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 5819 setValue(Inst, Result.first); 5820 } 5821 5822 // The last element of CLI.InVals has the SDValue for swifterror return. 5823 // Here we copy it to a virtual register and update SwiftErrorMap for 5824 // book-keeping. 5825 if (SwiftErrorVal && TLI.supportSwiftError()) { 5826 // Get the last element of InVals. 5827 SDValue Src = CLI.InVals.back(); 5828 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL)); 5829 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC); 5830 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 5831 // We update the virtual register for the actual swifterror argument. 5832 FuncInfo.setSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 5833 DAG.setRoot(CopyNode); 5834 } 5835 } 5836 5837 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5838 /// value is equal or not-equal to zero. 5839 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5840 for (const User *U : V->users()) { 5841 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U)) 5842 if (IC->isEquality()) 5843 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5844 if (C->isNullValue()) 5845 continue; 5846 // Unknown instruction. 5847 return false; 5848 } 5849 return true; 5850 } 5851 5852 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5853 Type *LoadTy, 5854 SelectionDAGBuilder &Builder) { 5855 5856 // Check to see if this load can be trivially constant folded, e.g. if the 5857 // input is from a string literal. 5858 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5859 // Cast pointer to the type we really want to load. 5860 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5861 PointerType::getUnqual(LoadTy)); 5862 5863 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 5864 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 5865 return Builder.getValue(LoadCst); 5866 } 5867 5868 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5869 // still constant memory, the input chain can be the entry node. 5870 SDValue Root; 5871 bool ConstantMemory = false; 5872 5873 // Do not serialize (non-volatile) loads of constant memory with anything. 5874 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5875 Root = Builder.DAG.getEntryNode(); 5876 ConstantMemory = true; 5877 } else { 5878 // Do not serialize non-volatile loads against each other. 5879 Root = Builder.DAG.getRoot(); 5880 } 5881 5882 SDValue Ptr = Builder.getValue(PtrVal); 5883 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 5884 Ptr, MachinePointerInfo(PtrVal), 5885 false /*volatile*/, 5886 false /*nontemporal*/, 5887 false /*isinvariant*/, 1 /* align=1 */); 5888 5889 if (!ConstantMemory) 5890 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5891 return LoadVal; 5892 } 5893 5894 /// processIntegerCallValue - Record the value for an instruction that 5895 /// produces an integer result, converting the type where necessary. 5896 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 5897 SDValue Value, 5898 bool IsSigned) { 5899 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5900 I.getType(), true); 5901 if (IsSigned) 5902 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 5903 else 5904 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 5905 setValue(&I, Value); 5906 } 5907 5908 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5909 /// If so, return true and lower it, otherwise return false and it will be 5910 /// lowered like a normal call. 5911 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5912 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5913 if (I.getNumArgOperands() != 3) 5914 return false; 5915 5916 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5917 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5918 !I.getArgOperand(2)->getType()->isIntegerTy() || 5919 !I.getType()->isIntegerTy()) 5920 return false; 5921 5922 const Value *Size = I.getArgOperand(2); 5923 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 5924 if (CSize && CSize->getZExtValue() == 0) { 5925 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 5926 I.getType(), true); 5927 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 5928 return true; 5929 } 5930 5931 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 5932 std::pair<SDValue, SDValue> Res = 5933 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5934 getValue(LHS), getValue(RHS), getValue(Size), 5935 MachinePointerInfo(LHS), 5936 MachinePointerInfo(RHS)); 5937 if (Res.first.getNode()) { 5938 processIntegerCallValue(I, Res.first, true); 5939 PendingLoads.push_back(Res.second); 5940 return true; 5941 } 5942 5943 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5944 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5945 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) { 5946 bool ActuallyDoIt = true; 5947 MVT LoadVT; 5948 Type *LoadTy; 5949 switch (CSize->getZExtValue()) { 5950 default: 5951 LoadVT = MVT::Other; 5952 LoadTy = nullptr; 5953 ActuallyDoIt = false; 5954 break; 5955 case 2: 5956 LoadVT = MVT::i16; 5957 LoadTy = Type::getInt16Ty(CSize->getContext()); 5958 break; 5959 case 4: 5960 LoadVT = MVT::i32; 5961 LoadTy = Type::getInt32Ty(CSize->getContext()); 5962 break; 5963 case 8: 5964 LoadVT = MVT::i64; 5965 LoadTy = Type::getInt64Ty(CSize->getContext()); 5966 break; 5967 /* 5968 case 16: 5969 LoadVT = MVT::v4i32; 5970 LoadTy = Type::getInt32Ty(CSize->getContext()); 5971 LoadTy = VectorType::get(LoadTy, 4); 5972 break; 5973 */ 5974 } 5975 5976 // This turns into unaligned loads. We only do this if the target natively 5977 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5978 // we'll only produce a small number of byte loads. 5979 5980 // Require that we can find a legal MVT, and only do this if the target 5981 // supports unaligned loads of that type. Expanding into byte loads would 5982 // bloat the code. 5983 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5984 if (ActuallyDoIt && CSize->getZExtValue() > 4) { 5985 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 5986 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 5987 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5988 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5989 // TODO: Check alignment of src and dest ptrs. 5990 if (!TLI.isTypeLegal(LoadVT) || 5991 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) || 5992 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS)) 5993 ActuallyDoIt = false; 5994 } 5995 5996 if (ActuallyDoIt) { 5997 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5998 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5999 6000 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal, 6001 ISD::SETNE); 6002 processIntegerCallValue(I, Res, false); 6003 return true; 6004 } 6005 } 6006 6007 6008 return false; 6009 } 6010 6011 /// visitMemChrCall -- See if we can lower a memchr call into an optimized 6012 /// form. If so, return true and lower it, otherwise return false and it 6013 /// will be lowered like a normal call. 6014 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6015 // Verify that the prototype makes sense. void *memchr(void *, int, size_t) 6016 if (I.getNumArgOperands() != 3) 6017 return false; 6018 6019 const Value *Src = I.getArgOperand(0); 6020 const Value *Char = I.getArgOperand(1); 6021 const Value *Length = I.getArgOperand(2); 6022 if (!Src->getType()->isPointerTy() || 6023 !Char->getType()->isIntegerTy() || 6024 !Length->getType()->isIntegerTy() || 6025 !I.getType()->isPointerTy()) 6026 return false; 6027 6028 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6029 std::pair<SDValue, SDValue> Res = 6030 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6031 getValue(Src), getValue(Char), getValue(Length), 6032 MachinePointerInfo(Src)); 6033 if (Res.first.getNode()) { 6034 setValue(&I, Res.first); 6035 PendingLoads.push_back(Res.second); 6036 return true; 6037 } 6038 6039 return false; 6040 } 6041 6042 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an 6043 /// optimized form. If so, return true and lower it, otherwise return false 6044 /// and it will be lowered like a normal call. 6045 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6046 // Verify that the prototype makes sense. char *strcpy(char *, char *) 6047 if (I.getNumArgOperands() != 2) 6048 return false; 6049 6050 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6051 if (!Arg0->getType()->isPointerTy() || 6052 !Arg1->getType()->isPointerTy() || 6053 !I.getType()->isPointerTy()) 6054 return false; 6055 6056 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6057 std::pair<SDValue, SDValue> Res = 6058 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6059 getValue(Arg0), getValue(Arg1), 6060 MachinePointerInfo(Arg0), 6061 MachinePointerInfo(Arg1), isStpcpy); 6062 if (Res.first.getNode()) { 6063 setValue(&I, Res.first); 6064 DAG.setRoot(Res.second); 6065 return true; 6066 } 6067 6068 return false; 6069 } 6070 6071 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form. 6072 /// If so, return true and lower it, otherwise return false and it will be 6073 /// lowered like a normal call. 6074 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6075 // Verify that the prototype makes sense. int strcmp(void*,void*) 6076 if (I.getNumArgOperands() != 2) 6077 return false; 6078 6079 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6080 if (!Arg0->getType()->isPointerTy() || 6081 !Arg1->getType()->isPointerTy() || 6082 !I.getType()->isIntegerTy()) 6083 return false; 6084 6085 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6086 std::pair<SDValue, SDValue> Res = 6087 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6088 getValue(Arg0), getValue(Arg1), 6089 MachinePointerInfo(Arg0), 6090 MachinePointerInfo(Arg1)); 6091 if (Res.first.getNode()) { 6092 processIntegerCallValue(I, Res.first, true); 6093 PendingLoads.push_back(Res.second); 6094 return true; 6095 } 6096 6097 return false; 6098 } 6099 6100 /// visitStrLenCall -- See if we can lower a strlen call into an optimized 6101 /// form. If so, return true and lower it, otherwise return false and it 6102 /// will be lowered like a normal call. 6103 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6104 // Verify that the prototype makes sense. size_t strlen(char *) 6105 if (I.getNumArgOperands() != 1) 6106 return false; 6107 6108 const Value *Arg0 = I.getArgOperand(0); 6109 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy()) 6110 return false; 6111 6112 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6113 std::pair<SDValue, SDValue> Res = 6114 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6115 getValue(Arg0), MachinePointerInfo(Arg0)); 6116 if (Res.first.getNode()) { 6117 processIntegerCallValue(I, Res.first, false); 6118 PendingLoads.push_back(Res.second); 6119 return true; 6120 } 6121 6122 return false; 6123 } 6124 6125 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized 6126 /// form. If so, return true and lower it, otherwise return false and it 6127 /// will be lowered like a normal call. 6128 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6129 // Verify that the prototype makes sense. size_t strnlen(char *, size_t) 6130 if (I.getNumArgOperands() != 2) 6131 return false; 6132 6133 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6134 if (!Arg0->getType()->isPointerTy() || 6135 !Arg1->getType()->isIntegerTy() || 6136 !I.getType()->isIntegerTy()) 6137 return false; 6138 6139 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6140 std::pair<SDValue, SDValue> Res = 6141 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6142 getValue(Arg0), getValue(Arg1), 6143 MachinePointerInfo(Arg0)); 6144 if (Res.first.getNode()) { 6145 processIntegerCallValue(I, Res.first, false); 6146 PendingLoads.push_back(Res.second); 6147 return true; 6148 } 6149 6150 return false; 6151 } 6152 6153 /// visitUnaryFloatCall - If a call instruction is a unary floating-point 6154 /// operation (as expected), translate it to an SDNode with the specified opcode 6155 /// and return true. 6156 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6157 unsigned Opcode) { 6158 // Sanity check that it really is a unary floating-point call. 6159 if (I.getNumArgOperands() != 1 || 6160 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 6161 I.getType() != I.getArgOperand(0)->getType() || 6162 !I.onlyReadsMemory()) 6163 return false; 6164 6165 SDValue Tmp = getValue(I.getArgOperand(0)); 6166 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6167 return true; 6168 } 6169 6170 /// visitBinaryFloatCall - If a call instruction is a binary floating-point 6171 /// operation (as expected), translate it to an SDNode with the specified opcode 6172 /// and return true. 6173 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6174 unsigned Opcode) { 6175 // Sanity check that it really is a binary floating-point call. 6176 if (I.getNumArgOperands() != 2 || 6177 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 6178 I.getType() != I.getArgOperand(0)->getType() || 6179 I.getType() != I.getArgOperand(1)->getType() || 6180 !I.onlyReadsMemory()) 6181 return false; 6182 6183 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6184 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6185 EVT VT = Tmp0.getValueType(); 6186 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6187 return true; 6188 } 6189 6190 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6191 // Handle inline assembly differently. 6192 if (isa<InlineAsm>(I.getCalledValue())) { 6193 visitInlineAsm(&I); 6194 return; 6195 } 6196 6197 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6198 ComputeUsesVAFloatArgument(I, &MMI); 6199 6200 const char *RenameFn = nullptr; 6201 if (Function *F = I.getCalledFunction()) { 6202 if (F->isDeclaration()) { 6203 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 6204 if (unsigned IID = II->getIntrinsicID(F)) { 6205 RenameFn = visitIntrinsicCall(I, IID); 6206 if (!RenameFn) 6207 return; 6208 } 6209 } 6210 if (Intrinsic::ID IID = F->getIntrinsicID()) { 6211 RenameFn = visitIntrinsicCall(I, IID); 6212 if (!RenameFn) 6213 return; 6214 } 6215 } 6216 6217 // Check for well-known libc/libm calls. If the function is internal, it 6218 // can't be a library call. Don't do the check if marked as nobuiltin for 6219 // some reason. 6220 LibFunc::Func Func; 6221 if (!I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName() && 6222 LibInfo->getLibFunc(F->getName(), Func) && 6223 LibInfo->hasOptimizedCodeGen(Func)) { 6224 switch (Func) { 6225 default: break; 6226 case LibFunc::copysign: 6227 case LibFunc::copysignf: 6228 case LibFunc::copysignl: 6229 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 6230 I.getArgOperand(0)->getType()->isFloatingPointTy() && 6231 I.getType() == I.getArgOperand(0)->getType() && 6232 I.getType() == I.getArgOperand(1)->getType() && 6233 I.onlyReadsMemory()) { 6234 SDValue LHS = getValue(I.getArgOperand(0)); 6235 SDValue RHS = getValue(I.getArgOperand(1)); 6236 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6237 LHS.getValueType(), LHS, RHS)); 6238 return; 6239 } 6240 break; 6241 case LibFunc::fabs: 6242 case LibFunc::fabsf: 6243 case LibFunc::fabsl: 6244 if (visitUnaryFloatCall(I, ISD::FABS)) 6245 return; 6246 break; 6247 case LibFunc::fmin: 6248 case LibFunc::fminf: 6249 case LibFunc::fminl: 6250 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6251 return; 6252 break; 6253 case LibFunc::fmax: 6254 case LibFunc::fmaxf: 6255 case LibFunc::fmaxl: 6256 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6257 return; 6258 break; 6259 case LibFunc::sin: 6260 case LibFunc::sinf: 6261 case LibFunc::sinl: 6262 if (visitUnaryFloatCall(I, ISD::FSIN)) 6263 return; 6264 break; 6265 case LibFunc::cos: 6266 case LibFunc::cosf: 6267 case LibFunc::cosl: 6268 if (visitUnaryFloatCall(I, ISD::FCOS)) 6269 return; 6270 break; 6271 case LibFunc::sqrt: 6272 case LibFunc::sqrtf: 6273 case LibFunc::sqrtl: 6274 case LibFunc::sqrt_finite: 6275 case LibFunc::sqrtf_finite: 6276 case LibFunc::sqrtl_finite: 6277 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6278 return; 6279 break; 6280 case LibFunc::floor: 6281 case LibFunc::floorf: 6282 case LibFunc::floorl: 6283 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6284 return; 6285 break; 6286 case LibFunc::nearbyint: 6287 case LibFunc::nearbyintf: 6288 case LibFunc::nearbyintl: 6289 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6290 return; 6291 break; 6292 case LibFunc::ceil: 6293 case LibFunc::ceilf: 6294 case LibFunc::ceill: 6295 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6296 return; 6297 break; 6298 case LibFunc::rint: 6299 case LibFunc::rintf: 6300 case LibFunc::rintl: 6301 if (visitUnaryFloatCall(I, ISD::FRINT)) 6302 return; 6303 break; 6304 case LibFunc::round: 6305 case LibFunc::roundf: 6306 case LibFunc::roundl: 6307 if (visitUnaryFloatCall(I, ISD::FROUND)) 6308 return; 6309 break; 6310 case LibFunc::trunc: 6311 case LibFunc::truncf: 6312 case LibFunc::truncl: 6313 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6314 return; 6315 break; 6316 case LibFunc::log2: 6317 case LibFunc::log2f: 6318 case LibFunc::log2l: 6319 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6320 return; 6321 break; 6322 case LibFunc::exp2: 6323 case LibFunc::exp2f: 6324 case LibFunc::exp2l: 6325 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6326 return; 6327 break; 6328 case LibFunc::memcmp: 6329 if (visitMemCmpCall(I)) 6330 return; 6331 break; 6332 case LibFunc::memchr: 6333 if (visitMemChrCall(I)) 6334 return; 6335 break; 6336 case LibFunc::strcpy: 6337 if (visitStrCpyCall(I, false)) 6338 return; 6339 break; 6340 case LibFunc::stpcpy: 6341 if (visitStrCpyCall(I, true)) 6342 return; 6343 break; 6344 case LibFunc::strcmp: 6345 if (visitStrCmpCall(I)) 6346 return; 6347 break; 6348 case LibFunc::strlen: 6349 if (visitStrLenCall(I)) 6350 return; 6351 break; 6352 case LibFunc::strnlen: 6353 if (visitStrNLenCall(I)) 6354 return; 6355 break; 6356 } 6357 } 6358 } 6359 6360 SDValue Callee; 6361 if (!RenameFn) 6362 Callee = getValue(I.getCalledValue()); 6363 else 6364 Callee = DAG.getExternalSymbol( 6365 RenameFn, 6366 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6367 6368 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 6369 // have to do anything here to lower funclet bundles. 6370 assert(!I.hasOperandBundlesOtherThan( 6371 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 6372 "Cannot lower calls with arbitrary operand bundles!"); 6373 6374 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 6375 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 6376 else 6377 // Check if we can potentially perform a tail call. More detailed checking 6378 // is be done within LowerCallTo, after more information about the call is 6379 // known. 6380 LowerCallTo(&I, Callee, I.isTailCall()); 6381 } 6382 6383 namespace { 6384 6385 /// AsmOperandInfo - This contains information for each constraint that we are 6386 /// lowering. 6387 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 6388 public: 6389 /// CallOperand - If this is the result output operand or a clobber 6390 /// this is null, otherwise it is the incoming operand to the CallInst. 6391 /// This gets modified as the asm is processed. 6392 SDValue CallOperand; 6393 6394 /// AssignedRegs - If this is a register or register class operand, this 6395 /// contains the set of register corresponding to the operand. 6396 RegsForValue AssignedRegs; 6397 6398 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 6399 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) { 6400 } 6401 6402 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 6403 /// corresponds to. If there is no Value* for this operand, it returns 6404 /// MVT::Other. 6405 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 6406 const DataLayout &DL) const { 6407 if (!CallOperandVal) return MVT::Other; 6408 6409 if (isa<BasicBlock>(CallOperandVal)) 6410 return TLI.getPointerTy(DL); 6411 6412 llvm::Type *OpTy = CallOperandVal->getType(); 6413 6414 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 6415 // If this is an indirect operand, the operand is a pointer to the 6416 // accessed type. 6417 if (isIndirect) { 6418 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 6419 if (!PtrTy) 6420 report_fatal_error("Indirect operand for inline asm not a pointer!"); 6421 OpTy = PtrTy->getElementType(); 6422 } 6423 6424 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 6425 if (StructType *STy = dyn_cast<StructType>(OpTy)) 6426 if (STy->getNumElements() == 1) 6427 OpTy = STy->getElementType(0); 6428 6429 // If OpTy is not a single value, it may be a struct/union that we 6430 // can tile with integers. 6431 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 6432 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 6433 switch (BitSize) { 6434 default: break; 6435 case 1: 6436 case 8: 6437 case 16: 6438 case 32: 6439 case 64: 6440 case 128: 6441 OpTy = IntegerType::get(Context, BitSize); 6442 break; 6443 } 6444 } 6445 6446 return TLI.getValueType(DL, OpTy, true); 6447 } 6448 }; 6449 6450 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 6451 6452 } // end anonymous namespace 6453 6454 /// GetRegistersForValue - Assign registers (virtual or physical) for the 6455 /// specified operand. We prefer to assign virtual registers, to allow the 6456 /// register allocator to handle the assignment process. However, if the asm 6457 /// uses features that we can't model on machineinstrs, we have SDISel do the 6458 /// allocation. This produces generally horrible, but correct, code. 6459 /// 6460 /// OpInfo describes the operand. 6461 /// 6462 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 6463 const SDLoc &DL, 6464 SDISelAsmOperandInfo &OpInfo) { 6465 LLVMContext &Context = *DAG.getContext(); 6466 6467 MachineFunction &MF = DAG.getMachineFunction(); 6468 SmallVector<unsigned, 4> Regs; 6469 6470 // If this is a constraint for a single physreg, or a constraint for a 6471 // register class, find it. 6472 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 6473 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(), 6474 OpInfo.ConstraintCode, 6475 OpInfo.ConstraintVT); 6476 6477 unsigned NumRegs = 1; 6478 if (OpInfo.ConstraintVT != MVT::Other) { 6479 // If this is a FP input in an integer register (or visa versa) insert a bit 6480 // cast of the input value. More generally, handle any case where the input 6481 // value disagrees with the register class we plan to stick this in. 6482 if (OpInfo.Type == InlineAsm::isInput && 6483 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 6484 // Try to convert to the first EVT that the reg class contains. If the 6485 // types are identical size, use a bitcast to convert (e.g. two differing 6486 // vector types). 6487 MVT RegVT = *PhysReg.second->vt_begin(); 6488 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 6489 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6490 RegVT, OpInfo.CallOperand); 6491 OpInfo.ConstraintVT = RegVT; 6492 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 6493 // If the input is a FP value and we want it in FP registers, do a 6494 // bitcast to the corresponding integer type. This turns an f64 value 6495 // into i64, which can be passed with two i32 values on a 32-bit 6496 // machine. 6497 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 6498 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6499 RegVT, OpInfo.CallOperand); 6500 OpInfo.ConstraintVT = RegVT; 6501 } 6502 } 6503 6504 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 6505 } 6506 6507 MVT RegVT; 6508 EVT ValueVT = OpInfo.ConstraintVT; 6509 6510 // If this is a constraint for a specific physical register, like {r17}, 6511 // assign it now. 6512 if (unsigned AssignedReg = PhysReg.first) { 6513 const TargetRegisterClass *RC = PhysReg.second; 6514 if (OpInfo.ConstraintVT == MVT::Other) 6515 ValueVT = *RC->vt_begin(); 6516 6517 // Get the actual register value type. This is important, because the user 6518 // may have asked for (e.g.) the AX register in i32 type. We need to 6519 // remember that AX is actually i16 to get the right extension. 6520 RegVT = *RC->vt_begin(); 6521 6522 // This is a explicit reference to a physical register. 6523 Regs.push_back(AssignedReg); 6524 6525 // If this is an expanded reference, add the rest of the regs to Regs. 6526 if (NumRegs != 1) { 6527 TargetRegisterClass::iterator I = RC->begin(); 6528 for (; *I != AssignedReg; ++I) 6529 assert(I != RC->end() && "Didn't find reg!"); 6530 6531 // Already added the first reg. 6532 --NumRegs; ++I; 6533 for (; NumRegs; --NumRegs, ++I) { 6534 assert(I != RC->end() && "Ran out of registers to allocate!"); 6535 Regs.push_back(*I); 6536 } 6537 } 6538 6539 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6540 return; 6541 } 6542 6543 // Otherwise, if this was a reference to an LLVM register class, create vregs 6544 // for this reference. 6545 if (const TargetRegisterClass *RC = PhysReg.second) { 6546 RegVT = *RC->vt_begin(); 6547 if (OpInfo.ConstraintVT == MVT::Other) 6548 ValueVT = RegVT; 6549 6550 // Create the appropriate number of virtual registers. 6551 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6552 for (; NumRegs; --NumRegs) 6553 Regs.push_back(RegInfo.createVirtualRegister(RC)); 6554 6555 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6556 return; 6557 } 6558 6559 // Otherwise, we couldn't allocate enough registers for this. 6560 } 6561 6562 /// visitInlineAsm - Handle a call to an InlineAsm object. 6563 /// 6564 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 6565 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 6566 6567 /// ConstraintOperands - Information about all of the constraints. 6568 SDISelAsmOperandInfoVector ConstraintOperands; 6569 6570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6571 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 6572 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 6573 6574 bool hasMemory = false; 6575 6576 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 6577 unsigned ResNo = 0; // ResNo - The result number of the next output. 6578 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6579 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 6580 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 6581 6582 MVT OpVT = MVT::Other; 6583 6584 // Compute the value type for each operand. 6585 switch (OpInfo.Type) { 6586 case InlineAsm::isOutput: 6587 // Indirect outputs just consume an argument. 6588 if (OpInfo.isIndirect) { 6589 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6590 break; 6591 } 6592 6593 // The return value of the call is this value. As such, there is no 6594 // corresponding argument. 6595 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6596 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 6597 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 6598 STy->getElementType(ResNo)); 6599 } else { 6600 assert(ResNo == 0 && "Asm only has one result!"); 6601 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 6602 } 6603 ++ResNo; 6604 break; 6605 case InlineAsm::isInput: 6606 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6607 break; 6608 case InlineAsm::isClobber: 6609 // Nothing to do. 6610 break; 6611 } 6612 6613 // If this is an input or an indirect output, process the call argument. 6614 // BasicBlocks are labels, currently appearing only in asm's. 6615 if (OpInfo.CallOperandVal) { 6616 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 6617 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 6618 } else { 6619 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 6620 } 6621 6622 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 6623 DAG.getDataLayout()).getSimpleVT(); 6624 } 6625 6626 OpInfo.ConstraintVT = OpVT; 6627 6628 // Indirect operand accesses access memory. 6629 if (OpInfo.isIndirect) 6630 hasMemory = true; 6631 else { 6632 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 6633 TargetLowering::ConstraintType 6634 CType = TLI.getConstraintType(OpInfo.Codes[j]); 6635 if (CType == TargetLowering::C_Memory) { 6636 hasMemory = true; 6637 break; 6638 } 6639 } 6640 } 6641 } 6642 6643 SDValue Chain, Flag; 6644 6645 // We won't need to flush pending loads if this asm doesn't touch 6646 // memory and is nonvolatile. 6647 if (hasMemory || IA->hasSideEffects()) 6648 Chain = getRoot(); 6649 else 6650 Chain = DAG.getRoot(); 6651 6652 // Second pass over the constraints: compute which constraint option to use 6653 // and assign registers to constraints that want a specific physreg. 6654 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6655 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6656 6657 // If this is an output operand with a matching input operand, look up the 6658 // matching input. If their types mismatch, e.g. one is an integer, the 6659 // other is floating point, or their sizes are different, flag it as an 6660 // error. 6661 if (OpInfo.hasMatchingInput()) { 6662 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 6663 6664 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 6665 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 6666 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 6667 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 6668 OpInfo.ConstraintVT); 6669 std::pair<unsigned, const TargetRegisterClass *> InputRC = 6670 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 6671 Input.ConstraintVT); 6672 if ((OpInfo.ConstraintVT.isInteger() != 6673 Input.ConstraintVT.isInteger()) || 6674 (MatchRC.second != InputRC.second)) { 6675 report_fatal_error("Unsupported asm: input constraint" 6676 " with a matching output constraint of" 6677 " incompatible type!"); 6678 } 6679 Input.ConstraintVT = OpInfo.ConstraintVT; 6680 } 6681 } 6682 6683 // Compute the constraint code and ConstraintType to use. 6684 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 6685 6686 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6687 OpInfo.Type == InlineAsm::isClobber) 6688 continue; 6689 6690 // If this is a memory input, and if the operand is not indirect, do what we 6691 // need to to provide an address for the memory input. 6692 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6693 !OpInfo.isIndirect) { 6694 assert((OpInfo.isMultipleAlternative || 6695 (OpInfo.Type == InlineAsm::isInput)) && 6696 "Can only indirectify direct input operands!"); 6697 6698 // Memory operands really want the address of the value. If we don't have 6699 // an indirect input, put it in the constpool if we can, otherwise spill 6700 // it to a stack slot. 6701 // TODO: This isn't quite right. We need to handle these according to 6702 // the addressing mode that the constraint wants. Also, this may take 6703 // an additional register for the computation and we don't want that 6704 // either. 6705 6706 // If the operand is a float, integer, or vector constant, spill to a 6707 // constant pool entry to get its address. 6708 const Value *OpVal = OpInfo.CallOperandVal; 6709 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6710 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6711 OpInfo.CallOperand = DAG.getConstantPool( 6712 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 6713 } else { 6714 // Otherwise, create a stack slot and emit a store to it before the 6715 // asm. 6716 Type *Ty = OpVal->getType(); 6717 auto &DL = DAG.getDataLayout(); 6718 uint64_t TySize = DL.getTypeAllocSize(Ty); 6719 unsigned Align = DL.getPrefTypeAlignment(Ty); 6720 MachineFunction &MF = DAG.getMachineFunction(); 6721 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6722 SDValue StackSlot = 6723 DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout())); 6724 Chain = DAG.getStore( 6725 Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot, 6726 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), 6727 false, false, 0); 6728 OpInfo.CallOperand = StackSlot; 6729 } 6730 6731 // There is no longer a Value* corresponding to this operand. 6732 OpInfo.CallOperandVal = nullptr; 6733 6734 // It is now an indirect operand. 6735 OpInfo.isIndirect = true; 6736 } 6737 6738 // If this constraint is for a specific register, allocate it before 6739 // anything else. 6740 if (OpInfo.ConstraintType == TargetLowering::C_Register) 6741 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6742 } 6743 6744 // Second pass - Loop over all of the operands, assigning virtual or physregs 6745 // to register class operands. 6746 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6747 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6748 6749 // C_Register operands have already been allocated, Other/Memory don't need 6750 // to be. 6751 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 6752 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 6753 } 6754 6755 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 6756 std::vector<SDValue> AsmNodeOperands; 6757 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 6758 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 6759 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 6760 6761 // If we have a !srcloc metadata node associated with it, we want to attach 6762 // this to the ultimately generated inline asm machineinstr. To do this, we 6763 // pass in the third operand as this (potentially null) inline asm MDNode. 6764 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 6765 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 6766 6767 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6768 // bits as operand 3. 6769 unsigned ExtraInfo = 0; 6770 if (IA->hasSideEffects()) 6771 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 6772 if (IA->isAlignStack()) 6773 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 6774 if (CS.isConvergent()) 6775 ExtraInfo |= InlineAsm::Extra_IsConvergent; 6776 // Set the asm dialect. 6777 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 6778 6779 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 6780 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6781 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 6782 6783 // Compute the constraint code and ConstraintType to use. 6784 TLI.ComputeConstraintToUse(OpInfo, SDValue()); 6785 6786 // Ideally, we would only check against memory constraints. However, the 6787 // meaning of an other constraint can be target-specific and we can't easily 6788 // reason about it. Therefore, be conservative and set MayLoad/MayStore 6789 // for other constriants as well. 6790 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 6791 OpInfo.ConstraintType == TargetLowering::C_Other) { 6792 if (OpInfo.Type == InlineAsm::isInput) 6793 ExtraInfo |= InlineAsm::Extra_MayLoad; 6794 else if (OpInfo.Type == InlineAsm::isOutput) 6795 ExtraInfo |= InlineAsm::Extra_MayStore; 6796 else if (OpInfo.Type == InlineAsm::isClobber) 6797 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 6798 } 6799 } 6800 6801 AsmNodeOperands.push_back(DAG.getTargetConstant( 6802 ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6803 6804 // Loop over all of the inputs, copying the operand values into the 6805 // appropriate registers and processing the output regs. 6806 RegsForValue RetValRegs; 6807 6808 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 6809 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 6810 6811 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6812 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6813 6814 switch (OpInfo.Type) { 6815 case InlineAsm::isOutput: { 6816 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 6817 OpInfo.ConstraintType != TargetLowering::C_Register) { 6818 // Memory output, or 'other' output (e.g. 'X' constraint). 6819 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 6820 6821 unsigned ConstraintID = 6822 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6823 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6824 "Failed to convert memory constraint code to constraint id."); 6825 6826 // Add information to the INLINEASM node to know about this output. 6827 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6828 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 6829 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 6830 MVT::i32)); 6831 AsmNodeOperands.push_back(OpInfo.CallOperand); 6832 break; 6833 } 6834 6835 // Otherwise, this is a register or register class output. 6836 6837 // Copy the output from the appropriate register. Find a register that 6838 // we can use. 6839 if (OpInfo.AssignedRegs.Regs.empty()) { 6840 emitInlineAsmError( 6841 CS, "couldn't allocate output register for constraint '" + 6842 Twine(OpInfo.ConstraintCode) + "'"); 6843 return; 6844 } 6845 6846 // If this is an indirect operand, store through the pointer after the 6847 // asm. 6848 if (OpInfo.isIndirect) { 6849 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 6850 OpInfo.CallOperandVal)); 6851 } else { 6852 // This is the result value of the call. 6853 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6854 // Concatenate this output onto the outputs list. 6855 RetValRegs.append(OpInfo.AssignedRegs); 6856 } 6857 6858 // Add information to the INLINEASM node to know that this register is 6859 // set. 6860 OpInfo.AssignedRegs 6861 .AddInlineAsmOperands(OpInfo.isEarlyClobber 6862 ? InlineAsm::Kind_RegDefEarlyClobber 6863 : InlineAsm::Kind_RegDef, 6864 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 6865 break; 6866 } 6867 case InlineAsm::isInput: { 6868 SDValue InOperandVal = OpInfo.CallOperand; 6869 6870 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 6871 // If this is required to match an output register we have already set, 6872 // just use its register. 6873 unsigned OperandNo = OpInfo.getMatchedOperand(); 6874 6875 // Scan until we find the definition we already emitted of this operand. 6876 // When we find it, create a RegsForValue operand. 6877 unsigned CurOp = InlineAsm::Op_FirstOperand; 6878 for (; OperandNo; --OperandNo) { 6879 // Advance to the next operand. 6880 unsigned OpFlag = 6881 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6882 assert((InlineAsm::isRegDefKind(OpFlag) || 6883 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 6884 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 6885 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 6886 } 6887 6888 unsigned OpFlag = 6889 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6890 if (InlineAsm::isRegDefKind(OpFlag) || 6891 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 6892 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 6893 if (OpInfo.isIndirect) { 6894 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 6895 emitInlineAsmError(CS, "inline asm not supported yet:" 6896 " don't know how to handle tied " 6897 "indirect register inputs"); 6898 return; 6899 } 6900 6901 RegsForValue MatchedRegs; 6902 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 6903 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 6904 MatchedRegs.RegVTs.push_back(RegVT); 6905 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 6906 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 6907 i != e; ++i) { 6908 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 6909 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC)); 6910 else { 6911 emitInlineAsmError( 6912 CS, "inline asm error: This value" 6913 " type register class is not natively supported!"); 6914 return; 6915 } 6916 } 6917 SDLoc dl = getCurSDLoc(); 6918 // Use the produced MatchedRegs object to 6919 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, 6920 Chain, &Flag, CS.getInstruction()); 6921 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 6922 true, OpInfo.getMatchedOperand(), dl, 6923 DAG, AsmNodeOperands); 6924 break; 6925 } 6926 6927 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 6928 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 6929 "Unexpected number of operands"); 6930 // Add information to the INLINEASM node to know about this input. 6931 // See InlineAsm.h isUseOperandTiedToDef. 6932 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 6933 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 6934 OpInfo.getMatchedOperand()); 6935 AsmNodeOperands.push_back(DAG.getTargetConstant( 6936 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6937 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 6938 break; 6939 } 6940 6941 // Treat indirect 'X' constraint as memory. 6942 if (OpInfo.ConstraintType == TargetLowering::C_Other && 6943 OpInfo.isIndirect) 6944 OpInfo.ConstraintType = TargetLowering::C_Memory; 6945 6946 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 6947 std::vector<SDValue> Ops; 6948 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 6949 Ops, DAG); 6950 if (Ops.empty()) { 6951 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 6952 Twine(OpInfo.ConstraintCode) + "'"); 6953 return; 6954 } 6955 6956 // Add information to the INLINEASM node to know about this input. 6957 unsigned ResOpType = 6958 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 6959 AsmNodeOperands.push_back(DAG.getTargetConstant( 6960 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 6961 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 6962 break; 6963 } 6964 6965 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 6966 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 6967 assert(InOperandVal.getValueType() == 6968 TLI.getPointerTy(DAG.getDataLayout()) && 6969 "Memory operands expect pointer values"); 6970 6971 unsigned ConstraintID = 6972 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 6973 assert(ConstraintID != InlineAsm::Constraint_Unknown && 6974 "Failed to convert memory constraint code to constraint id."); 6975 6976 // Add information to the INLINEASM node to know about this input. 6977 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6978 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 6979 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6980 getCurSDLoc(), 6981 MVT::i32)); 6982 AsmNodeOperands.push_back(InOperandVal); 6983 break; 6984 } 6985 6986 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 6987 OpInfo.ConstraintType == TargetLowering::C_Register) && 6988 "Unknown constraint type!"); 6989 6990 // TODO: Support this. 6991 if (OpInfo.isIndirect) { 6992 emitInlineAsmError( 6993 CS, "Don't know how to handle indirect register inputs yet " 6994 "for constraint '" + 6995 Twine(OpInfo.ConstraintCode) + "'"); 6996 return; 6997 } 6998 6999 // Copy the input into the appropriate registers. 7000 if (OpInfo.AssignedRegs.Regs.empty()) { 7001 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7002 Twine(OpInfo.ConstraintCode) + "'"); 7003 return; 7004 } 7005 7006 SDLoc dl = getCurSDLoc(); 7007 7008 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7009 Chain, &Flag, CS.getInstruction()); 7010 7011 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7012 dl, DAG, AsmNodeOperands); 7013 break; 7014 } 7015 case InlineAsm::isClobber: { 7016 // Add the clobbered value to the operand list, so that the register 7017 // allocator is aware that the physreg got clobbered. 7018 if (!OpInfo.AssignedRegs.Regs.empty()) 7019 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7020 false, 0, getCurSDLoc(), DAG, 7021 AsmNodeOperands); 7022 break; 7023 } 7024 } 7025 } 7026 7027 // Finish up input operands. Set the input chain and add the flag last. 7028 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7029 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7030 7031 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7032 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7033 Flag = Chain.getValue(1); 7034 7035 // If this asm returns a register value, copy the result from that register 7036 // and set it as the value of the call. 7037 if (!RetValRegs.Regs.empty()) { 7038 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7039 Chain, &Flag, CS.getInstruction()); 7040 7041 // FIXME: Why don't we do this for inline asms with MRVs? 7042 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7043 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7044 7045 // If any of the results of the inline asm is a vector, it may have the 7046 // wrong width/num elts. This can happen for register classes that can 7047 // contain multiple different value types. The preg or vreg allocated may 7048 // not have the same VT as was expected. Convert it to the right type 7049 // with bit_convert. 7050 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 7051 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7052 ResultType, Val); 7053 7054 } else if (ResultType != Val.getValueType() && 7055 ResultType.isInteger() && Val.getValueType().isInteger()) { 7056 // If a result value was tied to an input value, the computed result may 7057 // have a wider width than the expected result. Extract the relevant 7058 // portion. 7059 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7060 } 7061 7062 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7063 } 7064 7065 setValue(CS.getInstruction(), Val); 7066 // Don't need to use this as a chain in this case. 7067 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7068 return; 7069 } 7070 7071 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 7072 7073 // Process indirect outputs, first output all of the flagged copies out of 7074 // physregs. 7075 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7076 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7077 const Value *Ptr = IndirectStoresToEmit[i].second; 7078 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7079 Chain, &Flag, IA); 7080 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7081 } 7082 7083 // Emit the non-flagged stores from the physregs. 7084 SmallVector<SDValue, 8> OutChains; 7085 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7086 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), 7087 StoresToEmit[i].first, 7088 getValue(StoresToEmit[i].second), 7089 MachinePointerInfo(StoresToEmit[i].second), 7090 false, false, 0); 7091 OutChains.push_back(Val); 7092 } 7093 7094 if (!OutChains.empty()) 7095 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7096 7097 DAG.setRoot(Chain); 7098 } 7099 7100 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7101 const Twine &Message) { 7102 LLVMContext &Ctx = *DAG.getContext(); 7103 Ctx.emitError(CS.getInstruction(), Message); 7104 7105 // Make sure we leave the DAG in a valid state 7106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7107 auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7108 setValue(CS.getInstruction(), DAG.getUNDEF(VT)); 7109 } 7110 7111 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7112 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7113 MVT::Other, getRoot(), 7114 getValue(I.getArgOperand(0)), 7115 DAG.getSrcValue(I.getArgOperand(0)))); 7116 } 7117 7118 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7119 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7120 const DataLayout &DL = DAG.getDataLayout(); 7121 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7122 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7123 DAG.getSrcValue(I.getOperand(0)), 7124 DL.getABITypeAlignment(I.getType())); 7125 setValue(&I, V); 7126 DAG.setRoot(V.getValue(1)); 7127 } 7128 7129 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7130 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7131 MVT::Other, getRoot(), 7132 getValue(I.getArgOperand(0)), 7133 DAG.getSrcValue(I.getArgOperand(0)))); 7134 } 7135 7136 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7137 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7138 MVT::Other, getRoot(), 7139 getValue(I.getArgOperand(0)), 7140 getValue(I.getArgOperand(1)), 7141 DAG.getSrcValue(I.getArgOperand(0)), 7142 DAG.getSrcValue(I.getArgOperand(1)))); 7143 } 7144 7145 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7146 const Instruction &I, 7147 SDValue Op) { 7148 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7149 if (!Range) 7150 return Op; 7151 7152 Constant *Lo = cast<ConstantAsMetadata>(Range->getOperand(0))->getValue(); 7153 if (!Lo->isNullValue()) 7154 return Op; 7155 7156 Constant *Hi = cast<ConstantAsMetadata>(Range->getOperand(1))->getValue(); 7157 unsigned Bits = cast<ConstantInt>(Hi)->getValue().logBase2(); 7158 7159 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7160 7161 SDLoc SL = getCurSDLoc(); 7162 7163 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), 7164 Op, DAG.getValueType(SmallVT)); 7165 unsigned NumVals = Op.getNode()->getNumValues(); 7166 if (NumVals == 1) 7167 return ZExt; 7168 7169 SmallVector<SDValue, 4> Ops; 7170 7171 Ops.push_back(ZExt); 7172 for (unsigned I = 1; I != NumVals; ++I) 7173 Ops.push_back(Op.getValue(I)); 7174 7175 return DAG.getMergeValues(Ops, SL); 7176 } 7177 7178 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of 7179 /// the call being lowered. 7180 /// 7181 /// This is a helper for lowering intrinsics that follow a target calling 7182 /// convention or require stack pointer adjustment. Only a subset of the 7183 /// intrinsic's operands need to participate in the calling convention. 7184 void SelectionDAGBuilder::populateCallLoweringInfo( 7185 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7186 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7187 bool IsPatchPoint) { 7188 TargetLowering::ArgListTy Args; 7189 Args.reserve(NumArgs); 7190 7191 // Populate the argument list. 7192 // Attributes for args start at offset 1, after the return attribute. 7193 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1; 7194 ArgI != ArgE; ++ArgI) { 7195 const Value *V = CS->getOperand(ArgI); 7196 7197 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7198 7199 TargetLowering::ArgListEntry Entry; 7200 Entry.Node = getValue(V); 7201 Entry.Ty = V->getType(); 7202 Entry.setAttributes(&CS, AttrI); 7203 Args.push_back(Entry); 7204 } 7205 7206 CLI.setDebugLoc(getCurSDLoc()) 7207 .setChain(getRoot()) 7208 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7209 .setDiscardResult(CS->use_empty()) 7210 .setIsPatchPoint(IsPatchPoint); 7211 } 7212 7213 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 7214 /// or patchpoint target node's operand list. 7215 /// 7216 /// Constants are converted to TargetConstants purely as an optimization to 7217 /// avoid constant materialization and register allocation. 7218 /// 7219 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7220 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7221 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7222 /// address materialization and register allocation, but may also be required 7223 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7224 /// alloca in the entry block, then the runtime may assume that the alloca's 7225 /// StackMap location can be read immediately after compilation and that the 7226 /// location is valid at any point during execution (this is similar to the 7227 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7228 /// only available in a register, then the runtime would need to trap when 7229 /// execution reaches the StackMap in order to read the alloca's location. 7230 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7231 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7232 SelectionDAGBuilder &Builder) { 7233 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7234 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7235 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7236 Ops.push_back( 7237 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7238 Ops.push_back( 7239 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7240 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7241 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7242 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7243 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout()))); 7244 } else 7245 Ops.push_back(OpVal); 7246 } 7247 } 7248 7249 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 7250 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7251 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7252 // [live variables...]) 7253 7254 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7255 7256 SDValue Chain, InFlag, Callee, NullPtr; 7257 SmallVector<SDValue, 32> Ops; 7258 7259 SDLoc DL = getCurSDLoc(); 7260 Callee = getValue(CI.getCalledValue()); 7261 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7262 7263 // The stackmap intrinsic only records the live variables (the arguemnts 7264 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7265 // intrinsic, this won't be lowered to a function call. This means we don't 7266 // have to worry about calling conventions and target specific lowering code. 7267 // Instead we perform the call lowering right here. 7268 // 7269 // chain, flag = CALLSEQ_START(chain, 0) 7270 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7271 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7272 // 7273 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL); 7274 InFlag = Chain.getValue(1); 7275 7276 // Add the <id> and <numBytes> constants. 7277 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7278 Ops.push_back(DAG.getTargetConstant( 7279 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7280 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 7281 Ops.push_back(DAG.getTargetConstant( 7282 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 7283 MVT::i32)); 7284 7285 // Push live variables for the stack map. 7286 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 7287 7288 // We are not pushing any register mask info here on the operands list, 7289 // because the stackmap doesn't clobber anything. 7290 7291 // Push the chain and the glue flag. 7292 Ops.push_back(Chain); 7293 Ops.push_back(InFlag); 7294 7295 // Create the STACKMAP node. 7296 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7297 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 7298 Chain = SDValue(SM, 0); 7299 InFlag = Chain.getValue(1); 7300 7301 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 7302 7303 // Stackmaps don't generate values, so nothing goes into the NodeMap. 7304 7305 // Set the root to the target-lowered call chain. 7306 DAG.setRoot(Chain); 7307 7308 // Inform the Frame Information that we have a stackmap in this function. 7309 FuncInfo.MF->getFrameInfo()->setHasStackMap(); 7310 } 7311 7312 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 7313 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 7314 const BasicBlock *EHPadBB) { 7315 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 7316 // i32 <numBytes>, 7317 // i8* <target>, 7318 // i32 <numArgs>, 7319 // [Args...], 7320 // [live variables...]) 7321 7322 CallingConv::ID CC = CS.getCallingConv(); 7323 bool IsAnyRegCC = CC == CallingConv::AnyReg; 7324 bool HasDef = !CS->getType()->isVoidTy(); 7325 SDLoc dl = getCurSDLoc(); 7326 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 7327 7328 // Handle immediate and symbolic callees. 7329 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 7330 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 7331 /*isTarget=*/true); 7332 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 7333 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 7334 SDLoc(SymbolicCallee), 7335 SymbolicCallee->getValueType(0)); 7336 7337 // Get the real number of arguments participating in the call <numArgs> 7338 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 7339 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 7340 7341 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 7342 // Intrinsics include all meta-operands up to but not including CC. 7343 unsigned NumMetaOpers = PatchPointOpers::CCPos; 7344 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 7345 "Not enough arguments provided to the patchpoint intrinsic"); 7346 7347 // For AnyRegCC the arguments are lowered later on manually. 7348 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 7349 Type *ReturnTy = 7350 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 7351 7352 TargetLowering::CallLoweringInfo CLI(DAG); 7353 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 7354 true); 7355 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7356 7357 SDNode *CallEnd = Result.second.getNode(); 7358 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 7359 CallEnd = CallEnd->getOperand(0).getNode(); 7360 7361 /// Get a call instruction from the call sequence chain. 7362 /// Tail calls are not allowed. 7363 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 7364 "Expected a callseq node."); 7365 SDNode *Call = CallEnd->getOperand(0).getNode(); 7366 bool HasGlue = Call->getGluedNode(); 7367 7368 // Replace the target specific call node with the patchable intrinsic. 7369 SmallVector<SDValue, 8> Ops; 7370 7371 // Add the <id> and <numBytes> constants. 7372 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 7373 Ops.push_back(DAG.getTargetConstant( 7374 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 7375 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 7376 Ops.push_back(DAG.getTargetConstant( 7377 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 7378 MVT::i32)); 7379 7380 // Add the callee. 7381 Ops.push_back(Callee); 7382 7383 // Adjust <numArgs> to account for any arguments that have been passed on the 7384 // stack instead. 7385 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 7386 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 7387 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 7388 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 7389 7390 // Add the calling convention 7391 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 7392 7393 // Add the arguments we omitted previously. The register allocator should 7394 // place these in any free register. 7395 if (IsAnyRegCC) 7396 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 7397 Ops.push_back(getValue(CS.getArgument(i))); 7398 7399 // Push the arguments from the call instruction up to the register mask. 7400 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 7401 Ops.append(Call->op_begin() + 2, e); 7402 7403 // Push live variables for the stack map. 7404 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 7405 7406 // Push the register mask info. 7407 if (HasGlue) 7408 Ops.push_back(*(Call->op_end()-2)); 7409 else 7410 Ops.push_back(*(Call->op_end()-1)); 7411 7412 // Push the chain (this is originally the first operand of the call, but 7413 // becomes now the last or second to last operand). 7414 Ops.push_back(*(Call->op_begin())); 7415 7416 // Push the glue flag (last operand). 7417 if (HasGlue) 7418 Ops.push_back(*(Call->op_end()-1)); 7419 7420 SDVTList NodeTys; 7421 if (IsAnyRegCC && HasDef) { 7422 // Create the return types based on the intrinsic definition 7423 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7424 SmallVector<EVT, 3> ValueVTs; 7425 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7426 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 7427 7428 // There is always a chain and a glue type at the end 7429 ValueVTs.push_back(MVT::Other); 7430 ValueVTs.push_back(MVT::Glue); 7431 NodeTys = DAG.getVTList(ValueVTs); 7432 } else 7433 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7434 7435 // Replace the target specific call node with a PATCHPOINT node. 7436 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 7437 dl, NodeTys, Ops); 7438 7439 // Update the NodeMap. 7440 if (HasDef) { 7441 if (IsAnyRegCC) 7442 setValue(CS.getInstruction(), SDValue(MN, 0)); 7443 else 7444 setValue(CS.getInstruction(), Result.first); 7445 } 7446 7447 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 7448 // call sequence. Furthermore the location of the chain and glue can change 7449 // when the AnyReg calling convention is used and the intrinsic returns a 7450 // value. 7451 if (IsAnyRegCC && HasDef) { 7452 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 7453 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 7454 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 7455 } else 7456 DAG.ReplaceAllUsesWith(Call, MN); 7457 DAG.DeleteNode(Call); 7458 7459 // Inform the Frame Information that we have a patchpoint in this function. 7460 FuncInfo.MF->getFrameInfo()->setHasPatchPoint(); 7461 } 7462 7463 /// Returns an AttributeSet representing the attributes applied to the return 7464 /// value of the given call. 7465 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 7466 SmallVector<Attribute::AttrKind, 2> Attrs; 7467 if (CLI.RetSExt) 7468 Attrs.push_back(Attribute::SExt); 7469 if (CLI.RetZExt) 7470 Attrs.push_back(Attribute::ZExt); 7471 if (CLI.IsInReg) 7472 Attrs.push_back(Attribute::InReg); 7473 7474 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex, 7475 Attrs); 7476 } 7477 7478 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 7479 /// implementation, which just calls LowerCall. 7480 /// FIXME: When all targets are 7481 /// migrated to using LowerCall, this hook should be integrated into SDISel. 7482 std::pair<SDValue, SDValue> 7483 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 7484 // Handle the incoming return values from the call. 7485 CLI.Ins.clear(); 7486 Type *OrigRetTy = CLI.RetTy; 7487 SmallVector<EVT, 4> RetTys; 7488 SmallVector<uint64_t, 4> Offsets; 7489 auto &DL = CLI.DAG.getDataLayout(); 7490 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 7491 7492 SmallVector<ISD::OutputArg, 4> Outs; 7493 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 7494 7495 bool CanLowerReturn = 7496 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 7497 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 7498 7499 SDValue DemoteStackSlot; 7500 int DemoteStackIdx = -100; 7501 if (!CanLowerReturn) { 7502 // FIXME: equivalent assert? 7503 // assert(!CS.hasInAllocaArgument() && 7504 // "sret demotion is incompatible with inalloca"); 7505 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 7506 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 7507 MachineFunction &MF = CLI.DAG.getMachineFunction(); 7508 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 7509 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 7510 7511 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL)); 7512 ArgListEntry Entry; 7513 Entry.Node = DemoteStackSlot; 7514 Entry.Ty = StackSlotPtrType; 7515 Entry.isSExt = false; 7516 Entry.isZExt = false; 7517 Entry.isInReg = false; 7518 Entry.isSRet = true; 7519 Entry.isNest = false; 7520 Entry.isByVal = false; 7521 Entry.isReturned = false; 7522 Entry.isSwiftSelf = false; 7523 Entry.isSwiftError = false; 7524 Entry.Alignment = Align; 7525 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 7526 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 7527 7528 // sret demotion isn't compatible with tail-calls, since the sret argument 7529 // points into the callers stack frame. 7530 CLI.IsTailCall = false; 7531 } else { 7532 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7533 EVT VT = RetTys[I]; 7534 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7535 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7536 for (unsigned i = 0; i != NumRegs; ++i) { 7537 ISD::InputArg MyFlags; 7538 MyFlags.VT = RegisterVT; 7539 MyFlags.ArgVT = VT; 7540 MyFlags.Used = CLI.IsReturnValueUsed; 7541 if (CLI.RetSExt) 7542 MyFlags.Flags.setSExt(); 7543 if (CLI.RetZExt) 7544 MyFlags.Flags.setZExt(); 7545 if (CLI.IsInReg) 7546 MyFlags.Flags.setInReg(); 7547 CLI.Ins.push_back(MyFlags); 7548 } 7549 } 7550 } 7551 7552 // We push in swifterror return as the last element of CLI.Ins. 7553 ArgListTy &Args = CLI.getArgs(); 7554 if (supportSwiftError()) { 7555 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 7556 if (Args[i].isSwiftError) { 7557 ISD::InputArg MyFlags; 7558 MyFlags.VT = getPointerTy(DL); 7559 MyFlags.ArgVT = EVT(getPointerTy(DL)); 7560 MyFlags.Flags.setSwiftError(); 7561 CLI.Ins.push_back(MyFlags); 7562 } 7563 } 7564 } 7565 7566 // Handle all of the outgoing arguments. 7567 CLI.Outs.clear(); 7568 CLI.OutVals.clear(); 7569 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 7570 SmallVector<EVT, 4> ValueVTs; 7571 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 7572 Type *FinalType = Args[i].Ty; 7573 if (Args[i].isByVal) 7574 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 7575 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 7576 FinalType, CLI.CallConv, CLI.IsVarArg); 7577 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 7578 ++Value) { 7579 EVT VT = ValueVTs[Value]; 7580 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 7581 SDValue Op = SDValue(Args[i].Node.getNode(), 7582 Args[i].Node.getResNo() + Value); 7583 ISD::ArgFlagsTy Flags; 7584 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7585 7586 if (Args[i].isZExt) 7587 Flags.setZExt(); 7588 if (Args[i].isSExt) 7589 Flags.setSExt(); 7590 if (Args[i].isInReg) 7591 Flags.setInReg(); 7592 if (Args[i].isSRet) 7593 Flags.setSRet(); 7594 if (Args[i].isSwiftSelf) 7595 Flags.setSwiftSelf(); 7596 if (Args[i].isSwiftError) 7597 Flags.setSwiftError(); 7598 if (Args[i].isByVal) 7599 Flags.setByVal(); 7600 if (Args[i].isInAlloca) { 7601 Flags.setInAlloca(); 7602 // Set the byval flag for CCAssignFn callbacks that don't know about 7603 // inalloca. This way we can know how many bytes we should've allocated 7604 // and how many bytes a callee cleanup function will pop. If we port 7605 // inalloca to more targets, we'll have to add custom inalloca handling 7606 // in the various CC lowering callbacks. 7607 Flags.setByVal(); 7608 } 7609 if (Args[i].isByVal || Args[i].isInAlloca) { 7610 PointerType *Ty = cast<PointerType>(Args[i].Ty); 7611 Type *ElementTy = Ty->getElementType(); 7612 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 7613 // For ByVal, alignment should come from FE. BE will guess if this 7614 // info is not there but there are cases it cannot get right. 7615 unsigned FrameAlign; 7616 if (Args[i].Alignment) 7617 FrameAlign = Args[i].Alignment; 7618 else 7619 FrameAlign = getByValTypeAlignment(ElementTy, DL); 7620 Flags.setByValAlign(FrameAlign); 7621 } 7622 if (Args[i].isNest) 7623 Flags.setNest(); 7624 if (NeedsRegBlock) 7625 Flags.setInConsecutiveRegs(); 7626 Flags.setOrigAlign(OriginalAlignment); 7627 7628 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT); 7629 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT); 7630 SmallVector<SDValue, 4> Parts(NumParts); 7631 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 7632 7633 if (Args[i].isSExt) 7634 ExtendKind = ISD::SIGN_EXTEND; 7635 else if (Args[i].isZExt) 7636 ExtendKind = ISD::ZERO_EXTEND; 7637 7638 // Conservatively only handle 'returned' on non-vectors for now 7639 if (Args[i].isReturned && !Op.getValueType().isVector()) { 7640 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 7641 "unexpected use of 'returned'"); 7642 // Before passing 'returned' to the target lowering code, ensure that 7643 // either the register MVT and the actual EVT are the same size or that 7644 // the return value and argument are extended in the same way; in these 7645 // cases it's safe to pass the argument register value unchanged as the 7646 // return register value (although it's at the target's option whether 7647 // to do so) 7648 // TODO: allow code generation to take advantage of partially preserved 7649 // registers rather than clobbering the entire register when the 7650 // parameter extension method is not compatible with the return 7651 // extension method 7652 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 7653 (ExtendKind != ISD::ANY_EXTEND && 7654 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt)) 7655 Flags.setReturned(); 7656 } 7657 7658 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 7659 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind); 7660 7661 for (unsigned j = 0; j != NumParts; ++j) { 7662 // if it isn't first piece, alignment must be 1 7663 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 7664 i < CLI.NumFixedArgs, 7665 i, j*Parts[j].getValueType().getStoreSize()); 7666 if (NumParts > 1 && j == 0) 7667 MyFlags.Flags.setSplit(); 7668 else if (j != 0) { 7669 MyFlags.Flags.setOrigAlign(1); 7670 if (j == NumParts - 1) 7671 MyFlags.Flags.setSplitEnd(); 7672 } 7673 7674 CLI.Outs.push_back(MyFlags); 7675 CLI.OutVals.push_back(Parts[j]); 7676 } 7677 7678 if (NeedsRegBlock && Value == NumValues - 1) 7679 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 7680 } 7681 } 7682 7683 SmallVector<SDValue, 4> InVals; 7684 CLI.Chain = LowerCall(CLI, InVals); 7685 7686 // Update CLI.InVals to use outside of this function. 7687 CLI.InVals = InVals; 7688 7689 // Verify that the target's LowerCall behaved as expected. 7690 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 7691 "LowerCall didn't return a valid chain!"); 7692 assert((!CLI.IsTailCall || InVals.empty()) && 7693 "LowerCall emitted a return value for a tail call!"); 7694 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 7695 "LowerCall didn't emit the correct number of values!"); 7696 7697 // For a tail call, the return value is merely live-out and there aren't 7698 // any nodes in the DAG representing it. Return a special value to 7699 // indicate that a tail call has been emitted and no more Instructions 7700 // should be processed in the current block. 7701 if (CLI.IsTailCall) { 7702 CLI.DAG.setRoot(CLI.Chain); 7703 return std::make_pair(SDValue(), SDValue()); 7704 } 7705 7706 #ifndef NDEBUG 7707 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 7708 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 7709 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 7710 "LowerCall emitted a value with the wrong type!"); 7711 } 7712 #endif 7713 7714 SmallVector<SDValue, 4> ReturnValues; 7715 if (!CanLowerReturn) { 7716 // The instruction result is the result of loading from the 7717 // hidden sret parameter. 7718 SmallVector<EVT, 1> PVTs; 7719 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy); 7720 7721 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 7722 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 7723 EVT PtrVT = PVTs[0]; 7724 7725 unsigned NumValues = RetTys.size(); 7726 ReturnValues.resize(NumValues); 7727 SmallVector<SDValue, 4> Chains(NumValues); 7728 7729 // An aggregate return value cannot wrap around the address space, so 7730 // offsets to its parts don't wrap either. 7731 SDNodeFlags Flags; 7732 Flags.setNoUnsignedWrap(true); 7733 7734 for (unsigned i = 0; i < NumValues; ++i) { 7735 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 7736 CLI.DAG.getConstant(Offsets[i], CLI.DL, 7737 PtrVT), &Flags); 7738 SDValue L = CLI.DAG.getLoad( 7739 RetTys[i], CLI.DL, CLI.Chain, Add, 7740 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 7741 DemoteStackIdx, Offsets[i]), 7742 false, false, false, 1); 7743 ReturnValues[i] = L; 7744 Chains[i] = L.getValue(1); 7745 } 7746 7747 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 7748 } else { 7749 // Collect the legal value parts into potentially illegal values 7750 // that correspond to the original function's return values. 7751 Optional<ISD::NodeType> AssertOp; 7752 if (CLI.RetSExt) 7753 AssertOp = ISD::AssertSext; 7754 else if (CLI.RetZExt) 7755 AssertOp = ISD::AssertZext; 7756 unsigned CurReg = 0; 7757 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 7758 EVT VT = RetTys[I]; 7759 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 7760 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 7761 7762 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 7763 NumRegs, RegisterVT, VT, nullptr, 7764 AssertOp)); 7765 CurReg += NumRegs; 7766 } 7767 7768 // For a function returning void, there is no return value. We can't create 7769 // such a node, so we just return a null return value in that case. In 7770 // that case, nothing will actually look at the value. 7771 if (ReturnValues.empty()) 7772 return std::make_pair(SDValue(), CLI.Chain); 7773 } 7774 7775 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 7776 CLI.DAG.getVTList(RetTys), ReturnValues); 7777 return std::make_pair(Res, CLI.Chain); 7778 } 7779 7780 void TargetLowering::LowerOperationWrapper(SDNode *N, 7781 SmallVectorImpl<SDValue> &Results, 7782 SelectionDAG &DAG) const { 7783 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 7784 Results.push_back(Res); 7785 } 7786 7787 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 7788 llvm_unreachable("LowerOperation not implemented for this target!"); 7789 } 7790 7791 void 7792 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 7793 SDValue Op = getNonRegisterValue(V); 7794 assert((Op.getOpcode() != ISD::CopyFromReg || 7795 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 7796 "Copy from a reg to the same reg!"); 7797 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 7798 7799 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7800 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 7801 V->getType()); 7802 SDValue Chain = DAG.getEntryNode(); 7803 7804 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 7805 FuncInfo.PreferredExtendType.end()) 7806 ? ISD::ANY_EXTEND 7807 : FuncInfo.PreferredExtendType[V]; 7808 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 7809 PendingExports.push_back(Chain); 7810 } 7811 7812 #include "llvm/CodeGen/SelectionDAGISel.h" 7813 7814 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 7815 /// entry block, return true. This includes arguments used by switches, since 7816 /// the switch may expand into multiple basic blocks. 7817 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 7818 // With FastISel active, we may be splitting blocks, so force creation 7819 // of virtual registers for all non-dead arguments. 7820 if (FastISel) 7821 return A->use_empty(); 7822 7823 const BasicBlock &Entry = A->getParent()->front(); 7824 for (const User *U : A->users()) 7825 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 7826 return false; // Use not in entry block. 7827 7828 return true; 7829 } 7830 7831 void SelectionDAGISel::LowerArguments(const Function &F) { 7832 SelectionDAG &DAG = SDB->DAG; 7833 SDLoc dl = SDB->getCurSDLoc(); 7834 const DataLayout &DL = DAG.getDataLayout(); 7835 SmallVector<ISD::InputArg, 16> Ins; 7836 7837 if (!FuncInfo->CanLowerReturn) { 7838 // Put in an sret pointer parameter before all the other parameters. 7839 SmallVector<EVT, 1> ValueVTs; 7840 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7841 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7842 7843 // NOTE: Assuming that a pointer will never break down to more than one VT 7844 // or one register. 7845 ISD::ArgFlagsTy Flags; 7846 Flags.setSRet(); 7847 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 7848 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 7849 ISD::InputArg::NoArgIndex, 0); 7850 Ins.push_back(RetArg); 7851 } 7852 7853 // Set up the incoming argument description vector. 7854 unsigned Idx = 1; 7855 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 7856 I != E; ++I, ++Idx) { 7857 SmallVector<EVT, 4> ValueVTs; 7858 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7859 bool isArgValueUsed = !I->use_empty(); 7860 unsigned PartBase = 0; 7861 Type *FinalType = I->getType(); 7862 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7863 FinalType = cast<PointerType>(FinalType)->getElementType(); 7864 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 7865 FinalType, F.getCallingConv(), F.isVarArg()); 7866 for (unsigned Value = 0, NumValues = ValueVTs.size(); 7867 Value != NumValues; ++Value) { 7868 EVT VT = ValueVTs[Value]; 7869 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 7870 ISD::ArgFlagsTy Flags; 7871 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy); 7872 7873 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7874 Flags.setZExt(); 7875 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7876 Flags.setSExt(); 7877 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg)) 7878 Flags.setInReg(); 7879 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet)) 7880 Flags.setSRet(); 7881 if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftSelf)) 7882 Flags.setSwiftSelf(); 7883 if (F.getAttributes().hasAttribute(Idx, Attribute::SwiftError)) 7884 Flags.setSwiftError(); 7885 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) 7886 Flags.setByVal(); 7887 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) { 7888 Flags.setInAlloca(); 7889 // Set the byval flag for CCAssignFn callbacks that don't know about 7890 // inalloca. This way we can know how many bytes we should've allocated 7891 // and how many bytes a callee cleanup function will pop. If we port 7892 // inalloca to more targets, we'll have to add custom inalloca handling 7893 // in the various CC lowering callbacks. 7894 Flags.setByVal(); 7895 } 7896 if (F.getCallingConv() == CallingConv::X86_INTR) { 7897 // IA Interrupt passes frame (1st parameter) by value in the stack. 7898 if (Idx == 1) 7899 Flags.setByVal(); 7900 } 7901 if (Flags.isByVal() || Flags.isInAlloca()) { 7902 PointerType *Ty = cast<PointerType>(I->getType()); 7903 Type *ElementTy = Ty->getElementType(); 7904 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 7905 // For ByVal, alignment should be passed from FE. BE will guess if 7906 // this info is not there but there are cases it cannot get right. 7907 unsigned FrameAlign; 7908 if (F.getParamAlignment(Idx)) 7909 FrameAlign = F.getParamAlignment(Idx); 7910 else 7911 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 7912 Flags.setByValAlign(FrameAlign); 7913 } 7914 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest)) 7915 Flags.setNest(); 7916 if (NeedsRegBlock) 7917 Flags.setInConsecutiveRegs(); 7918 Flags.setOrigAlign(OriginalAlignment); 7919 7920 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7921 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7922 for (unsigned i = 0; i != NumRegs; ++i) { 7923 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 7924 Idx-1, PartBase+i*RegisterVT.getStoreSize()); 7925 if (NumRegs > 1 && i == 0) 7926 MyFlags.Flags.setSplit(); 7927 // if it isn't first piece, alignment must be 1 7928 else if (i > 0) { 7929 MyFlags.Flags.setOrigAlign(1); 7930 if (i == NumRegs - 1) 7931 MyFlags.Flags.setSplitEnd(); 7932 } 7933 Ins.push_back(MyFlags); 7934 } 7935 if (NeedsRegBlock && Value == NumValues - 1) 7936 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 7937 PartBase += VT.getStoreSize(); 7938 } 7939 } 7940 7941 // Call the target to set up the argument values. 7942 SmallVector<SDValue, 8> InVals; 7943 SDValue NewRoot = TLI->LowerFormalArguments( 7944 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 7945 7946 // Verify that the target's LowerFormalArguments behaved as expected. 7947 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 7948 "LowerFormalArguments didn't return a valid chain!"); 7949 assert(InVals.size() == Ins.size() && 7950 "LowerFormalArguments didn't emit the correct number of values!"); 7951 DEBUG({ 7952 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 7953 assert(InVals[i].getNode() && 7954 "LowerFormalArguments emitted a null value!"); 7955 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 7956 "LowerFormalArguments emitted a value with the wrong type!"); 7957 } 7958 }); 7959 7960 // Update the DAG with the new chain value resulting from argument lowering. 7961 DAG.setRoot(NewRoot); 7962 7963 // Set up the argument values. 7964 unsigned i = 0; 7965 Idx = 1; 7966 if (!FuncInfo->CanLowerReturn) { 7967 // Create a virtual register for the sret pointer, and put in a copy 7968 // from the sret argument into it. 7969 SmallVector<EVT, 1> ValueVTs; 7970 ComputeValueVTs(*TLI, DAG.getDataLayout(), 7971 PointerType::getUnqual(F.getReturnType()), ValueVTs); 7972 MVT VT = ValueVTs[0].getSimpleVT(); 7973 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7974 Optional<ISD::NodeType> AssertOp = None; 7975 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 7976 RegVT, VT, nullptr, AssertOp); 7977 7978 MachineFunction& MF = SDB->DAG.getMachineFunction(); 7979 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 7980 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 7981 FuncInfo->DemoteRegister = SRetReg; 7982 NewRoot = 7983 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 7984 DAG.setRoot(NewRoot); 7985 7986 // i indexes lowered arguments. Bump it past the hidden sret argument. 7987 // Idx indexes LLVM arguments. Don't touch it. 7988 ++i; 7989 } 7990 7991 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 7992 ++I, ++Idx) { 7993 SmallVector<SDValue, 4> ArgValues; 7994 SmallVector<EVT, 4> ValueVTs; 7995 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs); 7996 unsigned NumValues = ValueVTs.size(); 7997 7998 // If this argument is unused then remember its value. It is used to generate 7999 // debugging information. 8000 if (I->use_empty() && NumValues) { 8001 SDB->setUnusedArgValue(&*I, InVals[i]); 8002 8003 // Also remember any frame index for use in FastISel. 8004 if (FrameIndexSDNode *FI = 8005 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 8006 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8007 } 8008 8009 for (unsigned Val = 0; Val != NumValues; ++Val) { 8010 EVT VT = ValueVTs[Val]; 8011 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8012 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT); 8013 8014 if (!I->use_empty()) { 8015 Optional<ISD::NodeType> AssertOp; 8016 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 8017 AssertOp = ISD::AssertSext; 8018 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 8019 AssertOp = ISD::AssertZext; 8020 8021 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 8022 NumParts, PartVT, VT, 8023 nullptr, AssertOp)); 8024 } 8025 8026 i += NumParts; 8027 } 8028 8029 // We don't need to do anything else for unused arguments. 8030 if (ArgValues.empty()) 8031 continue; 8032 8033 // Note down frame index. 8034 if (FrameIndexSDNode *FI = 8035 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 8036 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8037 8038 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 8039 SDB->getCurSDLoc()); 8040 8041 SDB->setValue(&*I, Res); 8042 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 8043 if (LoadSDNode *LNode = 8044 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode())) 8045 if (FrameIndexSDNode *FI = 8046 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 8047 FuncInfo->setArgumentFrameIndex(&*I, FI->getIndex()); 8048 } 8049 8050 // Update SwiftErrorMap. 8051 if (Res.getOpcode() == ISD::CopyFromReg && TLI->supportSwiftError() && 8052 F.getAttributes().hasAttribute(Idx, Attribute::SwiftError)) { 8053 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8054 if (TargetRegisterInfo::isVirtualRegister(Reg)) 8055 FuncInfo->SwiftErrorMap[FuncInfo->MBB][0] = Reg; 8056 } 8057 8058 // If this argument is live outside of the entry block, insert a copy from 8059 // wherever we got it to the vreg that other BB's will reference it as. 8060 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 8061 // If we can, though, try to skip creating an unnecessary vreg. 8062 // FIXME: This isn't very clean... it would be nice to make this more 8063 // general. It's also subtly incompatible with the hacks FastISel 8064 // uses with vregs. 8065 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8066 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 8067 FuncInfo->ValueMap[&*I] = Reg; 8068 continue; 8069 } 8070 } 8071 if (!isOnlyUsedInEntryBlock(&*I, TM.Options.EnableFastISel)) { 8072 FuncInfo->InitializeRegForValue(&*I); 8073 SDB->CopyToExportRegsIfNeeded(&*I); 8074 } 8075 } 8076 8077 assert(i == InVals.size() && "Argument register count mismatch!"); 8078 8079 // Finally, if the target has anything special to do, allow it to do so. 8080 EmitFunctionEntryCode(); 8081 } 8082 8083 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 8084 /// ensure constants are generated when needed. Remember the virtual registers 8085 /// that need to be added to the Machine PHI nodes as input. We cannot just 8086 /// directly add them, because expansion might result in multiple MBB's for one 8087 /// BB. As such, the start of the BB might correspond to a different MBB than 8088 /// the end. 8089 /// 8090 void 8091 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 8092 const TerminatorInst *TI = LLVMBB->getTerminator(); 8093 8094 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 8095 8096 // Check PHI nodes in successors that expect a value to be available from this 8097 // block. 8098 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 8099 const BasicBlock *SuccBB = TI->getSuccessor(succ); 8100 if (!isa<PHINode>(SuccBB->begin())) continue; 8101 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 8102 8103 // If this terminator has multiple identical successors (common for 8104 // switches), only handle each succ once. 8105 if (!SuccsHandled.insert(SuccMBB).second) 8106 continue; 8107 8108 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 8109 8110 // At this point we know that there is a 1-1 correspondence between LLVM PHI 8111 // nodes and Machine PHI nodes, but the incoming operands have not been 8112 // emitted yet. 8113 for (BasicBlock::const_iterator I = SuccBB->begin(); 8114 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 8115 // Ignore dead phi's. 8116 if (PN->use_empty()) continue; 8117 8118 // Skip empty types 8119 if (PN->getType()->isEmptyTy()) 8120 continue; 8121 8122 unsigned Reg; 8123 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 8124 8125 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 8126 unsigned &RegOut = ConstantsOut[C]; 8127 if (RegOut == 0) { 8128 RegOut = FuncInfo.CreateRegs(C->getType()); 8129 CopyValueToVirtualRegister(C, RegOut); 8130 } 8131 Reg = RegOut; 8132 } else { 8133 DenseMap<const Value *, unsigned>::iterator I = 8134 FuncInfo.ValueMap.find(PHIOp); 8135 if (I != FuncInfo.ValueMap.end()) 8136 Reg = I->second; 8137 else { 8138 assert(isa<AllocaInst>(PHIOp) && 8139 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 8140 "Didn't codegen value into a register!??"); 8141 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 8142 CopyValueToVirtualRegister(PHIOp, Reg); 8143 } 8144 } 8145 8146 // Remember that this register needs to added to the machine PHI node as 8147 // the input for this MBB. 8148 SmallVector<EVT, 4> ValueVTs; 8149 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8150 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs); 8151 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 8152 EVT VT = ValueVTs[vti]; 8153 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 8154 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 8155 FuncInfo.PHINodesToUpdate.push_back( 8156 std::make_pair(&*MBBI++, Reg + i)); 8157 Reg += NumRegisters; 8158 } 8159 } 8160 } 8161 8162 ConstantsOut.clear(); 8163 } 8164 8165 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 8166 /// is 0. 8167 MachineBasicBlock * 8168 SelectionDAGBuilder::StackProtectorDescriptor:: 8169 AddSuccessorMBB(const BasicBlock *BB, 8170 MachineBasicBlock *ParentMBB, 8171 bool IsLikely, 8172 MachineBasicBlock *SuccMBB) { 8173 // If SuccBB has not been created yet, create it. 8174 if (!SuccMBB) { 8175 MachineFunction *MF = ParentMBB->getParent(); 8176 MachineFunction::iterator BBI(ParentMBB); 8177 SuccMBB = MF->CreateMachineBasicBlock(BB); 8178 MF->insert(++BBI, SuccMBB); 8179 } 8180 // Add it as a successor of ParentMBB. 8181 ParentMBB->addSuccessor( 8182 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 8183 return SuccMBB; 8184 } 8185 8186 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 8187 MachineFunction::iterator I(MBB); 8188 if (++I == FuncInfo.MF->end()) 8189 return nullptr; 8190 return &*I; 8191 } 8192 8193 /// During lowering new call nodes can be created (such as memset, etc.). 8194 /// Those will become new roots of the current DAG, but complications arise 8195 /// when they are tail calls. In such cases, the call lowering will update 8196 /// the root, but the builder still needs to know that a tail call has been 8197 /// lowered in order to avoid generating an additional return. 8198 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 8199 // If the node is null, we do have a tail call. 8200 if (MaybeTC.getNode() != nullptr) 8201 DAG.setRoot(MaybeTC); 8202 else 8203 HasTailCall = true; 8204 } 8205 8206 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters, 8207 unsigned *TotalCases, unsigned First, 8208 unsigned Last, 8209 unsigned Density) { 8210 assert(Last >= First); 8211 assert(TotalCases[Last] >= TotalCases[First]); 8212 8213 APInt LowCase = Clusters[First].Low->getValue(); 8214 APInt HighCase = Clusters[Last].High->getValue(); 8215 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 8216 8217 // FIXME: A range of consecutive cases has 100% density, but only requires one 8218 // comparison to lower. We should discriminate against such consecutive ranges 8219 // in jump tables. 8220 8221 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100); 8222 uint64_t Range = Diff + 1; 8223 8224 uint64_t NumCases = 8225 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 8226 8227 assert(NumCases < UINT64_MAX / 100); 8228 assert(Range >= NumCases); 8229 8230 return NumCases * 100 >= Range * Density; 8231 } 8232 8233 static inline bool areJTsAllowed(const TargetLowering &TLI, 8234 const SwitchInst *SI) { 8235 const Function *Fn = SI->getParent()->getParent(); 8236 if (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true") 8237 return false; 8238 8239 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 8240 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other); 8241 } 8242 8243 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters, 8244 unsigned First, unsigned Last, 8245 const SwitchInst *SI, 8246 MachineBasicBlock *DefaultMBB, 8247 CaseCluster &JTCluster) { 8248 assert(First <= Last); 8249 8250 auto Prob = BranchProbability::getZero(); 8251 unsigned NumCmps = 0; 8252 std::vector<MachineBasicBlock*> Table; 8253 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 8254 8255 // Initialize probabilities in JTProbs. 8256 for (unsigned I = First; I <= Last; ++I) 8257 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 8258 8259 for (unsigned I = First; I <= Last; ++I) { 8260 assert(Clusters[I].Kind == CC_Range); 8261 Prob += Clusters[I].Prob; 8262 APInt Low = Clusters[I].Low->getValue(); 8263 APInt High = Clusters[I].High->getValue(); 8264 NumCmps += (Low == High) ? 1 : 2; 8265 if (I != First) { 8266 // Fill the gap between this and the previous cluster. 8267 APInt PreviousHigh = Clusters[I - 1].High->getValue(); 8268 assert(PreviousHigh.slt(Low)); 8269 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 8270 for (uint64_t J = 0; J < Gap; J++) 8271 Table.push_back(DefaultMBB); 8272 } 8273 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 8274 for (uint64_t J = 0; J < ClusterSize; ++J) 8275 Table.push_back(Clusters[I].MBB); 8276 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 8277 } 8278 8279 unsigned NumDests = JTProbs.size(); 8280 if (isSuitableForBitTests(NumDests, NumCmps, 8281 Clusters[First].Low->getValue(), 8282 Clusters[Last].High->getValue())) { 8283 // Clusters[First..Last] should be lowered as bit tests instead. 8284 return false; 8285 } 8286 8287 // Create the MBB that will load from and jump through the table. 8288 // Note: We create it here, but it's not inserted into the function yet. 8289 MachineFunction *CurMF = FuncInfo.MF; 8290 MachineBasicBlock *JumpTableMBB = 8291 CurMF->CreateMachineBasicBlock(SI->getParent()); 8292 8293 // Add successors. Note: use table order for determinism. 8294 SmallPtrSet<MachineBasicBlock *, 8> Done; 8295 for (MachineBasicBlock *Succ : Table) { 8296 if (Done.count(Succ)) 8297 continue; 8298 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 8299 Done.insert(Succ); 8300 } 8301 JumpTableMBB->normalizeSuccProbs(); 8302 8303 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8304 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 8305 ->createJumpTableIndex(Table); 8306 8307 // Set up the jump table info. 8308 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 8309 JumpTableHeader JTH(Clusters[First].Low->getValue(), 8310 Clusters[Last].High->getValue(), SI->getCondition(), 8311 nullptr, false); 8312 JTCases.emplace_back(std::move(JTH), std::move(JT)); 8313 8314 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 8315 JTCases.size() - 1, Prob); 8316 return true; 8317 } 8318 8319 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 8320 const SwitchInst *SI, 8321 MachineBasicBlock *DefaultMBB) { 8322 #ifndef NDEBUG 8323 // Clusters must be non-empty, sorted, and only contain Range clusters. 8324 assert(!Clusters.empty()); 8325 for (CaseCluster &C : Clusters) 8326 assert(C.Kind == CC_Range); 8327 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 8328 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 8329 #endif 8330 8331 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8332 if (!areJTsAllowed(TLI, SI)) 8333 return; 8334 8335 const int64_t N = Clusters.size(); 8336 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries(); 8337 8338 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 8339 SmallVector<unsigned, 8> TotalCases(N); 8340 8341 for (unsigned i = 0; i < N; ++i) { 8342 APInt Hi = Clusters[i].High->getValue(); 8343 APInt Lo = Clusters[i].Low->getValue(); 8344 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 8345 if (i != 0) 8346 TotalCases[i] += TotalCases[i - 1]; 8347 } 8348 8349 unsigned MinDensity = JumpTableDensity; 8350 if (DefaultMBB->getParent()->getFunction()->optForSize()) 8351 MinDensity = OptsizeJumpTableDensity; 8352 if (N >= MinJumpTableSize 8353 && isDense(Clusters, &TotalCases[0], 0, N - 1, MinDensity)) { 8354 // Cheap case: the whole range might be suitable for jump table. 8355 CaseCluster JTCluster; 8356 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 8357 Clusters[0] = JTCluster; 8358 Clusters.resize(1); 8359 return; 8360 } 8361 } 8362 8363 // The algorithm below is not suitable for -O0. 8364 if (TM.getOptLevel() == CodeGenOpt::None) 8365 return; 8366 8367 // Split Clusters into minimum number of dense partitions. The algorithm uses 8368 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 8369 // for the Case Statement'" (1994), but builds the MinPartitions array in 8370 // reverse order to make it easier to reconstruct the partitions in ascending 8371 // order. In the choice between two optimal partitionings, it picks the one 8372 // which yields more jump tables. 8373 8374 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 8375 SmallVector<unsigned, 8> MinPartitions(N); 8376 // LastElement[i] is the last element of the partition starting at i. 8377 SmallVector<unsigned, 8> LastElement(N); 8378 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1]. 8379 SmallVector<unsigned, 8> NumTables(N); 8380 8381 // Base case: There is only one way to partition Clusters[N-1]. 8382 MinPartitions[N - 1] = 1; 8383 LastElement[N - 1] = N - 1; 8384 assert(MinJumpTableSize > 1); 8385 NumTables[N - 1] = 0; 8386 8387 // Note: loop indexes are signed to avoid underflow. 8388 for (int64_t i = N - 2; i >= 0; i--) { 8389 // Find optimal partitioning of Clusters[i..N-1]. 8390 // Baseline: Put Clusters[i] into a partition on its own. 8391 MinPartitions[i] = MinPartitions[i + 1] + 1; 8392 LastElement[i] = i; 8393 NumTables[i] = NumTables[i + 1]; 8394 8395 // Search for a solution that results in fewer partitions. 8396 for (int64_t j = N - 1; j > i; j--) { 8397 // Try building a partition from Clusters[i..j]. 8398 if (isDense(Clusters, &TotalCases[0], i, j, MinDensity)) { 8399 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 8400 bool IsTable = j - i + 1 >= MinJumpTableSize; 8401 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]); 8402 8403 // If this j leads to fewer partitions, or same number of partitions 8404 // with more lookup tables, it is a better partitioning. 8405 if (NumPartitions < MinPartitions[i] || 8406 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) { 8407 MinPartitions[i] = NumPartitions; 8408 LastElement[i] = j; 8409 NumTables[i] = Tables; 8410 } 8411 } 8412 } 8413 } 8414 8415 // Iterate over the partitions, replacing some with jump tables in-place. 8416 unsigned DstIndex = 0; 8417 for (unsigned First = 0, Last; First < N; First = Last + 1) { 8418 Last = LastElement[First]; 8419 assert(Last >= First); 8420 assert(DstIndex <= First); 8421 unsigned NumClusters = Last - First + 1; 8422 8423 CaseCluster JTCluster; 8424 if (NumClusters >= MinJumpTableSize && 8425 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 8426 Clusters[DstIndex++] = JTCluster; 8427 } else { 8428 for (unsigned I = First; I <= Last; ++I) 8429 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 8430 } 8431 } 8432 Clusters.resize(DstIndex); 8433 } 8434 8435 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) { 8436 // FIXME: Using the pointer type doesn't seem ideal. 8437 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits(); 8438 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1; 8439 return Range <= BW; 8440 } 8441 8442 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests, 8443 unsigned NumCmps, 8444 const APInt &Low, 8445 const APInt &High) { 8446 // FIXME: I don't think NumCmps is the correct metric: a single case and a 8447 // range of cases both require only one branch to lower. Just looking at the 8448 // number of clusters and destinations should be enough to decide whether to 8449 // build bit tests. 8450 8451 // To lower a range with bit tests, the range must fit the bitwidth of a 8452 // machine word. 8453 if (!rangeFitsInWord(Low, High)) 8454 return false; 8455 8456 // Decide whether it's profitable to lower this range with bit tests. Each 8457 // destination requires a bit test and branch, and there is an overall range 8458 // check branch. For a small number of clusters, separate comparisons might be 8459 // cheaper, and for many destinations, splitting the range might be better. 8460 return (NumDests == 1 && NumCmps >= 3) || 8461 (NumDests == 2 && NumCmps >= 5) || 8462 (NumDests == 3 && NumCmps >= 6); 8463 } 8464 8465 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 8466 unsigned First, unsigned Last, 8467 const SwitchInst *SI, 8468 CaseCluster &BTCluster) { 8469 assert(First <= Last); 8470 if (First == Last) 8471 return false; 8472 8473 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 8474 unsigned NumCmps = 0; 8475 for (int64_t I = First; I <= Last; ++I) { 8476 assert(Clusters[I].Kind == CC_Range); 8477 Dests.set(Clusters[I].MBB->getNumber()); 8478 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 8479 } 8480 unsigned NumDests = Dests.count(); 8481 8482 APInt Low = Clusters[First].Low->getValue(); 8483 APInt High = Clusters[Last].High->getValue(); 8484 assert(Low.slt(High)); 8485 8486 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High)) 8487 return false; 8488 8489 APInt LowBound; 8490 APInt CmpRange; 8491 8492 const int BitWidth = DAG.getTargetLoweringInfo() 8493 .getPointerTy(DAG.getDataLayout()) 8494 .getSizeInBits(); 8495 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!"); 8496 8497 // Check if the clusters cover a contiguous range such that no value in the 8498 // range will jump to the default statement. 8499 bool ContiguousRange = true; 8500 for (int64_t I = First + 1; I <= Last; ++I) { 8501 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 8502 ContiguousRange = false; 8503 break; 8504 } 8505 } 8506 8507 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 8508 // Optimize the case where all the case values fit in a word without having 8509 // to subtract minValue. In this case, we can optimize away the subtraction. 8510 LowBound = APInt::getNullValue(Low.getBitWidth()); 8511 CmpRange = High; 8512 ContiguousRange = false; 8513 } else { 8514 LowBound = Low; 8515 CmpRange = High - Low; 8516 } 8517 8518 CaseBitsVector CBV; 8519 auto TotalProb = BranchProbability::getZero(); 8520 for (unsigned i = First; i <= Last; ++i) { 8521 // Find the CaseBits for this destination. 8522 unsigned j; 8523 for (j = 0; j < CBV.size(); ++j) 8524 if (CBV[j].BB == Clusters[i].MBB) 8525 break; 8526 if (j == CBV.size()) 8527 CBV.push_back( 8528 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 8529 CaseBits *CB = &CBV[j]; 8530 8531 // Update Mask, Bits and ExtraProb. 8532 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 8533 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 8534 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 8535 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 8536 CB->Bits += Hi - Lo + 1; 8537 CB->ExtraProb += Clusters[i].Prob; 8538 TotalProb += Clusters[i].Prob; 8539 } 8540 8541 BitTestInfo BTI; 8542 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 8543 // Sort by probability first, number of bits second. 8544 if (a.ExtraProb != b.ExtraProb) 8545 return a.ExtraProb > b.ExtraProb; 8546 return a.Bits > b.Bits; 8547 }); 8548 8549 for (auto &CB : CBV) { 8550 MachineBasicBlock *BitTestBB = 8551 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 8552 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 8553 } 8554 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 8555 SI->getCondition(), -1U, MVT::Other, false, 8556 ContiguousRange, nullptr, nullptr, std::move(BTI), 8557 TotalProb); 8558 8559 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 8560 BitTestCases.size() - 1, TotalProb); 8561 return true; 8562 } 8563 8564 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 8565 const SwitchInst *SI) { 8566 // Partition Clusters into as few subsets as possible, where each subset has a 8567 // range that fits in a machine word and has <= 3 unique destinations. 8568 8569 #ifndef NDEBUG 8570 // Clusters must be sorted and contain Range or JumpTable clusters. 8571 assert(!Clusters.empty()); 8572 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 8573 for (const CaseCluster &C : Clusters) 8574 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 8575 for (unsigned i = 1; i < Clusters.size(); ++i) 8576 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 8577 #endif 8578 8579 // The algorithm below is not suitable for -O0. 8580 if (TM.getOptLevel() == CodeGenOpt::None) 8581 return; 8582 8583 // If target does not have legal shift left, do not emit bit tests at all. 8584 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8585 EVT PTy = TLI.getPointerTy(DAG.getDataLayout()); 8586 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 8587 return; 8588 8589 int BitWidth = PTy.getSizeInBits(); 8590 const int64_t N = Clusters.size(); 8591 8592 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 8593 SmallVector<unsigned, 8> MinPartitions(N); 8594 // LastElement[i] is the last element of the partition starting at i. 8595 SmallVector<unsigned, 8> LastElement(N); 8596 8597 // FIXME: This might not be the best algorithm for finding bit test clusters. 8598 8599 // Base case: There is only one way to partition Clusters[N-1]. 8600 MinPartitions[N - 1] = 1; 8601 LastElement[N - 1] = N - 1; 8602 8603 // Note: loop indexes are signed to avoid underflow. 8604 for (int64_t i = N - 2; i >= 0; --i) { 8605 // Find optimal partitioning of Clusters[i..N-1]. 8606 // Baseline: Put Clusters[i] into a partition on its own. 8607 MinPartitions[i] = MinPartitions[i + 1] + 1; 8608 LastElement[i] = i; 8609 8610 // Search for a solution that results in fewer partitions. 8611 // Note: the search is limited by BitWidth, reducing time complexity. 8612 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 8613 // Try building a partition from Clusters[i..j]. 8614 8615 // Check the range. 8616 if (!rangeFitsInWord(Clusters[i].Low->getValue(), 8617 Clusters[j].High->getValue())) 8618 continue; 8619 8620 // Check nbr of destinations and cluster types. 8621 // FIXME: This works, but doesn't seem very efficient. 8622 bool RangesOnly = true; 8623 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 8624 for (int64_t k = i; k <= j; k++) { 8625 if (Clusters[k].Kind != CC_Range) { 8626 RangesOnly = false; 8627 break; 8628 } 8629 Dests.set(Clusters[k].MBB->getNumber()); 8630 } 8631 if (!RangesOnly || Dests.count() > 3) 8632 break; 8633 8634 // Check if it's a better partition. 8635 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 8636 if (NumPartitions < MinPartitions[i]) { 8637 // Found a better partition. 8638 MinPartitions[i] = NumPartitions; 8639 LastElement[i] = j; 8640 } 8641 } 8642 } 8643 8644 // Iterate over the partitions, replacing with bit-test clusters in-place. 8645 unsigned DstIndex = 0; 8646 for (unsigned First = 0, Last; First < N; First = Last + 1) { 8647 Last = LastElement[First]; 8648 assert(First <= Last); 8649 assert(DstIndex <= First); 8650 8651 CaseCluster BitTestCluster; 8652 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 8653 Clusters[DstIndex++] = BitTestCluster; 8654 } else { 8655 size_t NumClusters = Last - First + 1; 8656 std::memmove(&Clusters[DstIndex], &Clusters[First], 8657 sizeof(Clusters[0]) * NumClusters); 8658 DstIndex += NumClusters; 8659 } 8660 } 8661 Clusters.resize(DstIndex); 8662 } 8663 8664 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 8665 MachineBasicBlock *SwitchMBB, 8666 MachineBasicBlock *DefaultMBB) { 8667 MachineFunction *CurMF = FuncInfo.MF; 8668 MachineBasicBlock *NextMBB = nullptr; 8669 MachineFunction::iterator BBI(W.MBB); 8670 if (++BBI != FuncInfo.MF->end()) 8671 NextMBB = &*BBI; 8672 8673 unsigned Size = W.LastCluster - W.FirstCluster + 1; 8674 8675 BranchProbabilityInfo *BPI = FuncInfo.BPI; 8676 8677 if (Size == 2 && W.MBB == SwitchMBB) { 8678 // If any two of the cases has the same destination, and if one value 8679 // is the same as the other, but has one bit unset that the other has set, 8680 // use bit manipulation to do two compares at once. For example: 8681 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 8682 // TODO: This could be extended to merge any 2 cases in switches with 3 8683 // cases. 8684 // TODO: Handle cases where W.CaseBB != SwitchBB. 8685 CaseCluster &Small = *W.FirstCluster; 8686 CaseCluster &Big = *W.LastCluster; 8687 8688 if (Small.Low == Small.High && Big.Low == Big.High && 8689 Small.MBB == Big.MBB) { 8690 const APInt &SmallValue = Small.Low->getValue(); 8691 const APInt &BigValue = Big.Low->getValue(); 8692 8693 // Check that there is only one bit different. 8694 APInt CommonBit = BigValue ^ SmallValue; 8695 if (CommonBit.isPowerOf2()) { 8696 SDValue CondLHS = getValue(Cond); 8697 EVT VT = CondLHS.getValueType(); 8698 SDLoc DL = getCurSDLoc(); 8699 8700 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 8701 DAG.getConstant(CommonBit, DL, VT)); 8702 SDValue Cond = DAG.getSetCC( 8703 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 8704 ISD::SETEQ); 8705 8706 // Update successor info. 8707 // Both Small and Big will jump to Small.BB, so we sum up the 8708 // probabilities. 8709 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 8710 if (BPI) 8711 addSuccessorWithProb( 8712 SwitchMBB, DefaultMBB, 8713 // The default destination is the first successor in IR. 8714 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 8715 else 8716 addSuccessorWithProb(SwitchMBB, DefaultMBB); 8717 8718 // Insert the true branch. 8719 SDValue BrCond = 8720 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 8721 DAG.getBasicBlock(Small.MBB)); 8722 // Insert the false branch. 8723 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 8724 DAG.getBasicBlock(DefaultMBB)); 8725 8726 DAG.setRoot(BrCond); 8727 return; 8728 } 8729 } 8730 } 8731 8732 if (TM.getOptLevel() != CodeGenOpt::None) { 8733 // Order cases by probability so the most likely case will be checked first. 8734 std::sort(W.FirstCluster, W.LastCluster + 1, 8735 [](const CaseCluster &a, const CaseCluster &b) { 8736 return a.Prob > b.Prob; 8737 }); 8738 8739 // Rearrange the case blocks so that the last one falls through if possible 8740 // without without changing the order of probabilities. 8741 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 8742 --I; 8743 if (I->Prob > W.LastCluster->Prob) 8744 break; 8745 if (I->Kind == CC_Range && I->MBB == NextMBB) { 8746 std::swap(*I, *W.LastCluster); 8747 break; 8748 } 8749 } 8750 } 8751 8752 // Compute total probability. 8753 BranchProbability DefaultProb = W.DefaultProb; 8754 BranchProbability UnhandledProbs = DefaultProb; 8755 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 8756 UnhandledProbs += I->Prob; 8757 8758 MachineBasicBlock *CurMBB = W.MBB; 8759 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 8760 MachineBasicBlock *Fallthrough; 8761 if (I == W.LastCluster) { 8762 // For the last cluster, fall through to the default destination. 8763 Fallthrough = DefaultMBB; 8764 } else { 8765 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 8766 CurMF->insert(BBI, Fallthrough); 8767 // Put Cond in a virtual register to make it available from the new blocks. 8768 ExportFromCurrentBlock(Cond); 8769 } 8770 UnhandledProbs -= I->Prob; 8771 8772 switch (I->Kind) { 8773 case CC_JumpTable: { 8774 // FIXME: Optimize away range check based on pivot comparisons. 8775 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 8776 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 8777 8778 // The jump block hasn't been inserted yet; insert it here. 8779 MachineBasicBlock *JumpMBB = JT->MBB; 8780 CurMF->insert(BBI, JumpMBB); 8781 8782 auto JumpProb = I->Prob; 8783 auto FallthroughProb = UnhandledProbs; 8784 8785 // If the default statement is a target of the jump table, we evenly 8786 // distribute the default probability to successors of CurMBB. Also 8787 // update the probability on the edge from JumpMBB to Fallthrough. 8788 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 8789 SE = JumpMBB->succ_end(); 8790 SI != SE; ++SI) { 8791 if (*SI == DefaultMBB) { 8792 JumpProb += DefaultProb / 2; 8793 FallthroughProb -= DefaultProb / 2; 8794 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 8795 JumpMBB->normalizeSuccProbs(); 8796 break; 8797 } 8798 } 8799 8800 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 8801 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 8802 CurMBB->normalizeSuccProbs(); 8803 8804 // The jump table header will be inserted in our current block, do the 8805 // range check, and fall through to our fallthrough block. 8806 JTH->HeaderBB = CurMBB; 8807 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 8808 8809 // If we're in the right place, emit the jump table header right now. 8810 if (CurMBB == SwitchMBB) { 8811 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 8812 JTH->Emitted = true; 8813 } 8814 break; 8815 } 8816 case CC_BitTests: { 8817 // FIXME: Optimize away range check based on pivot comparisons. 8818 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 8819 8820 // The bit test blocks haven't been inserted yet; insert them here. 8821 for (BitTestCase &BTC : BTB->Cases) 8822 CurMF->insert(BBI, BTC.ThisBB); 8823 8824 // Fill in fields of the BitTestBlock. 8825 BTB->Parent = CurMBB; 8826 BTB->Default = Fallthrough; 8827 8828 BTB->DefaultProb = UnhandledProbs; 8829 // If the cases in bit test don't form a contiguous range, we evenly 8830 // distribute the probability on the edge to Fallthrough to two 8831 // successors of CurMBB. 8832 if (!BTB->ContiguousRange) { 8833 BTB->Prob += DefaultProb / 2; 8834 BTB->DefaultProb -= DefaultProb / 2; 8835 } 8836 8837 // If we're in the right place, emit the bit test header right now. 8838 if (CurMBB == SwitchMBB) { 8839 visitBitTestHeader(*BTB, SwitchMBB); 8840 BTB->Emitted = true; 8841 } 8842 break; 8843 } 8844 case CC_Range: { 8845 const Value *RHS, *LHS, *MHS; 8846 ISD::CondCode CC; 8847 if (I->Low == I->High) { 8848 // Check Cond == I->Low. 8849 CC = ISD::SETEQ; 8850 LHS = Cond; 8851 RHS=I->Low; 8852 MHS = nullptr; 8853 } else { 8854 // Check I->Low <= Cond <= I->High. 8855 CC = ISD::SETLE; 8856 LHS = I->Low; 8857 MHS = Cond; 8858 RHS = I->High; 8859 } 8860 8861 // The false probability is the sum of all unhandled cases. 8862 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Prob, 8863 UnhandledProbs); 8864 8865 if (CurMBB == SwitchMBB) 8866 visitSwitchCase(CB, SwitchMBB); 8867 else 8868 SwitchCases.push_back(CB); 8869 8870 break; 8871 } 8872 } 8873 CurMBB = Fallthrough; 8874 } 8875 } 8876 8877 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 8878 CaseClusterIt First, 8879 CaseClusterIt Last) { 8880 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 8881 if (X.Prob != CC.Prob) 8882 return X.Prob > CC.Prob; 8883 8884 // Ties are broken by comparing the case value. 8885 return X.Low->getValue().slt(CC.Low->getValue()); 8886 }); 8887 } 8888 8889 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 8890 const SwitchWorkListItem &W, 8891 Value *Cond, 8892 MachineBasicBlock *SwitchMBB) { 8893 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 8894 "Clusters not sorted?"); 8895 8896 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 8897 8898 // Balance the tree based on branch probabilities to create a near-optimal (in 8899 // terms of search time given key frequency) binary search tree. See e.g. Kurt 8900 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 8901 CaseClusterIt LastLeft = W.FirstCluster; 8902 CaseClusterIt FirstRight = W.LastCluster; 8903 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 8904 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 8905 8906 // Move LastLeft and FirstRight towards each other from opposite directions to 8907 // find a partitioning of the clusters which balances the probability on both 8908 // sides. If LeftProb and RightProb are equal, alternate which side is 8909 // taken to ensure 0-probability nodes are distributed evenly. 8910 unsigned I = 0; 8911 while (LastLeft + 1 < FirstRight) { 8912 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 8913 LeftProb += (++LastLeft)->Prob; 8914 else 8915 RightProb += (--FirstRight)->Prob; 8916 I++; 8917 } 8918 8919 for (;;) { 8920 // Our binary search tree differs from a typical BST in that ours can have up 8921 // to three values in each leaf. The pivot selection above doesn't take that 8922 // into account, which means the tree might require more nodes and be less 8923 // efficient. We compensate for this here. 8924 8925 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 8926 unsigned NumRight = W.LastCluster - FirstRight + 1; 8927 8928 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 8929 // If one side has less than 3 clusters, and the other has more than 3, 8930 // consider taking a cluster from the other side. 8931 8932 if (NumLeft < NumRight) { 8933 // Consider moving the first cluster on the right to the left side. 8934 CaseCluster &CC = *FirstRight; 8935 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8936 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8937 if (LeftSideRank <= RightSideRank) { 8938 // Moving the cluster to the left does not demote it. 8939 ++LastLeft; 8940 ++FirstRight; 8941 continue; 8942 } 8943 } else { 8944 assert(NumRight < NumLeft); 8945 // Consider moving the last element on the left to the right side. 8946 CaseCluster &CC = *LastLeft; 8947 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 8948 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 8949 if (RightSideRank <= LeftSideRank) { 8950 // Moving the cluster to the right does not demot it. 8951 --LastLeft; 8952 --FirstRight; 8953 continue; 8954 } 8955 } 8956 } 8957 break; 8958 } 8959 8960 assert(LastLeft + 1 == FirstRight); 8961 assert(LastLeft >= W.FirstCluster); 8962 assert(FirstRight <= W.LastCluster); 8963 8964 // Use the first element on the right as pivot since we will make less-than 8965 // comparisons against it. 8966 CaseClusterIt PivotCluster = FirstRight; 8967 assert(PivotCluster > W.FirstCluster); 8968 assert(PivotCluster <= W.LastCluster); 8969 8970 CaseClusterIt FirstLeft = W.FirstCluster; 8971 CaseClusterIt LastRight = W.LastCluster; 8972 8973 const ConstantInt *Pivot = PivotCluster->Low; 8974 8975 // New blocks will be inserted immediately after the current one. 8976 MachineFunction::iterator BBI(W.MBB); 8977 ++BBI; 8978 8979 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 8980 // we can branch to its destination directly if it's squeezed exactly in 8981 // between the known lower bound and Pivot - 1. 8982 MachineBasicBlock *LeftMBB; 8983 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 8984 FirstLeft->Low == W.GE && 8985 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 8986 LeftMBB = FirstLeft->MBB; 8987 } else { 8988 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 8989 FuncInfo.MF->insert(BBI, LeftMBB); 8990 WorkList.push_back( 8991 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 8992 // Put Cond in a virtual register to make it available from the new blocks. 8993 ExportFromCurrentBlock(Cond); 8994 } 8995 8996 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 8997 // single cluster, RHS.Low == Pivot, and we can branch to its destination 8998 // directly if RHS.High equals the current upper bound. 8999 MachineBasicBlock *RightMBB; 9000 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 9001 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 9002 RightMBB = FirstRight->MBB; 9003 } else { 9004 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9005 FuncInfo.MF->insert(BBI, RightMBB); 9006 WorkList.push_back( 9007 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 9008 // Put Cond in a virtual register to make it available from the new blocks. 9009 ExportFromCurrentBlock(Cond); 9010 } 9011 9012 // Create the CaseBlock record that will be used to lower the branch. 9013 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 9014 LeftProb, RightProb); 9015 9016 if (W.MBB == SwitchMBB) 9017 visitSwitchCase(CB, SwitchMBB); 9018 else 9019 SwitchCases.push_back(CB); 9020 } 9021 9022 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 9023 // Extract cases from the switch. 9024 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9025 CaseClusterVector Clusters; 9026 Clusters.reserve(SI.getNumCases()); 9027 for (auto I : SI.cases()) { 9028 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 9029 const ConstantInt *CaseVal = I.getCaseValue(); 9030 BranchProbability Prob = 9031 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 9032 : BranchProbability(1, SI.getNumCases() + 1); 9033 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 9034 } 9035 9036 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 9037 9038 // Cluster adjacent cases with the same destination. We do this at all 9039 // optimization levels because it's cheap to do and will make codegen faster 9040 // if there are many clusters. 9041 sortAndRangeify(Clusters); 9042 9043 if (TM.getOptLevel() != CodeGenOpt::None) { 9044 // Replace an unreachable default with the most popular destination. 9045 // FIXME: Exploit unreachable default more aggressively. 9046 bool UnreachableDefault = 9047 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 9048 if (UnreachableDefault && !Clusters.empty()) { 9049 DenseMap<const BasicBlock *, unsigned> Popularity; 9050 unsigned MaxPop = 0; 9051 const BasicBlock *MaxBB = nullptr; 9052 for (auto I : SI.cases()) { 9053 const BasicBlock *BB = I.getCaseSuccessor(); 9054 if (++Popularity[BB] > MaxPop) { 9055 MaxPop = Popularity[BB]; 9056 MaxBB = BB; 9057 } 9058 } 9059 // Set new default. 9060 assert(MaxPop > 0 && MaxBB); 9061 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 9062 9063 // Remove cases that were pointing to the destination that is now the 9064 // default. 9065 CaseClusterVector New; 9066 New.reserve(Clusters.size()); 9067 for (CaseCluster &CC : Clusters) { 9068 if (CC.MBB != DefaultMBB) 9069 New.push_back(CC); 9070 } 9071 Clusters = std::move(New); 9072 } 9073 } 9074 9075 // If there is only the default destination, jump there directly. 9076 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 9077 if (Clusters.empty()) { 9078 SwitchMBB->addSuccessor(DefaultMBB); 9079 if (DefaultMBB != NextBlock(SwitchMBB)) { 9080 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 9081 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 9082 } 9083 return; 9084 } 9085 9086 findJumpTables(Clusters, &SI, DefaultMBB); 9087 findBitTestClusters(Clusters, &SI); 9088 9089 DEBUG({ 9090 dbgs() << "Case clusters: "; 9091 for (const CaseCluster &C : Clusters) { 9092 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 9093 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 9094 9095 C.Low->getValue().print(dbgs(), true); 9096 if (C.Low != C.High) { 9097 dbgs() << '-'; 9098 C.High->getValue().print(dbgs(), true); 9099 } 9100 dbgs() << ' '; 9101 } 9102 dbgs() << '\n'; 9103 }); 9104 9105 assert(!Clusters.empty()); 9106 SwitchWorkList WorkList; 9107 CaseClusterIt First = Clusters.begin(); 9108 CaseClusterIt Last = Clusters.end() - 1; 9109 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB); 9110 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 9111 9112 while (!WorkList.empty()) { 9113 SwitchWorkListItem W = WorkList.back(); 9114 WorkList.pop_back(); 9115 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 9116 9117 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) { 9118 // For optimized builds, lower large range as a balanced binary tree. 9119 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 9120 continue; 9121 } 9122 9123 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 9124 } 9125 } 9126