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