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