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