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