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/APFloat.h" 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Analysis/AliasAnalysis.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/TargetLibraryInfo.h" 37 #include "llvm/Analysis/ValueTracking.h" 38 #include "llvm/Analysis/VectorUtils.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/FunctionLoweringInfo.h" 41 #include "llvm/CodeGen/GCMetadata.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineJumpTableInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/RuntimeLibcalls.h" 54 #include "llvm/CodeGen/SelectionDAG.h" 55 #include "llvm/CodeGen/SelectionDAGNodes.h" 56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 57 #include "llvm/CodeGen/StackMaps.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/PatternMatch.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MachineValueType.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Target/TargetIntrinsicInfo.h" 110 #include "llvm/Target/TargetMachine.h" 111 #include "llvm/Target/TargetOptions.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstring> 117 #include <iterator> 118 #include <limits> 119 #include <numeric> 120 #include <tuple> 121 #include <utility> 122 #include <vector> 123 124 using namespace llvm; 125 using namespace PatternMatch; 126 127 #define DEBUG_TYPE "isel" 128 129 /// LimitFloatPrecision - Generate low-precision inline sequences for 130 /// some float libcalls (6, 8 or 12 bits). 131 static unsigned LimitFloatPrecision; 132 133 static cl::opt<unsigned, true> 134 LimitFPPrecision("limit-float-precision", 135 cl::desc("Generate low-precision inline sequences " 136 "for some float libcalls"), 137 cl::location(LimitFloatPrecision), cl::Hidden, 138 cl::init(0)); 139 140 static cl::opt<unsigned> SwitchPeelThreshold( 141 "switch-peel-threshold", cl::Hidden, cl::init(66), 142 cl::desc("Set the case probability threshold for peeling the case from a " 143 "switch statement. A value greater than 100 will void this " 144 "optimization")); 145 146 // Limit the width of DAG chains. This is important in general to prevent 147 // DAG-based analysis from blowing up. For example, alias analysis and 148 // load clustering may not complete in reasonable time. It is difficult to 149 // recognize and avoid this situation within each individual analysis, and 150 // future analyses are likely to have the same behavior. Limiting DAG width is 151 // the safe approach and will be especially important with global DAGs. 152 // 153 // MaxParallelChains default is arbitrarily high to avoid affecting 154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 155 // sequence over this should have been converted to llvm.memcpy by the 156 // frontend. It is easy to induce this behavior with .ll code such as: 157 // %buffer = alloca [4096 x i8] 158 // %data = load [4096 x i8]* %argPtr 159 // store [4096 x i8] %data, [4096 x i8]* %buffer 160 static const unsigned MaxParallelChains = 64; 161 162 // Return the calling convention if the Value passed requires ABI mangling as it 163 // is a parameter to a function or a return value from a function which is not 164 // an intrinsic. 165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 166 if (auto *R = dyn_cast<ReturnInst>(V)) 167 return R->getParent()->getParent()->getCallingConv(); 168 169 if (auto *CI = dyn_cast<CallInst>(V)) { 170 const bool IsInlineAsm = CI->isInlineAsm(); 171 const bool IsIndirectFunctionCall = 172 !IsInlineAsm && !CI->getCalledFunction(); 173 174 // It is possible that the call instruction is an inline asm statement or an 175 // indirect function call in which case the return value of 176 // getCalledFunction() would be nullptr. 177 const bool IsInstrinsicCall = 178 !IsInlineAsm && !IsIndirectFunctionCall && 179 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 180 181 if (!IsInlineAsm && !IsInstrinsicCall) 182 return CI->getCallingConv(); 183 } 184 185 return None; 186 } 187 188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC); 192 193 /// getCopyFromParts - Create a value that contains the specified legal parts 194 /// combined into the value they represent. If the parts combine to a type 195 /// larger than ValueVT then AssertOp can be used to specify whether the extra 196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 197 /// (ISD::AssertSext). 198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC = None, 202 Optional<ISD::NodeType> AssertOp = None) { 203 if (ValueVT.isVector()) 204 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 205 CC); 206 207 assert(NumParts > 0 && "No parts to assemble!"); 208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 209 SDValue Val = Parts[0]; 210 211 if (NumParts > 1) { 212 // Assemble the value from multiple parts. 213 if (ValueVT.isInteger()) { 214 unsigned PartBits = PartVT.getSizeInBits(); 215 unsigned ValueBits = ValueVT.getSizeInBits(); 216 217 // Assemble the power of 2 part. 218 unsigned RoundParts = NumParts & (NumParts - 1) ? 219 1 << Log2_32(NumParts) : NumParts; 220 unsigned RoundBits = PartBits * RoundParts; 221 EVT RoundVT = RoundBits == ValueBits ? 222 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 223 SDValue Lo, Hi; 224 225 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 226 227 if (RoundParts > 2) { 228 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 229 PartVT, HalfVT, V); 230 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 231 RoundParts / 2, PartVT, HalfVT, V); 232 } else { 233 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 235 } 236 237 if (DAG.getDataLayout().isBigEndian()) 238 std::swap(Lo, Hi); 239 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 241 242 if (RoundParts < NumParts) { 243 // Assemble the trailing non-power-of-2 part. 244 unsigned OddParts = NumParts - RoundParts; 245 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 246 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 247 OddVT, V, CC); 248 249 // Combine the round and odd parts. 250 Lo = Val; 251 if (DAG.getDataLayout().isBigEndian()) 252 std::swap(Lo, Hi); 253 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 254 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 255 Hi = 256 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 257 DAG.getConstant(Lo.getValueSizeInBits(), DL, 258 TLI.getPointerTy(DAG.getDataLayout()))); 259 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 260 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 261 } 262 } else if (PartVT.isFloatingPoint()) { 263 // FP split into multiple FP parts (for ppcf128) 264 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 265 "Unexpected split"); 266 SDValue Lo, Hi; 267 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 268 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 269 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 270 std::swap(Lo, Hi); 271 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 272 } else { 273 // FP split into integer parts (soft fp) 274 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 275 !PartVT.isVector() && "Unexpected split"); 276 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 277 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 278 } 279 } 280 281 // There is now one part, held in Val. Correct it to match ValueVT. 282 // PartEVT is the type of the register class that holds the value. 283 // ValueVT is the type of the inline asm operation. 284 EVT PartEVT = Val.getValueType(); 285 286 if (PartEVT == ValueVT) 287 return Val; 288 289 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 290 ValueVT.bitsLT(PartEVT)) { 291 // For an FP value in an integer part, we need to truncate to the right 292 // width first. 293 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 294 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 295 } 296 297 // Handle types that have the same size. 298 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle types with different sizes. 302 if (PartEVT.isInteger() && ValueVT.isInteger()) { 303 if (ValueVT.bitsLT(PartEVT)) { 304 // For a truncate, see if we have any information to 305 // indicate whether the truncated bits will always be 306 // zero or sign-extension. 307 if (AssertOp.hasValue()) 308 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 309 DAG.getValueType(ValueVT)); 310 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 311 } 312 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 313 } 314 315 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 // FP_ROUND's are always exact here. 317 if (ValueVT.bitsLT(Val.getValueType())) 318 return DAG.getNode( 319 ISD::FP_ROUND, DL, ValueVT, Val, 320 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 321 322 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 323 } 324 325 llvm_unreachable("Unknown mismatch!"); 326 } 327 328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 329 const Twine &ErrMsg) { 330 const Instruction *I = dyn_cast_or_null<Instruction>(V); 331 if (!V) 332 return Ctx.emitError(ErrMsg); 333 334 const char *AsmError = ", possible invalid constraint for vector type"; 335 if (const CallInst *CI = dyn_cast<CallInst>(I)) 336 if (isa<InlineAsm>(CI->getCalledValue())) 337 return Ctx.emitError(I, ErrMsg + AsmError); 338 339 return Ctx.emitError(I, ErrMsg); 340 } 341 342 /// getCopyFromPartsVector - Create a value that contains the specified legal 343 /// parts combined into the value they represent. If the parts combine to a 344 /// type larger than ValueVT then AssertOp can be used to specify whether the 345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 346 /// ValueVT (ISD::AssertSext). 347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 348 const SDValue *Parts, unsigned NumParts, 349 MVT PartVT, EVT ValueVT, const Value *V, 350 Optional<CallingConv::ID> CallConv) { 351 assert(ValueVT.isVector() && "Not a vector value"); 352 assert(NumParts > 0 && "No parts to assemble!"); 353 const bool IsABIRegCopy = CallConv.hasValue(); 354 355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 356 SDValue Val = Parts[0]; 357 358 // Handle a multi-element vector. 359 if (NumParts > 1) { 360 EVT IntermediateVT; 361 MVT RegisterVT; 362 unsigned NumIntermediates; 363 unsigned NumRegs; 364 365 if (IsABIRegCopy) { 366 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 367 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 368 NumIntermediates, RegisterVT); 369 } else { 370 NumRegs = 371 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 372 NumIntermediates, RegisterVT); 373 } 374 375 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 376 NumParts = NumRegs; // Silence a compiler warning. 377 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 378 assert(RegisterVT.getSizeInBits() == 379 Parts[0].getSimpleValueType().getSizeInBits() && 380 "Part type sizes don't match!"); 381 382 // Assemble the parts into intermediate operands. 383 SmallVector<SDValue, 8> Ops(NumIntermediates); 384 if (NumIntermediates == NumParts) { 385 // If the register was not expanded, truncate or copy the value, 386 // as appropriate. 387 for (unsigned i = 0; i != NumParts; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 389 PartVT, IntermediateVT, V); 390 } else if (NumParts > 0) { 391 // If the intermediate type was expanded, build the intermediate 392 // operands from the parts. 393 assert(NumParts % NumIntermediates == 0 && 394 "Must expand into a divisible number of parts!"); 395 unsigned Factor = NumParts / NumIntermediates; 396 for (unsigned i = 0; i != NumIntermediates; ++i) 397 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 398 PartVT, IntermediateVT, V); 399 } 400 401 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 402 // intermediate operands. 403 EVT BuiltVectorTy = 404 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 405 (IntermediateVT.isVector() 406 ? IntermediateVT.getVectorNumElements() * NumParts 407 : NumIntermediates)); 408 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 409 : ISD::BUILD_VECTOR, 410 DL, BuiltVectorTy, Ops); 411 } 412 413 // There is now one part, held in Val. Correct it to match ValueVT. 414 EVT PartEVT = Val.getValueType(); 415 416 if (PartEVT == ValueVT) 417 return Val; 418 419 if (PartEVT.isVector()) { 420 // If the element type of the source/dest vectors are the same, but the 421 // parts vector has more elements than the value vector, then we have a 422 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 423 // elements we want. 424 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 425 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 426 "Cannot narrow, it would be a lossy transformation"); 427 return DAG.getNode( 428 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 429 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 430 } 431 432 // Vector/Vector bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 437 "Cannot handle this kind of promotion"); 438 // Promoted vector extract 439 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 440 441 } 442 443 // Trivial bitcast if the types are the same size and the destination 444 // vector type is legal. 445 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 446 TLI.isTypeLegal(ValueVT)) 447 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 448 449 if (ValueVT.getVectorNumElements() != 1) { 450 // Certain ABIs require that vectors are passed as integers. For vectors 451 // are the same size, this is an obvious bitcast. 452 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 455 // Bitcast Val back the original type and extract the corresponding 456 // vector we want. 457 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 458 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 459 ValueVT.getVectorElementType(), Elts); 460 Val = DAG.getBitcast(WiderVecType, Val); 461 return DAG.getNode( 462 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 463 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 474 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 475 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 476 477 return DAG.getBuildVector(ValueVT, DL, Val); 478 } 479 480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 481 SDValue Val, SDValue *Parts, unsigned NumParts, 482 MVT PartVT, const Value *V, 483 Optional<CallingConv::ID> CallConv); 484 485 /// getCopyToParts - Create a series of nodes that contain the specified value 486 /// split into legal parts. If the parts contain more bits than Val, then, for 487 /// integers, ExtendKind can be used to specify how to generate the extra bits. 488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 489 SDValue *Parts, unsigned NumParts, MVT PartVT, 490 const Value *V, 491 Optional<CallingConv::ID> CallConv = None, 492 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 493 EVT ValueVT = Val.getValueType(); 494 495 // Handle the vector case separately. 496 if (ValueVT.isVector()) 497 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 498 CallConv); 499 500 unsigned PartBits = PartVT.getSizeInBits(); 501 unsigned OrigNumParts = NumParts; 502 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 503 "Copying to an illegal type!"); 504 505 if (NumParts == 0) 506 return; 507 508 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 509 EVT PartEVT = PartVT; 510 if (PartEVT == ValueVT) { 511 assert(NumParts == 1 && "No-op copy with multiple parts!"); 512 Parts[0] = Val; 513 return; 514 } 515 516 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 517 // If the parts cover more bits than the value has, promote the value. 518 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 519 assert(NumParts == 1 && "Do not know what to promote to!"); 520 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 521 } else { 522 if (ValueVT.isFloatingPoint()) { 523 // FP values need to be bitcast, then extended if they are being put 524 // into a larger container. 525 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 526 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 527 } 528 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 529 ValueVT.isInteger() && 530 "Unknown mismatch!"); 531 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 532 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 533 if (PartVT == MVT::x86mmx) 534 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 535 } 536 } else if (PartBits == ValueVT.getSizeInBits()) { 537 // Different types of the same size. 538 assert(NumParts == 1 && PartEVT != ValueVT); 539 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 540 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 541 // If the parts cover less bits than value has, truncate the value. 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 551 // The value may have changed - recompute ValueVT. 552 ValueVT = Val.getValueType(); 553 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 554 "Failed to tile the value with PartVT!"); 555 556 if (NumParts == 1) { 557 if (PartEVT != ValueVT) { 558 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 559 "scalar-to-vector conversion failed"); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 Parts[0] = Val; 564 return; 565 } 566 567 // Expand the value into multiple parts. 568 if (NumParts & (NumParts - 1)) { 569 // The number of parts is not a power of 2. Split off and copy the tail. 570 assert(PartVT.isInteger() && ValueVT.isInteger() && 571 "Do not know what to expand to!"); 572 unsigned RoundParts = 1 << Log2_32(NumParts); 573 unsigned RoundBits = RoundParts * PartBits; 574 unsigned OddParts = NumParts - RoundParts; 575 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 576 DAG.getIntPtrConstant(RoundBits, DL)); 577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 578 CallConv); 579 580 if (DAG.getDataLayout().isBigEndian()) 581 // The odd parts were reversed by getCopyToParts - unreverse them. 582 std::reverse(Parts + RoundParts, Parts + NumParts); 583 584 NumParts = RoundParts; 585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 587 } 588 589 // The number of parts is a power of 2. Repeatedly bisect the value using 590 // EXTRACT_ELEMENT. 591 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 592 EVT::getIntegerVT(*DAG.getContext(), 593 ValueVT.getSizeInBits()), 594 Val); 595 596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 597 for (unsigned i = 0; i < NumParts; i += StepSize) { 598 unsigned ThisBits = StepSize * PartBits / 2; 599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 600 SDValue &Part0 = Parts[i]; 601 SDValue &Part1 = Parts[i+StepSize/2]; 602 603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 607 608 if (ThisBits == PartBits && ThisVT != PartVT) { 609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 611 } 612 } 613 } 614 615 if (DAG.getDataLayout().isBigEndian()) 616 std::reverse(Parts, Parts + OrigNumParts); 617 } 618 619 static SDValue widenVectorToPartType(SelectionDAG &DAG, 620 SDValue Val, const SDLoc &DL, EVT PartVT) { 621 if (!PartVT.isVector()) 622 return SDValue(); 623 624 EVT ValueVT = Val.getValueType(); 625 unsigned PartNumElts = PartVT.getVectorNumElements(); 626 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 627 if (PartNumElts > ValueNumElts && 628 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 629 EVT ElementVT = PartVT.getVectorElementType(); 630 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 631 // undef elements. 632 SmallVector<SDValue, 16> Ops; 633 DAG.ExtractVectorElements(Val, Ops); 634 SDValue EltUndef = DAG.getUNDEF(ElementVT); 635 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 636 Ops.push_back(EltUndef); 637 638 // FIXME: Use CONCAT for 2x -> 4x. 639 return DAG.getBuildVector(PartVT, DL, Ops); 640 } 641 642 return SDValue(); 643 } 644 645 /// getCopyToPartsVector - Create a series of nodes that contain the specified 646 /// value split into legal parts. 647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 648 SDValue Val, SDValue *Parts, unsigned NumParts, 649 MVT PartVT, const Value *V, 650 Optional<CallingConv::ID> CallConv) { 651 EVT ValueVT = Val.getValueType(); 652 assert(ValueVT.isVector() && "Not a vector"); 653 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 654 const bool IsABIRegCopy = CallConv.hasValue(); 655 656 if (NumParts == 1) { 657 EVT PartEVT = PartVT; 658 if (PartEVT == ValueVT) { 659 // Nothing to do. 660 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 661 // Bitconvert vector->vector case. 662 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 663 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 664 Val = Widened; 665 } else if (PartVT.isVector() && 666 PartEVT.getVectorElementType().bitsGE( 667 ValueVT.getVectorElementType()) && 668 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 669 670 // Promoted vector extract 671 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 672 } else { 673 if (ValueVT.getVectorNumElements() == 1) { 674 Val = DAG.getNode( 675 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 676 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 677 } else { 678 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 679 "lossy conversion of vector to scalar type"); 680 EVT IntermediateType = 681 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 682 Val = DAG.getBitcast(IntermediateType, Val); 683 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 684 } 685 } 686 687 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 688 Parts[0] = Val; 689 return; 690 } 691 692 // Handle a multi-element vector. 693 EVT IntermediateVT; 694 MVT RegisterVT; 695 unsigned NumIntermediates; 696 unsigned NumRegs; 697 if (IsABIRegCopy) { 698 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 699 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 700 NumIntermediates, RegisterVT); 701 } else { 702 NumRegs = 703 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 704 NumIntermediates, RegisterVT); 705 } 706 707 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 708 NumParts = NumRegs; // Silence a compiler warning. 709 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 710 711 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 712 IntermediateVT.getVectorNumElements() : 1; 713 714 // Convert the vector to the appropiate type if necessary. 715 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 716 717 EVT BuiltVectorTy = EVT::getVectorVT( 718 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 719 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 720 if (ValueVT != BuiltVectorTy) { 721 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 722 Val = Widened; 723 724 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 725 } 726 727 // Split the vector into intermediate operands. 728 SmallVector<SDValue, 8> Ops(NumIntermediates); 729 for (unsigned i = 0; i != NumIntermediates; ++i) { 730 if (IntermediateVT.isVector()) { 731 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 732 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 733 } else { 734 Ops[i] = DAG.getNode( 735 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 736 DAG.getConstant(i, DL, IdxVT)); 737 } 738 } 739 740 // Split the intermediate operands into legal parts. 741 if (NumParts == NumIntermediates) { 742 // If the register was not expanded, promote or copy the value, 743 // as appropriate. 744 for (unsigned i = 0; i != NumParts; ++i) 745 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 746 } else if (NumParts > 0) { 747 // If the intermediate type was expanded, split each the value into 748 // legal parts. 749 assert(NumIntermediates != 0 && "division by zero"); 750 assert(NumParts % NumIntermediates == 0 && 751 "Must expand into a divisible number of parts!"); 752 unsigned Factor = NumParts / NumIntermediates; 753 for (unsigned i = 0; i != NumIntermediates; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 755 CallConv); 756 } 757 } 758 759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 760 EVT valuevt, Optional<CallingConv::ID> CC) 761 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 762 RegCount(1, regs.size()), CallConv(CC) {} 763 764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 765 const DataLayout &DL, unsigned Reg, Type *Ty, 766 Optional<CallingConv::ID> CC) { 767 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 768 769 CallConv = CC; 770 771 for (EVT ValueVT : ValueVTs) { 772 unsigned NumRegs = 773 isABIMangled() 774 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 775 : TLI.getNumRegisters(Context, ValueVT); 776 MVT RegisterVT = 777 isABIMangled() 778 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 779 : TLI.getRegisterType(Context, ValueVT); 780 for (unsigned i = 0; i != NumRegs; ++i) 781 Regs.push_back(Reg + i); 782 RegVTs.push_back(RegisterVT); 783 RegCount.push_back(NumRegs); 784 Reg += NumRegs; 785 } 786 } 787 788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 789 FunctionLoweringInfo &FuncInfo, 790 const SDLoc &dl, SDValue &Chain, 791 SDValue *Flag, const Value *V) const { 792 // A Value with type {} or [0 x %t] needs no registers. 793 if (ValueVTs.empty()) 794 return SDValue(); 795 796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 797 798 // Assemble the legal parts into the final values. 799 SmallVector<SDValue, 4> Values(ValueVTs.size()); 800 SmallVector<SDValue, 8> Parts; 801 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 802 // Copy the legal parts from the registers. 803 EVT ValueVT = ValueVTs[Value]; 804 unsigned NumRegs = RegCount[Value]; 805 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 806 *DAG.getContext(), 807 CallConv.getValue(), RegVTs[Value]) 808 : RegVTs[Value]; 809 810 Parts.resize(NumRegs); 811 for (unsigned i = 0; i != NumRegs; ++i) { 812 SDValue P; 813 if (!Flag) { 814 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 815 } else { 816 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 817 *Flag = P.getValue(2); 818 } 819 820 Chain = P.getValue(1); 821 Parts[i] = P; 822 823 // If the source register was virtual and if we know something about it, 824 // add an assert node. 825 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 826 !RegisterVT.isInteger()) 827 continue; 828 829 const FunctionLoweringInfo::LiveOutInfo *LOI = 830 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 831 if (!LOI) 832 continue; 833 834 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 835 unsigned NumSignBits = LOI->NumSignBits; 836 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 837 838 if (NumZeroBits == RegSize) { 839 // The current value is a zero. 840 // Explicitly express that as it would be easier for 841 // optimizations to kick in. 842 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 843 continue; 844 } 845 846 // FIXME: We capture more information than the dag can represent. For 847 // now, just use the tightest assertzext/assertsext possible. 848 bool isSExt; 849 EVT FromVT(MVT::Other); 850 if (NumZeroBits) { 851 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 852 isSExt = false; 853 } else if (NumSignBits > 1) { 854 FromVT = 855 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 856 isSExt = true; 857 } else { 858 continue; 859 } 860 // Add an assertion node. 861 assert(FromVT != MVT::Other); 862 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 863 RegisterVT, P, DAG.getValueType(FromVT)); 864 } 865 866 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 867 RegisterVT, ValueVT, V, CallConv); 868 Part += NumRegs; 869 Parts.clear(); 870 } 871 872 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 873 } 874 875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 876 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 877 const Value *V, 878 ISD::NodeType PreferredExtendType) const { 879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 ISD::NodeType ExtendKind = PreferredExtendType; 881 882 // Get the list of the values's legal parts. 883 unsigned NumRegs = Regs.size(); 884 SmallVector<SDValue, 8> Parts(NumRegs); 885 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 886 unsigned NumParts = RegCount[Value]; 887 888 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 889 *DAG.getContext(), 890 CallConv.getValue(), RegVTs[Value]) 891 : RegVTs[Value]; 892 893 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 894 ExtendKind = ISD::ZERO_EXTEND; 895 896 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 897 NumParts, RegisterVT, V, CallConv, ExtendKind); 898 Part += NumParts; 899 } 900 901 // Copy the parts into the registers. 902 SmallVector<SDValue, 8> Chains(NumRegs); 903 for (unsigned i = 0; i != NumRegs; ++i) { 904 SDValue Part; 905 if (!Flag) { 906 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 907 } else { 908 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 909 *Flag = Part.getValue(1); 910 } 911 912 Chains[i] = Part.getValue(0); 913 } 914 915 if (NumRegs == 1 || Flag) 916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 917 // flagged to it. That is the CopyToReg nodes and the user are considered 918 // a single scheduling unit. If we create a TokenFactor and return it as 919 // chain, then the TokenFactor is both a predecessor (operand) of the 920 // user as well as a successor (the TF operands are flagged to the user). 921 // c1, f1 = CopyToReg 922 // c2, f2 = CopyToReg 923 // c3 = TokenFactor c1, c2 924 // ... 925 // = op c3, ..., f2 926 Chain = Chains[NumRegs-1]; 927 else 928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 929 } 930 931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 932 unsigned MatchingIdx, const SDLoc &dl, 933 SelectionDAG &DAG, 934 std::vector<SDValue> &Ops) const { 935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 936 937 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 938 if (HasMatching) 939 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 940 else if (!Regs.empty() && 941 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 942 // Put the register class of the virtual registers in the flag word. That 943 // way, later passes can recompute register class constraints for inline 944 // assembly as well as normal instructions. 945 // Don't do this for tied operands that can use the regclass information 946 // from the def. 947 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 948 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 949 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 950 } 951 952 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 953 Ops.push_back(Res); 954 955 if (Code == InlineAsm::Kind_Clobber) { 956 // Clobbers should always have a 1:1 mapping with registers, and may 957 // reference registers that have illegal (e.g. vector) types. Hence, we 958 // shouldn't try to apply any sort of splitting logic to them. 959 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 960 "No 1:1 mapping from clobbers to regs?"); 961 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 962 (void)SP; 963 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 964 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 965 assert( 966 (Regs[I] != SP || 967 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 968 "If we clobbered the stack pointer, MFI should know about it."); 969 } 970 return; 971 } 972 973 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 974 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 975 MVT RegisterVT = RegVTs[Value]; 976 for (unsigned i = 0; i != NumRegs; ++i) { 977 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 978 unsigned TheReg = Regs[Reg++]; 979 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 980 } 981 } 982 } 983 984 SmallVector<std::pair<unsigned, unsigned>, 4> 985 RegsForValue::getRegsAndSizes() const { 986 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 987 unsigned I = 0; 988 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 989 unsigned RegCount = std::get<0>(CountAndVT); 990 MVT RegisterVT = std::get<1>(CountAndVT); 991 unsigned RegisterSize = RegisterVT.getSizeInBits(); 992 for (unsigned E = I + RegCount; I != E; ++I) 993 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 994 } 995 return OutVec; 996 } 997 998 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 999 const TargetLibraryInfo *li) { 1000 AA = aa; 1001 GFI = gfi; 1002 LibInfo = li; 1003 DL = &DAG.getDataLayout(); 1004 Context = DAG.getContext(); 1005 LPadToCallSiteMap.clear(); 1006 } 1007 1008 void SelectionDAGBuilder::clear() { 1009 NodeMap.clear(); 1010 UnusedArgNodeMap.clear(); 1011 PendingLoads.clear(); 1012 PendingExports.clear(); 1013 CurInst = nullptr; 1014 HasTailCall = false; 1015 SDNodeOrder = LowestSDNodeOrder; 1016 StatepointLowering.clear(); 1017 } 1018 1019 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1020 DanglingDebugInfoMap.clear(); 1021 } 1022 1023 SDValue SelectionDAGBuilder::getRoot() { 1024 if (PendingLoads.empty()) 1025 return DAG.getRoot(); 1026 1027 if (PendingLoads.size() == 1) { 1028 SDValue Root = PendingLoads[0]; 1029 DAG.setRoot(Root); 1030 PendingLoads.clear(); 1031 return Root; 1032 } 1033 1034 // Otherwise, we have to make a token factor node. 1035 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1036 PendingLoads.clear(); 1037 DAG.setRoot(Root); 1038 return Root; 1039 } 1040 1041 SDValue SelectionDAGBuilder::getControlRoot() { 1042 SDValue Root = DAG.getRoot(); 1043 1044 if (PendingExports.empty()) 1045 return Root; 1046 1047 // Turn all of the CopyToReg chains into one factored node. 1048 if (Root.getOpcode() != ISD::EntryToken) { 1049 unsigned i = 0, e = PendingExports.size(); 1050 for (; i != e; ++i) { 1051 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1052 if (PendingExports[i].getNode()->getOperand(0) == Root) 1053 break; // Don't add the root if we already indirectly depend on it. 1054 } 1055 1056 if (i == e) 1057 PendingExports.push_back(Root); 1058 } 1059 1060 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1061 PendingExports); 1062 PendingExports.clear(); 1063 DAG.setRoot(Root); 1064 return Root; 1065 } 1066 1067 void SelectionDAGBuilder::visit(const Instruction &I) { 1068 // Set up outgoing PHI node register values before emitting the terminator. 1069 if (I.isTerminator()) { 1070 HandlePHINodesInSuccessorBlocks(I.getParent()); 1071 } 1072 1073 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1074 if (!isa<DbgInfoIntrinsic>(I)) 1075 ++SDNodeOrder; 1076 1077 CurInst = &I; 1078 1079 visit(I.getOpcode(), I); 1080 1081 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1082 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1083 // maps to this instruction. 1084 // TODO: We could handle all flags (nsw, etc) here. 1085 // TODO: If an IR instruction maps to >1 node, only the final node will have 1086 // flags set. 1087 if (SDNode *Node = getNodeForIRValue(&I)) { 1088 SDNodeFlags IncomingFlags; 1089 IncomingFlags.copyFMF(*FPMO); 1090 if (!Node->getFlags().isDefined()) 1091 Node->setFlags(IncomingFlags); 1092 else 1093 Node->intersectFlagsWith(IncomingFlags); 1094 } 1095 } 1096 1097 if (!I.isTerminator() && !HasTailCall && 1098 !isStatepoint(&I)) // statepoints handle their exports internally 1099 CopyToExportRegsIfNeeded(&I); 1100 1101 CurInst = nullptr; 1102 } 1103 1104 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1105 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1106 } 1107 1108 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1109 // Note: this doesn't use InstVisitor, because it has to work with 1110 // ConstantExpr's in addition to instructions. 1111 switch (Opcode) { 1112 default: llvm_unreachable("Unknown instruction type encountered!"); 1113 // Build the switch statement using the Instruction.def file. 1114 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1115 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1116 #include "llvm/IR/Instruction.def" 1117 } 1118 } 1119 1120 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1121 const DIExpression *Expr) { 1122 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1123 const DbgValueInst *DI = DDI.getDI(); 1124 DIVariable *DanglingVariable = DI->getVariable(); 1125 DIExpression *DanglingExpr = DI->getExpression(); 1126 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1127 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1128 return true; 1129 } 1130 return false; 1131 }; 1132 1133 for (auto &DDIMI : DanglingDebugInfoMap) { 1134 DanglingDebugInfoVector &DDIV = DDIMI.second; 1135 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1136 } 1137 } 1138 1139 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1140 // generate the debug data structures now that we've seen its definition. 1141 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1142 SDValue Val) { 1143 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1144 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1145 return; 1146 1147 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1148 for (auto &DDI : DDIV) { 1149 const DbgValueInst *DI = DDI.getDI(); 1150 assert(DI && "Ill-formed DanglingDebugInfo"); 1151 DebugLoc dl = DDI.getdl(); 1152 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1153 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1154 DILocalVariable *Variable = DI->getVariable(); 1155 DIExpression *Expr = DI->getExpression(); 1156 assert(Variable->isValidLocationForIntrinsic(dl) && 1157 "Expected inlined-at fields to agree"); 1158 SDDbgValue *SDV; 1159 if (Val.getNode()) { 1160 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1161 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1162 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1163 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1164 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1165 // inserted after the definition of Val when emitting the instructions 1166 // after ISel. An alternative could be to teach 1167 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1168 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1169 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1170 << ValSDNodeOrder << "\n"); 1171 SDV = getDbgValue(Val, Variable, Expr, dl, 1172 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1173 DAG.AddDbgValue(SDV, Val.getNode(), false); 1174 } else 1175 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1176 << "in EmitFuncArgumentDbgValue\n"); 1177 } else 1178 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1179 } 1180 DDIV.clear(); 1181 } 1182 1183 /// getCopyFromRegs - If there was virtual register allocated for the value V 1184 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1185 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1186 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1187 SDValue Result; 1188 1189 if (It != FuncInfo.ValueMap.end()) { 1190 unsigned InReg = It->second; 1191 1192 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1193 DAG.getDataLayout(), InReg, Ty, 1194 None); // This is not an ABI copy. 1195 SDValue Chain = DAG.getEntryNode(); 1196 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1197 V); 1198 resolveDanglingDebugInfo(V, Result); 1199 } 1200 1201 return Result; 1202 } 1203 1204 /// getValue - Return an SDValue for the given Value. 1205 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1206 // If we already have an SDValue for this value, use it. It's important 1207 // to do this first, so that we don't create a CopyFromReg if we already 1208 // have a regular SDValue. 1209 SDValue &N = NodeMap[V]; 1210 if (N.getNode()) return N; 1211 1212 // If there's a virtual register allocated and initialized for this 1213 // value, use it. 1214 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1215 return copyFromReg; 1216 1217 // Otherwise create a new SDValue and remember it. 1218 SDValue Val = getValueImpl(V); 1219 NodeMap[V] = Val; 1220 resolveDanglingDebugInfo(V, Val); 1221 return Val; 1222 } 1223 1224 // Return true if SDValue exists for the given Value 1225 bool SelectionDAGBuilder::findValue(const Value *V) const { 1226 return (NodeMap.find(V) != NodeMap.end()) || 1227 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1228 } 1229 1230 /// getNonRegisterValue - Return an SDValue for the given Value, but 1231 /// don't look in FuncInfo.ValueMap for a virtual register. 1232 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1233 // If we already have an SDValue for this value, use it. 1234 SDValue &N = NodeMap[V]; 1235 if (N.getNode()) { 1236 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1237 // Remove the debug location from the node as the node is about to be used 1238 // in a location which may differ from the original debug location. This 1239 // is relevant to Constant and ConstantFP nodes because they can appear 1240 // as constant expressions inside PHI nodes. 1241 N->setDebugLoc(DebugLoc()); 1242 } 1243 return N; 1244 } 1245 1246 // Otherwise create a new SDValue and remember it. 1247 SDValue Val = getValueImpl(V); 1248 NodeMap[V] = Val; 1249 resolveDanglingDebugInfo(V, Val); 1250 return Val; 1251 } 1252 1253 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1254 /// Create an SDValue for the given value. 1255 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1256 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1257 1258 if (const Constant *C = dyn_cast<Constant>(V)) { 1259 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1260 1261 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1262 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1263 1264 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1265 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1266 1267 if (isa<ConstantPointerNull>(C)) { 1268 unsigned AS = V->getType()->getPointerAddressSpace(); 1269 return DAG.getConstant(0, getCurSDLoc(), 1270 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1271 } 1272 1273 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1274 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1275 1276 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1277 return DAG.getUNDEF(VT); 1278 1279 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1280 visit(CE->getOpcode(), *CE); 1281 SDValue N1 = NodeMap[V]; 1282 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1283 return N1; 1284 } 1285 1286 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1287 SmallVector<SDValue, 4> Constants; 1288 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1289 OI != OE; ++OI) { 1290 SDNode *Val = getValue(*OI).getNode(); 1291 // If the operand is an empty aggregate, there are no values. 1292 if (!Val) continue; 1293 // Add each leaf value from the operand to the Constants list 1294 // to form a flattened list of all the values. 1295 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1296 Constants.push_back(SDValue(Val, i)); 1297 } 1298 1299 return DAG.getMergeValues(Constants, getCurSDLoc()); 1300 } 1301 1302 if (const ConstantDataSequential *CDS = 1303 dyn_cast<ConstantDataSequential>(C)) { 1304 SmallVector<SDValue, 4> Ops; 1305 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1306 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1307 // Add each leaf value from the operand to the Constants list 1308 // to form a flattened list of all the values. 1309 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1310 Ops.push_back(SDValue(Val, i)); 1311 } 1312 1313 if (isa<ArrayType>(CDS->getType())) 1314 return DAG.getMergeValues(Ops, getCurSDLoc()); 1315 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1316 } 1317 1318 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1319 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1320 "Unknown struct or array constant!"); 1321 1322 SmallVector<EVT, 4> ValueVTs; 1323 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1324 unsigned NumElts = ValueVTs.size(); 1325 if (NumElts == 0) 1326 return SDValue(); // empty struct 1327 SmallVector<SDValue, 4> Constants(NumElts); 1328 for (unsigned i = 0; i != NumElts; ++i) { 1329 EVT EltVT = ValueVTs[i]; 1330 if (isa<UndefValue>(C)) 1331 Constants[i] = DAG.getUNDEF(EltVT); 1332 else if (EltVT.isFloatingPoint()) 1333 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1334 else 1335 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1336 } 1337 1338 return DAG.getMergeValues(Constants, getCurSDLoc()); 1339 } 1340 1341 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1342 return DAG.getBlockAddress(BA, VT); 1343 1344 VectorType *VecTy = cast<VectorType>(V->getType()); 1345 unsigned NumElements = VecTy->getNumElements(); 1346 1347 // Now that we know the number and type of the elements, get that number of 1348 // elements into the Ops array based on what kind of constant it is. 1349 SmallVector<SDValue, 16> Ops; 1350 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1351 for (unsigned i = 0; i != NumElements; ++i) 1352 Ops.push_back(getValue(CV->getOperand(i))); 1353 } else { 1354 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1355 EVT EltVT = 1356 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1357 1358 SDValue Op; 1359 if (EltVT.isFloatingPoint()) 1360 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1361 else 1362 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1363 Ops.assign(NumElements, Op); 1364 } 1365 1366 // Create a BUILD_VECTOR node. 1367 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1368 } 1369 1370 // If this is a static alloca, generate it as the frameindex instead of 1371 // computation. 1372 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1373 DenseMap<const AllocaInst*, int>::iterator SI = 1374 FuncInfo.StaticAllocaMap.find(AI); 1375 if (SI != FuncInfo.StaticAllocaMap.end()) 1376 return DAG.getFrameIndex(SI->second, 1377 TLI.getFrameIndexTy(DAG.getDataLayout())); 1378 } 1379 1380 // If this is an instruction which fast-isel has deferred, select it now. 1381 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1382 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1383 1384 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1385 Inst->getType(), getABIRegCopyCC(V)); 1386 SDValue Chain = DAG.getEntryNode(); 1387 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1388 } 1389 1390 llvm_unreachable("Can't get register for value!"); 1391 } 1392 1393 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1394 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1395 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1396 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1397 bool IsSEH = isAsynchronousEHPersonality(Pers); 1398 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1399 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1400 if (!IsSEH) 1401 CatchPadMBB->setIsEHScopeEntry(); 1402 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1403 if (IsMSVCCXX || IsCoreCLR) 1404 CatchPadMBB->setIsEHFuncletEntry(); 1405 // Wasm does not need catchpads anymore 1406 if (!IsWasmCXX) 1407 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1408 getControlRoot())); 1409 } 1410 1411 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1412 // Update machine-CFG edge. 1413 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1414 FuncInfo.MBB->addSuccessor(TargetMBB); 1415 1416 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1417 bool IsSEH = isAsynchronousEHPersonality(Pers); 1418 if (IsSEH) { 1419 // If this is not a fall-through branch or optimizations are switched off, 1420 // emit the branch. 1421 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1422 TM.getOptLevel() == CodeGenOpt::None) 1423 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1424 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1425 return; 1426 } 1427 1428 // Figure out the funclet membership for the catchret's successor. 1429 // This will be used by the FuncletLayout pass to determine how to order the 1430 // BB's. 1431 // A 'catchret' returns to the outer scope's color. 1432 Value *ParentPad = I.getCatchSwitchParentPad(); 1433 const BasicBlock *SuccessorColor; 1434 if (isa<ConstantTokenNone>(ParentPad)) 1435 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1436 else 1437 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1438 assert(SuccessorColor && "No parent funclet for catchret!"); 1439 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1440 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1441 1442 // Create the terminator node. 1443 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1444 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1445 DAG.getBasicBlock(SuccessorColorMBB)); 1446 DAG.setRoot(Ret); 1447 } 1448 1449 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1450 // Don't emit any special code for the cleanuppad instruction. It just marks 1451 // the start of an EH scope/funclet. 1452 FuncInfo.MBB->setIsEHScopeEntry(); 1453 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1454 if (Pers != EHPersonality::Wasm_CXX) { 1455 FuncInfo.MBB->setIsEHFuncletEntry(); 1456 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1457 } 1458 } 1459 1460 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1461 /// many places it could ultimately go. In the IR, we have a single unwind 1462 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1463 /// This function skips over imaginary basic blocks that hold catchswitch 1464 /// instructions, and finds all the "real" machine 1465 /// basic block destinations. As those destinations may not be successors of 1466 /// EHPadBB, here we also calculate the edge probability to those destinations. 1467 /// The passed-in Prob is the edge probability to EHPadBB. 1468 static void findUnwindDestinations( 1469 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1470 BranchProbability Prob, 1471 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1472 &UnwindDests) { 1473 EHPersonality Personality = 1474 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1475 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1476 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1477 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1478 bool IsSEH = isAsynchronousEHPersonality(Personality); 1479 1480 while (EHPadBB) { 1481 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1482 BasicBlock *NewEHPadBB = nullptr; 1483 if (isa<LandingPadInst>(Pad)) { 1484 // Stop on landingpads. They are not funclets. 1485 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1486 break; 1487 } else if (isa<CleanupPadInst>(Pad)) { 1488 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1489 // personalities. 1490 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1491 UnwindDests.back().first->setIsEHScopeEntry(); 1492 if (!IsWasmCXX) 1493 UnwindDests.back().first->setIsEHFuncletEntry(); 1494 break; 1495 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1496 // Add the catchpad handlers to the possible destinations. 1497 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1498 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1499 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1500 if (IsMSVCCXX || IsCoreCLR) 1501 UnwindDests.back().first->setIsEHFuncletEntry(); 1502 if (!IsSEH) 1503 UnwindDests.back().first->setIsEHScopeEntry(); 1504 } 1505 NewEHPadBB = CatchSwitch->getUnwindDest(); 1506 } else { 1507 continue; 1508 } 1509 1510 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1511 if (BPI && NewEHPadBB) 1512 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1513 EHPadBB = NewEHPadBB; 1514 } 1515 } 1516 1517 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1518 // Update successor info. 1519 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1520 auto UnwindDest = I.getUnwindDest(); 1521 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1522 BranchProbability UnwindDestProb = 1523 (BPI && UnwindDest) 1524 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1525 : BranchProbability::getZero(); 1526 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1527 for (auto &UnwindDest : UnwindDests) { 1528 UnwindDest.first->setIsEHPad(); 1529 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1530 } 1531 FuncInfo.MBB->normalizeSuccProbs(); 1532 1533 // Create the terminator node. 1534 SDValue Ret = 1535 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1536 DAG.setRoot(Ret); 1537 } 1538 1539 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1540 report_fatal_error("visitCatchSwitch not yet implemented!"); 1541 } 1542 1543 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1544 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1545 auto &DL = DAG.getDataLayout(); 1546 SDValue Chain = getControlRoot(); 1547 SmallVector<ISD::OutputArg, 8> Outs; 1548 SmallVector<SDValue, 8> OutVals; 1549 1550 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1551 // lower 1552 // 1553 // %val = call <ty> @llvm.experimental.deoptimize() 1554 // ret <ty> %val 1555 // 1556 // differently. 1557 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1558 LowerDeoptimizingReturn(); 1559 return; 1560 } 1561 1562 if (!FuncInfo.CanLowerReturn) { 1563 unsigned DemoteReg = FuncInfo.DemoteRegister; 1564 const Function *F = I.getParent()->getParent(); 1565 1566 // Emit a store of the return value through the virtual register. 1567 // Leave Outs empty so that LowerReturn won't try to load return 1568 // registers the usual way. 1569 SmallVector<EVT, 1> PtrValueVTs; 1570 ComputeValueVTs(TLI, DL, 1571 F->getReturnType()->getPointerTo( 1572 DAG.getDataLayout().getAllocaAddrSpace()), 1573 PtrValueVTs); 1574 1575 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1576 DemoteReg, PtrValueVTs[0]); 1577 SDValue RetOp = getValue(I.getOperand(0)); 1578 1579 SmallVector<EVT, 4> ValueVTs; 1580 SmallVector<uint64_t, 4> Offsets; 1581 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1582 unsigned NumValues = ValueVTs.size(); 1583 1584 SmallVector<SDValue, 4> Chains(NumValues); 1585 for (unsigned i = 0; i != NumValues; ++i) { 1586 // An aggregate return value cannot wrap around the address space, so 1587 // offsets to its parts don't wrap either. 1588 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1589 Chains[i] = DAG.getStore( 1590 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1591 // FIXME: better loc info would be nice. 1592 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1593 } 1594 1595 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1596 MVT::Other, Chains); 1597 } else if (I.getNumOperands() != 0) { 1598 SmallVector<EVT, 4> ValueVTs; 1599 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1600 unsigned NumValues = ValueVTs.size(); 1601 if (NumValues) { 1602 SDValue RetOp = getValue(I.getOperand(0)); 1603 1604 const Function *F = I.getParent()->getParent(); 1605 1606 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1607 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1608 Attribute::SExt)) 1609 ExtendKind = ISD::SIGN_EXTEND; 1610 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1611 Attribute::ZExt)) 1612 ExtendKind = ISD::ZERO_EXTEND; 1613 1614 LLVMContext &Context = F->getContext(); 1615 bool RetInReg = F->getAttributes().hasAttribute( 1616 AttributeList::ReturnIndex, Attribute::InReg); 1617 1618 for (unsigned j = 0; j != NumValues; ++j) { 1619 EVT VT = ValueVTs[j]; 1620 1621 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1622 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1623 1624 CallingConv::ID CC = F->getCallingConv(); 1625 1626 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1627 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1628 SmallVector<SDValue, 4> Parts(NumParts); 1629 getCopyToParts(DAG, getCurSDLoc(), 1630 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1631 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1632 1633 // 'inreg' on function refers to return value 1634 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1635 if (RetInReg) 1636 Flags.setInReg(); 1637 1638 // Propagate extension type if any 1639 if (ExtendKind == ISD::SIGN_EXTEND) 1640 Flags.setSExt(); 1641 else if (ExtendKind == ISD::ZERO_EXTEND) 1642 Flags.setZExt(); 1643 1644 for (unsigned i = 0; i < NumParts; ++i) { 1645 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1646 VT, /*isfixed=*/true, 0, 0)); 1647 OutVals.push_back(Parts[i]); 1648 } 1649 } 1650 } 1651 } 1652 1653 // Push in swifterror virtual register as the last element of Outs. This makes 1654 // sure swifterror virtual register will be returned in the swifterror 1655 // physical register. 1656 const Function *F = I.getParent()->getParent(); 1657 if (TLI.supportSwiftError() && 1658 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1659 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1660 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1661 Flags.setSwiftError(); 1662 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1663 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1664 true /*isfixed*/, 1 /*origidx*/, 1665 0 /*partOffs*/)); 1666 // Create SDNode for the swifterror virtual register. 1667 OutVals.push_back( 1668 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1669 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1670 EVT(TLI.getPointerTy(DL)))); 1671 } 1672 1673 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1674 CallingConv::ID CallConv = 1675 DAG.getMachineFunction().getFunction().getCallingConv(); 1676 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1677 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1678 1679 // Verify that the target's LowerReturn behaved as expected. 1680 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1681 "LowerReturn didn't return a valid chain!"); 1682 1683 // Update the DAG with the new chain value resulting from return lowering. 1684 DAG.setRoot(Chain); 1685 } 1686 1687 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1688 /// created for it, emit nodes to copy the value into the virtual 1689 /// registers. 1690 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1691 // Skip empty types 1692 if (V->getType()->isEmptyTy()) 1693 return; 1694 1695 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1696 if (VMI != FuncInfo.ValueMap.end()) { 1697 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1698 CopyValueToVirtualRegister(V, VMI->second); 1699 } 1700 } 1701 1702 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1703 /// the current basic block, add it to ValueMap now so that we'll get a 1704 /// CopyTo/FromReg. 1705 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1706 // No need to export constants. 1707 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1708 1709 // Already exported? 1710 if (FuncInfo.isExportedInst(V)) return; 1711 1712 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1713 CopyValueToVirtualRegister(V, Reg); 1714 } 1715 1716 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1717 const BasicBlock *FromBB) { 1718 // The operands of the setcc have to be in this block. We don't know 1719 // how to export them from some other block. 1720 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1721 // Can export from current BB. 1722 if (VI->getParent() == FromBB) 1723 return true; 1724 1725 // Is already exported, noop. 1726 return FuncInfo.isExportedInst(V); 1727 } 1728 1729 // If this is an argument, we can export it if the BB is the entry block or 1730 // if it is already exported. 1731 if (isa<Argument>(V)) { 1732 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1733 return true; 1734 1735 // Otherwise, can only export this if it is already exported. 1736 return FuncInfo.isExportedInst(V); 1737 } 1738 1739 // Otherwise, constants can always be exported. 1740 return true; 1741 } 1742 1743 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1744 BranchProbability 1745 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1746 const MachineBasicBlock *Dst) const { 1747 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1748 const BasicBlock *SrcBB = Src->getBasicBlock(); 1749 const BasicBlock *DstBB = Dst->getBasicBlock(); 1750 if (!BPI) { 1751 // If BPI is not available, set the default probability as 1 / N, where N is 1752 // the number of successors. 1753 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1754 return BranchProbability(1, SuccSize); 1755 } 1756 return BPI->getEdgeProbability(SrcBB, DstBB); 1757 } 1758 1759 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1760 MachineBasicBlock *Dst, 1761 BranchProbability Prob) { 1762 if (!FuncInfo.BPI) 1763 Src->addSuccessorWithoutProb(Dst); 1764 else { 1765 if (Prob.isUnknown()) 1766 Prob = getEdgeProbability(Src, Dst); 1767 Src->addSuccessor(Dst, Prob); 1768 } 1769 } 1770 1771 static bool InBlock(const Value *V, const BasicBlock *BB) { 1772 if (const Instruction *I = dyn_cast<Instruction>(V)) 1773 return I->getParent() == BB; 1774 return true; 1775 } 1776 1777 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1778 /// This function emits a branch and is used at the leaves of an OR or an 1779 /// AND operator tree. 1780 void 1781 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1782 MachineBasicBlock *TBB, 1783 MachineBasicBlock *FBB, 1784 MachineBasicBlock *CurBB, 1785 MachineBasicBlock *SwitchBB, 1786 BranchProbability TProb, 1787 BranchProbability FProb, 1788 bool InvertCond) { 1789 const BasicBlock *BB = CurBB->getBasicBlock(); 1790 1791 // If the leaf of the tree is a comparison, merge the condition into 1792 // the caseblock. 1793 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1794 // The operands of the cmp have to be in this block. We don't know 1795 // how to export them from some other block. If this is the first block 1796 // of the sequence, no exporting is needed. 1797 if (CurBB == SwitchBB || 1798 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1799 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1800 ISD::CondCode Condition; 1801 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1802 ICmpInst::Predicate Pred = 1803 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1804 Condition = getICmpCondCode(Pred); 1805 } else { 1806 const FCmpInst *FC = cast<FCmpInst>(Cond); 1807 FCmpInst::Predicate Pred = 1808 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1809 Condition = getFCmpCondCode(Pred); 1810 if (TM.Options.NoNaNsFPMath) 1811 Condition = getFCmpCodeWithoutNaN(Condition); 1812 } 1813 1814 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1815 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1816 SwitchCases.push_back(CB); 1817 return; 1818 } 1819 } 1820 1821 // Create a CaseBlock record representing this branch. 1822 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1823 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1824 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1825 SwitchCases.push_back(CB); 1826 } 1827 1828 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1829 MachineBasicBlock *TBB, 1830 MachineBasicBlock *FBB, 1831 MachineBasicBlock *CurBB, 1832 MachineBasicBlock *SwitchBB, 1833 Instruction::BinaryOps Opc, 1834 BranchProbability TProb, 1835 BranchProbability FProb, 1836 bool InvertCond) { 1837 // Skip over not part of the tree and remember to invert op and operands at 1838 // next level. 1839 Value *NotCond; 1840 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1841 InBlock(NotCond, CurBB->getBasicBlock())) { 1842 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1843 !InvertCond); 1844 return; 1845 } 1846 1847 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1848 // Compute the effective opcode for Cond, taking into account whether it needs 1849 // to be inverted, e.g. 1850 // and (not (or A, B)), C 1851 // gets lowered as 1852 // and (and (not A, not B), C) 1853 unsigned BOpc = 0; 1854 if (BOp) { 1855 BOpc = BOp->getOpcode(); 1856 if (InvertCond) { 1857 if (BOpc == Instruction::And) 1858 BOpc = Instruction::Or; 1859 else if (BOpc == Instruction::Or) 1860 BOpc = Instruction::And; 1861 } 1862 } 1863 1864 // If this node is not part of the or/and tree, emit it as a branch. 1865 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1866 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1867 BOp->getParent() != CurBB->getBasicBlock() || 1868 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1869 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1870 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1871 TProb, FProb, InvertCond); 1872 return; 1873 } 1874 1875 // Create TmpBB after CurBB. 1876 MachineFunction::iterator BBI(CurBB); 1877 MachineFunction &MF = DAG.getMachineFunction(); 1878 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1879 CurBB->getParent()->insert(++BBI, TmpBB); 1880 1881 if (Opc == Instruction::Or) { 1882 // Codegen X | Y as: 1883 // BB1: 1884 // jmp_if_X TBB 1885 // jmp TmpBB 1886 // TmpBB: 1887 // jmp_if_Y TBB 1888 // jmp FBB 1889 // 1890 1891 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1892 // The requirement is that 1893 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1894 // = TrueProb for original BB. 1895 // Assuming the original probabilities are A and B, one choice is to set 1896 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1897 // A/(1+B) and 2B/(1+B). This choice assumes that 1898 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1899 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1900 // TmpBB, but the math is more complicated. 1901 1902 auto NewTrueProb = TProb / 2; 1903 auto NewFalseProb = TProb / 2 + FProb; 1904 // Emit the LHS condition. 1905 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1906 NewTrueProb, NewFalseProb, InvertCond); 1907 1908 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1909 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1910 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1911 // Emit the RHS condition into TmpBB. 1912 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1913 Probs[0], Probs[1], InvertCond); 1914 } else { 1915 assert(Opc == Instruction::And && "Unknown merge op!"); 1916 // Codegen X & Y as: 1917 // BB1: 1918 // jmp_if_X TmpBB 1919 // jmp FBB 1920 // TmpBB: 1921 // jmp_if_Y TBB 1922 // jmp FBB 1923 // 1924 // This requires creation of TmpBB after CurBB. 1925 1926 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1927 // The requirement is that 1928 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1929 // = FalseProb for original BB. 1930 // Assuming the original probabilities are A and B, one choice is to set 1931 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1932 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1933 // TrueProb for BB1 * FalseProb for TmpBB. 1934 1935 auto NewTrueProb = TProb + FProb / 2; 1936 auto NewFalseProb = FProb / 2; 1937 // Emit the LHS condition. 1938 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1939 NewTrueProb, NewFalseProb, InvertCond); 1940 1941 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1942 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1943 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1944 // Emit the RHS condition into TmpBB. 1945 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1946 Probs[0], Probs[1], InvertCond); 1947 } 1948 } 1949 1950 /// If the set of cases should be emitted as a series of branches, return true. 1951 /// If we should emit this as a bunch of and/or'd together conditions, return 1952 /// false. 1953 bool 1954 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1955 if (Cases.size() != 2) return true; 1956 1957 // If this is two comparisons of the same values or'd or and'd together, they 1958 // will get folded into a single comparison, so don't emit two blocks. 1959 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1960 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1961 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1962 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1963 return false; 1964 } 1965 1966 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1967 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1968 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1969 Cases[0].CC == Cases[1].CC && 1970 isa<Constant>(Cases[0].CmpRHS) && 1971 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1972 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1973 return false; 1974 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1975 return false; 1976 } 1977 1978 return true; 1979 } 1980 1981 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1982 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1983 1984 // Update machine-CFG edges. 1985 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1986 1987 if (I.isUnconditional()) { 1988 // Update machine-CFG edges. 1989 BrMBB->addSuccessor(Succ0MBB); 1990 1991 // If this is not a fall-through branch or optimizations are switched off, 1992 // emit the branch. 1993 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1994 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1995 MVT::Other, getControlRoot(), 1996 DAG.getBasicBlock(Succ0MBB))); 1997 1998 return; 1999 } 2000 2001 // If this condition is one of the special cases we handle, do special stuff 2002 // now. 2003 const Value *CondVal = I.getCondition(); 2004 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2005 2006 // If this is a series of conditions that are or'd or and'd together, emit 2007 // this as a sequence of branches instead of setcc's with and/or operations. 2008 // As long as jumps are not expensive, this should improve performance. 2009 // For example, instead of something like: 2010 // cmp A, B 2011 // C = seteq 2012 // cmp D, E 2013 // F = setle 2014 // or C, F 2015 // jnz foo 2016 // Emit: 2017 // cmp A, B 2018 // je foo 2019 // cmp D, E 2020 // jle foo 2021 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2022 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2023 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2024 !I.getMetadata(LLVMContext::MD_unpredictable) && 2025 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2026 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2027 Opcode, 2028 getEdgeProbability(BrMBB, Succ0MBB), 2029 getEdgeProbability(BrMBB, Succ1MBB), 2030 /*InvertCond=*/false); 2031 // If the compares in later blocks need to use values not currently 2032 // exported from this block, export them now. This block should always 2033 // be the first entry. 2034 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2035 2036 // Allow some cases to be rejected. 2037 if (ShouldEmitAsBranches(SwitchCases)) { 2038 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2039 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2040 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2041 } 2042 2043 // Emit the branch for this block. 2044 visitSwitchCase(SwitchCases[0], BrMBB); 2045 SwitchCases.erase(SwitchCases.begin()); 2046 return; 2047 } 2048 2049 // Okay, we decided not to do this, remove any inserted MBB's and clear 2050 // SwitchCases. 2051 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2052 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2053 2054 SwitchCases.clear(); 2055 } 2056 } 2057 2058 // Create a CaseBlock record representing this branch. 2059 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2060 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2061 2062 // Use visitSwitchCase to actually insert the fast branch sequence for this 2063 // cond branch. 2064 visitSwitchCase(CB, BrMBB); 2065 } 2066 2067 /// visitSwitchCase - Emits the necessary code to represent a single node in 2068 /// the binary search tree resulting from lowering a switch instruction. 2069 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2070 MachineBasicBlock *SwitchBB) { 2071 SDValue Cond; 2072 SDValue CondLHS = getValue(CB.CmpLHS); 2073 SDLoc dl = CB.DL; 2074 2075 // Build the setcc now. 2076 if (!CB.CmpMHS) { 2077 // Fold "(X == true)" to X and "(X == false)" to !X to 2078 // handle common cases produced by branch lowering. 2079 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2080 CB.CC == ISD::SETEQ) 2081 Cond = CondLHS; 2082 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2083 CB.CC == ISD::SETEQ) { 2084 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2085 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2086 } else 2087 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2088 } else { 2089 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2090 2091 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2092 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2093 2094 SDValue CmpOp = getValue(CB.CmpMHS); 2095 EVT VT = CmpOp.getValueType(); 2096 2097 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2098 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2099 ISD::SETLE); 2100 } else { 2101 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2102 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2103 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2104 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2105 } 2106 } 2107 2108 // Update successor info 2109 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2110 // TrueBB and FalseBB are always different unless the incoming IR is 2111 // degenerate. This only happens when running llc on weird IR. 2112 if (CB.TrueBB != CB.FalseBB) 2113 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2114 SwitchBB->normalizeSuccProbs(); 2115 2116 // If the lhs block is the next block, invert the condition so that we can 2117 // fall through to the lhs instead of the rhs block. 2118 if (CB.TrueBB == NextBlock(SwitchBB)) { 2119 std::swap(CB.TrueBB, CB.FalseBB); 2120 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2121 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2122 } 2123 2124 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2125 MVT::Other, getControlRoot(), Cond, 2126 DAG.getBasicBlock(CB.TrueBB)); 2127 2128 // Insert the false branch. Do this even if it's a fall through branch, 2129 // this makes it easier to do DAG optimizations which require inverting 2130 // the branch condition. 2131 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2132 DAG.getBasicBlock(CB.FalseBB)); 2133 2134 DAG.setRoot(BrCond); 2135 } 2136 2137 /// visitJumpTable - Emit JumpTable node in the current MBB 2138 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2139 // Emit the code for the jump table 2140 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2141 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2142 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2143 JT.Reg, PTy); 2144 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2145 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2146 MVT::Other, Index.getValue(1), 2147 Table, Index); 2148 DAG.setRoot(BrJumpTable); 2149 } 2150 2151 /// visitJumpTableHeader - This function emits necessary code to produce index 2152 /// in the JumpTable from switch case. 2153 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2154 JumpTableHeader &JTH, 2155 MachineBasicBlock *SwitchBB) { 2156 SDLoc dl = getCurSDLoc(); 2157 2158 // Subtract the lowest switch case value from the value being switched on and 2159 // conditional branch to default mbb if the result is greater than the 2160 // difference between smallest and largest cases. 2161 SDValue SwitchOp = getValue(JTH.SValue); 2162 EVT VT = SwitchOp.getValueType(); 2163 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2164 DAG.getConstant(JTH.First, dl, VT)); 2165 2166 // The SDNode we just created, which holds the value being switched on minus 2167 // the smallest case value, needs to be copied to a virtual register so it 2168 // can be used as an index into the jump table in a subsequent basic block. 2169 // This value may be smaller or larger than the target's pointer type, and 2170 // therefore require extension or truncating. 2171 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2172 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2173 2174 unsigned JumpTableReg = 2175 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2176 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2177 JumpTableReg, SwitchOp); 2178 JT.Reg = JumpTableReg; 2179 2180 // Emit the range check for the jump table, and branch to the default block 2181 // for the switch statement if the value being switched on exceeds the largest 2182 // case in the switch. 2183 SDValue CMP = DAG.getSetCC( 2184 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2185 Sub.getValueType()), 2186 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2187 2188 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2189 MVT::Other, CopyTo, CMP, 2190 DAG.getBasicBlock(JT.Default)); 2191 2192 // Avoid emitting unnecessary branches to the next block. 2193 if (JT.MBB != NextBlock(SwitchBB)) 2194 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2195 DAG.getBasicBlock(JT.MBB)); 2196 2197 DAG.setRoot(BrCond); 2198 } 2199 2200 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2201 /// variable if there exists one. 2202 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2203 SDValue &Chain) { 2204 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2205 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2206 MachineFunction &MF = DAG.getMachineFunction(); 2207 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2208 MachineSDNode *Node = 2209 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2210 if (Global) { 2211 MachinePointerInfo MPInfo(Global); 2212 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2213 MachineMemOperand::MODereferenceable; 2214 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2215 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2216 DAG.setNodeMemRefs(Node, {MemRef}); 2217 } 2218 return SDValue(Node, 0); 2219 } 2220 2221 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2222 /// tail spliced into a stack protector check success bb. 2223 /// 2224 /// For a high level explanation of how this fits into the stack protector 2225 /// generation see the comment on the declaration of class 2226 /// StackProtectorDescriptor. 2227 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2228 MachineBasicBlock *ParentBB) { 2229 2230 // First create the loads to the guard/stack slot for the comparison. 2231 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2232 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2233 2234 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2235 int FI = MFI.getStackProtectorIndex(); 2236 2237 SDValue Guard; 2238 SDLoc dl = getCurSDLoc(); 2239 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2240 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2241 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2242 2243 // Generate code to load the content of the guard slot. 2244 SDValue GuardVal = DAG.getLoad( 2245 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2246 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2247 MachineMemOperand::MOVolatile); 2248 2249 if (TLI.useStackGuardXorFP()) 2250 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2251 2252 // Retrieve guard check function, nullptr if instrumentation is inlined. 2253 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2254 // The target provides a guard check function to validate the guard value. 2255 // Generate a call to that function with the content of the guard slot as 2256 // argument. 2257 auto *Fn = cast<Function>(GuardCheck); 2258 FunctionType *FnTy = Fn->getFunctionType(); 2259 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2260 2261 TargetLowering::ArgListTy Args; 2262 TargetLowering::ArgListEntry Entry; 2263 Entry.Node = GuardVal; 2264 Entry.Ty = FnTy->getParamType(0); 2265 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2266 Entry.IsInReg = true; 2267 Args.push_back(Entry); 2268 2269 TargetLowering::CallLoweringInfo CLI(DAG); 2270 CLI.setDebugLoc(getCurSDLoc()) 2271 .setChain(DAG.getEntryNode()) 2272 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2273 getValue(GuardCheck), std::move(Args)); 2274 2275 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2276 DAG.setRoot(Result.second); 2277 return; 2278 } 2279 2280 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2281 // Otherwise, emit a volatile load to retrieve the stack guard value. 2282 SDValue Chain = DAG.getEntryNode(); 2283 if (TLI.useLoadStackGuardNode()) { 2284 Guard = getLoadStackGuard(DAG, dl, Chain); 2285 } else { 2286 const Value *IRGuard = TLI.getSDagStackGuard(M); 2287 SDValue GuardPtr = getValue(IRGuard); 2288 2289 Guard = 2290 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2291 Align, MachineMemOperand::MOVolatile); 2292 } 2293 2294 // Perform the comparison via a subtract/getsetcc. 2295 EVT VT = Guard.getValueType(); 2296 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2297 2298 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2299 *DAG.getContext(), 2300 Sub.getValueType()), 2301 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2302 2303 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2304 // branch to failure MBB. 2305 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2306 MVT::Other, GuardVal.getOperand(0), 2307 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2308 // Otherwise branch to success MBB. 2309 SDValue Br = DAG.getNode(ISD::BR, dl, 2310 MVT::Other, BrCond, 2311 DAG.getBasicBlock(SPD.getSuccessMBB())); 2312 2313 DAG.setRoot(Br); 2314 } 2315 2316 /// Codegen the failure basic block for a stack protector check. 2317 /// 2318 /// A failure stack protector machine basic block consists simply of a call to 2319 /// __stack_chk_fail(). 2320 /// 2321 /// For a high level explanation of how this fits into the stack protector 2322 /// generation see the comment on the declaration of class 2323 /// StackProtectorDescriptor. 2324 void 2325 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2326 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2327 SDValue Chain = 2328 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2329 None, false, getCurSDLoc(), false, false).second; 2330 DAG.setRoot(Chain); 2331 } 2332 2333 /// visitBitTestHeader - This function emits necessary code to produce value 2334 /// suitable for "bit tests" 2335 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2336 MachineBasicBlock *SwitchBB) { 2337 SDLoc dl = getCurSDLoc(); 2338 2339 // Subtract the minimum value 2340 SDValue SwitchOp = getValue(B.SValue); 2341 EVT VT = SwitchOp.getValueType(); 2342 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2343 DAG.getConstant(B.First, dl, VT)); 2344 2345 // Check range 2346 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2347 SDValue RangeCmp = DAG.getSetCC( 2348 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2349 Sub.getValueType()), 2350 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2351 2352 // Determine the type of the test operands. 2353 bool UsePtrType = false; 2354 if (!TLI.isTypeLegal(VT)) 2355 UsePtrType = true; 2356 else { 2357 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2358 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2359 // Switch table case range are encoded into series of masks. 2360 // Just use pointer type, it's guaranteed to fit. 2361 UsePtrType = true; 2362 break; 2363 } 2364 } 2365 if (UsePtrType) { 2366 VT = TLI.getPointerTy(DAG.getDataLayout()); 2367 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2368 } 2369 2370 B.RegVT = VT.getSimpleVT(); 2371 B.Reg = FuncInfo.CreateReg(B.RegVT); 2372 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2373 2374 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2375 2376 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2377 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2378 SwitchBB->normalizeSuccProbs(); 2379 2380 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2381 MVT::Other, CopyTo, RangeCmp, 2382 DAG.getBasicBlock(B.Default)); 2383 2384 // Avoid emitting unnecessary branches to the next block. 2385 if (MBB != NextBlock(SwitchBB)) 2386 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2387 DAG.getBasicBlock(MBB)); 2388 2389 DAG.setRoot(BrRange); 2390 } 2391 2392 /// visitBitTestCase - this function produces one "bit test" 2393 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2394 MachineBasicBlock* NextMBB, 2395 BranchProbability BranchProbToNext, 2396 unsigned Reg, 2397 BitTestCase &B, 2398 MachineBasicBlock *SwitchBB) { 2399 SDLoc dl = getCurSDLoc(); 2400 MVT VT = BB.RegVT; 2401 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2402 SDValue Cmp; 2403 unsigned PopCount = countPopulation(B.Mask); 2404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2405 if (PopCount == 1) { 2406 // Testing for a single bit; just compare the shift count with what it 2407 // would need to be to shift a 1 bit in that position. 2408 Cmp = DAG.getSetCC( 2409 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2410 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2411 ISD::SETEQ); 2412 } else if (PopCount == BB.Range) { 2413 // There is only one zero bit in the range, test for it directly. 2414 Cmp = DAG.getSetCC( 2415 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2416 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2417 ISD::SETNE); 2418 } else { 2419 // Make desired shift 2420 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2421 DAG.getConstant(1, dl, VT), ShiftOp); 2422 2423 // Emit bit tests and jumps 2424 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2425 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2426 Cmp = DAG.getSetCC( 2427 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2428 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2429 } 2430 2431 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2432 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2433 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2434 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2435 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2436 // one as they are relative probabilities (and thus work more like weights), 2437 // and hence we need to normalize them to let the sum of them become one. 2438 SwitchBB->normalizeSuccProbs(); 2439 2440 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2441 MVT::Other, getControlRoot(), 2442 Cmp, DAG.getBasicBlock(B.TargetBB)); 2443 2444 // Avoid emitting unnecessary branches to the next block. 2445 if (NextMBB != NextBlock(SwitchBB)) 2446 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2447 DAG.getBasicBlock(NextMBB)); 2448 2449 DAG.setRoot(BrAnd); 2450 } 2451 2452 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2453 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2454 2455 // Retrieve successors. Look through artificial IR level blocks like 2456 // catchswitch for successors. 2457 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2458 const BasicBlock *EHPadBB = I.getSuccessor(1); 2459 2460 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2461 // have to do anything here to lower funclet bundles. 2462 assert(!I.hasOperandBundlesOtherThan( 2463 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2464 "Cannot lower invokes with arbitrary operand bundles yet!"); 2465 2466 const Value *Callee(I.getCalledValue()); 2467 const Function *Fn = dyn_cast<Function>(Callee); 2468 if (isa<InlineAsm>(Callee)) 2469 visitInlineAsm(&I); 2470 else if (Fn && Fn->isIntrinsic()) { 2471 switch (Fn->getIntrinsicID()) { 2472 default: 2473 llvm_unreachable("Cannot invoke this intrinsic"); 2474 case Intrinsic::donothing: 2475 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2476 break; 2477 case Intrinsic::experimental_patchpoint_void: 2478 case Intrinsic::experimental_patchpoint_i64: 2479 visitPatchpoint(&I, EHPadBB); 2480 break; 2481 case Intrinsic::experimental_gc_statepoint: 2482 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2483 break; 2484 } 2485 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2486 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2487 // Eventually we will support lowering the @llvm.experimental.deoptimize 2488 // intrinsic, and right now there are no plans to support other intrinsics 2489 // with deopt state. 2490 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2491 } else { 2492 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2493 } 2494 2495 // If the value of the invoke is used outside of its defining block, make it 2496 // available as a virtual register. 2497 // We already took care of the exported value for the statepoint instruction 2498 // during call to the LowerStatepoint. 2499 if (!isStatepoint(I)) { 2500 CopyToExportRegsIfNeeded(&I); 2501 } 2502 2503 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2504 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2505 BranchProbability EHPadBBProb = 2506 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2507 : BranchProbability::getZero(); 2508 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2509 2510 // Update successor info. 2511 addSuccessorWithProb(InvokeMBB, Return); 2512 for (auto &UnwindDest : UnwindDests) { 2513 UnwindDest.first->setIsEHPad(); 2514 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2515 } 2516 InvokeMBB->normalizeSuccProbs(); 2517 2518 // Drop into normal successor. 2519 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2520 MVT::Other, getControlRoot(), 2521 DAG.getBasicBlock(Return))); 2522 } 2523 2524 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2525 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2526 } 2527 2528 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2529 assert(FuncInfo.MBB->isEHPad() && 2530 "Call to landingpad not in landing pad!"); 2531 2532 // If there aren't registers to copy the values into (e.g., during SjLj 2533 // exceptions), then don't bother to create these DAG nodes. 2534 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2535 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2536 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2537 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2538 return; 2539 2540 // If landingpad's return type is token type, we don't create DAG nodes 2541 // for its exception pointer and selector value. The extraction of exception 2542 // pointer or selector value from token type landingpads is not currently 2543 // supported. 2544 if (LP.getType()->isTokenTy()) 2545 return; 2546 2547 SmallVector<EVT, 2> ValueVTs; 2548 SDLoc dl = getCurSDLoc(); 2549 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2550 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2551 2552 // Get the two live-in registers as SDValues. The physregs have already been 2553 // copied into virtual registers. 2554 SDValue Ops[2]; 2555 if (FuncInfo.ExceptionPointerVirtReg) { 2556 Ops[0] = DAG.getZExtOrTrunc( 2557 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2558 FuncInfo.ExceptionPointerVirtReg, 2559 TLI.getPointerTy(DAG.getDataLayout())), 2560 dl, ValueVTs[0]); 2561 } else { 2562 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2563 } 2564 Ops[1] = DAG.getZExtOrTrunc( 2565 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2566 FuncInfo.ExceptionSelectorVirtReg, 2567 TLI.getPointerTy(DAG.getDataLayout())), 2568 dl, ValueVTs[1]); 2569 2570 // Merge into one. 2571 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2572 DAG.getVTList(ValueVTs), Ops); 2573 setValue(&LP, Res); 2574 } 2575 2576 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2577 #ifndef NDEBUG 2578 for (const CaseCluster &CC : Clusters) 2579 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2580 #endif 2581 2582 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2583 return a.Low->getValue().slt(b.Low->getValue()); 2584 }); 2585 2586 // Merge adjacent clusters with the same destination. 2587 const unsigned N = Clusters.size(); 2588 unsigned DstIndex = 0; 2589 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2590 CaseCluster &CC = Clusters[SrcIndex]; 2591 const ConstantInt *CaseVal = CC.Low; 2592 MachineBasicBlock *Succ = CC.MBB; 2593 2594 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2595 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2596 // If this case has the same successor and is a neighbour, merge it into 2597 // the previous cluster. 2598 Clusters[DstIndex - 1].High = CaseVal; 2599 Clusters[DstIndex - 1].Prob += CC.Prob; 2600 } else { 2601 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2602 sizeof(Clusters[SrcIndex])); 2603 } 2604 } 2605 Clusters.resize(DstIndex); 2606 } 2607 2608 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2609 MachineBasicBlock *Last) { 2610 // Update JTCases. 2611 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2612 if (JTCases[i].first.HeaderBB == First) 2613 JTCases[i].first.HeaderBB = Last; 2614 2615 // Update BitTestCases. 2616 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2617 if (BitTestCases[i].Parent == First) 2618 BitTestCases[i].Parent = Last; 2619 } 2620 2621 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2622 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2623 2624 // Update machine-CFG edges with unique successors. 2625 SmallSet<BasicBlock*, 32> Done; 2626 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2627 BasicBlock *BB = I.getSuccessor(i); 2628 bool Inserted = Done.insert(BB).second; 2629 if (!Inserted) 2630 continue; 2631 2632 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2633 addSuccessorWithProb(IndirectBrMBB, Succ); 2634 } 2635 IndirectBrMBB->normalizeSuccProbs(); 2636 2637 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2638 MVT::Other, getControlRoot(), 2639 getValue(I.getAddress()))); 2640 } 2641 2642 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2643 if (!DAG.getTarget().Options.TrapUnreachable) 2644 return; 2645 2646 // We may be able to ignore unreachable behind a noreturn call. 2647 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2648 const BasicBlock &BB = *I.getParent(); 2649 if (&I != &BB.front()) { 2650 BasicBlock::const_iterator PredI = 2651 std::prev(BasicBlock::const_iterator(&I)); 2652 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2653 if (Call->doesNotReturn()) 2654 return; 2655 } 2656 } 2657 } 2658 2659 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2660 } 2661 2662 void SelectionDAGBuilder::visitFSub(const User &I) { 2663 // -0.0 - X --> fneg 2664 Type *Ty = I.getType(); 2665 if (isa<Constant>(I.getOperand(0)) && 2666 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2667 SDValue Op2 = getValue(I.getOperand(1)); 2668 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2669 Op2.getValueType(), Op2)); 2670 return; 2671 } 2672 2673 visitBinary(I, ISD::FSUB); 2674 } 2675 2676 /// Checks if the given instruction performs a vector reduction, in which case 2677 /// we have the freedom to alter the elements in the result as long as the 2678 /// reduction of them stays unchanged. 2679 static bool isVectorReductionOp(const User *I) { 2680 const Instruction *Inst = dyn_cast<Instruction>(I); 2681 if (!Inst || !Inst->getType()->isVectorTy()) 2682 return false; 2683 2684 auto OpCode = Inst->getOpcode(); 2685 switch (OpCode) { 2686 case Instruction::Add: 2687 case Instruction::Mul: 2688 case Instruction::And: 2689 case Instruction::Or: 2690 case Instruction::Xor: 2691 break; 2692 case Instruction::FAdd: 2693 case Instruction::FMul: 2694 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2695 if (FPOp->getFastMathFlags().isFast()) 2696 break; 2697 LLVM_FALLTHROUGH; 2698 default: 2699 return false; 2700 } 2701 2702 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2703 // Ensure the reduction size is a power of 2. 2704 if (!isPowerOf2_32(ElemNum)) 2705 return false; 2706 2707 unsigned ElemNumToReduce = ElemNum; 2708 2709 // Do DFS search on the def-use chain from the given instruction. We only 2710 // allow four kinds of operations during the search until we reach the 2711 // instruction that extracts the first element from the vector: 2712 // 2713 // 1. The reduction operation of the same opcode as the given instruction. 2714 // 2715 // 2. PHI node. 2716 // 2717 // 3. ShuffleVector instruction together with a reduction operation that 2718 // does a partial reduction. 2719 // 2720 // 4. ExtractElement that extracts the first element from the vector, and we 2721 // stop searching the def-use chain here. 2722 // 2723 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2724 // from 1-3 to the stack to continue the DFS. The given instruction is not 2725 // a reduction operation if we meet any other instructions other than those 2726 // listed above. 2727 2728 SmallVector<const User *, 16> UsersToVisit{Inst}; 2729 SmallPtrSet<const User *, 16> Visited; 2730 bool ReduxExtracted = false; 2731 2732 while (!UsersToVisit.empty()) { 2733 auto User = UsersToVisit.back(); 2734 UsersToVisit.pop_back(); 2735 if (!Visited.insert(User).second) 2736 continue; 2737 2738 for (const auto &U : User->users()) { 2739 auto Inst = dyn_cast<Instruction>(U); 2740 if (!Inst) 2741 return false; 2742 2743 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2744 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2745 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2746 return false; 2747 UsersToVisit.push_back(U); 2748 } else if (const ShuffleVectorInst *ShufInst = 2749 dyn_cast<ShuffleVectorInst>(U)) { 2750 // Detect the following pattern: A ShuffleVector instruction together 2751 // with a reduction that do partial reduction on the first and second 2752 // ElemNumToReduce / 2 elements, and store the result in 2753 // ElemNumToReduce / 2 elements in another vector. 2754 2755 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2756 if (ResultElements < ElemNum) 2757 return false; 2758 2759 if (ElemNumToReduce == 1) 2760 return false; 2761 if (!isa<UndefValue>(U->getOperand(1))) 2762 return false; 2763 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2764 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2765 return false; 2766 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2767 if (ShufInst->getMaskValue(i) != -1) 2768 return false; 2769 2770 // There is only one user of this ShuffleVector instruction, which 2771 // must be a reduction operation. 2772 if (!U->hasOneUse()) 2773 return false; 2774 2775 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2776 if (!U2 || U2->getOpcode() != OpCode) 2777 return false; 2778 2779 // Check operands of the reduction operation. 2780 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2781 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2782 UsersToVisit.push_back(U2); 2783 ElemNumToReduce /= 2; 2784 } else 2785 return false; 2786 } else if (isa<ExtractElementInst>(U)) { 2787 // At this moment we should have reduced all elements in the vector. 2788 if (ElemNumToReduce != 1) 2789 return false; 2790 2791 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2792 if (!Val || !Val->isZero()) 2793 return false; 2794 2795 ReduxExtracted = true; 2796 } else 2797 return false; 2798 } 2799 } 2800 return ReduxExtracted; 2801 } 2802 2803 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2804 SDNodeFlags Flags; 2805 2806 SDValue Op = getValue(I.getOperand(0)); 2807 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2808 Op, Flags); 2809 setValue(&I, UnNodeValue); 2810 } 2811 2812 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2813 SDNodeFlags Flags; 2814 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2815 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2816 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2817 } 2818 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2819 Flags.setExact(ExactOp->isExact()); 2820 } 2821 if (isVectorReductionOp(&I)) { 2822 Flags.setVectorReduction(true); 2823 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2824 } 2825 2826 SDValue Op1 = getValue(I.getOperand(0)); 2827 SDValue Op2 = getValue(I.getOperand(1)); 2828 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2829 Op1, Op2, Flags); 2830 setValue(&I, BinNodeValue); 2831 } 2832 2833 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2834 SDValue Op1 = getValue(I.getOperand(0)); 2835 SDValue Op2 = getValue(I.getOperand(1)); 2836 2837 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2838 Op1.getValueType(), DAG.getDataLayout()); 2839 2840 // Coerce the shift amount to the right type if we can. 2841 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2842 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2843 unsigned Op2Size = Op2.getValueSizeInBits(); 2844 SDLoc DL = getCurSDLoc(); 2845 2846 // If the operand is smaller than the shift count type, promote it. 2847 if (ShiftSize > Op2Size) 2848 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2849 2850 // If the operand is larger than the shift count type but the shift 2851 // count type has enough bits to represent any shift value, truncate 2852 // it now. This is a common case and it exposes the truncate to 2853 // optimization early. 2854 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2855 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2856 // Otherwise we'll need to temporarily settle for some other convenient 2857 // type. Type legalization will make adjustments once the shiftee is split. 2858 else 2859 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2860 } 2861 2862 bool nuw = false; 2863 bool nsw = false; 2864 bool exact = false; 2865 2866 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2867 2868 if (const OverflowingBinaryOperator *OFBinOp = 2869 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2870 nuw = OFBinOp->hasNoUnsignedWrap(); 2871 nsw = OFBinOp->hasNoSignedWrap(); 2872 } 2873 if (const PossiblyExactOperator *ExactOp = 2874 dyn_cast<const PossiblyExactOperator>(&I)) 2875 exact = ExactOp->isExact(); 2876 } 2877 SDNodeFlags Flags; 2878 Flags.setExact(exact); 2879 Flags.setNoSignedWrap(nsw); 2880 Flags.setNoUnsignedWrap(nuw); 2881 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2882 Flags); 2883 setValue(&I, Res); 2884 } 2885 2886 void SelectionDAGBuilder::visitSDiv(const User &I) { 2887 SDValue Op1 = getValue(I.getOperand(0)); 2888 SDValue Op2 = getValue(I.getOperand(1)); 2889 2890 SDNodeFlags Flags; 2891 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2892 cast<PossiblyExactOperator>(&I)->isExact()); 2893 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2894 Op2, Flags)); 2895 } 2896 2897 void SelectionDAGBuilder::visitICmp(const User &I) { 2898 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2899 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2900 predicate = IC->getPredicate(); 2901 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2902 predicate = ICmpInst::Predicate(IC->getPredicate()); 2903 SDValue Op1 = getValue(I.getOperand(0)); 2904 SDValue Op2 = getValue(I.getOperand(1)); 2905 ISD::CondCode Opcode = getICmpCondCode(predicate); 2906 2907 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2908 I.getType()); 2909 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2910 } 2911 2912 void SelectionDAGBuilder::visitFCmp(const User &I) { 2913 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2914 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2915 predicate = FC->getPredicate(); 2916 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2917 predicate = FCmpInst::Predicate(FC->getPredicate()); 2918 SDValue Op1 = getValue(I.getOperand(0)); 2919 SDValue Op2 = getValue(I.getOperand(1)); 2920 2921 ISD::CondCode Condition = getFCmpCondCode(predicate); 2922 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2923 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2924 Condition = getFCmpCodeWithoutNaN(Condition); 2925 2926 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2927 I.getType()); 2928 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2929 } 2930 2931 // Check if the condition of the select has one use or two users that are both 2932 // selects with the same condition. 2933 static bool hasOnlySelectUsers(const Value *Cond) { 2934 return llvm::all_of(Cond->users(), [](const Value *V) { 2935 return isa<SelectInst>(V); 2936 }); 2937 } 2938 2939 void SelectionDAGBuilder::visitSelect(const User &I) { 2940 SmallVector<EVT, 4> ValueVTs; 2941 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2942 ValueVTs); 2943 unsigned NumValues = ValueVTs.size(); 2944 if (NumValues == 0) return; 2945 2946 SmallVector<SDValue, 4> Values(NumValues); 2947 SDValue Cond = getValue(I.getOperand(0)); 2948 SDValue LHSVal = getValue(I.getOperand(1)); 2949 SDValue RHSVal = getValue(I.getOperand(2)); 2950 auto BaseOps = {Cond}; 2951 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2952 ISD::VSELECT : ISD::SELECT; 2953 2954 // Min/max matching is only viable if all output VTs are the same. 2955 if (is_splat(ValueVTs)) { 2956 EVT VT = ValueVTs[0]; 2957 LLVMContext &Ctx = *DAG.getContext(); 2958 auto &TLI = DAG.getTargetLoweringInfo(); 2959 2960 // We care about the legality of the operation after it has been type 2961 // legalized. 2962 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2963 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2964 VT = TLI.getTypeToTransformTo(Ctx, VT); 2965 2966 // If the vselect is legal, assume we want to leave this as a vector setcc + 2967 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2968 // min/max is legal on the scalar type. 2969 bool UseScalarMinMax = VT.isVector() && 2970 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2971 2972 Value *LHS, *RHS; 2973 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2974 ISD::NodeType Opc = ISD::DELETED_NODE; 2975 switch (SPR.Flavor) { 2976 case SPF_UMAX: Opc = ISD::UMAX; break; 2977 case SPF_UMIN: Opc = ISD::UMIN; break; 2978 case SPF_SMAX: Opc = ISD::SMAX; break; 2979 case SPF_SMIN: Opc = ISD::SMIN; break; 2980 case SPF_FMINNUM: 2981 switch (SPR.NaNBehavior) { 2982 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2983 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 2984 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2985 case SPNB_RETURNS_ANY: { 2986 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2987 Opc = ISD::FMINNUM; 2988 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 2989 Opc = ISD::FMINIMUM; 2990 else if (UseScalarMinMax) 2991 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2992 ISD::FMINNUM : ISD::FMINIMUM; 2993 break; 2994 } 2995 } 2996 break; 2997 case SPF_FMAXNUM: 2998 switch (SPR.NaNBehavior) { 2999 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3000 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3001 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3002 case SPNB_RETURNS_ANY: 3003 3004 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3005 Opc = ISD::FMAXNUM; 3006 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3007 Opc = ISD::FMAXIMUM; 3008 else if (UseScalarMinMax) 3009 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3010 ISD::FMAXNUM : ISD::FMAXIMUM; 3011 break; 3012 } 3013 break; 3014 default: break; 3015 } 3016 3017 if (Opc != ISD::DELETED_NODE && 3018 (TLI.isOperationLegalOrCustom(Opc, VT) || 3019 (UseScalarMinMax && 3020 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3021 // If the underlying comparison instruction is used by any other 3022 // instruction, the consumed instructions won't be destroyed, so it is 3023 // not profitable to convert to a min/max. 3024 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3025 OpCode = Opc; 3026 LHSVal = getValue(LHS); 3027 RHSVal = getValue(RHS); 3028 BaseOps = {}; 3029 } 3030 } 3031 3032 for (unsigned i = 0; i != NumValues; ++i) { 3033 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3034 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3035 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3036 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3037 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3038 Ops); 3039 } 3040 3041 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3042 DAG.getVTList(ValueVTs), Values)); 3043 } 3044 3045 void SelectionDAGBuilder::visitTrunc(const User &I) { 3046 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3047 SDValue N = getValue(I.getOperand(0)); 3048 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3049 I.getType()); 3050 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3051 } 3052 3053 void SelectionDAGBuilder::visitZExt(const User &I) { 3054 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3055 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3056 SDValue N = getValue(I.getOperand(0)); 3057 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3058 I.getType()); 3059 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3060 } 3061 3062 void SelectionDAGBuilder::visitSExt(const User &I) { 3063 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3064 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3065 SDValue N = getValue(I.getOperand(0)); 3066 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3067 I.getType()); 3068 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3069 } 3070 3071 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3072 // FPTrunc is never a no-op cast, no need to check 3073 SDValue N = getValue(I.getOperand(0)); 3074 SDLoc dl = getCurSDLoc(); 3075 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3076 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3077 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3078 DAG.getTargetConstant( 3079 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3080 } 3081 3082 void SelectionDAGBuilder::visitFPExt(const User &I) { 3083 // FPExt is never a no-op cast, no need to check 3084 SDValue N = getValue(I.getOperand(0)); 3085 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3086 I.getType()); 3087 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3088 } 3089 3090 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3091 // FPToUI is never a no-op cast, no need to check 3092 SDValue N = getValue(I.getOperand(0)); 3093 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3094 I.getType()); 3095 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3096 } 3097 3098 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3099 // FPToSI is never a no-op cast, no need to check 3100 SDValue N = getValue(I.getOperand(0)); 3101 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3102 I.getType()); 3103 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3104 } 3105 3106 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3107 // UIToFP is never a no-op cast, no need to check 3108 SDValue N = getValue(I.getOperand(0)); 3109 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3110 I.getType()); 3111 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3112 } 3113 3114 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3115 // SIToFP is never a no-op cast, no need to check 3116 SDValue N = getValue(I.getOperand(0)); 3117 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3118 I.getType()); 3119 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3120 } 3121 3122 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3123 // What to do depends on the size of the integer and the size of the pointer. 3124 // We can either truncate, zero extend, or no-op, accordingly. 3125 SDValue N = getValue(I.getOperand(0)); 3126 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3127 I.getType()); 3128 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3129 } 3130 3131 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3132 // What to do depends on the size of the integer and the size of the pointer. 3133 // We can either truncate, zero extend, or no-op, accordingly. 3134 SDValue N = getValue(I.getOperand(0)); 3135 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3136 I.getType()); 3137 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3138 } 3139 3140 void SelectionDAGBuilder::visitBitCast(const User &I) { 3141 SDValue N = getValue(I.getOperand(0)); 3142 SDLoc dl = getCurSDLoc(); 3143 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3144 I.getType()); 3145 3146 // BitCast assures us that source and destination are the same size so this is 3147 // either a BITCAST or a no-op. 3148 if (DestVT != N.getValueType()) 3149 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3150 DestVT, N)); // convert types. 3151 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3152 // might fold any kind of constant expression to an integer constant and that 3153 // is not what we are looking for. Only recognize a bitcast of a genuine 3154 // constant integer as an opaque constant. 3155 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3156 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3157 /*isOpaque*/true)); 3158 else 3159 setValue(&I, N); // noop cast. 3160 } 3161 3162 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3163 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3164 const Value *SV = I.getOperand(0); 3165 SDValue N = getValue(SV); 3166 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3167 3168 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3169 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3170 3171 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3172 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3173 3174 setValue(&I, N); 3175 } 3176 3177 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3178 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3179 SDValue InVec = getValue(I.getOperand(0)); 3180 SDValue InVal = getValue(I.getOperand(1)); 3181 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3182 TLI.getVectorIdxTy(DAG.getDataLayout())); 3183 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3184 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3185 InVec, InVal, InIdx)); 3186 } 3187 3188 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3189 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3190 SDValue InVec = getValue(I.getOperand(0)); 3191 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3192 TLI.getVectorIdxTy(DAG.getDataLayout())); 3193 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3194 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3195 InVec, InIdx)); 3196 } 3197 3198 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3199 SDValue Src1 = getValue(I.getOperand(0)); 3200 SDValue Src2 = getValue(I.getOperand(1)); 3201 SDLoc DL = getCurSDLoc(); 3202 3203 SmallVector<int, 8> Mask; 3204 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3205 unsigned MaskNumElts = Mask.size(); 3206 3207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3208 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3209 EVT SrcVT = Src1.getValueType(); 3210 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3211 3212 if (SrcNumElts == MaskNumElts) { 3213 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3214 return; 3215 } 3216 3217 // Normalize the shuffle vector since mask and vector length don't match. 3218 if (SrcNumElts < MaskNumElts) { 3219 // Mask is longer than the source vectors. We can use concatenate vector to 3220 // make the mask and vectors lengths match. 3221 3222 if (MaskNumElts % SrcNumElts == 0) { 3223 // Mask length is a multiple of the source vector length. 3224 // Check if the shuffle is some kind of concatenation of the input 3225 // vectors. 3226 unsigned NumConcat = MaskNumElts / SrcNumElts; 3227 bool IsConcat = true; 3228 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3229 for (unsigned i = 0; i != MaskNumElts; ++i) { 3230 int Idx = Mask[i]; 3231 if (Idx < 0) 3232 continue; 3233 // Ensure the indices in each SrcVT sized piece are sequential and that 3234 // the same source is used for the whole piece. 3235 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3236 (ConcatSrcs[i / SrcNumElts] >= 0 && 3237 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3238 IsConcat = false; 3239 break; 3240 } 3241 // Remember which source this index came from. 3242 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3243 } 3244 3245 // The shuffle is concatenating multiple vectors together. Just emit 3246 // a CONCAT_VECTORS operation. 3247 if (IsConcat) { 3248 SmallVector<SDValue, 8> ConcatOps; 3249 for (auto Src : ConcatSrcs) { 3250 if (Src < 0) 3251 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3252 else if (Src == 0) 3253 ConcatOps.push_back(Src1); 3254 else 3255 ConcatOps.push_back(Src2); 3256 } 3257 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3258 return; 3259 } 3260 } 3261 3262 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3263 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3264 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3265 PaddedMaskNumElts); 3266 3267 // Pad both vectors with undefs to make them the same length as the mask. 3268 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3269 3270 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3271 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3272 MOps1[0] = Src1; 3273 MOps2[0] = Src2; 3274 3275 Src1 = Src1.isUndef() 3276 ? DAG.getUNDEF(PaddedVT) 3277 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3278 Src2 = Src2.isUndef() 3279 ? DAG.getUNDEF(PaddedVT) 3280 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3281 3282 // Readjust mask for new input vector length. 3283 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3284 for (unsigned i = 0; i != MaskNumElts; ++i) { 3285 int Idx = Mask[i]; 3286 if (Idx >= (int)SrcNumElts) 3287 Idx -= SrcNumElts - PaddedMaskNumElts; 3288 MappedOps[i] = Idx; 3289 } 3290 3291 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3292 3293 // If the concatenated vector was padded, extract a subvector with the 3294 // correct number of elements. 3295 if (MaskNumElts != PaddedMaskNumElts) 3296 Result = DAG.getNode( 3297 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3298 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3299 3300 setValue(&I, Result); 3301 return; 3302 } 3303 3304 if (SrcNumElts > MaskNumElts) { 3305 // Analyze the access pattern of the vector to see if we can extract 3306 // two subvectors and do the shuffle. 3307 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3308 bool CanExtract = true; 3309 for (int Idx : Mask) { 3310 unsigned Input = 0; 3311 if (Idx < 0) 3312 continue; 3313 3314 if (Idx >= (int)SrcNumElts) { 3315 Input = 1; 3316 Idx -= SrcNumElts; 3317 } 3318 3319 // If all the indices come from the same MaskNumElts sized portion of 3320 // the sources we can use extract. Also make sure the extract wouldn't 3321 // extract past the end of the source. 3322 int NewStartIdx = alignDown(Idx, MaskNumElts); 3323 if (NewStartIdx + MaskNumElts > SrcNumElts || 3324 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3325 CanExtract = false; 3326 // Make sure we always update StartIdx as we use it to track if all 3327 // elements are undef. 3328 StartIdx[Input] = NewStartIdx; 3329 } 3330 3331 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3332 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3333 return; 3334 } 3335 if (CanExtract) { 3336 // Extract appropriate subvector and generate a vector shuffle 3337 for (unsigned Input = 0; Input < 2; ++Input) { 3338 SDValue &Src = Input == 0 ? Src1 : Src2; 3339 if (StartIdx[Input] < 0) 3340 Src = DAG.getUNDEF(VT); 3341 else { 3342 Src = DAG.getNode( 3343 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3344 DAG.getConstant(StartIdx[Input], DL, 3345 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3346 } 3347 } 3348 3349 // Calculate new mask. 3350 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3351 for (int &Idx : MappedOps) { 3352 if (Idx >= (int)SrcNumElts) 3353 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3354 else if (Idx >= 0) 3355 Idx -= StartIdx[0]; 3356 } 3357 3358 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3359 return; 3360 } 3361 } 3362 3363 // We can't use either concat vectors or extract subvectors so fall back to 3364 // replacing the shuffle with extract and build vector. 3365 // to insert and build vector. 3366 EVT EltVT = VT.getVectorElementType(); 3367 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3368 SmallVector<SDValue,8> Ops; 3369 for (int Idx : Mask) { 3370 SDValue Res; 3371 3372 if (Idx < 0) { 3373 Res = DAG.getUNDEF(EltVT); 3374 } else { 3375 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3376 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3377 3378 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3379 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3380 } 3381 3382 Ops.push_back(Res); 3383 } 3384 3385 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3386 } 3387 3388 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3389 ArrayRef<unsigned> Indices; 3390 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3391 Indices = IV->getIndices(); 3392 else 3393 Indices = cast<ConstantExpr>(&I)->getIndices(); 3394 3395 const Value *Op0 = I.getOperand(0); 3396 const Value *Op1 = I.getOperand(1); 3397 Type *AggTy = I.getType(); 3398 Type *ValTy = Op1->getType(); 3399 bool IntoUndef = isa<UndefValue>(Op0); 3400 bool FromUndef = isa<UndefValue>(Op1); 3401 3402 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3403 3404 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3405 SmallVector<EVT, 4> AggValueVTs; 3406 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3407 SmallVector<EVT, 4> ValValueVTs; 3408 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3409 3410 unsigned NumAggValues = AggValueVTs.size(); 3411 unsigned NumValValues = ValValueVTs.size(); 3412 SmallVector<SDValue, 4> Values(NumAggValues); 3413 3414 // Ignore an insertvalue that produces an empty object 3415 if (!NumAggValues) { 3416 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3417 return; 3418 } 3419 3420 SDValue Agg = getValue(Op0); 3421 unsigned i = 0; 3422 // Copy the beginning value(s) from the original aggregate. 3423 for (; i != LinearIndex; ++i) 3424 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3425 SDValue(Agg.getNode(), Agg.getResNo() + i); 3426 // Copy values from the inserted value(s). 3427 if (NumValValues) { 3428 SDValue Val = getValue(Op1); 3429 for (; i != LinearIndex + NumValValues; ++i) 3430 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3431 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3432 } 3433 // Copy remaining value(s) from the original aggregate. 3434 for (; i != NumAggValues; ++i) 3435 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3436 SDValue(Agg.getNode(), Agg.getResNo() + i); 3437 3438 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3439 DAG.getVTList(AggValueVTs), Values)); 3440 } 3441 3442 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3443 ArrayRef<unsigned> Indices; 3444 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3445 Indices = EV->getIndices(); 3446 else 3447 Indices = cast<ConstantExpr>(&I)->getIndices(); 3448 3449 const Value *Op0 = I.getOperand(0); 3450 Type *AggTy = Op0->getType(); 3451 Type *ValTy = I.getType(); 3452 bool OutOfUndef = isa<UndefValue>(Op0); 3453 3454 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3455 3456 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3457 SmallVector<EVT, 4> ValValueVTs; 3458 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3459 3460 unsigned NumValValues = ValValueVTs.size(); 3461 3462 // Ignore a extractvalue that produces an empty object 3463 if (!NumValValues) { 3464 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3465 return; 3466 } 3467 3468 SmallVector<SDValue, 4> Values(NumValValues); 3469 3470 SDValue Agg = getValue(Op0); 3471 // Copy out the selected value(s). 3472 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3473 Values[i - LinearIndex] = 3474 OutOfUndef ? 3475 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3476 SDValue(Agg.getNode(), Agg.getResNo() + i); 3477 3478 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3479 DAG.getVTList(ValValueVTs), Values)); 3480 } 3481 3482 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3483 Value *Op0 = I.getOperand(0); 3484 // Note that the pointer operand may be a vector of pointers. Take the scalar 3485 // element which holds a pointer. 3486 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3487 SDValue N = getValue(Op0); 3488 SDLoc dl = getCurSDLoc(); 3489 3490 // Normalize Vector GEP - all scalar operands should be converted to the 3491 // splat vector. 3492 unsigned VectorWidth = I.getType()->isVectorTy() ? 3493 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3494 3495 if (VectorWidth && !N.getValueType().isVector()) { 3496 LLVMContext &Context = *DAG.getContext(); 3497 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3498 N = DAG.getSplatBuildVector(VT, dl, N); 3499 } 3500 3501 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3502 GTI != E; ++GTI) { 3503 const Value *Idx = GTI.getOperand(); 3504 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3505 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3506 if (Field) { 3507 // N = N + Offset 3508 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3509 3510 // In an inbounds GEP with an offset that is nonnegative even when 3511 // interpreted as signed, assume there is no unsigned overflow. 3512 SDNodeFlags Flags; 3513 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3514 Flags.setNoUnsignedWrap(true); 3515 3516 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3517 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3518 } 3519 } else { 3520 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3521 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3522 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3523 3524 // If this is a scalar constant or a splat vector of constants, 3525 // handle it quickly. 3526 const auto *CI = dyn_cast<ConstantInt>(Idx); 3527 if (!CI && isa<ConstantDataVector>(Idx) && 3528 cast<ConstantDataVector>(Idx)->getSplatValue()) 3529 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3530 3531 if (CI) { 3532 if (CI->isZero()) 3533 continue; 3534 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3535 LLVMContext &Context = *DAG.getContext(); 3536 SDValue OffsVal = VectorWidth ? 3537 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3538 DAG.getConstant(Offs, dl, IdxTy); 3539 3540 // In an inbouds GEP with an offset that is nonnegative even when 3541 // interpreted as signed, assume there is no unsigned overflow. 3542 SDNodeFlags Flags; 3543 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3544 Flags.setNoUnsignedWrap(true); 3545 3546 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3547 continue; 3548 } 3549 3550 // N = N + Idx * ElementSize; 3551 SDValue IdxN = getValue(Idx); 3552 3553 if (!IdxN.getValueType().isVector() && VectorWidth) { 3554 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3555 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3556 } 3557 3558 // If the index is smaller or larger than intptr_t, truncate or extend 3559 // it. 3560 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3561 3562 // If this is a multiply by a power of two, turn it into a shl 3563 // immediately. This is a very common case. 3564 if (ElementSize != 1) { 3565 if (ElementSize.isPowerOf2()) { 3566 unsigned Amt = ElementSize.logBase2(); 3567 IdxN = DAG.getNode(ISD::SHL, dl, 3568 N.getValueType(), IdxN, 3569 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3570 } else { 3571 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3572 IdxN = DAG.getNode(ISD::MUL, dl, 3573 N.getValueType(), IdxN, Scale); 3574 } 3575 } 3576 3577 N = DAG.getNode(ISD::ADD, dl, 3578 N.getValueType(), N, IdxN); 3579 } 3580 } 3581 3582 setValue(&I, N); 3583 } 3584 3585 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3586 // If this is a fixed sized alloca in the entry block of the function, 3587 // allocate it statically on the stack. 3588 if (FuncInfo.StaticAllocaMap.count(&I)) 3589 return; // getValue will auto-populate this. 3590 3591 SDLoc dl = getCurSDLoc(); 3592 Type *Ty = I.getAllocatedType(); 3593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3594 auto &DL = DAG.getDataLayout(); 3595 uint64_t TySize = DL.getTypeAllocSize(Ty); 3596 unsigned Align = 3597 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3598 3599 SDValue AllocSize = getValue(I.getArraySize()); 3600 3601 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3602 if (AllocSize.getValueType() != IntPtr) 3603 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3604 3605 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3606 AllocSize, 3607 DAG.getConstant(TySize, dl, IntPtr)); 3608 3609 // Handle alignment. If the requested alignment is less than or equal to 3610 // the stack alignment, ignore it. If the size is greater than or equal to 3611 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3612 unsigned StackAlign = 3613 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3614 if (Align <= StackAlign) 3615 Align = 0; 3616 3617 // Round the size of the allocation up to the stack alignment size 3618 // by add SA-1 to the size. This doesn't overflow because we're computing 3619 // an address inside an alloca. 3620 SDNodeFlags Flags; 3621 Flags.setNoUnsignedWrap(true); 3622 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3623 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3624 3625 // Mask out the low bits for alignment purposes. 3626 AllocSize = 3627 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3628 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3629 3630 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3631 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3632 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3633 setValue(&I, DSA); 3634 DAG.setRoot(DSA.getValue(1)); 3635 3636 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3637 } 3638 3639 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3640 if (I.isAtomic()) 3641 return visitAtomicLoad(I); 3642 3643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3644 const Value *SV = I.getOperand(0); 3645 if (TLI.supportSwiftError()) { 3646 // Swifterror values can come from either a function parameter with 3647 // swifterror attribute or an alloca with swifterror attribute. 3648 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3649 if (Arg->hasSwiftErrorAttr()) 3650 return visitLoadFromSwiftError(I); 3651 } 3652 3653 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3654 if (Alloca->isSwiftError()) 3655 return visitLoadFromSwiftError(I); 3656 } 3657 } 3658 3659 SDValue Ptr = getValue(SV); 3660 3661 Type *Ty = I.getType(); 3662 3663 bool isVolatile = I.isVolatile(); 3664 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3665 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3666 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3667 unsigned Alignment = I.getAlignment(); 3668 3669 AAMDNodes AAInfo; 3670 I.getAAMetadata(AAInfo); 3671 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3672 3673 SmallVector<EVT, 4> ValueVTs; 3674 SmallVector<uint64_t, 4> Offsets; 3675 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3676 unsigned NumValues = ValueVTs.size(); 3677 if (NumValues == 0) 3678 return; 3679 3680 SDValue Root; 3681 bool ConstantMemory = false; 3682 if (isVolatile || NumValues > MaxParallelChains) 3683 // Serialize volatile loads with other side effects. 3684 Root = getRoot(); 3685 else if (AA && 3686 AA->pointsToConstantMemory(MemoryLocation( 3687 SV, 3688 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3689 AAInfo))) { 3690 // Do not serialize (non-volatile) loads of constant memory with anything. 3691 Root = DAG.getEntryNode(); 3692 ConstantMemory = true; 3693 } else { 3694 // Do not serialize non-volatile loads against each other. 3695 Root = DAG.getRoot(); 3696 } 3697 3698 SDLoc dl = getCurSDLoc(); 3699 3700 if (isVolatile) 3701 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3702 3703 // An aggregate load cannot wrap around the address space, so offsets to its 3704 // parts don't wrap either. 3705 SDNodeFlags Flags; 3706 Flags.setNoUnsignedWrap(true); 3707 3708 SmallVector<SDValue, 4> Values(NumValues); 3709 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3710 EVT PtrVT = Ptr.getValueType(); 3711 unsigned ChainI = 0; 3712 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3713 // Serializing loads here may result in excessive register pressure, and 3714 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3715 // could recover a bit by hoisting nodes upward in the chain by recognizing 3716 // they are side-effect free or do not alias. The optimizer should really 3717 // avoid this case by converting large object/array copies to llvm.memcpy 3718 // (MaxParallelChains should always remain as failsafe). 3719 if (ChainI == MaxParallelChains) { 3720 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3721 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3722 makeArrayRef(Chains.data(), ChainI)); 3723 Root = Chain; 3724 ChainI = 0; 3725 } 3726 SDValue A = DAG.getNode(ISD::ADD, dl, 3727 PtrVT, Ptr, 3728 DAG.getConstant(Offsets[i], dl, PtrVT), 3729 Flags); 3730 auto MMOFlags = MachineMemOperand::MONone; 3731 if (isVolatile) 3732 MMOFlags |= MachineMemOperand::MOVolatile; 3733 if (isNonTemporal) 3734 MMOFlags |= MachineMemOperand::MONonTemporal; 3735 if (isInvariant) 3736 MMOFlags |= MachineMemOperand::MOInvariant; 3737 if (isDereferenceable) 3738 MMOFlags |= MachineMemOperand::MODereferenceable; 3739 MMOFlags |= TLI.getMMOFlags(I); 3740 3741 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3742 MachinePointerInfo(SV, Offsets[i]), Alignment, 3743 MMOFlags, AAInfo, Ranges); 3744 3745 Values[i] = L; 3746 Chains[ChainI] = L.getValue(1); 3747 } 3748 3749 if (!ConstantMemory) { 3750 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3751 makeArrayRef(Chains.data(), ChainI)); 3752 if (isVolatile) 3753 DAG.setRoot(Chain); 3754 else 3755 PendingLoads.push_back(Chain); 3756 } 3757 3758 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3759 DAG.getVTList(ValueVTs), Values)); 3760 } 3761 3762 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3763 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3764 "call visitStoreToSwiftError when backend supports swifterror"); 3765 3766 SmallVector<EVT, 4> ValueVTs; 3767 SmallVector<uint64_t, 4> Offsets; 3768 const Value *SrcV = I.getOperand(0); 3769 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3770 SrcV->getType(), ValueVTs, &Offsets); 3771 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3772 "expect a single EVT for swifterror"); 3773 3774 SDValue Src = getValue(SrcV); 3775 // Create a virtual register, then update the virtual register. 3776 unsigned VReg; bool CreatedVReg; 3777 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3778 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3779 // Chain can be getRoot or getControlRoot. 3780 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3781 SDValue(Src.getNode(), Src.getResNo())); 3782 DAG.setRoot(CopyNode); 3783 if (CreatedVReg) 3784 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3785 } 3786 3787 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3788 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3789 "call visitLoadFromSwiftError when backend supports swifterror"); 3790 3791 assert(!I.isVolatile() && 3792 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3793 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3794 "Support volatile, non temporal, invariant for load_from_swift_error"); 3795 3796 const Value *SV = I.getOperand(0); 3797 Type *Ty = I.getType(); 3798 AAMDNodes AAInfo; 3799 I.getAAMetadata(AAInfo); 3800 assert( 3801 (!AA || 3802 !AA->pointsToConstantMemory(MemoryLocation( 3803 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3804 AAInfo))) && 3805 "load_from_swift_error should not be constant memory"); 3806 3807 SmallVector<EVT, 4> ValueVTs; 3808 SmallVector<uint64_t, 4> Offsets; 3809 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3810 ValueVTs, &Offsets); 3811 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3812 "expect a single EVT for swifterror"); 3813 3814 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3815 SDValue L = DAG.getCopyFromReg( 3816 getRoot(), getCurSDLoc(), 3817 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3818 ValueVTs[0]); 3819 3820 setValue(&I, L); 3821 } 3822 3823 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3824 if (I.isAtomic()) 3825 return visitAtomicStore(I); 3826 3827 const Value *SrcV = I.getOperand(0); 3828 const Value *PtrV = I.getOperand(1); 3829 3830 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3831 if (TLI.supportSwiftError()) { 3832 // Swifterror values can come from either a function parameter with 3833 // swifterror attribute or an alloca with swifterror attribute. 3834 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3835 if (Arg->hasSwiftErrorAttr()) 3836 return visitStoreToSwiftError(I); 3837 } 3838 3839 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3840 if (Alloca->isSwiftError()) 3841 return visitStoreToSwiftError(I); 3842 } 3843 } 3844 3845 SmallVector<EVT, 4> ValueVTs; 3846 SmallVector<uint64_t, 4> Offsets; 3847 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3848 SrcV->getType(), ValueVTs, &Offsets); 3849 unsigned NumValues = ValueVTs.size(); 3850 if (NumValues == 0) 3851 return; 3852 3853 // Get the lowered operands. Note that we do this after 3854 // checking if NumResults is zero, because with zero results 3855 // the operands won't have values in the map. 3856 SDValue Src = getValue(SrcV); 3857 SDValue Ptr = getValue(PtrV); 3858 3859 SDValue Root = getRoot(); 3860 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3861 SDLoc dl = getCurSDLoc(); 3862 EVT PtrVT = Ptr.getValueType(); 3863 unsigned Alignment = I.getAlignment(); 3864 AAMDNodes AAInfo; 3865 I.getAAMetadata(AAInfo); 3866 3867 auto MMOFlags = MachineMemOperand::MONone; 3868 if (I.isVolatile()) 3869 MMOFlags |= MachineMemOperand::MOVolatile; 3870 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3871 MMOFlags |= MachineMemOperand::MONonTemporal; 3872 MMOFlags |= TLI.getMMOFlags(I); 3873 3874 // An aggregate load cannot wrap around the address space, so offsets to its 3875 // parts don't wrap either. 3876 SDNodeFlags Flags; 3877 Flags.setNoUnsignedWrap(true); 3878 3879 unsigned ChainI = 0; 3880 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3881 // See visitLoad comments. 3882 if (ChainI == MaxParallelChains) { 3883 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3884 makeArrayRef(Chains.data(), ChainI)); 3885 Root = Chain; 3886 ChainI = 0; 3887 } 3888 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3889 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3890 SDValue St = DAG.getStore( 3891 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3892 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3893 Chains[ChainI] = St; 3894 } 3895 3896 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3897 makeArrayRef(Chains.data(), ChainI)); 3898 DAG.setRoot(StoreNode); 3899 } 3900 3901 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3902 bool IsCompressing) { 3903 SDLoc sdl = getCurSDLoc(); 3904 3905 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3906 unsigned& Alignment) { 3907 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3908 Src0 = I.getArgOperand(0); 3909 Ptr = I.getArgOperand(1); 3910 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3911 Mask = I.getArgOperand(3); 3912 }; 3913 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3914 unsigned& Alignment) { 3915 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3916 Src0 = I.getArgOperand(0); 3917 Ptr = I.getArgOperand(1); 3918 Mask = I.getArgOperand(2); 3919 Alignment = 0; 3920 }; 3921 3922 Value *PtrOperand, *MaskOperand, *Src0Operand; 3923 unsigned Alignment; 3924 if (IsCompressing) 3925 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3926 else 3927 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3928 3929 SDValue Ptr = getValue(PtrOperand); 3930 SDValue Src0 = getValue(Src0Operand); 3931 SDValue Mask = getValue(MaskOperand); 3932 3933 EVT VT = Src0.getValueType(); 3934 if (!Alignment) 3935 Alignment = DAG.getEVTAlignment(VT); 3936 3937 AAMDNodes AAInfo; 3938 I.getAAMetadata(AAInfo); 3939 3940 MachineMemOperand *MMO = 3941 DAG.getMachineFunction(). 3942 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3943 MachineMemOperand::MOStore, VT.getStoreSize(), 3944 Alignment, AAInfo); 3945 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3946 MMO, false /* Truncating */, 3947 IsCompressing); 3948 DAG.setRoot(StoreNode); 3949 setValue(&I, StoreNode); 3950 } 3951 3952 // Get a uniform base for the Gather/Scatter intrinsic. 3953 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3954 // We try to represent it as a base pointer + vector of indices. 3955 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3956 // The first operand of the GEP may be a single pointer or a vector of pointers 3957 // Example: 3958 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3959 // or 3960 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3961 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3962 // 3963 // When the first GEP operand is a single pointer - it is the uniform base we 3964 // are looking for. If first operand of the GEP is a splat vector - we 3965 // extract the splat value and use it as a uniform base. 3966 // In all other cases the function returns 'false'. 3967 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3968 SDValue &Scale, SelectionDAGBuilder* SDB) { 3969 SelectionDAG& DAG = SDB->DAG; 3970 LLVMContext &Context = *DAG.getContext(); 3971 3972 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3973 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3974 if (!GEP) 3975 return false; 3976 3977 const Value *GEPPtr = GEP->getPointerOperand(); 3978 if (!GEPPtr->getType()->isVectorTy()) 3979 Ptr = GEPPtr; 3980 else if (!(Ptr = getSplatValue(GEPPtr))) 3981 return false; 3982 3983 unsigned FinalIndex = GEP->getNumOperands() - 1; 3984 Value *IndexVal = GEP->getOperand(FinalIndex); 3985 3986 // Ensure all the other indices are 0. 3987 for (unsigned i = 1; i < FinalIndex; ++i) { 3988 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3989 if (!C || !C->isZero()) 3990 return false; 3991 } 3992 3993 // The operands of the GEP may be defined in another basic block. 3994 // In this case we'll not find nodes for the operands. 3995 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3996 return false; 3997 3998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3999 const DataLayout &DL = DAG.getDataLayout(); 4000 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4001 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4002 Base = SDB->getValue(Ptr); 4003 Index = SDB->getValue(IndexVal); 4004 4005 if (!Index.getValueType().isVector()) { 4006 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4007 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4008 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4009 } 4010 return true; 4011 } 4012 4013 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4014 SDLoc sdl = getCurSDLoc(); 4015 4016 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4017 const Value *Ptr = I.getArgOperand(1); 4018 SDValue Src0 = getValue(I.getArgOperand(0)); 4019 SDValue Mask = getValue(I.getArgOperand(3)); 4020 EVT VT = Src0.getValueType(); 4021 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4022 if (!Alignment) 4023 Alignment = DAG.getEVTAlignment(VT); 4024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4025 4026 AAMDNodes AAInfo; 4027 I.getAAMetadata(AAInfo); 4028 4029 SDValue Base; 4030 SDValue Index; 4031 SDValue Scale; 4032 const Value *BasePtr = Ptr; 4033 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4034 4035 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4036 MachineMemOperand *MMO = DAG.getMachineFunction(). 4037 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4038 MachineMemOperand::MOStore, VT.getStoreSize(), 4039 Alignment, AAInfo); 4040 if (!UniformBase) { 4041 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4042 Index = getValue(Ptr); 4043 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4044 } 4045 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4046 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4047 Ops, MMO); 4048 DAG.setRoot(Scatter); 4049 setValue(&I, Scatter); 4050 } 4051 4052 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4053 SDLoc sdl = getCurSDLoc(); 4054 4055 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4056 unsigned& Alignment) { 4057 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4058 Ptr = I.getArgOperand(0); 4059 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4060 Mask = I.getArgOperand(2); 4061 Src0 = I.getArgOperand(3); 4062 }; 4063 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4064 unsigned& Alignment) { 4065 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4066 Ptr = I.getArgOperand(0); 4067 Alignment = 0; 4068 Mask = I.getArgOperand(1); 4069 Src0 = I.getArgOperand(2); 4070 }; 4071 4072 Value *PtrOperand, *MaskOperand, *Src0Operand; 4073 unsigned Alignment; 4074 if (IsExpanding) 4075 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4076 else 4077 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4078 4079 SDValue Ptr = getValue(PtrOperand); 4080 SDValue Src0 = getValue(Src0Operand); 4081 SDValue Mask = getValue(MaskOperand); 4082 4083 EVT VT = Src0.getValueType(); 4084 if (!Alignment) 4085 Alignment = DAG.getEVTAlignment(VT); 4086 4087 AAMDNodes AAInfo; 4088 I.getAAMetadata(AAInfo); 4089 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4090 4091 // Do not serialize masked loads of constant memory with anything. 4092 bool AddToChain = 4093 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4094 PtrOperand, 4095 LocationSize::precise( 4096 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4097 AAInfo)); 4098 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4099 4100 MachineMemOperand *MMO = 4101 DAG.getMachineFunction(). 4102 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4103 MachineMemOperand::MOLoad, VT.getStoreSize(), 4104 Alignment, AAInfo, Ranges); 4105 4106 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4107 ISD::NON_EXTLOAD, IsExpanding); 4108 if (AddToChain) 4109 PendingLoads.push_back(Load.getValue(1)); 4110 setValue(&I, Load); 4111 } 4112 4113 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4114 SDLoc sdl = getCurSDLoc(); 4115 4116 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4117 const Value *Ptr = I.getArgOperand(0); 4118 SDValue Src0 = getValue(I.getArgOperand(3)); 4119 SDValue Mask = getValue(I.getArgOperand(2)); 4120 4121 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4122 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4123 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4124 if (!Alignment) 4125 Alignment = DAG.getEVTAlignment(VT); 4126 4127 AAMDNodes AAInfo; 4128 I.getAAMetadata(AAInfo); 4129 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4130 4131 SDValue Root = DAG.getRoot(); 4132 SDValue Base; 4133 SDValue Index; 4134 SDValue Scale; 4135 const Value *BasePtr = Ptr; 4136 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4137 bool ConstantMemory = false; 4138 if (UniformBase && AA && 4139 AA->pointsToConstantMemory( 4140 MemoryLocation(BasePtr, 4141 LocationSize::precise( 4142 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4143 AAInfo))) { 4144 // Do not serialize (non-volatile) loads of constant memory with anything. 4145 Root = DAG.getEntryNode(); 4146 ConstantMemory = true; 4147 } 4148 4149 MachineMemOperand *MMO = 4150 DAG.getMachineFunction(). 4151 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4152 MachineMemOperand::MOLoad, VT.getStoreSize(), 4153 Alignment, AAInfo, Ranges); 4154 4155 if (!UniformBase) { 4156 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4157 Index = getValue(Ptr); 4158 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4159 } 4160 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4161 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4162 Ops, MMO); 4163 4164 SDValue OutChain = Gather.getValue(1); 4165 if (!ConstantMemory) 4166 PendingLoads.push_back(OutChain); 4167 setValue(&I, Gather); 4168 } 4169 4170 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4171 SDLoc dl = getCurSDLoc(); 4172 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4173 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4174 SyncScope::ID SSID = I.getSyncScopeID(); 4175 4176 SDValue InChain = getRoot(); 4177 4178 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4179 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4180 SDValue L = DAG.getAtomicCmpSwap( 4181 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4182 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4183 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4184 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4185 4186 SDValue OutChain = L.getValue(2); 4187 4188 setValue(&I, L); 4189 DAG.setRoot(OutChain); 4190 } 4191 4192 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4193 SDLoc dl = getCurSDLoc(); 4194 ISD::NodeType NT; 4195 switch (I.getOperation()) { 4196 default: llvm_unreachable("Unknown atomicrmw operation"); 4197 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4198 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4199 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4200 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4201 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4202 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4203 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4204 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4205 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4206 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4207 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4208 } 4209 AtomicOrdering Order = I.getOrdering(); 4210 SyncScope::ID SSID = I.getSyncScopeID(); 4211 4212 SDValue InChain = getRoot(); 4213 4214 SDValue L = 4215 DAG.getAtomic(NT, dl, 4216 getValue(I.getValOperand()).getSimpleValueType(), 4217 InChain, 4218 getValue(I.getPointerOperand()), 4219 getValue(I.getValOperand()), 4220 I.getPointerOperand(), 4221 /* Alignment=*/ 0, Order, SSID); 4222 4223 SDValue OutChain = L.getValue(1); 4224 4225 setValue(&I, L); 4226 DAG.setRoot(OutChain); 4227 } 4228 4229 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4230 SDLoc dl = getCurSDLoc(); 4231 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4232 SDValue Ops[3]; 4233 Ops[0] = getRoot(); 4234 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4235 TLI.getFenceOperandTy(DAG.getDataLayout())); 4236 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4237 TLI.getFenceOperandTy(DAG.getDataLayout())); 4238 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4239 } 4240 4241 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4242 SDLoc dl = getCurSDLoc(); 4243 AtomicOrdering Order = I.getOrdering(); 4244 SyncScope::ID SSID = I.getSyncScopeID(); 4245 4246 SDValue InChain = getRoot(); 4247 4248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4249 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4250 4251 if (!TLI.supportsUnalignedAtomics() && 4252 I.getAlignment() < VT.getStoreSize()) 4253 report_fatal_error("Cannot generate unaligned atomic load"); 4254 4255 MachineMemOperand *MMO = 4256 DAG.getMachineFunction(). 4257 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4258 MachineMemOperand::MOVolatile | 4259 MachineMemOperand::MOLoad, 4260 VT.getStoreSize(), 4261 I.getAlignment() ? I.getAlignment() : 4262 DAG.getEVTAlignment(VT), 4263 AAMDNodes(), nullptr, SSID, Order); 4264 4265 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4266 SDValue L = 4267 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4268 getValue(I.getPointerOperand()), MMO); 4269 4270 SDValue OutChain = L.getValue(1); 4271 4272 setValue(&I, L); 4273 DAG.setRoot(OutChain); 4274 } 4275 4276 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4277 SDLoc dl = getCurSDLoc(); 4278 4279 AtomicOrdering Order = I.getOrdering(); 4280 SyncScope::ID SSID = I.getSyncScopeID(); 4281 4282 SDValue InChain = getRoot(); 4283 4284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4285 EVT VT = 4286 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4287 4288 if (I.getAlignment() < VT.getStoreSize()) 4289 report_fatal_error("Cannot generate unaligned atomic store"); 4290 4291 SDValue OutChain = 4292 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4293 InChain, 4294 getValue(I.getPointerOperand()), 4295 getValue(I.getValueOperand()), 4296 I.getPointerOperand(), I.getAlignment(), 4297 Order, SSID); 4298 4299 DAG.setRoot(OutChain); 4300 } 4301 4302 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4303 /// node. 4304 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4305 unsigned Intrinsic) { 4306 // Ignore the callsite's attributes. A specific call site may be marked with 4307 // readnone, but the lowering code will expect the chain based on the 4308 // definition. 4309 const Function *F = I.getCalledFunction(); 4310 bool HasChain = !F->doesNotAccessMemory(); 4311 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4312 4313 // Build the operand list. 4314 SmallVector<SDValue, 8> Ops; 4315 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4316 if (OnlyLoad) { 4317 // We don't need to serialize loads against other loads. 4318 Ops.push_back(DAG.getRoot()); 4319 } else { 4320 Ops.push_back(getRoot()); 4321 } 4322 } 4323 4324 // Info is set by getTgtMemInstrinsic 4325 TargetLowering::IntrinsicInfo Info; 4326 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4327 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4328 DAG.getMachineFunction(), 4329 Intrinsic); 4330 4331 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4332 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4333 Info.opc == ISD::INTRINSIC_W_CHAIN) 4334 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4335 TLI.getPointerTy(DAG.getDataLayout()))); 4336 4337 // Add all operands of the call to the operand list. 4338 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4339 SDValue Op = getValue(I.getArgOperand(i)); 4340 Ops.push_back(Op); 4341 } 4342 4343 SmallVector<EVT, 4> ValueVTs; 4344 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4345 4346 if (HasChain) 4347 ValueVTs.push_back(MVT::Other); 4348 4349 SDVTList VTs = DAG.getVTList(ValueVTs); 4350 4351 // Create the node. 4352 SDValue Result; 4353 if (IsTgtIntrinsic) { 4354 // This is target intrinsic that touches memory 4355 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4356 Ops, Info.memVT, 4357 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4358 Info.flags, Info.size); 4359 } else if (!HasChain) { 4360 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4361 } else if (!I.getType()->isVoidTy()) { 4362 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4363 } else { 4364 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4365 } 4366 4367 if (HasChain) { 4368 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4369 if (OnlyLoad) 4370 PendingLoads.push_back(Chain); 4371 else 4372 DAG.setRoot(Chain); 4373 } 4374 4375 if (!I.getType()->isVoidTy()) { 4376 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4377 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4378 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4379 } else 4380 Result = lowerRangeToAssertZExt(DAG, I, Result); 4381 4382 setValue(&I, Result); 4383 } 4384 } 4385 4386 /// GetSignificand - Get the significand and build it into a floating-point 4387 /// number with exponent of 1: 4388 /// 4389 /// Op = (Op & 0x007fffff) | 0x3f800000; 4390 /// 4391 /// where Op is the hexadecimal representation of floating point value. 4392 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4393 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4394 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4395 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4396 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4397 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4398 } 4399 4400 /// GetExponent - Get the exponent: 4401 /// 4402 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4403 /// 4404 /// where Op is the hexadecimal representation of floating point value. 4405 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4406 const TargetLowering &TLI, const SDLoc &dl) { 4407 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4408 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4409 SDValue t1 = DAG.getNode( 4410 ISD::SRL, dl, MVT::i32, t0, 4411 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4412 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4413 DAG.getConstant(127, dl, MVT::i32)); 4414 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4415 } 4416 4417 /// getF32Constant - Get 32-bit floating point constant. 4418 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4419 const SDLoc &dl) { 4420 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4421 MVT::f32); 4422 } 4423 4424 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4425 SelectionDAG &DAG) { 4426 // TODO: What fast-math-flags should be set on the floating-point nodes? 4427 4428 // IntegerPartOfX = ((int32_t)(t0); 4429 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4430 4431 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4432 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4433 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4434 4435 // IntegerPartOfX <<= 23; 4436 IntegerPartOfX = DAG.getNode( 4437 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4438 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4439 DAG.getDataLayout()))); 4440 4441 SDValue TwoToFractionalPartOfX; 4442 if (LimitFloatPrecision <= 6) { 4443 // For floating-point precision of 6: 4444 // 4445 // TwoToFractionalPartOfX = 4446 // 0.997535578f + 4447 // (0.735607626f + 0.252464424f * x) * x; 4448 // 4449 // error 0.0144103317, which is 6 bits 4450 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4451 getF32Constant(DAG, 0x3e814304, dl)); 4452 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4453 getF32Constant(DAG, 0x3f3c50c8, dl)); 4454 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4455 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4456 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4457 } else if (LimitFloatPrecision <= 12) { 4458 // For floating-point precision of 12: 4459 // 4460 // TwoToFractionalPartOfX = 4461 // 0.999892986f + 4462 // (0.696457318f + 4463 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4464 // 4465 // error 0.000107046256, which is 13 to 14 bits 4466 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4467 getF32Constant(DAG, 0x3da235e3, dl)); 4468 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4469 getF32Constant(DAG, 0x3e65b8f3, dl)); 4470 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4471 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4472 getF32Constant(DAG, 0x3f324b07, dl)); 4473 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4474 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4475 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4476 } else { // LimitFloatPrecision <= 18 4477 // For floating-point precision of 18: 4478 // 4479 // TwoToFractionalPartOfX = 4480 // 0.999999982f + 4481 // (0.693148872f + 4482 // (0.240227044f + 4483 // (0.554906021e-1f + 4484 // (0.961591928e-2f + 4485 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4486 // error 2.47208000*10^(-7), which is better than 18 bits 4487 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4488 getF32Constant(DAG, 0x3924b03e, dl)); 4489 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4490 getF32Constant(DAG, 0x3ab24b87, dl)); 4491 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4492 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4493 getF32Constant(DAG, 0x3c1d8c17, dl)); 4494 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4495 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4496 getF32Constant(DAG, 0x3d634a1d, dl)); 4497 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4498 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4499 getF32Constant(DAG, 0x3e75fe14, dl)); 4500 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4501 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4502 getF32Constant(DAG, 0x3f317234, dl)); 4503 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4504 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4505 getF32Constant(DAG, 0x3f800000, dl)); 4506 } 4507 4508 // Add the exponent into the result in integer domain. 4509 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4510 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4511 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4512 } 4513 4514 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4515 /// limited-precision mode. 4516 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4517 const TargetLowering &TLI) { 4518 if (Op.getValueType() == MVT::f32 && 4519 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4520 4521 // Put the exponent in the right bit position for later addition to the 4522 // final result: 4523 // 4524 // #define LOG2OFe 1.4426950f 4525 // t0 = Op * LOG2OFe 4526 4527 // TODO: What fast-math-flags should be set here? 4528 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4529 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4530 return getLimitedPrecisionExp2(t0, dl, DAG); 4531 } 4532 4533 // No special expansion. 4534 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4535 } 4536 4537 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4538 /// limited-precision mode. 4539 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4540 const TargetLowering &TLI) { 4541 // TODO: What fast-math-flags should be set on the floating-point nodes? 4542 4543 if (Op.getValueType() == MVT::f32 && 4544 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4545 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4546 4547 // Scale the exponent by log(2) [0.69314718f]. 4548 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4549 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4550 getF32Constant(DAG, 0x3f317218, dl)); 4551 4552 // Get the significand and build it into a floating-point number with 4553 // exponent of 1. 4554 SDValue X = GetSignificand(DAG, Op1, dl); 4555 4556 SDValue LogOfMantissa; 4557 if (LimitFloatPrecision <= 6) { 4558 // For floating-point precision of 6: 4559 // 4560 // LogofMantissa = 4561 // -1.1609546f + 4562 // (1.4034025f - 0.23903021f * x) * x; 4563 // 4564 // error 0.0034276066, which is better than 8 bits 4565 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4566 getF32Constant(DAG, 0xbe74c456, dl)); 4567 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4568 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4569 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4570 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4571 getF32Constant(DAG, 0x3f949a29, dl)); 4572 } else if (LimitFloatPrecision <= 12) { 4573 // For floating-point precision of 12: 4574 // 4575 // LogOfMantissa = 4576 // -1.7417939f + 4577 // (2.8212026f + 4578 // (-1.4699568f + 4579 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4580 // 4581 // error 0.000061011436, which is 14 bits 4582 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4583 getF32Constant(DAG, 0xbd67b6d6, dl)); 4584 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4585 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4586 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4587 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4588 getF32Constant(DAG, 0x3fbc278b, dl)); 4589 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4590 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4591 getF32Constant(DAG, 0x40348e95, dl)); 4592 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4593 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4594 getF32Constant(DAG, 0x3fdef31a, dl)); 4595 } else { // LimitFloatPrecision <= 18 4596 // For floating-point precision of 18: 4597 // 4598 // LogOfMantissa = 4599 // -2.1072184f + 4600 // (4.2372794f + 4601 // (-3.7029485f + 4602 // (2.2781945f + 4603 // (-0.87823314f + 4604 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4605 // 4606 // error 0.0000023660568, which is better than 18 bits 4607 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4608 getF32Constant(DAG, 0xbc91e5ac, dl)); 4609 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4610 getF32Constant(DAG, 0x3e4350aa, dl)); 4611 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4612 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4613 getF32Constant(DAG, 0x3f60d3e3, dl)); 4614 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4615 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4616 getF32Constant(DAG, 0x4011cdf0, dl)); 4617 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4618 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4619 getF32Constant(DAG, 0x406cfd1c, dl)); 4620 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4621 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4622 getF32Constant(DAG, 0x408797cb, dl)); 4623 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4624 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4625 getF32Constant(DAG, 0x4006dcab, dl)); 4626 } 4627 4628 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4629 } 4630 4631 // No special expansion. 4632 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4633 } 4634 4635 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4636 /// limited-precision mode. 4637 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4638 const TargetLowering &TLI) { 4639 // TODO: What fast-math-flags should be set on the floating-point nodes? 4640 4641 if (Op.getValueType() == MVT::f32 && 4642 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4643 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4644 4645 // Get the exponent. 4646 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4647 4648 // Get the significand and build it into a floating-point number with 4649 // exponent of 1. 4650 SDValue X = GetSignificand(DAG, Op1, dl); 4651 4652 // Different possible minimax approximations of significand in 4653 // floating-point for various degrees of accuracy over [1,2]. 4654 SDValue Log2ofMantissa; 4655 if (LimitFloatPrecision <= 6) { 4656 // For floating-point precision of 6: 4657 // 4658 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4659 // 4660 // error 0.0049451742, which is more than 7 bits 4661 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4662 getF32Constant(DAG, 0xbeb08fe0, dl)); 4663 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4664 getF32Constant(DAG, 0x40019463, dl)); 4665 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4666 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4667 getF32Constant(DAG, 0x3fd6633d, dl)); 4668 } else if (LimitFloatPrecision <= 12) { 4669 // For floating-point precision of 12: 4670 // 4671 // Log2ofMantissa = 4672 // -2.51285454f + 4673 // (4.07009056f + 4674 // (-2.12067489f + 4675 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4676 // 4677 // error 0.0000876136000, which is better than 13 bits 4678 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4679 getF32Constant(DAG, 0xbda7262e, dl)); 4680 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4681 getF32Constant(DAG, 0x3f25280b, dl)); 4682 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4683 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4684 getF32Constant(DAG, 0x4007b923, dl)); 4685 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4686 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4687 getF32Constant(DAG, 0x40823e2f, dl)); 4688 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4689 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4690 getF32Constant(DAG, 0x4020d29c, dl)); 4691 } else { // LimitFloatPrecision <= 18 4692 // For floating-point precision of 18: 4693 // 4694 // Log2ofMantissa = 4695 // -3.0400495f + 4696 // (6.1129976f + 4697 // (-5.3420409f + 4698 // (3.2865683f + 4699 // (-1.2669343f + 4700 // (0.27515199f - 4701 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4702 // 4703 // error 0.0000018516, which is better than 18 bits 4704 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4705 getF32Constant(DAG, 0xbcd2769e, dl)); 4706 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4707 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4708 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4709 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4710 getF32Constant(DAG, 0x3fa22ae7, dl)); 4711 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4712 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4713 getF32Constant(DAG, 0x40525723, dl)); 4714 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4715 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4716 getF32Constant(DAG, 0x40aaf200, dl)); 4717 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4718 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4719 getF32Constant(DAG, 0x40c39dad, dl)); 4720 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4721 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4722 getF32Constant(DAG, 0x4042902c, dl)); 4723 } 4724 4725 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4726 } 4727 4728 // No special expansion. 4729 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4730 } 4731 4732 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4733 /// limited-precision mode. 4734 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4735 const TargetLowering &TLI) { 4736 // TODO: What fast-math-flags should be set on the floating-point nodes? 4737 4738 if (Op.getValueType() == MVT::f32 && 4739 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4740 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4741 4742 // Scale the exponent by log10(2) [0.30102999f]. 4743 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4744 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4745 getF32Constant(DAG, 0x3e9a209a, dl)); 4746 4747 // Get the significand and build it into a floating-point number with 4748 // exponent of 1. 4749 SDValue X = GetSignificand(DAG, Op1, dl); 4750 4751 SDValue Log10ofMantissa; 4752 if (LimitFloatPrecision <= 6) { 4753 // For floating-point precision of 6: 4754 // 4755 // Log10ofMantissa = 4756 // -0.50419619f + 4757 // (0.60948995f - 0.10380950f * x) * x; 4758 // 4759 // error 0.0014886165, which is 6 bits 4760 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4761 getF32Constant(DAG, 0xbdd49a13, dl)); 4762 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4763 getF32Constant(DAG, 0x3f1c0789, dl)); 4764 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4765 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4766 getF32Constant(DAG, 0x3f011300, dl)); 4767 } else if (LimitFloatPrecision <= 12) { 4768 // For floating-point precision of 12: 4769 // 4770 // Log10ofMantissa = 4771 // -0.64831180f + 4772 // (0.91751397f + 4773 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4774 // 4775 // error 0.00019228036, which is better than 12 bits 4776 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4777 getF32Constant(DAG, 0x3d431f31, dl)); 4778 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4779 getF32Constant(DAG, 0x3ea21fb2, dl)); 4780 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4781 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4782 getF32Constant(DAG, 0x3f6ae232, dl)); 4783 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4784 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4785 getF32Constant(DAG, 0x3f25f7c3, dl)); 4786 } else { // LimitFloatPrecision <= 18 4787 // For floating-point precision of 18: 4788 // 4789 // Log10ofMantissa = 4790 // -0.84299375f + 4791 // (1.5327582f + 4792 // (-1.0688956f + 4793 // (0.49102474f + 4794 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4795 // 4796 // error 0.0000037995730, which is better than 18 bits 4797 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4798 getF32Constant(DAG, 0x3c5d51ce, dl)); 4799 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4800 getF32Constant(DAG, 0x3e00685a, dl)); 4801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4802 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4803 getF32Constant(DAG, 0x3efb6798, dl)); 4804 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4805 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4806 getF32Constant(DAG, 0x3f88d192, dl)); 4807 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4808 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4809 getF32Constant(DAG, 0x3fc4316c, dl)); 4810 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4811 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4812 getF32Constant(DAG, 0x3f57ce70, dl)); 4813 } 4814 4815 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4816 } 4817 4818 // No special expansion. 4819 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4820 } 4821 4822 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4823 /// limited-precision mode. 4824 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4825 const TargetLowering &TLI) { 4826 if (Op.getValueType() == MVT::f32 && 4827 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4828 return getLimitedPrecisionExp2(Op, dl, DAG); 4829 4830 // No special expansion. 4831 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4832 } 4833 4834 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4835 /// limited-precision mode with x == 10.0f. 4836 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4837 SelectionDAG &DAG, const TargetLowering &TLI) { 4838 bool IsExp10 = false; 4839 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4840 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4841 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4842 APFloat Ten(10.0f); 4843 IsExp10 = LHSC->isExactlyValue(Ten); 4844 } 4845 } 4846 4847 // TODO: What fast-math-flags should be set on the FMUL node? 4848 if (IsExp10) { 4849 // Put the exponent in the right bit position for later addition to the 4850 // final result: 4851 // 4852 // #define LOG2OF10 3.3219281f 4853 // t0 = Op * LOG2OF10; 4854 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4855 getF32Constant(DAG, 0x40549a78, dl)); 4856 return getLimitedPrecisionExp2(t0, dl, DAG); 4857 } 4858 4859 // No special expansion. 4860 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4861 } 4862 4863 /// ExpandPowI - Expand a llvm.powi intrinsic. 4864 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4865 SelectionDAG &DAG) { 4866 // If RHS is a constant, we can expand this out to a multiplication tree, 4867 // otherwise we end up lowering to a call to __powidf2 (for example). When 4868 // optimizing for size, we only want to do this if the expansion would produce 4869 // a small number of multiplies, otherwise we do the full expansion. 4870 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4871 // Get the exponent as a positive value. 4872 unsigned Val = RHSC->getSExtValue(); 4873 if ((int)Val < 0) Val = -Val; 4874 4875 // powi(x, 0) -> 1.0 4876 if (Val == 0) 4877 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4878 4879 const Function &F = DAG.getMachineFunction().getFunction(); 4880 if (!F.optForSize() || 4881 // If optimizing for size, don't insert too many multiplies. 4882 // This inserts up to 5 multiplies. 4883 countPopulation(Val) + Log2_32(Val) < 7) { 4884 // We use the simple binary decomposition method to generate the multiply 4885 // sequence. There are more optimal ways to do this (for example, 4886 // powi(x,15) generates one more multiply than it should), but this has 4887 // the benefit of being both really simple and much better than a libcall. 4888 SDValue Res; // Logically starts equal to 1.0 4889 SDValue CurSquare = LHS; 4890 // TODO: Intrinsics should have fast-math-flags that propagate to these 4891 // nodes. 4892 while (Val) { 4893 if (Val & 1) { 4894 if (Res.getNode()) 4895 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4896 else 4897 Res = CurSquare; // 1.0*CurSquare. 4898 } 4899 4900 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4901 CurSquare, CurSquare); 4902 Val >>= 1; 4903 } 4904 4905 // If the original was negative, invert the result, producing 1/(x*x*x). 4906 if (RHSC->getSExtValue() < 0) 4907 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4908 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4909 return Res; 4910 } 4911 } 4912 4913 // Otherwise, expand to a libcall. 4914 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4915 } 4916 4917 // getUnderlyingArgReg - Find underlying register used for a truncated or 4918 // bitcasted argument. 4919 static unsigned getUnderlyingArgReg(const SDValue &N) { 4920 switch (N.getOpcode()) { 4921 case ISD::CopyFromReg: 4922 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4923 case ISD::BITCAST: 4924 case ISD::AssertZext: 4925 case ISD::AssertSext: 4926 case ISD::TRUNCATE: 4927 return getUnderlyingArgReg(N.getOperand(0)); 4928 default: 4929 return 0; 4930 } 4931 } 4932 4933 /// If the DbgValueInst is a dbg_value of a function argument, create the 4934 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4935 /// instruction selection, they will be inserted to the entry BB. 4936 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4937 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4938 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4939 const Argument *Arg = dyn_cast<Argument>(V); 4940 if (!Arg) 4941 return false; 4942 4943 MachineFunction &MF = DAG.getMachineFunction(); 4944 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4945 4946 bool IsIndirect = false; 4947 Optional<MachineOperand> Op; 4948 // Some arguments' frame index is recorded during argument lowering. 4949 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4950 if (FI != std::numeric_limits<int>::max()) 4951 Op = MachineOperand::CreateFI(FI); 4952 4953 if (!Op && N.getNode()) { 4954 unsigned Reg = getUnderlyingArgReg(N); 4955 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4956 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4957 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4958 if (PR) 4959 Reg = PR; 4960 } 4961 if (Reg) { 4962 Op = MachineOperand::CreateReg(Reg, false); 4963 IsIndirect = IsDbgDeclare; 4964 } 4965 } 4966 4967 if (!Op && N.getNode()) 4968 // Check if frame index is available. 4969 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4970 if (FrameIndexSDNode *FINode = 4971 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4972 Op = MachineOperand::CreateFI(FINode->getIndex()); 4973 4974 if (!Op) { 4975 // Check if ValueMap has reg number. 4976 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4977 if (VMI != FuncInfo.ValueMap.end()) { 4978 const auto &TLI = DAG.getTargetLoweringInfo(); 4979 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4980 V->getType(), getABIRegCopyCC(V)); 4981 if (RFV.occupiesMultipleRegs()) { 4982 unsigned Offset = 0; 4983 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4984 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4985 auto FragmentExpr = DIExpression::createFragmentExpression( 4986 Expr, Offset, RegAndSize.second); 4987 if (!FragmentExpr) 4988 continue; 4989 FuncInfo.ArgDbgValues.push_back( 4990 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4991 Op->getReg(), Variable, *FragmentExpr)); 4992 Offset += RegAndSize.second; 4993 } 4994 return true; 4995 } 4996 Op = MachineOperand::CreateReg(VMI->second, false); 4997 IsIndirect = IsDbgDeclare; 4998 } 4999 } 5000 5001 if (!Op) 5002 return false; 5003 5004 assert(Variable->isValidLocationForIntrinsic(DL) && 5005 "Expected inlined-at fields to agree"); 5006 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5007 FuncInfo.ArgDbgValues.push_back( 5008 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5009 *Op, Variable, Expr)); 5010 5011 return true; 5012 } 5013 5014 /// Return the appropriate SDDbgValue based on N. 5015 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5016 DILocalVariable *Variable, 5017 DIExpression *Expr, 5018 const DebugLoc &dl, 5019 unsigned DbgSDNodeOrder) { 5020 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5021 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5022 // stack slot locations. 5023 // 5024 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5025 // debug values here after optimization: 5026 // 5027 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5028 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5029 // 5030 // Both describe the direct values of their associated variables. 5031 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5032 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5033 } 5034 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5035 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5036 } 5037 5038 // VisualStudio defines setjmp as _setjmp 5039 #if defined(_MSC_VER) && defined(setjmp) && \ 5040 !defined(setjmp_undefined_for_msvc) 5041 # pragma push_macro("setjmp") 5042 # undef setjmp 5043 # define setjmp_undefined_for_msvc 5044 #endif 5045 5046 /// Lower the call to the specified intrinsic function. If we want to emit this 5047 /// as a call to a named external function, return the name. Otherwise, lower it 5048 /// and return null. 5049 const char * 5050 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5051 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5052 SDLoc sdl = getCurSDLoc(); 5053 DebugLoc dl = getCurDebugLoc(); 5054 SDValue Res; 5055 5056 switch (Intrinsic) { 5057 default: 5058 // By default, turn this into a target intrinsic node. 5059 visitTargetIntrinsic(I, Intrinsic); 5060 return nullptr; 5061 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5062 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5063 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5064 case Intrinsic::returnaddress: 5065 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5066 TLI.getPointerTy(DAG.getDataLayout()), 5067 getValue(I.getArgOperand(0)))); 5068 return nullptr; 5069 case Intrinsic::addressofreturnaddress: 5070 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5071 TLI.getPointerTy(DAG.getDataLayout()))); 5072 return nullptr; 5073 case Intrinsic::sponentry: 5074 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5075 TLI.getPointerTy(DAG.getDataLayout()))); 5076 return nullptr; 5077 case Intrinsic::frameaddress: 5078 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5079 TLI.getPointerTy(DAG.getDataLayout()), 5080 getValue(I.getArgOperand(0)))); 5081 return nullptr; 5082 case Intrinsic::read_register: { 5083 Value *Reg = I.getArgOperand(0); 5084 SDValue Chain = getRoot(); 5085 SDValue RegName = 5086 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5087 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5088 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5089 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5090 setValue(&I, Res); 5091 DAG.setRoot(Res.getValue(1)); 5092 return nullptr; 5093 } 5094 case Intrinsic::write_register: { 5095 Value *Reg = I.getArgOperand(0); 5096 Value *RegValue = I.getArgOperand(1); 5097 SDValue Chain = getRoot(); 5098 SDValue RegName = 5099 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5100 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5101 RegName, getValue(RegValue))); 5102 return nullptr; 5103 } 5104 case Intrinsic::setjmp: 5105 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5106 case Intrinsic::longjmp: 5107 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5108 case Intrinsic::memcpy: { 5109 const auto &MCI = cast<MemCpyInst>(I); 5110 SDValue Op1 = getValue(I.getArgOperand(0)); 5111 SDValue Op2 = getValue(I.getArgOperand(1)); 5112 SDValue Op3 = getValue(I.getArgOperand(2)); 5113 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5114 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5115 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5116 unsigned Align = MinAlign(DstAlign, SrcAlign); 5117 bool isVol = MCI.isVolatile(); 5118 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5119 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5120 // node. 5121 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5122 false, isTC, 5123 MachinePointerInfo(I.getArgOperand(0)), 5124 MachinePointerInfo(I.getArgOperand(1))); 5125 updateDAGForMaybeTailCall(MC); 5126 return nullptr; 5127 } 5128 case Intrinsic::memset: { 5129 const auto &MSI = cast<MemSetInst>(I); 5130 SDValue Op1 = getValue(I.getArgOperand(0)); 5131 SDValue Op2 = getValue(I.getArgOperand(1)); 5132 SDValue Op3 = getValue(I.getArgOperand(2)); 5133 // @llvm.memset defines 0 and 1 to both mean no alignment. 5134 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5135 bool isVol = MSI.isVolatile(); 5136 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5137 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5138 isTC, MachinePointerInfo(I.getArgOperand(0))); 5139 updateDAGForMaybeTailCall(MS); 5140 return nullptr; 5141 } 5142 case Intrinsic::memmove: { 5143 const auto &MMI = cast<MemMoveInst>(I); 5144 SDValue Op1 = getValue(I.getArgOperand(0)); 5145 SDValue Op2 = getValue(I.getArgOperand(1)); 5146 SDValue Op3 = getValue(I.getArgOperand(2)); 5147 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5148 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5149 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5150 unsigned Align = MinAlign(DstAlign, SrcAlign); 5151 bool isVol = MMI.isVolatile(); 5152 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5153 // FIXME: Support passing different dest/src alignments to the memmove DAG 5154 // node. 5155 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5156 isTC, MachinePointerInfo(I.getArgOperand(0)), 5157 MachinePointerInfo(I.getArgOperand(1))); 5158 updateDAGForMaybeTailCall(MM); 5159 return nullptr; 5160 } 5161 case Intrinsic::memcpy_element_unordered_atomic: { 5162 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5163 SDValue Dst = getValue(MI.getRawDest()); 5164 SDValue Src = getValue(MI.getRawSource()); 5165 SDValue Length = getValue(MI.getLength()); 5166 5167 unsigned DstAlign = MI.getDestAlignment(); 5168 unsigned SrcAlign = MI.getSourceAlignment(); 5169 Type *LengthTy = MI.getLength()->getType(); 5170 unsigned ElemSz = MI.getElementSizeInBytes(); 5171 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5172 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5173 SrcAlign, Length, LengthTy, ElemSz, isTC, 5174 MachinePointerInfo(MI.getRawDest()), 5175 MachinePointerInfo(MI.getRawSource())); 5176 updateDAGForMaybeTailCall(MC); 5177 return nullptr; 5178 } 5179 case Intrinsic::memmove_element_unordered_atomic: { 5180 auto &MI = cast<AtomicMemMoveInst>(I); 5181 SDValue Dst = getValue(MI.getRawDest()); 5182 SDValue Src = getValue(MI.getRawSource()); 5183 SDValue Length = getValue(MI.getLength()); 5184 5185 unsigned DstAlign = MI.getDestAlignment(); 5186 unsigned SrcAlign = MI.getSourceAlignment(); 5187 Type *LengthTy = MI.getLength()->getType(); 5188 unsigned ElemSz = MI.getElementSizeInBytes(); 5189 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5190 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5191 SrcAlign, Length, LengthTy, ElemSz, isTC, 5192 MachinePointerInfo(MI.getRawDest()), 5193 MachinePointerInfo(MI.getRawSource())); 5194 updateDAGForMaybeTailCall(MC); 5195 return nullptr; 5196 } 5197 case Intrinsic::memset_element_unordered_atomic: { 5198 auto &MI = cast<AtomicMemSetInst>(I); 5199 SDValue Dst = getValue(MI.getRawDest()); 5200 SDValue Val = getValue(MI.getValue()); 5201 SDValue Length = getValue(MI.getLength()); 5202 5203 unsigned DstAlign = MI.getDestAlignment(); 5204 Type *LengthTy = MI.getLength()->getType(); 5205 unsigned ElemSz = MI.getElementSizeInBytes(); 5206 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5207 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5208 LengthTy, ElemSz, isTC, 5209 MachinePointerInfo(MI.getRawDest())); 5210 updateDAGForMaybeTailCall(MC); 5211 return nullptr; 5212 } 5213 case Intrinsic::dbg_addr: 5214 case Intrinsic::dbg_declare: { 5215 const auto &DI = cast<DbgVariableIntrinsic>(I); 5216 DILocalVariable *Variable = DI.getVariable(); 5217 DIExpression *Expression = DI.getExpression(); 5218 dropDanglingDebugInfo(Variable, Expression); 5219 assert(Variable && "Missing variable"); 5220 5221 // Check if address has undef value. 5222 const Value *Address = DI.getVariableLocation(); 5223 if (!Address || isa<UndefValue>(Address) || 5224 (Address->use_empty() && !isa<Argument>(Address))) { 5225 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5226 return nullptr; 5227 } 5228 5229 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5230 5231 // Check if this variable can be described by a frame index, typically 5232 // either as a static alloca or a byval parameter. 5233 int FI = std::numeric_limits<int>::max(); 5234 if (const auto *AI = 5235 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5236 if (AI->isStaticAlloca()) { 5237 auto I = FuncInfo.StaticAllocaMap.find(AI); 5238 if (I != FuncInfo.StaticAllocaMap.end()) 5239 FI = I->second; 5240 } 5241 } else if (const auto *Arg = dyn_cast<Argument>( 5242 Address->stripInBoundsConstantOffsets())) { 5243 FI = FuncInfo.getArgumentFrameIndex(Arg); 5244 } 5245 5246 // llvm.dbg.addr is control dependent and always generates indirect 5247 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5248 // the MachineFunction variable table. 5249 if (FI != std::numeric_limits<int>::max()) { 5250 if (Intrinsic == Intrinsic::dbg_addr) { 5251 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5252 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5253 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5254 } 5255 return nullptr; 5256 } 5257 5258 SDValue &N = NodeMap[Address]; 5259 if (!N.getNode() && isa<Argument>(Address)) 5260 // Check unused arguments map. 5261 N = UnusedArgNodeMap[Address]; 5262 SDDbgValue *SDV; 5263 if (N.getNode()) { 5264 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5265 Address = BCI->getOperand(0); 5266 // Parameters are handled specially. 5267 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5268 if (isParameter && FINode) { 5269 // Byval parameter. We have a frame index at this point. 5270 SDV = 5271 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5272 /*IsIndirect*/ true, dl, SDNodeOrder); 5273 } else if (isa<Argument>(Address)) { 5274 // Address is an argument, so try to emit its dbg value using 5275 // virtual register info from the FuncInfo.ValueMap. 5276 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5277 return nullptr; 5278 } else { 5279 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5280 true, dl, SDNodeOrder); 5281 } 5282 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5283 } else { 5284 // If Address is an argument then try to emit its dbg value using 5285 // virtual register info from the FuncInfo.ValueMap. 5286 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5287 N)) { 5288 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5289 } 5290 } 5291 return nullptr; 5292 } 5293 case Intrinsic::dbg_label: { 5294 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5295 DILabel *Label = DI.getLabel(); 5296 assert(Label && "Missing label"); 5297 5298 SDDbgLabel *SDV; 5299 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5300 DAG.AddDbgLabel(SDV); 5301 return nullptr; 5302 } 5303 case Intrinsic::dbg_value: { 5304 const DbgValueInst &DI = cast<DbgValueInst>(I); 5305 assert(DI.getVariable() && "Missing variable"); 5306 5307 DILocalVariable *Variable = DI.getVariable(); 5308 DIExpression *Expression = DI.getExpression(); 5309 dropDanglingDebugInfo(Variable, Expression); 5310 const Value *V = DI.getValue(); 5311 if (!V) 5312 return nullptr; 5313 5314 SDDbgValue *SDV; 5315 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5316 isa<ConstantPointerNull>(V)) { 5317 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5318 DAG.AddDbgValue(SDV, nullptr, false); 5319 return nullptr; 5320 } 5321 5322 // Do not use getValue() in here; we don't want to generate code at 5323 // this point if it hasn't been done yet. 5324 SDValue N = NodeMap[V]; 5325 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5326 N = UnusedArgNodeMap[V]; 5327 if (N.getNode()) { 5328 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5329 return nullptr; 5330 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5331 DAG.AddDbgValue(SDV, N.getNode(), false); 5332 return nullptr; 5333 } 5334 5335 // The value is not used in this block yet (or it would have an SDNode). 5336 // We still want the value to appear for the user if possible -- if it has 5337 // an associated VReg, we can refer to that instead. 5338 if (!isa<Argument>(V)) { 5339 auto VMI = FuncInfo.ValueMap.find(V); 5340 if (VMI != FuncInfo.ValueMap.end()) { 5341 unsigned Reg = VMI->second; 5342 // If this is a PHI node, it may be split up into several MI PHI nodes 5343 // (in FunctionLoweringInfo::set). 5344 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5345 V->getType(), None); 5346 if (RFV.occupiesMultipleRegs()) { 5347 unsigned Offset = 0; 5348 unsigned BitsToDescribe = 0; 5349 if (auto VarSize = Variable->getSizeInBits()) 5350 BitsToDescribe = *VarSize; 5351 if (auto Fragment = Expression->getFragmentInfo()) 5352 BitsToDescribe = Fragment->SizeInBits; 5353 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5354 unsigned RegisterSize = RegAndSize.second; 5355 // Bail out if all bits are described already. 5356 if (Offset >= BitsToDescribe) 5357 break; 5358 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5359 ? BitsToDescribe - Offset 5360 : RegisterSize; 5361 auto FragmentExpr = DIExpression::createFragmentExpression( 5362 Expression, Offset, FragmentSize); 5363 if (!FragmentExpr) 5364 continue; 5365 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5366 false, dl, SDNodeOrder); 5367 DAG.AddDbgValue(SDV, nullptr, false); 5368 Offset += RegisterSize; 5369 } 5370 } else { 5371 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5372 SDNodeOrder); 5373 DAG.AddDbgValue(SDV, nullptr, false); 5374 } 5375 return nullptr; 5376 } 5377 } 5378 5379 // TODO: When we get here we will either drop the dbg.value completely, or 5380 // we try to move it forward by letting it dangle for awhile. So we should 5381 // probably add an extra DbgValue to the DAG here, with a reference to 5382 // "noreg", to indicate that we have lost the debug location for the 5383 // variable. 5384 5385 if (!V->use_empty() ) { 5386 // Do not call getValue(V) yet, as we don't want to generate code. 5387 // Remember it for later. 5388 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5389 return nullptr; 5390 } 5391 5392 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5393 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5394 return nullptr; 5395 } 5396 5397 case Intrinsic::eh_typeid_for: { 5398 // Find the type id for the given typeinfo. 5399 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5400 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5401 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5402 setValue(&I, Res); 5403 return nullptr; 5404 } 5405 5406 case Intrinsic::eh_return_i32: 5407 case Intrinsic::eh_return_i64: 5408 DAG.getMachineFunction().setCallsEHReturn(true); 5409 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5410 MVT::Other, 5411 getControlRoot(), 5412 getValue(I.getArgOperand(0)), 5413 getValue(I.getArgOperand(1)))); 5414 return nullptr; 5415 case Intrinsic::eh_unwind_init: 5416 DAG.getMachineFunction().setCallsUnwindInit(true); 5417 return nullptr; 5418 case Intrinsic::eh_dwarf_cfa: 5419 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5420 TLI.getPointerTy(DAG.getDataLayout()), 5421 getValue(I.getArgOperand(0)))); 5422 return nullptr; 5423 case Intrinsic::eh_sjlj_callsite: { 5424 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5425 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5426 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5427 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5428 5429 MMI.setCurrentCallSite(CI->getZExtValue()); 5430 return nullptr; 5431 } 5432 case Intrinsic::eh_sjlj_functioncontext: { 5433 // Get and store the index of the function context. 5434 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5435 AllocaInst *FnCtx = 5436 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5437 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5438 MFI.setFunctionContextIndex(FI); 5439 return nullptr; 5440 } 5441 case Intrinsic::eh_sjlj_setjmp: { 5442 SDValue Ops[2]; 5443 Ops[0] = getRoot(); 5444 Ops[1] = getValue(I.getArgOperand(0)); 5445 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5446 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5447 setValue(&I, Op.getValue(0)); 5448 DAG.setRoot(Op.getValue(1)); 5449 return nullptr; 5450 } 5451 case Intrinsic::eh_sjlj_longjmp: 5452 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5453 getRoot(), getValue(I.getArgOperand(0)))); 5454 return nullptr; 5455 case Intrinsic::eh_sjlj_setup_dispatch: 5456 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5457 getRoot())); 5458 return nullptr; 5459 case Intrinsic::masked_gather: 5460 visitMaskedGather(I); 5461 return nullptr; 5462 case Intrinsic::masked_load: 5463 visitMaskedLoad(I); 5464 return nullptr; 5465 case Intrinsic::masked_scatter: 5466 visitMaskedScatter(I); 5467 return nullptr; 5468 case Intrinsic::masked_store: 5469 visitMaskedStore(I); 5470 return nullptr; 5471 case Intrinsic::masked_expandload: 5472 visitMaskedLoad(I, true /* IsExpanding */); 5473 return nullptr; 5474 case Intrinsic::masked_compressstore: 5475 visitMaskedStore(I, true /* IsCompressing */); 5476 return nullptr; 5477 case Intrinsic::x86_mmx_pslli_w: 5478 case Intrinsic::x86_mmx_pslli_d: 5479 case Intrinsic::x86_mmx_pslli_q: 5480 case Intrinsic::x86_mmx_psrli_w: 5481 case Intrinsic::x86_mmx_psrli_d: 5482 case Intrinsic::x86_mmx_psrli_q: 5483 case Intrinsic::x86_mmx_psrai_w: 5484 case Intrinsic::x86_mmx_psrai_d: { 5485 SDValue ShAmt = getValue(I.getArgOperand(1)); 5486 if (isa<ConstantSDNode>(ShAmt)) { 5487 visitTargetIntrinsic(I, Intrinsic); 5488 return nullptr; 5489 } 5490 unsigned NewIntrinsic = 0; 5491 EVT ShAmtVT = MVT::v2i32; 5492 switch (Intrinsic) { 5493 case Intrinsic::x86_mmx_pslli_w: 5494 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5495 break; 5496 case Intrinsic::x86_mmx_pslli_d: 5497 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5498 break; 5499 case Intrinsic::x86_mmx_pslli_q: 5500 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5501 break; 5502 case Intrinsic::x86_mmx_psrli_w: 5503 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5504 break; 5505 case Intrinsic::x86_mmx_psrli_d: 5506 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5507 break; 5508 case Intrinsic::x86_mmx_psrli_q: 5509 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5510 break; 5511 case Intrinsic::x86_mmx_psrai_w: 5512 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5513 break; 5514 case Intrinsic::x86_mmx_psrai_d: 5515 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5516 break; 5517 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5518 } 5519 5520 // The vector shift intrinsics with scalars uses 32b shift amounts but 5521 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5522 // to be zero. 5523 // We must do this early because v2i32 is not a legal type. 5524 SDValue ShOps[2]; 5525 ShOps[0] = ShAmt; 5526 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5527 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5528 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5529 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5530 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5531 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5532 getValue(I.getArgOperand(0)), ShAmt); 5533 setValue(&I, Res); 5534 return nullptr; 5535 } 5536 case Intrinsic::powi: 5537 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5538 getValue(I.getArgOperand(1)), DAG)); 5539 return nullptr; 5540 case Intrinsic::log: 5541 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5542 return nullptr; 5543 case Intrinsic::log2: 5544 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5545 return nullptr; 5546 case Intrinsic::log10: 5547 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5548 return nullptr; 5549 case Intrinsic::exp: 5550 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5551 return nullptr; 5552 case Intrinsic::exp2: 5553 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5554 return nullptr; 5555 case Intrinsic::pow: 5556 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5557 getValue(I.getArgOperand(1)), DAG, TLI)); 5558 return nullptr; 5559 case Intrinsic::sqrt: 5560 case Intrinsic::fabs: 5561 case Intrinsic::sin: 5562 case Intrinsic::cos: 5563 case Intrinsic::floor: 5564 case Intrinsic::ceil: 5565 case Intrinsic::trunc: 5566 case Intrinsic::rint: 5567 case Intrinsic::nearbyint: 5568 case Intrinsic::round: 5569 case Intrinsic::canonicalize: { 5570 unsigned Opcode; 5571 switch (Intrinsic) { 5572 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5573 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5574 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5575 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5576 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5577 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5578 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5579 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5580 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5581 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5582 case Intrinsic::round: Opcode = ISD::FROUND; break; 5583 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5584 } 5585 5586 setValue(&I, DAG.getNode(Opcode, sdl, 5587 getValue(I.getArgOperand(0)).getValueType(), 5588 getValue(I.getArgOperand(0)))); 5589 return nullptr; 5590 } 5591 case Intrinsic::minnum: { 5592 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5593 unsigned Opc = 5594 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5595 ? ISD::FMINIMUM 5596 : ISD::FMINNUM; 5597 setValue(&I, DAG.getNode(Opc, sdl, VT, 5598 getValue(I.getArgOperand(0)), 5599 getValue(I.getArgOperand(1)))); 5600 return nullptr; 5601 } 5602 case Intrinsic::maxnum: { 5603 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5604 unsigned Opc = 5605 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5606 ? ISD::FMAXIMUM 5607 : ISD::FMAXNUM; 5608 setValue(&I, DAG.getNode(Opc, sdl, VT, 5609 getValue(I.getArgOperand(0)), 5610 getValue(I.getArgOperand(1)))); 5611 return nullptr; 5612 } 5613 case Intrinsic::minimum: 5614 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5615 getValue(I.getArgOperand(0)).getValueType(), 5616 getValue(I.getArgOperand(0)), 5617 getValue(I.getArgOperand(1)))); 5618 return nullptr; 5619 case Intrinsic::maximum: 5620 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5621 getValue(I.getArgOperand(0)).getValueType(), 5622 getValue(I.getArgOperand(0)), 5623 getValue(I.getArgOperand(1)))); 5624 return nullptr; 5625 case Intrinsic::copysign: 5626 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5627 getValue(I.getArgOperand(0)).getValueType(), 5628 getValue(I.getArgOperand(0)), 5629 getValue(I.getArgOperand(1)))); 5630 return nullptr; 5631 case Intrinsic::fma: 5632 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5633 getValue(I.getArgOperand(0)).getValueType(), 5634 getValue(I.getArgOperand(0)), 5635 getValue(I.getArgOperand(1)), 5636 getValue(I.getArgOperand(2)))); 5637 return nullptr; 5638 case Intrinsic::experimental_constrained_fadd: 5639 case Intrinsic::experimental_constrained_fsub: 5640 case Intrinsic::experimental_constrained_fmul: 5641 case Intrinsic::experimental_constrained_fdiv: 5642 case Intrinsic::experimental_constrained_frem: 5643 case Intrinsic::experimental_constrained_fma: 5644 case Intrinsic::experimental_constrained_sqrt: 5645 case Intrinsic::experimental_constrained_pow: 5646 case Intrinsic::experimental_constrained_powi: 5647 case Intrinsic::experimental_constrained_sin: 5648 case Intrinsic::experimental_constrained_cos: 5649 case Intrinsic::experimental_constrained_exp: 5650 case Intrinsic::experimental_constrained_exp2: 5651 case Intrinsic::experimental_constrained_log: 5652 case Intrinsic::experimental_constrained_log10: 5653 case Intrinsic::experimental_constrained_log2: 5654 case Intrinsic::experimental_constrained_rint: 5655 case Intrinsic::experimental_constrained_nearbyint: 5656 case Intrinsic::experimental_constrained_maxnum: 5657 case Intrinsic::experimental_constrained_minnum: 5658 case Intrinsic::experimental_constrained_ceil: 5659 case Intrinsic::experimental_constrained_floor: 5660 case Intrinsic::experimental_constrained_round: 5661 case Intrinsic::experimental_constrained_trunc: 5662 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5663 return nullptr; 5664 case Intrinsic::fmuladd: { 5665 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5666 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5667 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5668 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5669 getValue(I.getArgOperand(0)).getValueType(), 5670 getValue(I.getArgOperand(0)), 5671 getValue(I.getArgOperand(1)), 5672 getValue(I.getArgOperand(2)))); 5673 } else { 5674 // TODO: Intrinsic calls should have fast-math-flags. 5675 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5676 getValue(I.getArgOperand(0)).getValueType(), 5677 getValue(I.getArgOperand(0)), 5678 getValue(I.getArgOperand(1))); 5679 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5680 getValue(I.getArgOperand(0)).getValueType(), 5681 Mul, 5682 getValue(I.getArgOperand(2))); 5683 setValue(&I, Add); 5684 } 5685 return nullptr; 5686 } 5687 case Intrinsic::convert_to_fp16: 5688 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5689 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5690 getValue(I.getArgOperand(0)), 5691 DAG.getTargetConstant(0, sdl, 5692 MVT::i32)))); 5693 return nullptr; 5694 case Intrinsic::convert_from_fp16: 5695 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5696 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5697 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5698 getValue(I.getArgOperand(0))))); 5699 return nullptr; 5700 case Intrinsic::pcmarker: { 5701 SDValue Tmp = getValue(I.getArgOperand(0)); 5702 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5703 return nullptr; 5704 } 5705 case Intrinsic::readcyclecounter: { 5706 SDValue Op = getRoot(); 5707 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5708 DAG.getVTList(MVT::i64, MVT::Other), Op); 5709 setValue(&I, Res); 5710 DAG.setRoot(Res.getValue(1)); 5711 return nullptr; 5712 } 5713 case Intrinsic::bitreverse: 5714 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5715 getValue(I.getArgOperand(0)).getValueType(), 5716 getValue(I.getArgOperand(0)))); 5717 return nullptr; 5718 case Intrinsic::bswap: 5719 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5720 getValue(I.getArgOperand(0)).getValueType(), 5721 getValue(I.getArgOperand(0)))); 5722 return nullptr; 5723 case Intrinsic::cttz: { 5724 SDValue Arg = getValue(I.getArgOperand(0)); 5725 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5726 EVT Ty = Arg.getValueType(); 5727 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5728 sdl, Ty, Arg)); 5729 return nullptr; 5730 } 5731 case Intrinsic::ctlz: { 5732 SDValue Arg = getValue(I.getArgOperand(0)); 5733 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5734 EVT Ty = Arg.getValueType(); 5735 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5736 sdl, Ty, Arg)); 5737 return nullptr; 5738 } 5739 case Intrinsic::ctpop: { 5740 SDValue Arg = getValue(I.getArgOperand(0)); 5741 EVT Ty = Arg.getValueType(); 5742 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5743 return nullptr; 5744 } 5745 case Intrinsic::fshl: 5746 case Intrinsic::fshr: { 5747 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5748 SDValue X = getValue(I.getArgOperand(0)); 5749 SDValue Y = getValue(I.getArgOperand(1)); 5750 SDValue Z = getValue(I.getArgOperand(2)); 5751 EVT VT = X.getValueType(); 5752 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5753 SDValue Zero = DAG.getConstant(0, sdl, VT); 5754 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5755 5756 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5757 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5758 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5759 return nullptr; 5760 } 5761 5762 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5763 // avoid the select that is necessary in the general case to filter out 5764 // the 0-shift possibility that leads to UB. 5765 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5766 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5767 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5768 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5769 return nullptr; 5770 } 5771 5772 // Some targets only rotate one way. Try the opposite direction. 5773 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5774 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5775 // Negate the shift amount because it is safe to ignore the high bits. 5776 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5777 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5778 return nullptr; 5779 } 5780 5781 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5782 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5783 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5784 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5785 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5786 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5787 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5788 return nullptr; 5789 } 5790 5791 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5792 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5793 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5794 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5795 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5796 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5797 5798 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5799 // and that is undefined. We must compare and select to avoid UB. 5800 EVT CCVT = MVT::i1; 5801 if (VT.isVector()) 5802 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5803 5804 // For fshl, 0-shift returns the 1st arg (X). 5805 // For fshr, 0-shift returns the 2nd arg (Y). 5806 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5807 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5808 return nullptr; 5809 } 5810 case Intrinsic::sadd_sat: { 5811 SDValue Op1 = getValue(I.getArgOperand(0)); 5812 SDValue Op2 = getValue(I.getArgOperand(1)); 5813 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5814 return nullptr; 5815 } 5816 case Intrinsic::uadd_sat: { 5817 SDValue Op1 = getValue(I.getArgOperand(0)); 5818 SDValue Op2 = getValue(I.getArgOperand(1)); 5819 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5820 return nullptr; 5821 } 5822 case Intrinsic::ssub_sat: { 5823 SDValue Op1 = getValue(I.getArgOperand(0)); 5824 SDValue Op2 = getValue(I.getArgOperand(1)); 5825 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5826 return nullptr; 5827 } 5828 case Intrinsic::usub_sat: { 5829 SDValue Op1 = getValue(I.getArgOperand(0)); 5830 SDValue Op2 = getValue(I.getArgOperand(1)); 5831 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5832 return nullptr; 5833 } 5834 case Intrinsic::smul_fix: { 5835 SDValue Op1 = getValue(I.getArgOperand(0)); 5836 SDValue Op2 = getValue(I.getArgOperand(1)); 5837 SDValue Op3 = getValue(I.getArgOperand(2)); 5838 setValue(&I, 5839 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5840 return nullptr; 5841 } 5842 case Intrinsic::stacksave: { 5843 SDValue Op = getRoot(); 5844 Res = DAG.getNode( 5845 ISD::STACKSAVE, sdl, 5846 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5847 setValue(&I, Res); 5848 DAG.setRoot(Res.getValue(1)); 5849 return nullptr; 5850 } 5851 case Intrinsic::stackrestore: 5852 Res = getValue(I.getArgOperand(0)); 5853 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5854 return nullptr; 5855 case Intrinsic::get_dynamic_area_offset: { 5856 SDValue Op = getRoot(); 5857 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5858 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5859 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5860 // target. 5861 if (PtrTy != ResTy) 5862 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5863 " intrinsic!"); 5864 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5865 Op); 5866 DAG.setRoot(Op); 5867 setValue(&I, Res); 5868 return nullptr; 5869 } 5870 case Intrinsic::stackguard: { 5871 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5872 MachineFunction &MF = DAG.getMachineFunction(); 5873 const Module &M = *MF.getFunction().getParent(); 5874 SDValue Chain = getRoot(); 5875 if (TLI.useLoadStackGuardNode()) { 5876 Res = getLoadStackGuard(DAG, sdl, Chain); 5877 } else { 5878 const Value *Global = TLI.getSDagStackGuard(M); 5879 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5880 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5881 MachinePointerInfo(Global, 0), Align, 5882 MachineMemOperand::MOVolatile); 5883 } 5884 if (TLI.useStackGuardXorFP()) 5885 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5886 DAG.setRoot(Chain); 5887 setValue(&I, Res); 5888 return nullptr; 5889 } 5890 case Intrinsic::stackprotector: { 5891 // Emit code into the DAG to store the stack guard onto the stack. 5892 MachineFunction &MF = DAG.getMachineFunction(); 5893 MachineFrameInfo &MFI = MF.getFrameInfo(); 5894 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5895 SDValue Src, Chain = getRoot(); 5896 5897 if (TLI.useLoadStackGuardNode()) 5898 Src = getLoadStackGuard(DAG, sdl, Chain); 5899 else 5900 Src = getValue(I.getArgOperand(0)); // The guard's value. 5901 5902 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5903 5904 int FI = FuncInfo.StaticAllocaMap[Slot]; 5905 MFI.setStackProtectorIndex(FI); 5906 5907 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5908 5909 // Store the stack protector onto the stack. 5910 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5911 DAG.getMachineFunction(), FI), 5912 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5913 setValue(&I, Res); 5914 DAG.setRoot(Res); 5915 return nullptr; 5916 } 5917 case Intrinsic::objectsize: { 5918 // If we don't know by now, we're never going to know. 5919 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5920 5921 assert(CI && "Non-constant type in __builtin_object_size?"); 5922 5923 SDValue Arg = getValue(I.getCalledValue()); 5924 EVT Ty = Arg.getValueType(); 5925 5926 if (CI->isZero()) 5927 Res = DAG.getConstant(-1ULL, sdl, Ty); 5928 else 5929 Res = DAG.getConstant(0, sdl, Ty); 5930 5931 setValue(&I, Res); 5932 return nullptr; 5933 } 5934 5935 case Intrinsic::is_constant: 5936 // If this wasn't constant-folded away by now, then it's not a 5937 // constant. 5938 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5939 return nullptr; 5940 5941 case Intrinsic::annotation: 5942 case Intrinsic::ptr_annotation: 5943 case Intrinsic::launder_invariant_group: 5944 case Intrinsic::strip_invariant_group: 5945 // Drop the intrinsic, but forward the value 5946 setValue(&I, getValue(I.getOperand(0))); 5947 return nullptr; 5948 case Intrinsic::assume: 5949 case Intrinsic::var_annotation: 5950 case Intrinsic::sideeffect: 5951 // Discard annotate attributes, assumptions, and artificial side-effects. 5952 return nullptr; 5953 5954 case Intrinsic::codeview_annotation: { 5955 // Emit a label associated with this metadata. 5956 MachineFunction &MF = DAG.getMachineFunction(); 5957 MCSymbol *Label = 5958 MF.getMMI().getContext().createTempSymbol("annotation", true); 5959 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5960 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5961 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5962 DAG.setRoot(Res); 5963 return nullptr; 5964 } 5965 5966 case Intrinsic::init_trampoline: { 5967 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5968 5969 SDValue Ops[6]; 5970 Ops[0] = getRoot(); 5971 Ops[1] = getValue(I.getArgOperand(0)); 5972 Ops[2] = getValue(I.getArgOperand(1)); 5973 Ops[3] = getValue(I.getArgOperand(2)); 5974 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5975 Ops[5] = DAG.getSrcValue(F); 5976 5977 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5978 5979 DAG.setRoot(Res); 5980 return nullptr; 5981 } 5982 case Intrinsic::adjust_trampoline: 5983 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5984 TLI.getPointerTy(DAG.getDataLayout()), 5985 getValue(I.getArgOperand(0)))); 5986 return nullptr; 5987 case Intrinsic::gcroot: { 5988 assert(DAG.getMachineFunction().getFunction().hasGC() && 5989 "only valid in functions with gc specified, enforced by Verifier"); 5990 assert(GFI && "implied by previous"); 5991 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5992 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5993 5994 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5995 GFI->addStackRoot(FI->getIndex(), TypeMap); 5996 return nullptr; 5997 } 5998 case Intrinsic::gcread: 5999 case Intrinsic::gcwrite: 6000 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6001 case Intrinsic::flt_rounds: 6002 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6003 return nullptr; 6004 6005 case Intrinsic::expect: 6006 // Just replace __builtin_expect(exp, c) with EXP. 6007 setValue(&I, getValue(I.getArgOperand(0))); 6008 return nullptr; 6009 6010 case Intrinsic::debugtrap: 6011 case Intrinsic::trap: { 6012 StringRef TrapFuncName = 6013 I.getAttributes() 6014 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6015 .getValueAsString(); 6016 if (TrapFuncName.empty()) { 6017 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6018 ISD::TRAP : ISD::DEBUGTRAP; 6019 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6020 return nullptr; 6021 } 6022 TargetLowering::ArgListTy Args; 6023 6024 TargetLowering::CallLoweringInfo CLI(DAG); 6025 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6026 CallingConv::C, I.getType(), 6027 DAG.getExternalSymbol(TrapFuncName.data(), 6028 TLI.getPointerTy(DAG.getDataLayout())), 6029 std::move(Args)); 6030 6031 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6032 DAG.setRoot(Result.second); 6033 return nullptr; 6034 } 6035 6036 case Intrinsic::uadd_with_overflow: 6037 case Intrinsic::sadd_with_overflow: 6038 case Intrinsic::usub_with_overflow: 6039 case Intrinsic::ssub_with_overflow: 6040 case Intrinsic::umul_with_overflow: 6041 case Intrinsic::smul_with_overflow: { 6042 ISD::NodeType Op; 6043 switch (Intrinsic) { 6044 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6045 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6046 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6047 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6048 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6049 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6050 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6051 } 6052 SDValue Op1 = getValue(I.getArgOperand(0)); 6053 SDValue Op2 = getValue(I.getArgOperand(1)); 6054 6055 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6056 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6057 return nullptr; 6058 } 6059 case Intrinsic::prefetch: { 6060 SDValue Ops[5]; 6061 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6062 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6063 Ops[0] = DAG.getRoot(); 6064 Ops[1] = getValue(I.getArgOperand(0)); 6065 Ops[2] = getValue(I.getArgOperand(1)); 6066 Ops[3] = getValue(I.getArgOperand(2)); 6067 Ops[4] = getValue(I.getArgOperand(3)); 6068 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6069 DAG.getVTList(MVT::Other), Ops, 6070 EVT::getIntegerVT(*Context, 8), 6071 MachinePointerInfo(I.getArgOperand(0)), 6072 0, /* align */ 6073 Flags); 6074 6075 // Chain the prefetch in parallell with any pending loads, to stay out of 6076 // the way of later optimizations. 6077 PendingLoads.push_back(Result); 6078 Result = getRoot(); 6079 DAG.setRoot(Result); 6080 return nullptr; 6081 } 6082 case Intrinsic::lifetime_start: 6083 case Intrinsic::lifetime_end: { 6084 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6085 // Stack coloring is not enabled in O0, discard region information. 6086 if (TM.getOptLevel() == CodeGenOpt::None) 6087 return nullptr; 6088 6089 SmallVector<Value *, 4> Allocas; 6090 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6091 6092 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6093 E = Allocas.end(); Object != E; ++Object) { 6094 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6095 6096 // Could not find an Alloca. 6097 if (!LifetimeObject) 6098 continue; 6099 6100 // First check that the Alloca is static, otherwise it won't have a 6101 // valid frame index. 6102 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6103 if (SI == FuncInfo.StaticAllocaMap.end()) 6104 return nullptr; 6105 6106 int FI = SI->second; 6107 6108 SDValue Ops[2]; 6109 Ops[0] = getRoot(); 6110 Ops[1] = 6111 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6112 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6113 6114 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6115 DAG.setRoot(Res); 6116 } 6117 return nullptr; 6118 } 6119 case Intrinsic::invariant_start: 6120 // Discard region information. 6121 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6122 return nullptr; 6123 case Intrinsic::invariant_end: 6124 // Discard region information. 6125 return nullptr; 6126 case Intrinsic::clear_cache: 6127 return TLI.getClearCacheBuiltinName(); 6128 case Intrinsic::donothing: 6129 // ignore 6130 return nullptr; 6131 case Intrinsic::experimental_stackmap: 6132 visitStackmap(I); 6133 return nullptr; 6134 case Intrinsic::experimental_patchpoint_void: 6135 case Intrinsic::experimental_patchpoint_i64: 6136 visitPatchpoint(&I); 6137 return nullptr; 6138 case Intrinsic::experimental_gc_statepoint: 6139 LowerStatepoint(ImmutableStatepoint(&I)); 6140 return nullptr; 6141 case Intrinsic::experimental_gc_result: 6142 visitGCResult(cast<GCResultInst>(I)); 6143 return nullptr; 6144 case Intrinsic::experimental_gc_relocate: 6145 visitGCRelocate(cast<GCRelocateInst>(I)); 6146 return nullptr; 6147 case Intrinsic::instrprof_increment: 6148 llvm_unreachable("instrprof failed to lower an increment"); 6149 case Intrinsic::instrprof_value_profile: 6150 llvm_unreachable("instrprof failed to lower a value profiling call"); 6151 case Intrinsic::localescape: { 6152 MachineFunction &MF = DAG.getMachineFunction(); 6153 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6154 6155 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6156 // is the same on all targets. 6157 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6158 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6159 if (isa<ConstantPointerNull>(Arg)) 6160 continue; // Skip null pointers. They represent a hole in index space. 6161 AllocaInst *Slot = cast<AllocaInst>(Arg); 6162 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6163 "can only escape static allocas"); 6164 int FI = FuncInfo.StaticAllocaMap[Slot]; 6165 MCSymbol *FrameAllocSym = 6166 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6167 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6168 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6169 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6170 .addSym(FrameAllocSym) 6171 .addFrameIndex(FI); 6172 } 6173 6174 MF.setHasLocalEscape(true); 6175 6176 return nullptr; 6177 } 6178 6179 case Intrinsic::localrecover: { 6180 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6181 MachineFunction &MF = DAG.getMachineFunction(); 6182 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6183 6184 // Get the symbol that defines the frame offset. 6185 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6186 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6187 unsigned IdxVal = 6188 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6189 MCSymbol *FrameAllocSym = 6190 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6191 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6192 6193 // Create a MCSymbol for the label to avoid any target lowering 6194 // that would make this PC relative. 6195 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6196 SDValue OffsetVal = 6197 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6198 6199 // Add the offset to the FP. 6200 Value *FP = I.getArgOperand(1); 6201 SDValue FPVal = getValue(FP); 6202 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6203 setValue(&I, Add); 6204 6205 return nullptr; 6206 } 6207 6208 case Intrinsic::eh_exceptionpointer: 6209 case Intrinsic::eh_exceptioncode: { 6210 // Get the exception pointer vreg, copy from it, and resize it to fit. 6211 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6212 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6213 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6214 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6215 SDValue N = 6216 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6217 if (Intrinsic == Intrinsic::eh_exceptioncode) 6218 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6219 setValue(&I, N); 6220 return nullptr; 6221 } 6222 case Intrinsic::xray_customevent: { 6223 // Here we want to make sure that the intrinsic behaves as if it has a 6224 // specific calling convention, and only for x86_64. 6225 // FIXME: Support other platforms later. 6226 const auto &Triple = DAG.getTarget().getTargetTriple(); 6227 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6228 return nullptr; 6229 6230 SDLoc DL = getCurSDLoc(); 6231 SmallVector<SDValue, 8> Ops; 6232 6233 // We want to say that we always want the arguments in registers. 6234 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6235 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6237 SDValue Chain = getRoot(); 6238 Ops.push_back(LogEntryVal); 6239 Ops.push_back(StrSizeVal); 6240 Ops.push_back(Chain); 6241 6242 // We need to enforce the calling convention for the callsite, so that 6243 // argument ordering is enforced correctly, and that register allocation can 6244 // see that some registers may be assumed clobbered and have to preserve 6245 // them across calls to the intrinsic. 6246 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6247 DL, NodeTys, Ops); 6248 SDValue patchableNode = SDValue(MN, 0); 6249 DAG.setRoot(patchableNode); 6250 setValue(&I, patchableNode); 6251 return nullptr; 6252 } 6253 case Intrinsic::xray_typedevent: { 6254 // Here we want to make sure that the intrinsic behaves as if it has a 6255 // specific calling convention, and only for x86_64. 6256 // FIXME: Support other platforms later. 6257 const auto &Triple = DAG.getTarget().getTargetTriple(); 6258 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6259 return nullptr; 6260 6261 SDLoc DL = getCurSDLoc(); 6262 SmallVector<SDValue, 8> Ops; 6263 6264 // We want to say that we always want the arguments in registers. 6265 // It's unclear to me how manipulating the selection DAG here forces callers 6266 // to provide arguments in registers instead of on the stack. 6267 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6268 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6269 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6270 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6271 SDValue Chain = getRoot(); 6272 Ops.push_back(LogTypeId); 6273 Ops.push_back(LogEntryVal); 6274 Ops.push_back(StrSizeVal); 6275 Ops.push_back(Chain); 6276 6277 // We need to enforce the calling convention for the callsite, so that 6278 // argument ordering is enforced correctly, and that register allocation can 6279 // see that some registers may be assumed clobbered and have to preserve 6280 // them across calls to the intrinsic. 6281 MachineSDNode *MN = DAG.getMachineNode( 6282 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6283 SDValue patchableNode = SDValue(MN, 0); 6284 DAG.setRoot(patchableNode); 6285 setValue(&I, patchableNode); 6286 return nullptr; 6287 } 6288 case Intrinsic::experimental_deoptimize: 6289 LowerDeoptimizeCall(&I); 6290 return nullptr; 6291 6292 case Intrinsic::experimental_vector_reduce_fadd: 6293 case Intrinsic::experimental_vector_reduce_fmul: 6294 case Intrinsic::experimental_vector_reduce_add: 6295 case Intrinsic::experimental_vector_reduce_mul: 6296 case Intrinsic::experimental_vector_reduce_and: 6297 case Intrinsic::experimental_vector_reduce_or: 6298 case Intrinsic::experimental_vector_reduce_xor: 6299 case Intrinsic::experimental_vector_reduce_smax: 6300 case Intrinsic::experimental_vector_reduce_smin: 6301 case Intrinsic::experimental_vector_reduce_umax: 6302 case Intrinsic::experimental_vector_reduce_umin: 6303 case Intrinsic::experimental_vector_reduce_fmax: 6304 case Intrinsic::experimental_vector_reduce_fmin: 6305 visitVectorReduce(I, Intrinsic); 6306 return nullptr; 6307 6308 case Intrinsic::icall_branch_funnel: { 6309 SmallVector<SDValue, 16> Ops; 6310 Ops.push_back(DAG.getRoot()); 6311 Ops.push_back(getValue(I.getArgOperand(0))); 6312 6313 int64_t Offset; 6314 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6315 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6316 if (!Base) 6317 report_fatal_error( 6318 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6319 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6320 6321 struct BranchFunnelTarget { 6322 int64_t Offset; 6323 SDValue Target; 6324 }; 6325 SmallVector<BranchFunnelTarget, 8> Targets; 6326 6327 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6328 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6329 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6330 if (ElemBase != Base) 6331 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6332 "to the same GlobalValue"); 6333 6334 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6335 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6336 if (!GA) 6337 report_fatal_error( 6338 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6339 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6340 GA->getGlobal(), getCurSDLoc(), 6341 Val.getValueType(), GA->getOffset())}); 6342 } 6343 llvm::sort(Targets, 6344 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6345 return T1.Offset < T2.Offset; 6346 }); 6347 6348 for (auto &T : Targets) { 6349 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6350 Ops.push_back(T.Target); 6351 } 6352 6353 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6354 getCurSDLoc(), MVT::Other, Ops), 6355 0); 6356 DAG.setRoot(N); 6357 setValue(&I, N); 6358 HasTailCall = true; 6359 return nullptr; 6360 } 6361 6362 case Intrinsic::wasm_landingpad_index: 6363 // Information this intrinsic contained has been transferred to 6364 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6365 // delete it now. 6366 return nullptr; 6367 } 6368 } 6369 6370 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6371 const ConstrainedFPIntrinsic &FPI) { 6372 SDLoc sdl = getCurSDLoc(); 6373 unsigned Opcode; 6374 switch (FPI.getIntrinsicID()) { 6375 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6376 case Intrinsic::experimental_constrained_fadd: 6377 Opcode = ISD::STRICT_FADD; 6378 break; 6379 case Intrinsic::experimental_constrained_fsub: 6380 Opcode = ISD::STRICT_FSUB; 6381 break; 6382 case Intrinsic::experimental_constrained_fmul: 6383 Opcode = ISD::STRICT_FMUL; 6384 break; 6385 case Intrinsic::experimental_constrained_fdiv: 6386 Opcode = ISD::STRICT_FDIV; 6387 break; 6388 case Intrinsic::experimental_constrained_frem: 6389 Opcode = ISD::STRICT_FREM; 6390 break; 6391 case Intrinsic::experimental_constrained_fma: 6392 Opcode = ISD::STRICT_FMA; 6393 break; 6394 case Intrinsic::experimental_constrained_sqrt: 6395 Opcode = ISD::STRICT_FSQRT; 6396 break; 6397 case Intrinsic::experimental_constrained_pow: 6398 Opcode = ISD::STRICT_FPOW; 6399 break; 6400 case Intrinsic::experimental_constrained_powi: 6401 Opcode = ISD::STRICT_FPOWI; 6402 break; 6403 case Intrinsic::experimental_constrained_sin: 6404 Opcode = ISD::STRICT_FSIN; 6405 break; 6406 case Intrinsic::experimental_constrained_cos: 6407 Opcode = ISD::STRICT_FCOS; 6408 break; 6409 case Intrinsic::experimental_constrained_exp: 6410 Opcode = ISD::STRICT_FEXP; 6411 break; 6412 case Intrinsic::experimental_constrained_exp2: 6413 Opcode = ISD::STRICT_FEXP2; 6414 break; 6415 case Intrinsic::experimental_constrained_log: 6416 Opcode = ISD::STRICT_FLOG; 6417 break; 6418 case Intrinsic::experimental_constrained_log10: 6419 Opcode = ISD::STRICT_FLOG10; 6420 break; 6421 case Intrinsic::experimental_constrained_log2: 6422 Opcode = ISD::STRICT_FLOG2; 6423 break; 6424 case Intrinsic::experimental_constrained_rint: 6425 Opcode = ISD::STRICT_FRINT; 6426 break; 6427 case Intrinsic::experimental_constrained_nearbyint: 6428 Opcode = ISD::STRICT_FNEARBYINT; 6429 break; 6430 case Intrinsic::experimental_constrained_maxnum: 6431 Opcode = ISD::STRICT_FMAXNUM; 6432 break; 6433 case Intrinsic::experimental_constrained_minnum: 6434 Opcode = ISD::STRICT_FMINNUM; 6435 break; 6436 case Intrinsic::experimental_constrained_ceil: 6437 Opcode = ISD::STRICT_FCEIL; 6438 break; 6439 case Intrinsic::experimental_constrained_floor: 6440 Opcode = ISD::STRICT_FFLOOR; 6441 break; 6442 case Intrinsic::experimental_constrained_round: 6443 Opcode = ISD::STRICT_FROUND; 6444 break; 6445 case Intrinsic::experimental_constrained_trunc: 6446 Opcode = ISD::STRICT_FTRUNC; 6447 break; 6448 } 6449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6450 SDValue Chain = getRoot(); 6451 SmallVector<EVT, 4> ValueVTs; 6452 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6453 ValueVTs.push_back(MVT::Other); // Out chain 6454 6455 SDVTList VTs = DAG.getVTList(ValueVTs); 6456 SDValue Result; 6457 if (FPI.isUnaryOp()) 6458 Result = DAG.getNode(Opcode, sdl, VTs, 6459 { Chain, getValue(FPI.getArgOperand(0)) }); 6460 else if (FPI.isTernaryOp()) 6461 Result = DAG.getNode(Opcode, sdl, VTs, 6462 { Chain, getValue(FPI.getArgOperand(0)), 6463 getValue(FPI.getArgOperand(1)), 6464 getValue(FPI.getArgOperand(2)) }); 6465 else 6466 Result = DAG.getNode(Opcode, sdl, VTs, 6467 { Chain, getValue(FPI.getArgOperand(0)), 6468 getValue(FPI.getArgOperand(1)) }); 6469 6470 assert(Result.getNode()->getNumValues() == 2); 6471 SDValue OutChain = Result.getValue(1); 6472 DAG.setRoot(OutChain); 6473 SDValue FPResult = Result.getValue(0); 6474 setValue(&FPI, FPResult); 6475 } 6476 6477 std::pair<SDValue, SDValue> 6478 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6479 const BasicBlock *EHPadBB) { 6480 MachineFunction &MF = DAG.getMachineFunction(); 6481 MachineModuleInfo &MMI = MF.getMMI(); 6482 MCSymbol *BeginLabel = nullptr; 6483 6484 if (EHPadBB) { 6485 // Insert a label before the invoke call to mark the try range. This can be 6486 // used to detect deletion of the invoke via the MachineModuleInfo. 6487 BeginLabel = MMI.getContext().createTempSymbol(); 6488 6489 // For SjLj, keep track of which landing pads go with which invokes 6490 // so as to maintain the ordering of pads in the LSDA. 6491 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6492 if (CallSiteIndex) { 6493 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6494 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6495 6496 // Now that the call site is handled, stop tracking it. 6497 MMI.setCurrentCallSite(0); 6498 } 6499 6500 // Both PendingLoads and PendingExports must be flushed here; 6501 // this call might not return. 6502 (void)getRoot(); 6503 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6504 6505 CLI.setChain(getRoot()); 6506 } 6507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6508 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6509 6510 assert((CLI.IsTailCall || Result.second.getNode()) && 6511 "Non-null chain expected with non-tail call!"); 6512 assert((Result.second.getNode() || !Result.first.getNode()) && 6513 "Null value expected with tail call!"); 6514 6515 if (!Result.second.getNode()) { 6516 // As a special case, a null chain means that a tail call has been emitted 6517 // and the DAG root is already updated. 6518 HasTailCall = true; 6519 6520 // Since there's no actual continuation from this block, nothing can be 6521 // relying on us setting vregs for them. 6522 PendingExports.clear(); 6523 } else { 6524 DAG.setRoot(Result.second); 6525 } 6526 6527 if (EHPadBB) { 6528 // Insert a label at the end of the invoke call to mark the try range. This 6529 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6530 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6531 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6532 6533 // Inform MachineModuleInfo of range. 6534 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6535 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6536 // actually use outlined funclets and their LSDA info style. 6537 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6538 assert(CLI.CS); 6539 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6540 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6541 BeginLabel, EndLabel); 6542 } else if (!isScopedEHPersonality(Pers)) { 6543 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6544 } 6545 } 6546 6547 return Result; 6548 } 6549 6550 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6551 bool isTailCall, 6552 const BasicBlock *EHPadBB) { 6553 auto &DL = DAG.getDataLayout(); 6554 FunctionType *FTy = CS.getFunctionType(); 6555 Type *RetTy = CS.getType(); 6556 6557 TargetLowering::ArgListTy Args; 6558 Args.reserve(CS.arg_size()); 6559 6560 const Value *SwiftErrorVal = nullptr; 6561 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6562 6563 // We can't tail call inside a function with a swifterror argument. Lowering 6564 // does not support this yet. It would have to move into the swifterror 6565 // register before the call. 6566 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6567 if (TLI.supportSwiftError() && 6568 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6569 isTailCall = false; 6570 6571 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6572 i != e; ++i) { 6573 TargetLowering::ArgListEntry Entry; 6574 const Value *V = *i; 6575 6576 // Skip empty types 6577 if (V->getType()->isEmptyTy()) 6578 continue; 6579 6580 SDValue ArgNode = getValue(V); 6581 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6582 6583 Entry.setAttributes(&CS, i - CS.arg_begin()); 6584 6585 // Use swifterror virtual register as input to the call. 6586 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6587 SwiftErrorVal = V; 6588 // We find the virtual register for the actual swifterror argument. 6589 // Instead of using the Value, we use the virtual register instead. 6590 Entry.Node = DAG.getRegister(FuncInfo 6591 .getOrCreateSwiftErrorVRegUseAt( 6592 CS.getInstruction(), FuncInfo.MBB, V) 6593 .first, 6594 EVT(TLI.getPointerTy(DL))); 6595 } 6596 6597 Args.push_back(Entry); 6598 6599 // If we have an explicit sret argument that is an Instruction, (i.e., it 6600 // might point to function-local memory), we can't meaningfully tail-call. 6601 if (Entry.IsSRet && isa<Instruction>(V)) 6602 isTailCall = false; 6603 } 6604 6605 // Check if target-independent constraints permit a tail call here. 6606 // Target-dependent constraints are checked within TLI->LowerCallTo. 6607 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6608 isTailCall = false; 6609 6610 // Disable tail calls if there is an swifterror argument. Targets have not 6611 // been updated to support tail calls. 6612 if (TLI.supportSwiftError() && SwiftErrorVal) 6613 isTailCall = false; 6614 6615 TargetLowering::CallLoweringInfo CLI(DAG); 6616 CLI.setDebugLoc(getCurSDLoc()) 6617 .setChain(getRoot()) 6618 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6619 .setTailCall(isTailCall) 6620 .setConvergent(CS.isConvergent()); 6621 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6622 6623 if (Result.first.getNode()) { 6624 const Instruction *Inst = CS.getInstruction(); 6625 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6626 setValue(Inst, Result.first); 6627 } 6628 6629 // The last element of CLI.InVals has the SDValue for swifterror return. 6630 // Here we copy it to a virtual register and update SwiftErrorMap for 6631 // book-keeping. 6632 if (SwiftErrorVal && TLI.supportSwiftError()) { 6633 // Get the last element of InVals. 6634 SDValue Src = CLI.InVals.back(); 6635 unsigned VReg; bool CreatedVReg; 6636 std::tie(VReg, CreatedVReg) = 6637 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6638 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6639 // We update the virtual register for the actual swifterror argument. 6640 if (CreatedVReg) 6641 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6642 DAG.setRoot(CopyNode); 6643 } 6644 } 6645 6646 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6647 SelectionDAGBuilder &Builder) { 6648 // Check to see if this load can be trivially constant folded, e.g. if the 6649 // input is from a string literal. 6650 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6651 // Cast pointer to the type we really want to load. 6652 Type *LoadTy = 6653 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6654 if (LoadVT.isVector()) 6655 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6656 6657 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6658 PointerType::getUnqual(LoadTy)); 6659 6660 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6661 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6662 return Builder.getValue(LoadCst); 6663 } 6664 6665 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6666 // still constant memory, the input chain can be the entry node. 6667 SDValue Root; 6668 bool ConstantMemory = false; 6669 6670 // Do not serialize (non-volatile) loads of constant memory with anything. 6671 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6672 Root = Builder.DAG.getEntryNode(); 6673 ConstantMemory = true; 6674 } else { 6675 // Do not serialize non-volatile loads against each other. 6676 Root = Builder.DAG.getRoot(); 6677 } 6678 6679 SDValue Ptr = Builder.getValue(PtrVal); 6680 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6681 Ptr, MachinePointerInfo(PtrVal), 6682 /* Alignment = */ 1); 6683 6684 if (!ConstantMemory) 6685 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6686 return LoadVal; 6687 } 6688 6689 /// Record the value for an instruction that produces an integer result, 6690 /// converting the type where necessary. 6691 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6692 SDValue Value, 6693 bool IsSigned) { 6694 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6695 I.getType(), true); 6696 if (IsSigned) 6697 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6698 else 6699 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6700 setValue(&I, Value); 6701 } 6702 6703 /// See if we can lower a memcmp call into an optimized form. If so, return 6704 /// true and lower it. Otherwise return false, and it will be lowered like a 6705 /// normal call. 6706 /// The caller already checked that \p I calls the appropriate LibFunc with a 6707 /// correct prototype. 6708 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6709 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6710 const Value *Size = I.getArgOperand(2); 6711 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6712 if (CSize && CSize->getZExtValue() == 0) { 6713 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6714 I.getType(), true); 6715 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6716 return true; 6717 } 6718 6719 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6720 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6721 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6722 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6723 if (Res.first.getNode()) { 6724 processIntegerCallValue(I, Res.first, true); 6725 PendingLoads.push_back(Res.second); 6726 return true; 6727 } 6728 6729 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6730 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6731 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6732 return false; 6733 6734 // If the target has a fast compare for the given size, it will return a 6735 // preferred load type for that size. Require that the load VT is legal and 6736 // that the target supports unaligned loads of that type. Otherwise, return 6737 // INVALID. 6738 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6739 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6740 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6741 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6742 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6743 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6744 // TODO: Check alignment of src and dest ptrs. 6745 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6746 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6747 if (!TLI.isTypeLegal(LVT) || 6748 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6749 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6750 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6751 } 6752 6753 return LVT; 6754 }; 6755 6756 // This turns into unaligned loads. We only do this if the target natively 6757 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6758 // we'll only produce a small number of byte loads. 6759 MVT LoadVT; 6760 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6761 switch (NumBitsToCompare) { 6762 default: 6763 return false; 6764 case 16: 6765 LoadVT = MVT::i16; 6766 break; 6767 case 32: 6768 LoadVT = MVT::i32; 6769 break; 6770 case 64: 6771 case 128: 6772 case 256: 6773 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6774 break; 6775 } 6776 6777 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6778 return false; 6779 6780 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6781 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6782 6783 // Bitcast to a wide integer type if the loads are vectors. 6784 if (LoadVT.isVector()) { 6785 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6786 LoadL = DAG.getBitcast(CmpVT, LoadL); 6787 LoadR = DAG.getBitcast(CmpVT, LoadR); 6788 } 6789 6790 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6791 processIntegerCallValue(I, Cmp, false); 6792 return true; 6793 } 6794 6795 /// See if we can lower a memchr call into an optimized form. If so, return 6796 /// true and lower it. Otherwise return false, and it will be lowered like a 6797 /// normal call. 6798 /// The caller already checked that \p I calls the appropriate LibFunc with a 6799 /// correct prototype. 6800 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6801 const Value *Src = I.getArgOperand(0); 6802 const Value *Char = I.getArgOperand(1); 6803 const Value *Length = I.getArgOperand(2); 6804 6805 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6806 std::pair<SDValue, SDValue> Res = 6807 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6808 getValue(Src), getValue(Char), getValue(Length), 6809 MachinePointerInfo(Src)); 6810 if (Res.first.getNode()) { 6811 setValue(&I, Res.first); 6812 PendingLoads.push_back(Res.second); 6813 return true; 6814 } 6815 6816 return false; 6817 } 6818 6819 /// See if we can lower a mempcpy call into an optimized form. If so, return 6820 /// true and lower it. Otherwise return false, and it will be lowered like a 6821 /// normal call. 6822 /// The caller already checked that \p I calls the appropriate LibFunc with a 6823 /// correct prototype. 6824 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6825 SDValue Dst = getValue(I.getArgOperand(0)); 6826 SDValue Src = getValue(I.getArgOperand(1)); 6827 SDValue Size = getValue(I.getArgOperand(2)); 6828 6829 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6830 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6831 unsigned Align = std::min(DstAlign, SrcAlign); 6832 if (Align == 0) // Alignment of one or both could not be inferred. 6833 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6834 6835 bool isVol = false; 6836 SDLoc sdl = getCurSDLoc(); 6837 6838 // In the mempcpy context we need to pass in a false value for isTailCall 6839 // because the return pointer needs to be adjusted by the size of 6840 // the copied memory. 6841 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6842 false, /*isTailCall=*/false, 6843 MachinePointerInfo(I.getArgOperand(0)), 6844 MachinePointerInfo(I.getArgOperand(1))); 6845 assert(MC.getNode() != nullptr && 6846 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6847 DAG.setRoot(MC); 6848 6849 // Check if Size needs to be truncated or extended. 6850 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6851 6852 // Adjust return pointer to point just past the last dst byte. 6853 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6854 Dst, Size); 6855 setValue(&I, DstPlusSize); 6856 return true; 6857 } 6858 6859 /// See if we can lower a strcpy call into an optimized form. If so, return 6860 /// true and lower it, otherwise return false and it will be lowered like a 6861 /// normal call. 6862 /// The caller already checked that \p I calls the appropriate LibFunc with a 6863 /// correct prototype. 6864 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6865 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6866 6867 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6868 std::pair<SDValue, SDValue> Res = 6869 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6870 getValue(Arg0), getValue(Arg1), 6871 MachinePointerInfo(Arg0), 6872 MachinePointerInfo(Arg1), isStpcpy); 6873 if (Res.first.getNode()) { 6874 setValue(&I, Res.first); 6875 DAG.setRoot(Res.second); 6876 return true; 6877 } 6878 6879 return false; 6880 } 6881 6882 /// See if we can lower a strcmp call into an optimized form. If so, return 6883 /// true and lower it, otherwise return false and it will be lowered like a 6884 /// normal call. 6885 /// The caller already checked that \p I calls the appropriate LibFunc with a 6886 /// correct prototype. 6887 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6888 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6889 6890 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6891 std::pair<SDValue, SDValue> Res = 6892 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6893 getValue(Arg0), getValue(Arg1), 6894 MachinePointerInfo(Arg0), 6895 MachinePointerInfo(Arg1)); 6896 if (Res.first.getNode()) { 6897 processIntegerCallValue(I, Res.first, true); 6898 PendingLoads.push_back(Res.second); 6899 return true; 6900 } 6901 6902 return false; 6903 } 6904 6905 /// See if we can lower a strlen call into an optimized form. If so, return 6906 /// true and lower it, otherwise return false and it will be lowered like a 6907 /// normal call. 6908 /// The caller already checked that \p I calls the appropriate LibFunc with a 6909 /// correct prototype. 6910 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6911 const Value *Arg0 = I.getArgOperand(0); 6912 6913 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6914 std::pair<SDValue, SDValue> Res = 6915 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6916 getValue(Arg0), MachinePointerInfo(Arg0)); 6917 if (Res.first.getNode()) { 6918 processIntegerCallValue(I, Res.first, false); 6919 PendingLoads.push_back(Res.second); 6920 return true; 6921 } 6922 6923 return false; 6924 } 6925 6926 /// See if we can lower a strnlen call into an optimized form. If so, return 6927 /// true and lower it, otherwise return false and it will be lowered like a 6928 /// normal call. 6929 /// The caller already checked that \p I calls the appropriate LibFunc with a 6930 /// correct prototype. 6931 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6932 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6933 6934 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6935 std::pair<SDValue, SDValue> Res = 6936 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6937 getValue(Arg0), getValue(Arg1), 6938 MachinePointerInfo(Arg0)); 6939 if (Res.first.getNode()) { 6940 processIntegerCallValue(I, Res.first, false); 6941 PendingLoads.push_back(Res.second); 6942 return true; 6943 } 6944 6945 return false; 6946 } 6947 6948 /// See if we can lower a unary floating-point operation into an SDNode with 6949 /// the specified Opcode. If so, return true and lower it, otherwise return 6950 /// false and it will be lowered like a normal call. 6951 /// The caller already checked that \p I calls the appropriate LibFunc with a 6952 /// correct prototype. 6953 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6954 unsigned Opcode) { 6955 // We already checked this call's prototype; verify it doesn't modify errno. 6956 if (!I.onlyReadsMemory()) 6957 return false; 6958 6959 SDValue Tmp = getValue(I.getArgOperand(0)); 6960 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6961 return true; 6962 } 6963 6964 /// See if we can lower a binary floating-point operation into an SDNode with 6965 /// the specified Opcode. If so, return true and lower it. Otherwise return 6966 /// false, and it will be lowered like a normal call. 6967 /// The caller already checked that \p I calls the appropriate LibFunc with a 6968 /// correct prototype. 6969 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6970 unsigned Opcode) { 6971 // We already checked this call's prototype; verify it doesn't modify errno. 6972 if (!I.onlyReadsMemory()) 6973 return false; 6974 6975 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6976 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6977 EVT VT = Tmp0.getValueType(); 6978 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6979 return true; 6980 } 6981 6982 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6983 // Handle inline assembly differently. 6984 if (isa<InlineAsm>(I.getCalledValue())) { 6985 visitInlineAsm(&I); 6986 return; 6987 } 6988 6989 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6990 computeUsesVAFloatArgument(I, MMI); 6991 6992 const char *RenameFn = nullptr; 6993 if (Function *F = I.getCalledFunction()) { 6994 if (F->isDeclaration()) { 6995 // Is this an LLVM intrinsic or a target-specific intrinsic? 6996 unsigned IID = F->getIntrinsicID(); 6997 if (!IID) 6998 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 6999 IID = II->getIntrinsicID(F); 7000 7001 if (IID) { 7002 RenameFn = visitIntrinsicCall(I, IID); 7003 if (!RenameFn) 7004 return; 7005 } 7006 } 7007 7008 // Check for well-known libc/libm calls. If the function is internal, it 7009 // can't be a library call. Don't do the check if marked as nobuiltin for 7010 // some reason or the call site requires strict floating point semantics. 7011 LibFunc Func; 7012 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7013 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7014 LibInfo->hasOptimizedCodeGen(Func)) { 7015 switch (Func) { 7016 default: break; 7017 case LibFunc_copysign: 7018 case LibFunc_copysignf: 7019 case LibFunc_copysignl: 7020 // We already checked this call's prototype; verify it doesn't modify 7021 // errno. 7022 if (I.onlyReadsMemory()) { 7023 SDValue LHS = getValue(I.getArgOperand(0)); 7024 SDValue RHS = getValue(I.getArgOperand(1)); 7025 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7026 LHS.getValueType(), LHS, RHS)); 7027 return; 7028 } 7029 break; 7030 case LibFunc_fabs: 7031 case LibFunc_fabsf: 7032 case LibFunc_fabsl: 7033 if (visitUnaryFloatCall(I, ISD::FABS)) 7034 return; 7035 break; 7036 case LibFunc_fmin: 7037 case LibFunc_fminf: 7038 case LibFunc_fminl: 7039 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7040 return; 7041 break; 7042 case LibFunc_fmax: 7043 case LibFunc_fmaxf: 7044 case LibFunc_fmaxl: 7045 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7046 return; 7047 break; 7048 case LibFunc_sin: 7049 case LibFunc_sinf: 7050 case LibFunc_sinl: 7051 if (visitUnaryFloatCall(I, ISD::FSIN)) 7052 return; 7053 break; 7054 case LibFunc_cos: 7055 case LibFunc_cosf: 7056 case LibFunc_cosl: 7057 if (visitUnaryFloatCall(I, ISD::FCOS)) 7058 return; 7059 break; 7060 case LibFunc_sqrt: 7061 case LibFunc_sqrtf: 7062 case LibFunc_sqrtl: 7063 case LibFunc_sqrt_finite: 7064 case LibFunc_sqrtf_finite: 7065 case LibFunc_sqrtl_finite: 7066 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7067 return; 7068 break; 7069 case LibFunc_floor: 7070 case LibFunc_floorf: 7071 case LibFunc_floorl: 7072 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7073 return; 7074 break; 7075 case LibFunc_nearbyint: 7076 case LibFunc_nearbyintf: 7077 case LibFunc_nearbyintl: 7078 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7079 return; 7080 break; 7081 case LibFunc_ceil: 7082 case LibFunc_ceilf: 7083 case LibFunc_ceill: 7084 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7085 return; 7086 break; 7087 case LibFunc_rint: 7088 case LibFunc_rintf: 7089 case LibFunc_rintl: 7090 if (visitUnaryFloatCall(I, ISD::FRINT)) 7091 return; 7092 break; 7093 case LibFunc_round: 7094 case LibFunc_roundf: 7095 case LibFunc_roundl: 7096 if (visitUnaryFloatCall(I, ISD::FROUND)) 7097 return; 7098 break; 7099 case LibFunc_trunc: 7100 case LibFunc_truncf: 7101 case LibFunc_truncl: 7102 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7103 return; 7104 break; 7105 case LibFunc_log2: 7106 case LibFunc_log2f: 7107 case LibFunc_log2l: 7108 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7109 return; 7110 break; 7111 case LibFunc_exp2: 7112 case LibFunc_exp2f: 7113 case LibFunc_exp2l: 7114 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7115 return; 7116 break; 7117 case LibFunc_memcmp: 7118 if (visitMemCmpCall(I)) 7119 return; 7120 break; 7121 case LibFunc_mempcpy: 7122 if (visitMemPCpyCall(I)) 7123 return; 7124 break; 7125 case LibFunc_memchr: 7126 if (visitMemChrCall(I)) 7127 return; 7128 break; 7129 case LibFunc_strcpy: 7130 if (visitStrCpyCall(I, false)) 7131 return; 7132 break; 7133 case LibFunc_stpcpy: 7134 if (visitStrCpyCall(I, true)) 7135 return; 7136 break; 7137 case LibFunc_strcmp: 7138 if (visitStrCmpCall(I)) 7139 return; 7140 break; 7141 case LibFunc_strlen: 7142 if (visitStrLenCall(I)) 7143 return; 7144 break; 7145 case LibFunc_strnlen: 7146 if (visitStrNLenCall(I)) 7147 return; 7148 break; 7149 } 7150 } 7151 } 7152 7153 SDValue Callee; 7154 if (!RenameFn) 7155 Callee = getValue(I.getCalledValue()); 7156 else 7157 Callee = DAG.getExternalSymbol( 7158 RenameFn, 7159 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7160 7161 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7162 // have to do anything here to lower funclet bundles. 7163 assert(!I.hasOperandBundlesOtherThan( 7164 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7165 "Cannot lower calls with arbitrary operand bundles!"); 7166 7167 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7168 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7169 else 7170 // Check if we can potentially perform a tail call. More detailed checking 7171 // is be done within LowerCallTo, after more information about the call is 7172 // known. 7173 LowerCallTo(&I, Callee, I.isTailCall()); 7174 } 7175 7176 namespace { 7177 7178 /// AsmOperandInfo - This contains information for each constraint that we are 7179 /// lowering. 7180 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7181 public: 7182 /// CallOperand - If this is the result output operand or a clobber 7183 /// this is null, otherwise it is the incoming operand to the CallInst. 7184 /// This gets modified as the asm is processed. 7185 SDValue CallOperand; 7186 7187 /// AssignedRegs - If this is a register or register class operand, this 7188 /// contains the set of register corresponding to the operand. 7189 RegsForValue AssignedRegs; 7190 7191 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7192 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7193 } 7194 7195 /// Whether or not this operand accesses memory 7196 bool hasMemory(const TargetLowering &TLI) const { 7197 // Indirect operand accesses access memory. 7198 if (isIndirect) 7199 return true; 7200 7201 for (const auto &Code : Codes) 7202 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7203 return true; 7204 7205 return false; 7206 } 7207 7208 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7209 /// corresponds to. If there is no Value* for this operand, it returns 7210 /// MVT::Other. 7211 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7212 const DataLayout &DL) const { 7213 if (!CallOperandVal) return MVT::Other; 7214 7215 if (isa<BasicBlock>(CallOperandVal)) 7216 return TLI.getPointerTy(DL); 7217 7218 llvm::Type *OpTy = CallOperandVal->getType(); 7219 7220 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7221 // If this is an indirect operand, the operand is a pointer to the 7222 // accessed type. 7223 if (isIndirect) { 7224 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7225 if (!PtrTy) 7226 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7227 OpTy = PtrTy->getElementType(); 7228 } 7229 7230 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7231 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7232 if (STy->getNumElements() == 1) 7233 OpTy = STy->getElementType(0); 7234 7235 // If OpTy is not a single value, it may be a struct/union that we 7236 // can tile with integers. 7237 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7238 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7239 switch (BitSize) { 7240 default: break; 7241 case 1: 7242 case 8: 7243 case 16: 7244 case 32: 7245 case 64: 7246 case 128: 7247 OpTy = IntegerType::get(Context, BitSize); 7248 break; 7249 } 7250 } 7251 7252 return TLI.getValueType(DL, OpTy, true); 7253 } 7254 }; 7255 7256 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7257 7258 } // end anonymous namespace 7259 7260 /// Make sure that the output operand \p OpInfo and its corresponding input 7261 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7262 /// out). 7263 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7264 SDISelAsmOperandInfo &MatchingOpInfo, 7265 SelectionDAG &DAG) { 7266 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7267 return; 7268 7269 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7270 const auto &TLI = DAG.getTargetLoweringInfo(); 7271 7272 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7273 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7274 OpInfo.ConstraintVT); 7275 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7276 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7277 MatchingOpInfo.ConstraintVT); 7278 if ((OpInfo.ConstraintVT.isInteger() != 7279 MatchingOpInfo.ConstraintVT.isInteger()) || 7280 (MatchRC.second != InputRC.second)) { 7281 // FIXME: error out in a more elegant fashion 7282 report_fatal_error("Unsupported asm: input constraint" 7283 " with a matching output constraint of" 7284 " incompatible type!"); 7285 } 7286 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7287 } 7288 7289 /// Get a direct memory input to behave well as an indirect operand. 7290 /// This may introduce stores, hence the need for a \p Chain. 7291 /// \return The (possibly updated) chain. 7292 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7293 SDISelAsmOperandInfo &OpInfo, 7294 SelectionDAG &DAG) { 7295 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7296 7297 // If we don't have an indirect input, put it in the constpool if we can, 7298 // otherwise spill it to a stack slot. 7299 // TODO: This isn't quite right. We need to handle these according to 7300 // the addressing mode that the constraint wants. Also, this may take 7301 // an additional register for the computation and we don't want that 7302 // either. 7303 7304 // If the operand is a float, integer, or vector constant, spill to a 7305 // constant pool entry to get its address. 7306 const Value *OpVal = OpInfo.CallOperandVal; 7307 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7308 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7309 OpInfo.CallOperand = DAG.getConstantPool( 7310 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7311 return Chain; 7312 } 7313 7314 // Otherwise, create a stack slot and emit a store to it before the asm. 7315 Type *Ty = OpVal->getType(); 7316 auto &DL = DAG.getDataLayout(); 7317 uint64_t TySize = DL.getTypeAllocSize(Ty); 7318 unsigned Align = DL.getPrefTypeAlignment(Ty); 7319 MachineFunction &MF = DAG.getMachineFunction(); 7320 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7321 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7322 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7323 MachinePointerInfo::getFixedStack(MF, SSFI)); 7324 OpInfo.CallOperand = StackSlot; 7325 7326 return Chain; 7327 } 7328 7329 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7330 /// specified operand. We prefer to assign virtual registers, to allow the 7331 /// register allocator to handle the assignment process. However, if the asm 7332 /// uses features that we can't model on machineinstrs, we have SDISel do the 7333 /// allocation. This produces generally horrible, but correct, code. 7334 /// 7335 /// OpInfo describes the operand 7336 /// RefOpInfo describes the matching operand if any, the operand otherwise 7337 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7338 SDISelAsmOperandInfo &OpInfo, 7339 SDISelAsmOperandInfo &RefOpInfo) { 7340 LLVMContext &Context = *DAG.getContext(); 7341 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7342 7343 MachineFunction &MF = DAG.getMachineFunction(); 7344 SmallVector<unsigned, 4> Regs; 7345 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7346 7347 // If this is a constraint for a single physreg, or a constraint for a 7348 // register class, find it. 7349 unsigned AssignedReg; 7350 const TargetRegisterClass *RC; 7351 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7352 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7353 // RC is unset only on failure. Return immediately. 7354 if (!RC) 7355 return; 7356 7357 // Get the actual register value type. This is important, because the user 7358 // may have asked for (e.g.) the AX register in i32 type. We need to 7359 // remember that AX is actually i16 to get the right extension. 7360 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7361 7362 if (OpInfo.ConstraintVT != MVT::Other) { 7363 // If this is an FP operand in an integer register (or visa versa), or more 7364 // generally if the operand value disagrees with the register class we plan 7365 // to stick it in, fix the operand type. 7366 // 7367 // If this is an input value, the bitcast to the new type is done now. 7368 // Bitcast for output value is done at the end of visitInlineAsm(). 7369 if ((OpInfo.Type == InlineAsm::isOutput || 7370 OpInfo.Type == InlineAsm::isInput) && 7371 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7372 // Try to convert to the first EVT that the reg class contains. If the 7373 // types are identical size, use a bitcast to convert (e.g. two differing 7374 // vector types). Note: output bitcast is done at the end of 7375 // visitInlineAsm(). 7376 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7377 // Exclude indirect inputs while they are unsupported because the code 7378 // to perform the load is missing and thus OpInfo.CallOperand still 7379 // refers to the input address rather than the pointed-to value. 7380 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7381 OpInfo.CallOperand = 7382 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7383 OpInfo.ConstraintVT = RegVT; 7384 // If the operand is an FP value and we want it in integer registers, 7385 // use the corresponding integer type. This turns an f64 value into 7386 // i64, which can be passed with two i32 values on a 32-bit machine. 7387 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7388 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7389 if (OpInfo.Type == InlineAsm::isInput) 7390 OpInfo.CallOperand = 7391 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7392 OpInfo.ConstraintVT = VT; 7393 } 7394 } 7395 } 7396 7397 // No need to allocate a matching input constraint since the constraint it's 7398 // matching to has already been allocated. 7399 if (OpInfo.isMatchingInputConstraint()) 7400 return; 7401 7402 EVT ValueVT = OpInfo.ConstraintVT; 7403 if (OpInfo.ConstraintVT == MVT::Other) 7404 ValueVT = RegVT; 7405 7406 // Initialize NumRegs. 7407 unsigned NumRegs = 1; 7408 if (OpInfo.ConstraintVT != MVT::Other) 7409 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7410 7411 // If this is a constraint for a specific physical register, like {r17}, 7412 // assign it now. 7413 7414 // If this associated to a specific register, initialize iterator to correct 7415 // place. If virtual, make sure we have enough registers 7416 7417 // Initialize iterator if necessary 7418 TargetRegisterClass::iterator I = RC->begin(); 7419 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7420 7421 // Do not check for single registers. 7422 if (AssignedReg) { 7423 for (; *I != AssignedReg; ++I) 7424 assert(I != RC->end() && "AssignedReg should be member of RC"); 7425 } 7426 7427 for (; NumRegs; --NumRegs, ++I) { 7428 assert(I != RC->end() && "Ran out of registers to allocate!"); 7429 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7430 Regs.push_back(R); 7431 } 7432 7433 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7434 } 7435 7436 static unsigned 7437 findMatchingInlineAsmOperand(unsigned OperandNo, 7438 const std::vector<SDValue> &AsmNodeOperands) { 7439 // Scan until we find the definition we already emitted of this operand. 7440 unsigned CurOp = InlineAsm::Op_FirstOperand; 7441 for (; OperandNo; --OperandNo) { 7442 // Advance to the next operand. 7443 unsigned OpFlag = 7444 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7445 assert((InlineAsm::isRegDefKind(OpFlag) || 7446 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7447 InlineAsm::isMemKind(OpFlag)) && 7448 "Skipped past definitions?"); 7449 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7450 } 7451 return CurOp; 7452 } 7453 7454 namespace { 7455 7456 class ExtraFlags { 7457 unsigned Flags = 0; 7458 7459 public: 7460 explicit ExtraFlags(ImmutableCallSite CS) { 7461 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7462 if (IA->hasSideEffects()) 7463 Flags |= InlineAsm::Extra_HasSideEffects; 7464 if (IA->isAlignStack()) 7465 Flags |= InlineAsm::Extra_IsAlignStack; 7466 if (CS.isConvergent()) 7467 Flags |= InlineAsm::Extra_IsConvergent; 7468 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7469 } 7470 7471 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7472 // Ideally, we would only check against memory constraints. However, the 7473 // meaning of an Other constraint can be target-specific and we can't easily 7474 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7475 // for Other constraints as well. 7476 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7477 OpInfo.ConstraintType == TargetLowering::C_Other) { 7478 if (OpInfo.Type == InlineAsm::isInput) 7479 Flags |= InlineAsm::Extra_MayLoad; 7480 else if (OpInfo.Type == InlineAsm::isOutput) 7481 Flags |= InlineAsm::Extra_MayStore; 7482 else if (OpInfo.Type == InlineAsm::isClobber) 7483 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7484 } 7485 } 7486 7487 unsigned get() const { return Flags; } 7488 }; 7489 7490 } // end anonymous namespace 7491 7492 /// visitInlineAsm - Handle a call to an InlineAsm object. 7493 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7494 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7495 7496 /// ConstraintOperands - Information about all of the constraints. 7497 SDISelAsmOperandInfoVector ConstraintOperands; 7498 7499 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7500 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7501 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7502 7503 bool hasMemory = false; 7504 7505 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7506 ExtraFlags ExtraInfo(CS); 7507 7508 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7509 unsigned ResNo = 0; // ResNo - The result number of the next output. 7510 for (auto &T : TargetConstraints) { 7511 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7512 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7513 7514 // Compute the value type for each operand. 7515 if (OpInfo.Type == InlineAsm::isInput || 7516 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7517 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7518 7519 // Process the call argument. BasicBlocks are labels, currently appearing 7520 // only in asm's. 7521 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7522 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7523 } else { 7524 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7525 } 7526 7527 OpInfo.ConstraintVT = 7528 OpInfo 7529 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7530 .getSimpleVT(); 7531 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7532 // The return value of the call is this value. As such, there is no 7533 // corresponding argument. 7534 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7535 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7536 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7537 DAG.getDataLayout(), STy->getElementType(ResNo)); 7538 } else { 7539 assert(ResNo == 0 && "Asm only has one result!"); 7540 OpInfo.ConstraintVT = 7541 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7542 } 7543 ++ResNo; 7544 } else { 7545 OpInfo.ConstraintVT = MVT::Other; 7546 } 7547 7548 if (!hasMemory) 7549 hasMemory = OpInfo.hasMemory(TLI); 7550 7551 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7552 // FIXME: Could we compute this on OpInfo rather than T? 7553 7554 // Compute the constraint code and ConstraintType to use. 7555 TLI.ComputeConstraintToUse(T, SDValue()); 7556 7557 ExtraInfo.update(T); 7558 } 7559 7560 SDValue Chain, Flag; 7561 7562 // We won't need to flush pending loads if this asm doesn't touch 7563 // memory and is nonvolatile. 7564 if (hasMemory || IA->hasSideEffects()) 7565 Chain = getRoot(); 7566 else 7567 Chain = DAG.getRoot(); 7568 7569 // Second pass over the constraints: compute which constraint option to use 7570 // and assign registers to constraints that want a specific physreg. 7571 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7572 // If this is an output operand with a matching input operand, look up the 7573 // matching input. If their types mismatch, e.g. one is an integer, the 7574 // other is floating point, or their sizes are different, flag it as an 7575 // error. 7576 if (OpInfo.hasMatchingInput()) { 7577 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7578 patchMatchingInput(OpInfo, Input, DAG); 7579 } 7580 7581 // Compute the constraint code and ConstraintType to use. 7582 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7583 7584 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7585 OpInfo.Type == InlineAsm::isClobber) 7586 continue; 7587 7588 // If this is a memory input, and if the operand is not indirect, do what we 7589 // need to provide an address for the memory input. 7590 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7591 !OpInfo.isIndirect) { 7592 assert((OpInfo.isMultipleAlternative || 7593 (OpInfo.Type == InlineAsm::isInput)) && 7594 "Can only indirectify direct input operands!"); 7595 7596 // Memory operands really want the address of the value. 7597 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7598 7599 // There is no longer a Value* corresponding to this operand. 7600 OpInfo.CallOperandVal = nullptr; 7601 7602 // It is now an indirect operand. 7603 OpInfo.isIndirect = true; 7604 } 7605 7606 // If this constraint is for a specific register, allocate it before 7607 // anything else. 7608 SDISelAsmOperandInfo &RefOpInfo = 7609 OpInfo.isMatchingInputConstraint() 7610 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7611 : OpInfo; 7612 if (RefOpInfo.ConstraintType == TargetLowering::C_Register) 7613 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7614 } 7615 7616 // Third pass - Loop over all of the operands, assigning virtual or physregs 7617 // to register class operands. 7618 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7619 SDISelAsmOperandInfo &RefOpInfo = 7620 OpInfo.isMatchingInputConstraint() 7621 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7622 : OpInfo; 7623 7624 // C_Register operands have already been allocated, Other/Memory don't need 7625 // to be. 7626 if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7627 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7628 } 7629 7630 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7631 std::vector<SDValue> AsmNodeOperands; 7632 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7633 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7634 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7635 7636 // If we have a !srcloc metadata node associated with it, we want to attach 7637 // this to the ultimately generated inline asm machineinstr. To do this, we 7638 // pass in the third operand as this (potentially null) inline asm MDNode. 7639 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7640 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7641 7642 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7643 // bits as operand 3. 7644 AsmNodeOperands.push_back(DAG.getTargetConstant( 7645 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7646 7647 // Loop over all of the inputs, copying the operand values into the 7648 // appropriate registers and processing the output regs. 7649 RegsForValue RetValRegs; 7650 7651 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7652 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7653 7654 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7655 switch (OpInfo.Type) { 7656 case InlineAsm::isOutput: 7657 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7658 OpInfo.ConstraintType != TargetLowering::C_Register) { 7659 // Memory output, or 'other' output (e.g. 'X' constraint). 7660 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7661 7662 unsigned ConstraintID = 7663 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7664 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7665 "Failed to convert memory constraint code to constraint id."); 7666 7667 // Add information to the INLINEASM node to know about this output. 7668 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7669 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7670 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7671 MVT::i32)); 7672 AsmNodeOperands.push_back(OpInfo.CallOperand); 7673 break; 7674 } 7675 7676 // Otherwise, this is a register or register class output. 7677 7678 // Copy the output from the appropriate register. Find a register that 7679 // we can use. 7680 if (OpInfo.AssignedRegs.Regs.empty()) { 7681 emitInlineAsmError( 7682 CS, "couldn't allocate output register for constraint '" + 7683 Twine(OpInfo.ConstraintCode) + "'"); 7684 return; 7685 } 7686 7687 // If this is an indirect operand, store through the pointer after the 7688 // asm. 7689 if (OpInfo.isIndirect) { 7690 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7691 OpInfo.CallOperandVal)); 7692 } else { 7693 // This is the result value of the call. 7694 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7695 // Concatenate this output onto the outputs list. 7696 RetValRegs.append(OpInfo.AssignedRegs); 7697 } 7698 7699 // Add information to the INLINEASM node to know that this register is 7700 // set. 7701 OpInfo.AssignedRegs 7702 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7703 ? InlineAsm::Kind_RegDefEarlyClobber 7704 : InlineAsm::Kind_RegDef, 7705 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7706 break; 7707 7708 case InlineAsm::isInput: { 7709 SDValue InOperandVal = OpInfo.CallOperand; 7710 7711 if (OpInfo.isMatchingInputConstraint()) { 7712 // If this is required to match an output register we have already set, 7713 // just use its register. 7714 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7715 AsmNodeOperands); 7716 unsigned OpFlag = 7717 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7718 if (InlineAsm::isRegDefKind(OpFlag) || 7719 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7720 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7721 if (OpInfo.isIndirect) { 7722 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7723 emitInlineAsmError(CS, "inline asm not supported yet:" 7724 " don't know how to handle tied " 7725 "indirect register inputs"); 7726 return; 7727 } 7728 7729 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7730 SmallVector<unsigned, 4> Regs; 7731 7732 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7733 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7734 MachineRegisterInfo &RegInfo = 7735 DAG.getMachineFunction().getRegInfo(); 7736 for (unsigned i = 0; i != NumRegs; ++i) 7737 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7738 } else { 7739 emitInlineAsmError(CS, "inline asm error: This value type register " 7740 "class is not natively supported!"); 7741 return; 7742 } 7743 7744 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7745 7746 SDLoc dl = getCurSDLoc(); 7747 // Use the produced MatchedRegs object to 7748 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7749 CS.getInstruction()); 7750 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7751 true, OpInfo.getMatchedOperand(), dl, 7752 DAG, AsmNodeOperands); 7753 break; 7754 } 7755 7756 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7757 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7758 "Unexpected number of operands"); 7759 // Add information to the INLINEASM node to know about this input. 7760 // See InlineAsm.h isUseOperandTiedToDef. 7761 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7762 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7763 OpInfo.getMatchedOperand()); 7764 AsmNodeOperands.push_back(DAG.getTargetConstant( 7765 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7766 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7767 break; 7768 } 7769 7770 // Treat indirect 'X' constraint as memory. 7771 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7772 OpInfo.isIndirect) 7773 OpInfo.ConstraintType = TargetLowering::C_Memory; 7774 7775 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7776 std::vector<SDValue> Ops; 7777 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7778 Ops, DAG); 7779 if (Ops.empty()) { 7780 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7781 Twine(OpInfo.ConstraintCode) + "'"); 7782 return; 7783 } 7784 7785 // Add information to the INLINEASM node to know about this input. 7786 unsigned ResOpType = 7787 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7788 AsmNodeOperands.push_back(DAG.getTargetConstant( 7789 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7790 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7791 break; 7792 } 7793 7794 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7795 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7796 assert(InOperandVal.getValueType() == 7797 TLI.getPointerTy(DAG.getDataLayout()) && 7798 "Memory operands expect pointer values"); 7799 7800 unsigned ConstraintID = 7801 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7802 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7803 "Failed to convert memory constraint code to constraint id."); 7804 7805 // Add information to the INLINEASM node to know about this input. 7806 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7807 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7808 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7809 getCurSDLoc(), 7810 MVT::i32)); 7811 AsmNodeOperands.push_back(InOperandVal); 7812 break; 7813 } 7814 7815 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7816 OpInfo.ConstraintType == TargetLowering::C_Register) && 7817 "Unknown constraint type!"); 7818 7819 // TODO: Support this. 7820 if (OpInfo.isIndirect) { 7821 emitInlineAsmError( 7822 CS, "Don't know how to handle indirect register inputs yet " 7823 "for constraint '" + 7824 Twine(OpInfo.ConstraintCode) + "'"); 7825 return; 7826 } 7827 7828 // Copy the input into the appropriate registers. 7829 if (OpInfo.AssignedRegs.Regs.empty()) { 7830 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7831 Twine(OpInfo.ConstraintCode) + "'"); 7832 return; 7833 } 7834 7835 SDLoc dl = getCurSDLoc(); 7836 7837 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7838 Chain, &Flag, CS.getInstruction()); 7839 7840 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7841 dl, DAG, AsmNodeOperands); 7842 break; 7843 } 7844 case InlineAsm::isClobber: 7845 // Add the clobbered value to the operand list, so that the register 7846 // allocator is aware that the physreg got clobbered. 7847 if (!OpInfo.AssignedRegs.Regs.empty()) 7848 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7849 false, 0, getCurSDLoc(), DAG, 7850 AsmNodeOperands); 7851 break; 7852 } 7853 } 7854 7855 // Finish up input operands. Set the input chain and add the flag last. 7856 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7857 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7858 7859 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7860 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7861 Flag = Chain.getValue(1); 7862 7863 // If this asm returns a register value, copy the result from that register 7864 // and set it as the value of the call. 7865 if (!RetValRegs.Regs.empty()) { 7866 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7867 Chain, &Flag, CS.getInstruction()); 7868 7869 llvm::Type *CSResultType = CS.getType(); 7870 unsigned numRet; 7871 ArrayRef<Type *> ResultTypes; 7872 SmallVector<SDValue, 1> ResultValues(1); 7873 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) { 7874 numRet = StructResult->getNumElements(); 7875 assert(Val->getNumOperands() == numRet && 7876 "Mismatch in number of output operands in asm result"); 7877 ResultTypes = StructResult->elements(); 7878 ArrayRef<SDUse> ValueUses = Val->ops(); 7879 ResultValues.resize(numRet); 7880 std::transform(ValueUses.begin(), ValueUses.end(), ResultValues.begin(), 7881 [](const SDUse &u) -> SDValue { return u.get(); }); 7882 } else { 7883 numRet = 1; 7884 ResultValues[0] = Val; 7885 ResultTypes = makeArrayRef(CSResultType); 7886 } 7887 SmallVector<EVT, 1> ResultVTs(numRet); 7888 for (unsigned i = 0; i < numRet; i++) { 7889 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), ResultTypes[i]); 7890 SDValue Val = ResultValues[i]; 7891 assert(ResultTypes[i]->isSized() && "Unexpected unsized type"); 7892 // If the type of the inline asm call site return value is different but 7893 // has same size as the type of the asm output bitcast it. One example 7894 // of this is for vectors with different width / number of elements. 7895 // This can happen for register classes that can contain multiple 7896 // different value types. The preg or vreg allocated may not have the 7897 // same VT as was expected. 7898 // 7899 // This can also happen for a return value that disagrees with the 7900 // register class it is put in, eg. a double in a general-purpose 7901 // register on a 32-bit machine. 7902 if (ResultVT != Val.getValueType() && 7903 ResultVT.getSizeInBits() == Val.getValueSizeInBits()) 7904 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, Val); 7905 else if (ResultVT != Val.getValueType() && ResultVT.isInteger() && 7906 Val.getValueType().isInteger()) { 7907 // If a result value was tied to an input value, the computed result 7908 // may have a wider width than the expected result. Extract the 7909 // relevant portion. 7910 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, Val); 7911 } 7912 7913 assert(ResultVT == Val.getValueType() && "Asm result value mismatch!"); 7914 ResultVTs[i] = ResultVT; 7915 ResultValues[i] = Val; 7916 } 7917 7918 Val = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7919 DAG.getVTList(ResultVTs), ResultValues); 7920 setValue(CS.getInstruction(), Val); 7921 // Don't need to use this as a chain in this case. 7922 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7923 return; 7924 } 7925 7926 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7927 7928 // Process indirect outputs, first output all of the flagged copies out of 7929 // physregs. 7930 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7931 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7932 const Value *Ptr = IndirectStoresToEmit[i].second; 7933 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7934 Chain, &Flag, IA); 7935 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7936 } 7937 7938 // Emit the non-flagged stores from the physregs. 7939 SmallVector<SDValue, 8> OutChains; 7940 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7941 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7942 getValue(StoresToEmit[i].second), 7943 MachinePointerInfo(StoresToEmit[i].second)); 7944 OutChains.push_back(Val); 7945 } 7946 7947 if (!OutChains.empty()) 7948 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7949 7950 DAG.setRoot(Chain); 7951 } 7952 7953 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7954 const Twine &Message) { 7955 LLVMContext &Ctx = *DAG.getContext(); 7956 Ctx.emitError(CS.getInstruction(), Message); 7957 7958 // Make sure we leave the DAG in a valid state 7959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7960 SmallVector<EVT, 1> ValueVTs; 7961 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7962 7963 if (ValueVTs.empty()) 7964 return; 7965 7966 SmallVector<SDValue, 1> Ops; 7967 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7968 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7969 7970 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7971 } 7972 7973 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7974 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7975 MVT::Other, getRoot(), 7976 getValue(I.getArgOperand(0)), 7977 DAG.getSrcValue(I.getArgOperand(0)))); 7978 } 7979 7980 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7981 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7982 const DataLayout &DL = DAG.getDataLayout(); 7983 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7984 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7985 DAG.getSrcValue(I.getOperand(0)), 7986 DL.getABITypeAlignment(I.getType())); 7987 setValue(&I, V); 7988 DAG.setRoot(V.getValue(1)); 7989 } 7990 7991 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7992 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7993 MVT::Other, getRoot(), 7994 getValue(I.getArgOperand(0)), 7995 DAG.getSrcValue(I.getArgOperand(0)))); 7996 } 7997 7998 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7999 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8000 MVT::Other, getRoot(), 8001 getValue(I.getArgOperand(0)), 8002 getValue(I.getArgOperand(1)), 8003 DAG.getSrcValue(I.getArgOperand(0)), 8004 DAG.getSrcValue(I.getArgOperand(1)))); 8005 } 8006 8007 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8008 const Instruction &I, 8009 SDValue Op) { 8010 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8011 if (!Range) 8012 return Op; 8013 8014 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8015 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8016 return Op; 8017 8018 APInt Lo = CR.getUnsignedMin(); 8019 if (!Lo.isMinValue()) 8020 return Op; 8021 8022 APInt Hi = CR.getUnsignedMax(); 8023 unsigned Bits = std::max(Hi.getActiveBits(), 8024 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8025 8026 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8027 8028 SDLoc SL = getCurSDLoc(); 8029 8030 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8031 DAG.getValueType(SmallVT)); 8032 unsigned NumVals = Op.getNode()->getNumValues(); 8033 if (NumVals == 1) 8034 return ZExt; 8035 8036 SmallVector<SDValue, 4> Ops; 8037 8038 Ops.push_back(ZExt); 8039 for (unsigned I = 1; I != NumVals; ++I) 8040 Ops.push_back(Op.getValue(I)); 8041 8042 return DAG.getMergeValues(Ops, SL); 8043 } 8044 8045 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8046 /// the call being lowered. 8047 /// 8048 /// This is a helper for lowering intrinsics that follow a target calling 8049 /// convention or require stack pointer adjustment. Only a subset of the 8050 /// intrinsic's operands need to participate in the calling convention. 8051 void SelectionDAGBuilder::populateCallLoweringInfo( 8052 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8053 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8054 bool IsPatchPoint) { 8055 TargetLowering::ArgListTy Args; 8056 Args.reserve(NumArgs); 8057 8058 // Populate the argument list. 8059 // Attributes for args start at offset 1, after the return attribute. 8060 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8061 ArgI != ArgE; ++ArgI) { 8062 const Value *V = CS->getOperand(ArgI); 8063 8064 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8065 8066 TargetLowering::ArgListEntry Entry; 8067 Entry.Node = getValue(V); 8068 Entry.Ty = V->getType(); 8069 Entry.setAttributes(&CS, ArgI); 8070 Args.push_back(Entry); 8071 } 8072 8073 CLI.setDebugLoc(getCurSDLoc()) 8074 .setChain(getRoot()) 8075 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8076 .setDiscardResult(CS->use_empty()) 8077 .setIsPatchPoint(IsPatchPoint); 8078 } 8079 8080 /// Add a stack map intrinsic call's live variable operands to a stackmap 8081 /// or patchpoint target node's operand list. 8082 /// 8083 /// Constants are converted to TargetConstants purely as an optimization to 8084 /// avoid constant materialization and register allocation. 8085 /// 8086 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8087 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8088 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8089 /// address materialization and register allocation, but may also be required 8090 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8091 /// alloca in the entry block, then the runtime may assume that the alloca's 8092 /// StackMap location can be read immediately after compilation and that the 8093 /// location is valid at any point during execution (this is similar to the 8094 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8095 /// only available in a register, then the runtime would need to trap when 8096 /// execution reaches the StackMap in order to read the alloca's location. 8097 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8098 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8099 SelectionDAGBuilder &Builder) { 8100 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8101 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8103 Ops.push_back( 8104 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8105 Ops.push_back( 8106 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8107 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8108 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8109 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8110 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8111 } else 8112 Ops.push_back(OpVal); 8113 } 8114 } 8115 8116 /// Lower llvm.experimental.stackmap directly to its target opcode. 8117 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8118 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8119 // [live variables...]) 8120 8121 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8122 8123 SDValue Chain, InFlag, Callee, NullPtr; 8124 SmallVector<SDValue, 32> Ops; 8125 8126 SDLoc DL = getCurSDLoc(); 8127 Callee = getValue(CI.getCalledValue()); 8128 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8129 8130 // The stackmap intrinsic only records the live variables (the arguemnts 8131 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8132 // intrinsic, this won't be lowered to a function call. This means we don't 8133 // have to worry about calling conventions and target specific lowering code. 8134 // Instead we perform the call lowering right here. 8135 // 8136 // chain, flag = CALLSEQ_START(chain, 0, 0) 8137 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8138 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8139 // 8140 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8141 InFlag = Chain.getValue(1); 8142 8143 // Add the <id> and <numBytes> constants. 8144 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8145 Ops.push_back(DAG.getTargetConstant( 8146 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8147 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8148 Ops.push_back(DAG.getTargetConstant( 8149 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8150 MVT::i32)); 8151 8152 // Push live variables for the stack map. 8153 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8154 8155 // We are not pushing any register mask info here on the operands list, 8156 // because the stackmap doesn't clobber anything. 8157 8158 // Push the chain and the glue flag. 8159 Ops.push_back(Chain); 8160 Ops.push_back(InFlag); 8161 8162 // Create the STACKMAP node. 8163 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8164 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8165 Chain = SDValue(SM, 0); 8166 InFlag = Chain.getValue(1); 8167 8168 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8169 8170 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8171 8172 // Set the root to the target-lowered call chain. 8173 DAG.setRoot(Chain); 8174 8175 // Inform the Frame Information that we have a stackmap in this function. 8176 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8177 } 8178 8179 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8180 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8181 const BasicBlock *EHPadBB) { 8182 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8183 // i32 <numBytes>, 8184 // i8* <target>, 8185 // i32 <numArgs>, 8186 // [Args...], 8187 // [live variables...]) 8188 8189 CallingConv::ID CC = CS.getCallingConv(); 8190 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8191 bool HasDef = !CS->getType()->isVoidTy(); 8192 SDLoc dl = getCurSDLoc(); 8193 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8194 8195 // Handle immediate and symbolic callees. 8196 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8197 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8198 /*isTarget=*/true); 8199 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8200 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8201 SDLoc(SymbolicCallee), 8202 SymbolicCallee->getValueType(0)); 8203 8204 // Get the real number of arguments participating in the call <numArgs> 8205 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8206 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8207 8208 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8209 // Intrinsics include all meta-operands up to but not including CC. 8210 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8211 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8212 "Not enough arguments provided to the patchpoint intrinsic"); 8213 8214 // For AnyRegCC the arguments are lowered later on manually. 8215 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8216 Type *ReturnTy = 8217 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8218 8219 TargetLowering::CallLoweringInfo CLI(DAG); 8220 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8221 true); 8222 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8223 8224 SDNode *CallEnd = Result.second.getNode(); 8225 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8226 CallEnd = CallEnd->getOperand(0).getNode(); 8227 8228 /// Get a call instruction from the call sequence chain. 8229 /// Tail calls are not allowed. 8230 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8231 "Expected a callseq node."); 8232 SDNode *Call = CallEnd->getOperand(0).getNode(); 8233 bool HasGlue = Call->getGluedNode(); 8234 8235 // Replace the target specific call node with the patchable intrinsic. 8236 SmallVector<SDValue, 8> Ops; 8237 8238 // Add the <id> and <numBytes> constants. 8239 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8240 Ops.push_back(DAG.getTargetConstant( 8241 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8242 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8243 Ops.push_back(DAG.getTargetConstant( 8244 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8245 MVT::i32)); 8246 8247 // Add the callee. 8248 Ops.push_back(Callee); 8249 8250 // Adjust <numArgs> to account for any arguments that have been passed on the 8251 // stack instead. 8252 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8253 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8254 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8255 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8256 8257 // Add the calling convention 8258 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8259 8260 // Add the arguments we omitted previously. The register allocator should 8261 // place these in any free register. 8262 if (IsAnyRegCC) 8263 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8264 Ops.push_back(getValue(CS.getArgument(i))); 8265 8266 // Push the arguments from the call instruction up to the register mask. 8267 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8268 Ops.append(Call->op_begin() + 2, e); 8269 8270 // Push live variables for the stack map. 8271 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8272 8273 // Push the register mask info. 8274 if (HasGlue) 8275 Ops.push_back(*(Call->op_end()-2)); 8276 else 8277 Ops.push_back(*(Call->op_end()-1)); 8278 8279 // Push the chain (this is originally the first operand of the call, but 8280 // becomes now the last or second to last operand). 8281 Ops.push_back(*(Call->op_begin())); 8282 8283 // Push the glue flag (last operand). 8284 if (HasGlue) 8285 Ops.push_back(*(Call->op_end()-1)); 8286 8287 SDVTList NodeTys; 8288 if (IsAnyRegCC && HasDef) { 8289 // Create the return types based on the intrinsic definition 8290 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8291 SmallVector<EVT, 3> ValueVTs; 8292 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8293 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8294 8295 // There is always a chain and a glue type at the end 8296 ValueVTs.push_back(MVT::Other); 8297 ValueVTs.push_back(MVT::Glue); 8298 NodeTys = DAG.getVTList(ValueVTs); 8299 } else 8300 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8301 8302 // Replace the target specific call node with a PATCHPOINT node. 8303 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8304 dl, NodeTys, Ops); 8305 8306 // Update the NodeMap. 8307 if (HasDef) { 8308 if (IsAnyRegCC) 8309 setValue(CS.getInstruction(), SDValue(MN, 0)); 8310 else 8311 setValue(CS.getInstruction(), Result.first); 8312 } 8313 8314 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8315 // call sequence. Furthermore the location of the chain and glue can change 8316 // when the AnyReg calling convention is used and the intrinsic returns a 8317 // value. 8318 if (IsAnyRegCC && HasDef) { 8319 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8320 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8321 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8322 } else 8323 DAG.ReplaceAllUsesWith(Call, MN); 8324 DAG.DeleteNode(Call); 8325 8326 // Inform the Frame Information that we have a patchpoint in this function. 8327 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8328 } 8329 8330 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8331 unsigned Intrinsic) { 8332 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8333 SDValue Op1 = getValue(I.getArgOperand(0)); 8334 SDValue Op2; 8335 if (I.getNumArgOperands() > 1) 8336 Op2 = getValue(I.getArgOperand(1)); 8337 SDLoc dl = getCurSDLoc(); 8338 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8339 SDValue Res; 8340 FastMathFlags FMF; 8341 if (isa<FPMathOperator>(I)) 8342 FMF = I.getFastMathFlags(); 8343 8344 switch (Intrinsic) { 8345 case Intrinsic::experimental_vector_reduce_fadd: 8346 if (FMF.isFast()) 8347 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8348 else 8349 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8350 break; 8351 case Intrinsic::experimental_vector_reduce_fmul: 8352 if (FMF.isFast()) 8353 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8354 else 8355 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8356 break; 8357 case Intrinsic::experimental_vector_reduce_add: 8358 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8359 break; 8360 case Intrinsic::experimental_vector_reduce_mul: 8361 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8362 break; 8363 case Intrinsic::experimental_vector_reduce_and: 8364 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8365 break; 8366 case Intrinsic::experimental_vector_reduce_or: 8367 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8368 break; 8369 case Intrinsic::experimental_vector_reduce_xor: 8370 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8371 break; 8372 case Intrinsic::experimental_vector_reduce_smax: 8373 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8374 break; 8375 case Intrinsic::experimental_vector_reduce_smin: 8376 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8377 break; 8378 case Intrinsic::experimental_vector_reduce_umax: 8379 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8380 break; 8381 case Intrinsic::experimental_vector_reduce_umin: 8382 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8383 break; 8384 case Intrinsic::experimental_vector_reduce_fmax: 8385 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8386 break; 8387 case Intrinsic::experimental_vector_reduce_fmin: 8388 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8389 break; 8390 default: 8391 llvm_unreachable("Unhandled vector reduce intrinsic"); 8392 } 8393 setValue(&I, Res); 8394 } 8395 8396 /// Returns an AttributeList representing the attributes applied to the return 8397 /// value of the given call. 8398 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8399 SmallVector<Attribute::AttrKind, 2> Attrs; 8400 if (CLI.RetSExt) 8401 Attrs.push_back(Attribute::SExt); 8402 if (CLI.RetZExt) 8403 Attrs.push_back(Attribute::ZExt); 8404 if (CLI.IsInReg) 8405 Attrs.push_back(Attribute::InReg); 8406 8407 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8408 Attrs); 8409 } 8410 8411 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8412 /// implementation, which just calls LowerCall. 8413 /// FIXME: When all targets are 8414 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8415 std::pair<SDValue, SDValue> 8416 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8417 // Handle the incoming return values from the call. 8418 CLI.Ins.clear(); 8419 Type *OrigRetTy = CLI.RetTy; 8420 SmallVector<EVT, 4> RetTys; 8421 SmallVector<uint64_t, 4> Offsets; 8422 auto &DL = CLI.DAG.getDataLayout(); 8423 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8424 8425 if (CLI.IsPostTypeLegalization) { 8426 // If we are lowering a libcall after legalization, split the return type. 8427 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8428 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8429 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8430 EVT RetVT = OldRetTys[i]; 8431 uint64_t Offset = OldOffsets[i]; 8432 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8433 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8434 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8435 RetTys.append(NumRegs, RegisterVT); 8436 for (unsigned j = 0; j != NumRegs; ++j) 8437 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8438 } 8439 } 8440 8441 SmallVector<ISD::OutputArg, 4> Outs; 8442 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8443 8444 bool CanLowerReturn = 8445 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8446 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8447 8448 SDValue DemoteStackSlot; 8449 int DemoteStackIdx = -100; 8450 if (!CanLowerReturn) { 8451 // FIXME: equivalent assert? 8452 // assert(!CS.hasInAllocaArgument() && 8453 // "sret demotion is incompatible with inalloca"); 8454 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8455 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8456 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8457 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8458 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8459 DL.getAllocaAddrSpace()); 8460 8461 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8462 ArgListEntry Entry; 8463 Entry.Node = DemoteStackSlot; 8464 Entry.Ty = StackSlotPtrType; 8465 Entry.IsSExt = false; 8466 Entry.IsZExt = false; 8467 Entry.IsInReg = false; 8468 Entry.IsSRet = true; 8469 Entry.IsNest = false; 8470 Entry.IsByVal = false; 8471 Entry.IsReturned = false; 8472 Entry.IsSwiftSelf = false; 8473 Entry.IsSwiftError = false; 8474 Entry.Alignment = Align; 8475 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8476 CLI.NumFixedArgs += 1; 8477 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8478 8479 // sret demotion isn't compatible with tail-calls, since the sret argument 8480 // points into the callers stack frame. 8481 CLI.IsTailCall = false; 8482 } else { 8483 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8484 EVT VT = RetTys[I]; 8485 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8486 CLI.CallConv, VT); 8487 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8488 CLI.CallConv, VT); 8489 for (unsigned i = 0; i != NumRegs; ++i) { 8490 ISD::InputArg MyFlags; 8491 MyFlags.VT = RegisterVT; 8492 MyFlags.ArgVT = VT; 8493 MyFlags.Used = CLI.IsReturnValueUsed; 8494 if (CLI.RetSExt) 8495 MyFlags.Flags.setSExt(); 8496 if (CLI.RetZExt) 8497 MyFlags.Flags.setZExt(); 8498 if (CLI.IsInReg) 8499 MyFlags.Flags.setInReg(); 8500 CLI.Ins.push_back(MyFlags); 8501 } 8502 } 8503 } 8504 8505 // We push in swifterror return as the last element of CLI.Ins. 8506 ArgListTy &Args = CLI.getArgs(); 8507 if (supportSwiftError()) { 8508 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8509 if (Args[i].IsSwiftError) { 8510 ISD::InputArg MyFlags; 8511 MyFlags.VT = getPointerTy(DL); 8512 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8513 MyFlags.Flags.setSwiftError(); 8514 CLI.Ins.push_back(MyFlags); 8515 } 8516 } 8517 } 8518 8519 // Handle all of the outgoing arguments. 8520 CLI.Outs.clear(); 8521 CLI.OutVals.clear(); 8522 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8523 SmallVector<EVT, 4> ValueVTs; 8524 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8525 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8526 Type *FinalType = Args[i].Ty; 8527 if (Args[i].IsByVal) 8528 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8529 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8530 FinalType, CLI.CallConv, CLI.IsVarArg); 8531 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8532 ++Value) { 8533 EVT VT = ValueVTs[Value]; 8534 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8535 SDValue Op = SDValue(Args[i].Node.getNode(), 8536 Args[i].Node.getResNo() + Value); 8537 ISD::ArgFlagsTy Flags; 8538 8539 // Certain targets (such as MIPS), may have a different ABI alignment 8540 // for a type depending on the context. Give the target a chance to 8541 // specify the alignment it wants. 8542 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8543 8544 if (Args[i].IsZExt) 8545 Flags.setZExt(); 8546 if (Args[i].IsSExt) 8547 Flags.setSExt(); 8548 if (Args[i].IsInReg) { 8549 // If we are using vectorcall calling convention, a structure that is 8550 // passed InReg - is surely an HVA 8551 if (CLI.CallConv == CallingConv::X86_VectorCall && 8552 isa<StructType>(FinalType)) { 8553 // The first value of a structure is marked 8554 if (0 == Value) 8555 Flags.setHvaStart(); 8556 Flags.setHva(); 8557 } 8558 // Set InReg Flag 8559 Flags.setInReg(); 8560 } 8561 if (Args[i].IsSRet) 8562 Flags.setSRet(); 8563 if (Args[i].IsSwiftSelf) 8564 Flags.setSwiftSelf(); 8565 if (Args[i].IsSwiftError) 8566 Flags.setSwiftError(); 8567 if (Args[i].IsByVal) 8568 Flags.setByVal(); 8569 if (Args[i].IsInAlloca) { 8570 Flags.setInAlloca(); 8571 // Set the byval flag for CCAssignFn callbacks that don't know about 8572 // inalloca. This way we can know how many bytes we should've allocated 8573 // and how many bytes a callee cleanup function will pop. If we port 8574 // inalloca to more targets, we'll have to add custom inalloca handling 8575 // in the various CC lowering callbacks. 8576 Flags.setByVal(); 8577 } 8578 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8579 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8580 Type *ElementTy = Ty->getElementType(); 8581 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8582 // For ByVal, alignment should come from FE. BE will guess if this 8583 // info is not there but there are cases it cannot get right. 8584 unsigned FrameAlign; 8585 if (Args[i].Alignment) 8586 FrameAlign = Args[i].Alignment; 8587 else 8588 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8589 Flags.setByValAlign(FrameAlign); 8590 } 8591 if (Args[i].IsNest) 8592 Flags.setNest(); 8593 if (NeedsRegBlock) 8594 Flags.setInConsecutiveRegs(); 8595 Flags.setOrigAlign(OriginalAlignment); 8596 8597 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8598 CLI.CallConv, VT); 8599 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8600 CLI.CallConv, VT); 8601 SmallVector<SDValue, 4> Parts(NumParts); 8602 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8603 8604 if (Args[i].IsSExt) 8605 ExtendKind = ISD::SIGN_EXTEND; 8606 else if (Args[i].IsZExt) 8607 ExtendKind = ISD::ZERO_EXTEND; 8608 8609 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8610 // for now. 8611 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8612 CanLowerReturn) { 8613 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8614 "unexpected use of 'returned'"); 8615 // Before passing 'returned' to the target lowering code, ensure that 8616 // either the register MVT and the actual EVT are the same size or that 8617 // the return value and argument are extended in the same way; in these 8618 // cases it's safe to pass the argument register value unchanged as the 8619 // return register value (although it's at the target's option whether 8620 // to do so) 8621 // TODO: allow code generation to take advantage of partially preserved 8622 // registers rather than clobbering the entire register when the 8623 // parameter extension method is not compatible with the return 8624 // extension method 8625 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8626 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8627 CLI.RetZExt == Args[i].IsZExt)) 8628 Flags.setReturned(); 8629 } 8630 8631 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8632 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8633 8634 for (unsigned j = 0; j != NumParts; ++j) { 8635 // if it isn't first piece, alignment must be 1 8636 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8637 i < CLI.NumFixedArgs, 8638 i, j*Parts[j].getValueType().getStoreSize()); 8639 if (NumParts > 1 && j == 0) 8640 MyFlags.Flags.setSplit(); 8641 else if (j != 0) { 8642 MyFlags.Flags.setOrigAlign(1); 8643 if (j == NumParts - 1) 8644 MyFlags.Flags.setSplitEnd(); 8645 } 8646 8647 CLI.Outs.push_back(MyFlags); 8648 CLI.OutVals.push_back(Parts[j]); 8649 } 8650 8651 if (NeedsRegBlock && Value == NumValues - 1) 8652 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8653 } 8654 } 8655 8656 SmallVector<SDValue, 4> InVals; 8657 CLI.Chain = LowerCall(CLI, InVals); 8658 8659 // Update CLI.InVals to use outside of this function. 8660 CLI.InVals = InVals; 8661 8662 // Verify that the target's LowerCall behaved as expected. 8663 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8664 "LowerCall didn't return a valid chain!"); 8665 assert((!CLI.IsTailCall || InVals.empty()) && 8666 "LowerCall emitted a return value for a tail call!"); 8667 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8668 "LowerCall didn't emit the correct number of values!"); 8669 8670 // For a tail call, the return value is merely live-out and there aren't 8671 // any nodes in the DAG representing it. Return a special value to 8672 // indicate that a tail call has been emitted and no more Instructions 8673 // should be processed in the current block. 8674 if (CLI.IsTailCall) { 8675 CLI.DAG.setRoot(CLI.Chain); 8676 return std::make_pair(SDValue(), SDValue()); 8677 } 8678 8679 #ifndef NDEBUG 8680 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8681 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8682 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8683 "LowerCall emitted a value with the wrong type!"); 8684 } 8685 #endif 8686 8687 SmallVector<SDValue, 4> ReturnValues; 8688 if (!CanLowerReturn) { 8689 // The instruction result is the result of loading from the 8690 // hidden sret parameter. 8691 SmallVector<EVT, 1> PVTs; 8692 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8693 8694 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8695 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8696 EVT PtrVT = PVTs[0]; 8697 8698 unsigned NumValues = RetTys.size(); 8699 ReturnValues.resize(NumValues); 8700 SmallVector<SDValue, 4> Chains(NumValues); 8701 8702 // An aggregate return value cannot wrap around the address space, so 8703 // offsets to its parts don't wrap either. 8704 SDNodeFlags Flags; 8705 Flags.setNoUnsignedWrap(true); 8706 8707 for (unsigned i = 0; i < NumValues; ++i) { 8708 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8709 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8710 PtrVT), Flags); 8711 SDValue L = CLI.DAG.getLoad( 8712 RetTys[i], CLI.DL, CLI.Chain, Add, 8713 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8714 DemoteStackIdx, Offsets[i]), 8715 /* Alignment = */ 1); 8716 ReturnValues[i] = L; 8717 Chains[i] = L.getValue(1); 8718 } 8719 8720 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8721 } else { 8722 // Collect the legal value parts into potentially illegal values 8723 // that correspond to the original function's return values. 8724 Optional<ISD::NodeType> AssertOp; 8725 if (CLI.RetSExt) 8726 AssertOp = ISD::AssertSext; 8727 else if (CLI.RetZExt) 8728 AssertOp = ISD::AssertZext; 8729 unsigned CurReg = 0; 8730 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8731 EVT VT = RetTys[I]; 8732 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8733 CLI.CallConv, VT); 8734 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8735 CLI.CallConv, VT); 8736 8737 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8738 NumRegs, RegisterVT, VT, nullptr, 8739 CLI.CallConv, AssertOp)); 8740 CurReg += NumRegs; 8741 } 8742 8743 // For a function returning void, there is no return value. We can't create 8744 // such a node, so we just return a null return value in that case. In 8745 // that case, nothing will actually look at the value. 8746 if (ReturnValues.empty()) 8747 return std::make_pair(SDValue(), CLI.Chain); 8748 } 8749 8750 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8751 CLI.DAG.getVTList(RetTys), ReturnValues); 8752 return std::make_pair(Res, CLI.Chain); 8753 } 8754 8755 void TargetLowering::LowerOperationWrapper(SDNode *N, 8756 SmallVectorImpl<SDValue> &Results, 8757 SelectionDAG &DAG) const { 8758 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8759 Results.push_back(Res); 8760 } 8761 8762 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8763 llvm_unreachable("LowerOperation not implemented for this target!"); 8764 } 8765 8766 void 8767 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8768 SDValue Op = getNonRegisterValue(V); 8769 assert((Op.getOpcode() != ISD::CopyFromReg || 8770 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8771 "Copy from a reg to the same reg!"); 8772 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8773 8774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8775 // If this is an InlineAsm we have to match the registers required, not the 8776 // notional registers required by the type. 8777 8778 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8779 None); // This is not an ABI copy. 8780 SDValue Chain = DAG.getEntryNode(); 8781 8782 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8783 FuncInfo.PreferredExtendType.end()) 8784 ? ISD::ANY_EXTEND 8785 : FuncInfo.PreferredExtendType[V]; 8786 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8787 PendingExports.push_back(Chain); 8788 } 8789 8790 #include "llvm/CodeGen/SelectionDAGISel.h" 8791 8792 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8793 /// entry block, return true. This includes arguments used by switches, since 8794 /// the switch may expand into multiple basic blocks. 8795 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8796 // With FastISel active, we may be splitting blocks, so force creation 8797 // of virtual registers for all non-dead arguments. 8798 if (FastISel) 8799 return A->use_empty(); 8800 8801 const BasicBlock &Entry = A->getParent()->front(); 8802 for (const User *U : A->users()) 8803 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8804 return false; // Use not in entry block. 8805 8806 return true; 8807 } 8808 8809 using ArgCopyElisionMapTy = 8810 DenseMap<const Argument *, 8811 std::pair<const AllocaInst *, const StoreInst *>>; 8812 8813 /// Scan the entry block of the function in FuncInfo for arguments that look 8814 /// like copies into a local alloca. Record any copied arguments in 8815 /// ArgCopyElisionCandidates. 8816 static void 8817 findArgumentCopyElisionCandidates(const DataLayout &DL, 8818 FunctionLoweringInfo *FuncInfo, 8819 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8820 // Record the state of every static alloca used in the entry block. Argument 8821 // allocas are all used in the entry block, so we need approximately as many 8822 // entries as we have arguments. 8823 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8824 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8825 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8826 StaticAllocas.reserve(NumArgs * 2); 8827 8828 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8829 if (!V) 8830 return nullptr; 8831 V = V->stripPointerCasts(); 8832 const auto *AI = dyn_cast<AllocaInst>(V); 8833 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8834 return nullptr; 8835 auto Iter = StaticAllocas.insert({AI, Unknown}); 8836 return &Iter.first->second; 8837 }; 8838 8839 // Look for stores of arguments to static allocas. Look through bitcasts and 8840 // GEPs to handle type coercions, as long as the alloca is fully initialized 8841 // by the store. Any non-store use of an alloca escapes it and any subsequent 8842 // unanalyzed store might write it. 8843 // FIXME: Handle structs initialized with multiple stores. 8844 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8845 // Look for stores, and handle non-store uses conservatively. 8846 const auto *SI = dyn_cast<StoreInst>(&I); 8847 if (!SI) { 8848 // We will look through cast uses, so ignore them completely. 8849 if (I.isCast()) 8850 continue; 8851 // Ignore debug info intrinsics, they don't escape or store to allocas. 8852 if (isa<DbgInfoIntrinsic>(I)) 8853 continue; 8854 // This is an unknown instruction. Assume it escapes or writes to all 8855 // static alloca operands. 8856 for (const Use &U : I.operands()) { 8857 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8858 *Info = StaticAllocaInfo::Clobbered; 8859 } 8860 continue; 8861 } 8862 8863 // If the stored value is a static alloca, mark it as escaped. 8864 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8865 *Info = StaticAllocaInfo::Clobbered; 8866 8867 // Check if the destination is a static alloca. 8868 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8869 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8870 if (!Info) 8871 continue; 8872 const AllocaInst *AI = cast<AllocaInst>(Dst); 8873 8874 // Skip allocas that have been initialized or clobbered. 8875 if (*Info != StaticAllocaInfo::Unknown) 8876 continue; 8877 8878 // Check if the stored value is an argument, and that this store fully 8879 // initializes the alloca. Don't elide copies from the same argument twice. 8880 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8881 const auto *Arg = dyn_cast<Argument>(Val); 8882 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8883 Arg->getType()->isEmptyTy() || 8884 DL.getTypeStoreSize(Arg->getType()) != 8885 DL.getTypeAllocSize(AI->getAllocatedType()) || 8886 ArgCopyElisionCandidates.count(Arg)) { 8887 *Info = StaticAllocaInfo::Clobbered; 8888 continue; 8889 } 8890 8891 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8892 << '\n'); 8893 8894 // Mark this alloca and store for argument copy elision. 8895 *Info = StaticAllocaInfo::Elidable; 8896 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8897 8898 // Stop scanning if we've seen all arguments. This will happen early in -O0 8899 // builds, which is useful, because -O0 builds have large entry blocks and 8900 // many allocas. 8901 if (ArgCopyElisionCandidates.size() == NumArgs) 8902 break; 8903 } 8904 } 8905 8906 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8907 /// ArgVal is a load from a suitable fixed stack object. 8908 static void tryToElideArgumentCopy( 8909 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8910 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8911 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8912 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8913 SDValue ArgVal, bool &ArgHasUses) { 8914 // Check if this is a load from a fixed stack object. 8915 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8916 if (!LNode) 8917 return; 8918 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8919 if (!FINode) 8920 return; 8921 8922 // Check that the fixed stack object is the right size and alignment. 8923 // Look at the alignment that the user wrote on the alloca instead of looking 8924 // at the stack object. 8925 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8926 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8927 const AllocaInst *AI = ArgCopyIter->second.first; 8928 int FixedIndex = FINode->getIndex(); 8929 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8930 int OldIndex = AllocaIndex; 8931 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8932 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8933 LLVM_DEBUG( 8934 dbgs() << " argument copy elision failed due to bad fixed stack " 8935 "object size\n"); 8936 return; 8937 } 8938 unsigned RequiredAlignment = AI->getAlignment(); 8939 if (!RequiredAlignment) { 8940 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8941 AI->getAllocatedType()); 8942 } 8943 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8944 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8945 "greater than stack argument alignment (" 8946 << RequiredAlignment << " vs " 8947 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8948 return; 8949 } 8950 8951 // Perform the elision. Delete the old stack object and replace its only use 8952 // in the variable info map. Mark the stack object as mutable. 8953 LLVM_DEBUG({ 8954 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8955 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8956 << '\n'; 8957 }); 8958 MFI.RemoveStackObject(OldIndex); 8959 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8960 AllocaIndex = FixedIndex; 8961 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8962 Chains.push_back(ArgVal.getValue(1)); 8963 8964 // Avoid emitting code for the store implementing the copy. 8965 const StoreInst *SI = ArgCopyIter->second.second; 8966 ElidedArgCopyInstrs.insert(SI); 8967 8968 // Check for uses of the argument again so that we can avoid exporting ArgVal 8969 // if it is't used by anything other than the store. 8970 for (const Value *U : Arg.users()) { 8971 if (U != SI) { 8972 ArgHasUses = true; 8973 break; 8974 } 8975 } 8976 } 8977 8978 void SelectionDAGISel::LowerArguments(const Function &F) { 8979 SelectionDAG &DAG = SDB->DAG; 8980 SDLoc dl = SDB->getCurSDLoc(); 8981 const DataLayout &DL = DAG.getDataLayout(); 8982 SmallVector<ISD::InputArg, 16> Ins; 8983 8984 if (!FuncInfo->CanLowerReturn) { 8985 // Put in an sret pointer parameter before all the other parameters. 8986 SmallVector<EVT, 1> ValueVTs; 8987 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8988 F.getReturnType()->getPointerTo( 8989 DAG.getDataLayout().getAllocaAddrSpace()), 8990 ValueVTs); 8991 8992 // NOTE: Assuming that a pointer will never break down to more than one VT 8993 // or one register. 8994 ISD::ArgFlagsTy Flags; 8995 Flags.setSRet(); 8996 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8997 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8998 ISD::InputArg::NoArgIndex, 0); 8999 Ins.push_back(RetArg); 9000 } 9001 9002 // Look for stores of arguments to static allocas. Mark such arguments with a 9003 // flag to ask the target to give us the memory location of that argument if 9004 // available. 9005 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9006 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9007 9008 // Set up the incoming argument description vector. 9009 for (const Argument &Arg : F.args()) { 9010 unsigned ArgNo = Arg.getArgNo(); 9011 SmallVector<EVT, 4> ValueVTs; 9012 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9013 bool isArgValueUsed = !Arg.use_empty(); 9014 unsigned PartBase = 0; 9015 Type *FinalType = Arg.getType(); 9016 if (Arg.hasAttribute(Attribute::ByVal)) 9017 FinalType = cast<PointerType>(FinalType)->getElementType(); 9018 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9019 FinalType, F.getCallingConv(), F.isVarArg()); 9020 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9021 Value != NumValues; ++Value) { 9022 EVT VT = ValueVTs[Value]; 9023 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9024 ISD::ArgFlagsTy Flags; 9025 9026 // Certain targets (such as MIPS), may have a different ABI alignment 9027 // for a type depending on the context. Give the target a chance to 9028 // specify the alignment it wants. 9029 unsigned OriginalAlignment = 9030 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9031 9032 if (Arg.hasAttribute(Attribute::ZExt)) 9033 Flags.setZExt(); 9034 if (Arg.hasAttribute(Attribute::SExt)) 9035 Flags.setSExt(); 9036 if (Arg.hasAttribute(Attribute::InReg)) { 9037 // If we are using vectorcall calling convention, a structure that is 9038 // passed InReg - is surely an HVA 9039 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9040 isa<StructType>(Arg.getType())) { 9041 // The first value of a structure is marked 9042 if (0 == Value) 9043 Flags.setHvaStart(); 9044 Flags.setHva(); 9045 } 9046 // Set InReg Flag 9047 Flags.setInReg(); 9048 } 9049 if (Arg.hasAttribute(Attribute::StructRet)) 9050 Flags.setSRet(); 9051 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9052 Flags.setSwiftSelf(); 9053 if (Arg.hasAttribute(Attribute::SwiftError)) 9054 Flags.setSwiftError(); 9055 if (Arg.hasAttribute(Attribute::ByVal)) 9056 Flags.setByVal(); 9057 if (Arg.hasAttribute(Attribute::InAlloca)) { 9058 Flags.setInAlloca(); 9059 // Set the byval flag for CCAssignFn callbacks that don't know about 9060 // inalloca. This way we can know how many bytes we should've allocated 9061 // and how many bytes a callee cleanup function will pop. If we port 9062 // inalloca to more targets, we'll have to add custom inalloca handling 9063 // in the various CC lowering callbacks. 9064 Flags.setByVal(); 9065 } 9066 if (F.getCallingConv() == CallingConv::X86_INTR) { 9067 // IA Interrupt passes frame (1st parameter) by value in the stack. 9068 if (ArgNo == 0) 9069 Flags.setByVal(); 9070 } 9071 if (Flags.isByVal() || Flags.isInAlloca()) { 9072 PointerType *Ty = cast<PointerType>(Arg.getType()); 9073 Type *ElementTy = Ty->getElementType(); 9074 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9075 // For ByVal, alignment should be passed from FE. BE will guess if 9076 // this info is not there but there are cases it cannot get right. 9077 unsigned FrameAlign; 9078 if (Arg.getParamAlignment()) 9079 FrameAlign = Arg.getParamAlignment(); 9080 else 9081 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9082 Flags.setByValAlign(FrameAlign); 9083 } 9084 if (Arg.hasAttribute(Attribute::Nest)) 9085 Flags.setNest(); 9086 if (NeedsRegBlock) 9087 Flags.setInConsecutiveRegs(); 9088 Flags.setOrigAlign(OriginalAlignment); 9089 if (ArgCopyElisionCandidates.count(&Arg)) 9090 Flags.setCopyElisionCandidate(); 9091 9092 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9093 *CurDAG->getContext(), F.getCallingConv(), VT); 9094 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9095 *CurDAG->getContext(), F.getCallingConv(), VT); 9096 for (unsigned i = 0; i != NumRegs; ++i) { 9097 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9098 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9099 if (NumRegs > 1 && i == 0) 9100 MyFlags.Flags.setSplit(); 9101 // if it isn't first piece, alignment must be 1 9102 else if (i > 0) { 9103 MyFlags.Flags.setOrigAlign(1); 9104 if (i == NumRegs - 1) 9105 MyFlags.Flags.setSplitEnd(); 9106 } 9107 Ins.push_back(MyFlags); 9108 } 9109 if (NeedsRegBlock && Value == NumValues - 1) 9110 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9111 PartBase += VT.getStoreSize(); 9112 } 9113 } 9114 9115 // Call the target to set up the argument values. 9116 SmallVector<SDValue, 8> InVals; 9117 SDValue NewRoot = TLI->LowerFormalArguments( 9118 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9119 9120 // Verify that the target's LowerFormalArguments behaved as expected. 9121 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9122 "LowerFormalArguments didn't return a valid chain!"); 9123 assert(InVals.size() == Ins.size() && 9124 "LowerFormalArguments didn't emit the correct number of values!"); 9125 LLVM_DEBUG({ 9126 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9127 assert(InVals[i].getNode() && 9128 "LowerFormalArguments emitted a null value!"); 9129 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9130 "LowerFormalArguments emitted a value with the wrong type!"); 9131 } 9132 }); 9133 9134 // Update the DAG with the new chain value resulting from argument lowering. 9135 DAG.setRoot(NewRoot); 9136 9137 // Set up the argument values. 9138 unsigned i = 0; 9139 if (!FuncInfo->CanLowerReturn) { 9140 // Create a virtual register for the sret pointer, and put in a copy 9141 // from the sret argument into it. 9142 SmallVector<EVT, 1> ValueVTs; 9143 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9144 F.getReturnType()->getPointerTo( 9145 DAG.getDataLayout().getAllocaAddrSpace()), 9146 ValueVTs); 9147 MVT VT = ValueVTs[0].getSimpleVT(); 9148 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9149 Optional<ISD::NodeType> AssertOp = None; 9150 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9151 nullptr, F.getCallingConv(), AssertOp); 9152 9153 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9154 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9155 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9156 FuncInfo->DemoteRegister = SRetReg; 9157 NewRoot = 9158 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9159 DAG.setRoot(NewRoot); 9160 9161 // i indexes lowered arguments. Bump it past the hidden sret argument. 9162 ++i; 9163 } 9164 9165 SmallVector<SDValue, 4> Chains; 9166 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9167 for (const Argument &Arg : F.args()) { 9168 SmallVector<SDValue, 4> ArgValues; 9169 SmallVector<EVT, 4> ValueVTs; 9170 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9171 unsigned NumValues = ValueVTs.size(); 9172 if (NumValues == 0) 9173 continue; 9174 9175 bool ArgHasUses = !Arg.use_empty(); 9176 9177 // Elide the copying store if the target loaded this argument from a 9178 // suitable fixed stack object. 9179 if (Ins[i].Flags.isCopyElisionCandidate()) { 9180 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9181 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9182 InVals[i], ArgHasUses); 9183 } 9184 9185 // If this argument is unused then remember its value. It is used to generate 9186 // debugging information. 9187 bool isSwiftErrorArg = 9188 TLI->supportSwiftError() && 9189 Arg.hasAttribute(Attribute::SwiftError); 9190 if (!ArgHasUses && !isSwiftErrorArg) { 9191 SDB->setUnusedArgValue(&Arg, InVals[i]); 9192 9193 // Also remember any frame index for use in FastISel. 9194 if (FrameIndexSDNode *FI = 9195 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9196 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9197 } 9198 9199 for (unsigned Val = 0; Val != NumValues; ++Val) { 9200 EVT VT = ValueVTs[Val]; 9201 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9202 F.getCallingConv(), VT); 9203 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9204 *CurDAG->getContext(), F.getCallingConv(), VT); 9205 9206 // Even an apparant 'unused' swifterror argument needs to be returned. So 9207 // we do generate a copy for it that can be used on return from the 9208 // function. 9209 if (ArgHasUses || isSwiftErrorArg) { 9210 Optional<ISD::NodeType> AssertOp; 9211 if (Arg.hasAttribute(Attribute::SExt)) 9212 AssertOp = ISD::AssertSext; 9213 else if (Arg.hasAttribute(Attribute::ZExt)) 9214 AssertOp = ISD::AssertZext; 9215 9216 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9217 PartVT, VT, nullptr, 9218 F.getCallingConv(), AssertOp)); 9219 } 9220 9221 i += NumParts; 9222 } 9223 9224 // We don't need to do anything else for unused arguments. 9225 if (ArgValues.empty()) 9226 continue; 9227 9228 // Note down frame index. 9229 if (FrameIndexSDNode *FI = 9230 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9231 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9232 9233 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9234 SDB->getCurSDLoc()); 9235 9236 SDB->setValue(&Arg, Res); 9237 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9238 // We want to associate the argument with the frame index, among 9239 // involved operands, that correspond to the lowest address. The 9240 // getCopyFromParts function, called earlier, is swapping the order of 9241 // the operands to BUILD_PAIR depending on endianness. The result of 9242 // that swapping is that the least significant bits of the argument will 9243 // be in the first operand of the BUILD_PAIR node, and the most 9244 // significant bits will be in the second operand. 9245 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9246 if (LoadSDNode *LNode = 9247 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9248 if (FrameIndexSDNode *FI = 9249 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9250 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9251 } 9252 9253 // Update the SwiftErrorVRegDefMap. 9254 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9255 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9256 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9257 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9258 FuncInfo->SwiftErrorArg, Reg); 9259 } 9260 9261 // If this argument is live outside of the entry block, insert a copy from 9262 // wherever we got it to the vreg that other BB's will reference it as. 9263 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9264 // If we can, though, try to skip creating an unnecessary vreg. 9265 // FIXME: This isn't very clean... it would be nice to make this more 9266 // general. It's also subtly incompatible with the hacks FastISel 9267 // uses with vregs. 9268 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9269 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9270 FuncInfo->ValueMap[&Arg] = Reg; 9271 continue; 9272 } 9273 } 9274 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9275 FuncInfo->InitializeRegForValue(&Arg); 9276 SDB->CopyToExportRegsIfNeeded(&Arg); 9277 } 9278 } 9279 9280 if (!Chains.empty()) { 9281 Chains.push_back(NewRoot); 9282 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9283 } 9284 9285 DAG.setRoot(NewRoot); 9286 9287 assert(i == InVals.size() && "Argument register count mismatch!"); 9288 9289 // If any argument copy elisions occurred and we have debug info, update the 9290 // stale frame indices used in the dbg.declare variable info table. 9291 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9292 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9293 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9294 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9295 if (I != ArgCopyElisionFrameIndexMap.end()) 9296 VI.Slot = I->second; 9297 } 9298 } 9299 9300 // Finally, if the target has anything special to do, allow it to do so. 9301 EmitFunctionEntryCode(); 9302 } 9303 9304 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9305 /// ensure constants are generated when needed. Remember the virtual registers 9306 /// that need to be added to the Machine PHI nodes as input. We cannot just 9307 /// directly add them, because expansion might result in multiple MBB's for one 9308 /// BB. As such, the start of the BB might correspond to a different MBB than 9309 /// the end. 9310 void 9311 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9312 const Instruction *TI = LLVMBB->getTerminator(); 9313 9314 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9315 9316 // Check PHI nodes in successors that expect a value to be available from this 9317 // block. 9318 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9319 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9320 if (!isa<PHINode>(SuccBB->begin())) continue; 9321 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9322 9323 // If this terminator has multiple identical successors (common for 9324 // switches), only handle each succ once. 9325 if (!SuccsHandled.insert(SuccMBB).second) 9326 continue; 9327 9328 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9329 9330 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9331 // nodes and Machine PHI nodes, but the incoming operands have not been 9332 // emitted yet. 9333 for (const PHINode &PN : SuccBB->phis()) { 9334 // Ignore dead phi's. 9335 if (PN.use_empty()) 9336 continue; 9337 9338 // Skip empty types 9339 if (PN.getType()->isEmptyTy()) 9340 continue; 9341 9342 unsigned Reg; 9343 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9344 9345 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9346 unsigned &RegOut = ConstantsOut[C]; 9347 if (RegOut == 0) { 9348 RegOut = FuncInfo.CreateRegs(C->getType()); 9349 CopyValueToVirtualRegister(C, RegOut); 9350 } 9351 Reg = RegOut; 9352 } else { 9353 DenseMap<const Value *, unsigned>::iterator I = 9354 FuncInfo.ValueMap.find(PHIOp); 9355 if (I != FuncInfo.ValueMap.end()) 9356 Reg = I->second; 9357 else { 9358 assert(isa<AllocaInst>(PHIOp) && 9359 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9360 "Didn't codegen value into a register!??"); 9361 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9362 CopyValueToVirtualRegister(PHIOp, Reg); 9363 } 9364 } 9365 9366 // Remember that this register needs to added to the machine PHI node as 9367 // the input for this MBB. 9368 SmallVector<EVT, 4> ValueVTs; 9369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9370 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9371 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9372 EVT VT = ValueVTs[vti]; 9373 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9374 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9375 FuncInfo.PHINodesToUpdate.push_back( 9376 std::make_pair(&*MBBI++, Reg + i)); 9377 Reg += NumRegisters; 9378 } 9379 } 9380 } 9381 9382 ConstantsOut.clear(); 9383 } 9384 9385 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9386 /// is 0. 9387 MachineBasicBlock * 9388 SelectionDAGBuilder::StackProtectorDescriptor:: 9389 AddSuccessorMBB(const BasicBlock *BB, 9390 MachineBasicBlock *ParentMBB, 9391 bool IsLikely, 9392 MachineBasicBlock *SuccMBB) { 9393 // If SuccBB has not been created yet, create it. 9394 if (!SuccMBB) { 9395 MachineFunction *MF = ParentMBB->getParent(); 9396 MachineFunction::iterator BBI(ParentMBB); 9397 SuccMBB = MF->CreateMachineBasicBlock(BB); 9398 MF->insert(++BBI, SuccMBB); 9399 } 9400 // Add it as a successor of ParentMBB. 9401 ParentMBB->addSuccessor( 9402 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9403 return SuccMBB; 9404 } 9405 9406 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9407 MachineFunction::iterator I(MBB); 9408 if (++I == FuncInfo.MF->end()) 9409 return nullptr; 9410 return &*I; 9411 } 9412 9413 /// During lowering new call nodes can be created (such as memset, etc.). 9414 /// Those will become new roots of the current DAG, but complications arise 9415 /// when they are tail calls. In such cases, the call lowering will update 9416 /// the root, but the builder still needs to know that a tail call has been 9417 /// lowered in order to avoid generating an additional return. 9418 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9419 // If the node is null, we do have a tail call. 9420 if (MaybeTC.getNode() != nullptr) 9421 DAG.setRoot(MaybeTC); 9422 else 9423 HasTailCall = true; 9424 } 9425 9426 uint64_t 9427 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9428 unsigned First, unsigned Last) const { 9429 assert(Last >= First); 9430 const APInt &LowCase = Clusters[First].Low->getValue(); 9431 const APInt &HighCase = Clusters[Last].High->getValue(); 9432 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9433 9434 // FIXME: A range of consecutive cases has 100% density, but only requires one 9435 // comparison to lower. We should discriminate against such consecutive ranges 9436 // in jump tables. 9437 9438 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9439 } 9440 9441 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9442 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9443 unsigned Last) const { 9444 assert(Last >= First); 9445 assert(TotalCases[Last] >= TotalCases[First]); 9446 uint64_t NumCases = 9447 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9448 return NumCases; 9449 } 9450 9451 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9452 unsigned First, unsigned Last, 9453 const SwitchInst *SI, 9454 MachineBasicBlock *DefaultMBB, 9455 CaseCluster &JTCluster) { 9456 assert(First <= Last); 9457 9458 auto Prob = BranchProbability::getZero(); 9459 unsigned NumCmps = 0; 9460 std::vector<MachineBasicBlock*> Table; 9461 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9462 9463 // Initialize probabilities in JTProbs. 9464 for (unsigned I = First; I <= Last; ++I) 9465 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9466 9467 for (unsigned I = First; I <= Last; ++I) { 9468 assert(Clusters[I].Kind == CC_Range); 9469 Prob += Clusters[I].Prob; 9470 const APInt &Low = Clusters[I].Low->getValue(); 9471 const APInt &High = Clusters[I].High->getValue(); 9472 NumCmps += (Low == High) ? 1 : 2; 9473 if (I != First) { 9474 // Fill the gap between this and the previous cluster. 9475 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9476 assert(PreviousHigh.slt(Low)); 9477 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9478 for (uint64_t J = 0; J < Gap; J++) 9479 Table.push_back(DefaultMBB); 9480 } 9481 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9482 for (uint64_t J = 0; J < ClusterSize; ++J) 9483 Table.push_back(Clusters[I].MBB); 9484 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9485 } 9486 9487 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9488 unsigned NumDests = JTProbs.size(); 9489 if (TLI.isSuitableForBitTests( 9490 NumDests, NumCmps, Clusters[First].Low->getValue(), 9491 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9492 // Clusters[First..Last] should be lowered as bit tests instead. 9493 return false; 9494 } 9495 9496 // Create the MBB that will load from and jump through the table. 9497 // Note: We create it here, but it's not inserted into the function yet. 9498 MachineFunction *CurMF = FuncInfo.MF; 9499 MachineBasicBlock *JumpTableMBB = 9500 CurMF->CreateMachineBasicBlock(SI->getParent()); 9501 9502 // Add successors. Note: use table order for determinism. 9503 SmallPtrSet<MachineBasicBlock *, 8> Done; 9504 for (MachineBasicBlock *Succ : Table) { 9505 if (Done.count(Succ)) 9506 continue; 9507 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9508 Done.insert(Succ); 9509 } 9510 JumpTableMBB->normalizeSuccProbs(); 9511 9512 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9513 ->createJumpTableIndex(Table); 9514 9515 // Set up the jump table info. 9516 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9517 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9518 Clusters[Last].High->getValue(), SI->getCondition(), 9519 nullptr, false); 9520 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9521 9522 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9523 JTCases.size() - 1, Prob); 9524 return true; 9525 } 9526 9527 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9528 const SwitchInst *SI, 9529 MachineBasicBlock *DefaultMBB) { 9530 #ifndef NDEBUG 9531 // Clusters must be non-empty, sorted, and only contain Range clusters. 9532 assert(!Clusters.empty()); 9533 for (CaseCluster &C : Clusters) 9534 assert(C.Kind == CC_Range); 9535 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9536 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9537 #endif 9538 9539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9540 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9541 return; 9542 9543 const int64_t N = Clusters.size(); 9544 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9545 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9546 9547 if (N < 2 || N < MinJumpTableEntries) 9548 return; 9549 9550 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9551 SmallVector<unsigned, 8> TotalCases(N); 9552 for (unsigned i = 0; i < N; ++i) { 9553 const APInt &Hi = Clusters[i].High->getValue(); 9554 const APInt &Lo = Clusters[i].Low->getValue(); 9555 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9556 if (i != 0) 9557 TotalCases[i] += TotalCases[i - 1]; 9558 } 9559 9560 // Cheap case: the whole range may be suitable for jump table. 9561 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9562 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9563 assert(NumCases < UINT64_MAX / 100); 9564 assert(Range >= NumCases); 9565 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9566 CaseCluster JTCluster; 9567 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9568 Clusters[0] = JTCluster; 9569 Clusters.resize(1); 9570 return; 9571 } 9572 } 9573 9574 // The algorithm below is not suitable for -O0. 9575 if (TM.getOptLevel() == CodeGenOpt::None) 9576 return; 9577 9578 // Split Clusters into minimum number of dense partitions. The algorithm uses 9579 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9580 // for the Case Statement'" (1994), but builds the MinPartitions array in 9581 // reverse order to make it easier to reconstruct the partitions in ascending 9582 // order. In the choice between two optimal partitionings, it picks the one 9583 // which yields more jump tables. 9584 9585 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9586 SmallVector<unsigned, 8> MinPartitions(N); 9587 // LastElement[i] is the last element of the partition starting at i. 9588 SmallVector<unsigned, 8> LastElement(N); 9589 // PartitionsScore[i] is used to break ties when choosing between two 9590 // partitionings resulting in the same number of partitions. 9591 SmallVector<unsigned, 8> PartitionsScore(N); 9592 // For PartitionsScore, a small number of comparisons is considered as good as 9593 // a jump table and a single comparison is considered better than a jump 9594 // table. 9595 enum PartitionScores : unsigned { 9596 NoTable = 0, 9597 Table = 1, 9598 FewCases = 1, 9599 SingleCase = 2 9600 }; 9601 9602 // Base case: There is only one way to partition Clusters[N-1]. 9603 MinPartitions[N - 1] = 1; 9604 LastElement[N - 1] = N - 1; 9605 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9606 9607 // Note: loop indexes are signed to avoid underflow. 9608 for (int64_t i = N - 2; i >= 0; i--) { 9609 // Find optimal partitioning of Clusters[i..N-1]. 9610 // Baseline: Put Clusters[i] into a partition on its own. 9611 MinPartitions[i] = MinPartitions[i + 1] + 1; 9612 LastElement[i] = i; 9613 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9614 9615 // Search for a solution that results in fewer partitions. 9616 for (int64_t j = N - 1; j > i; j--) { 9617 // Try building a partition from Clusters[i..j]. 9618 uint64_t Range = getJumpTableRange(Clusters, i, j); 9619 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9620 assert(NumCases < UINT64_MAX / 100); 9621 assert(Range >= NumCases); 9622 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9623 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9624 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9625 int64_t NumEntries = j - i + 1; 9626 9627 if (NumEntries == 1) 9628 Score += PartitionScores::SingleCase; 9629 else if (NumEntries <= SmallNumberOfEntries) 9630 Score += PartitionScores::FewCases; 9631 else if (NumEntries >= MinJumpTableEntries) 9632 Score += PartitionScores::Table; 9633 9634 // If this leads to fewer partitions, or to the same number of 9635 // partitions with better score, it is a better partitioning. 9636 if (NumPartitions < MinPartitions[i] || 9637 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9638 MinPartitions[i] = NumPartitions; 9639 LastElement[i] = j; 9640 PartitionsScore[i] = Score; 9641 } 9642 } 9643 } 9644 } 9645 9646 // Iterate over the partitions, replacing some with jump tables in-place. 9647 unsigned DstIndex = 0; 9648 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9649 Last = LastElement[First]; 9650 assert(Last >= First); 9651 assert(DstIndex <= First); 9652 unsigned NumClusters = Last - First + 1; 9653 9654 CaseCluster JTCluster; 9655 if (NumClusters >= MinJumpTableEntries && 9656 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9657 Clusters[DstIndex++] = JTCluster; 9658 } else { 9659 for (unsigned I = First; I <= Last; ++I) 9660 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9661 } 9662 } 9663 Clusters.resize(DstIndex); 9664 } 9665 9666 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9667 unsigned First, unsigned Last, 9668 const SwitchInst *SI, 9669 CaseCluster &BTCluster) { 9670 assert(First <= Last); 9671 if (First == Last) 9672 return false; 9673 9674 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9675 unsigned NumCmps = 0; 9676 for (int64_t I = First; I <= Last; ++I) { 9677 assert(Clusters[I].Kind == CC_Range); 9678 Dests.set(Clusters[I].MBB->getNumber()); 9679 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9680 } 9681 unsigned NumDests = Dests.count(); 9682 9683 APInt Low = Clusters[First].Low->getValue(); 9684 APInt High = Clusters[Last].High->getValue(); 9685 assert(Low.slt(High)); 9686 9687 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9688 const DataLayout &DL = DAG.getDataLayout(); 9689 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9690 return false; 9691 9692 APInt LowBound; 9693 APInt CmpRange; 9694 9695 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9696 assert(TLI.rangeFitsInWord(Low, High, DL) && 9697 "Case range must fit in bit mask!"); 9698 9699 // Check if the clusters cover a contiguous range such that no value in the 9700 // range will jump to the default statement. 9701 bool ContiguousRange = true; 9702 for (int64_t I = First + 1; I <= Last; ++I) { 9703 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9704 ContiguousRange = false; 9705 break; 9706 } 9707 } 9708 9709 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9710 // Optimize the case where all the case values fit in a word without having 9711 // to subtract minValue. In this case, we can optimize away the subtraction. 9712 LowBound = APInt::getNullValue(Low.getBitWidth()); 9713 CmpRange = High; 9714 ContiguousRange = false; 9715 } else { 9716 LowBound = Low; 9717 CmpRange = High - Low; 9718 } 9719 9720 CaseBitsVector CBV; 9721 auto TotalProb = BranchProbability::getZero(); 9722 for (unsigned i = First; i <= Last; ++i) { 9723 // Find the CaseBits for this destination. 9724 unsigned j; 9725 for (j = 0; j < CBV.size(); ++j) 9726 if (CBV[j].BB == Clusters[i].MBB) 9727 break; 9728 if (j == CBV.size()) 9729 CBV.push_back( 9730 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9731 CaseBits *CB = &CBV[j]; 9732 9733 // Update Mask, Bits and ExtraProb. 9734 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9735 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9736 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9737 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9738 CB->Bits += Hi - Lo + 1; 9739 CB->ExtraProb += Clusters[i].Prob; 9740 TotalProb += Clusters[i].Prob; 9741 } 9742 9743 BitTestInfo BTI; 9744 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9745 // Sort by probability first, number of bits second, bit mask third. 9746 if (a.ExtraProb != b.ExtraProb) 9747 return a.ExtraProb > b.ExtraProb; 9748 if (a.Bits != b.Bits) 9749 return a.Bits > b.Bits; 9750 return a.Mask < b.Mask; 9751 }); 9752 9753 for (auto &CB : CBV) { 9754 MachineBasicBlock *BitTestBB = 9755 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9756 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9757 } 9758 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9759 SI->getCondition(), -1U, MVT::Other, false, 9760 ContiguousRange, nullptr, nullptr, std::move(BTI), 9761 TotalProb); 9762 9763 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9764 BitTestCases.size() - 1, TotalProb); 9765 return true; 9766 } 9767 9768 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9769 const SwitchInst *SI) { 9770 // Partition Clusters into as few subsets as possible, where each subset has a 9771 // range that fits in a machine word and has <= 3 unique destinations. 9772 9773 #ifndef NDEBUG 9774 // Clusters must be sorted and contain Range or JumpTable clusters. 9775 assert(!Clusters.empty()); 9776 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9777 for (const CaseCluster &C : Clusters) 9778 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9779 for (unsigned i = 1; i < Clusters.size(); ++i) 9780 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9781 #endif 9782 9783 // The algorithm below is not suitable for -O0. 9784 if (TM.getOptLevel() == CodeGenOpt::None) 9785 return; 9786 9787 // If target does not have legal shift left, do not emit bit tests at all. 9788 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9789 const DataLayout &DL = DAG.getDataLayout(); 9790 9791 EVT PTy = TLI.getPointerTy(DL); 9792 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9793 return; 9794 9795 int BitWidth = PTy.getSizeInBits(); 9796 const int64_t N = Clusters.size(); 9797 9798 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9799 SmallVector<unsigned, 8> MinPartitions(N); 9800 // LastElement[i] is the last element of the partition starting at i. 9801 SmallVector<unsigned, 8> LastElement(N); 9802 9803 // FIXME: This might not be the best algorithm for finding bit test clusters. 9804 9805 // Base case: There is only one way to partition Clusters[N-1]. 9806 MinPartitions[N - 1] = 1; 9807 LastElement[N - 1] = N - 1; 9808 9809 // Note: loop indexes are signed to avoid underflow. 9810 for (int64_t i = N - 2; i >= 0; --i) { 9811 // Find optimal partitioning of Clusters[i..N-1]. 9812 // Baseline: Put Clusters[i] into a partition on its own. 9813 MinPartitions[i] = MinPartitions[i + 1] + 1; 9814 LastElement[i] = i; 9815 9816 // Search for a solution that results in fewer partitions. 9817 // Note: the search is limited by BitWidth, reducing time complexity. 9818 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9819 // Try building a partition from Clusters[i..j]. 9820 9821 // Check the range. 9822 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9823 Clusters[j].High->getValue(), DL)) 9824 continue; 9825 9826 // Check nbr of destinations and cluster types. 9827 // FIXME: This works, but doesn't seem very efficient. 9828 bool RangesOnly = true; 9829 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9830 for (int64_t k = i; k <= j; k++) { 9831 if (Clusters[k].Kind != CC_Range) { 9832 RangesOnly = false; 9833 break; 9834 } 9835 Dests.set(Clusters[k].MBB->getNumber()); 9836 } 9837 if (!RangesOnly || Dests.count() > 3) 9838 break; 9839 9840 // Check if it's a better partition. 9841 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9842 if (NumPartitions < MinPartitions[i]) { 9843 // Found a better partition. 9844 MinPartitions[i] = NumPartitions; 9845 LastElement[i] = j; 9846 } 9847 } 9848 } 9849 9850 // Iterate over the partitions, replacing with bit-test clusters in-place. 9851 unsigned DstIndex = 0; 9852 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9853 Last = LastElement[First]; 9854 assert(First <= Last); 9855 assert(DstIndex <= First); 9856 9857 CaseCluster BitTestCluster; 9858 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9859 Clusters[DstIndex++] = BitTestCluster; 9860 } else { 9861 size_t NumClusters = Last - First + 1; 9862 std::memmove(&Clusters[DstIndex], &Clusters[First], 9863 sizeof(Clusters[0]) * NumClusters); 9864 DstIndex += NumClusters; 9865 } 9866 } 9867 Clusters.resize(DstIndex); 9868 } 9869 9870 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9871 MachineBasicBlock *SwitchMBB, 9872 MachineBasicBlock *DefaultMBB) { 9873 MachineFunction *CurMF = FuncInfo.MF; 9874 MachineBasicBlock *NextMBB = nullptr; 9875 MachineFunction::iterator BBI(W.MBB); 9876 if (++BBI != FuncInfo.MF->end()) 9877 NextMBB = &*BBI; 9878 9879 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9880 9881 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9882 9883 if (Size == 2 && W.MBB == SwitchMBB) { 9884 // If any two of the cases has the same destination, and if one value 9885 // is the same as the other, but has one bit unset that the other has set, 9886 // use bit manipulation to do two compares at once. For example: 9887 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9888 // TODO: This could be extended to merge any 2 cases in switches with 3 9889 // cases. 9890 // TODO: Handle cases where W.CaseBB != SwitchBB. 9891 CaseCluster &Small = *W.FirstCluster; 9892 CaseCluster &Big = *W.LastCluster; 9893 9894 if (Small.Low == Small.High && Big.Low == Big.High && 9895 Small.MBB == Big.MBB) { 9896 const APInt &SmallValue = Small.Low->getValue(); 9897 const APInt &BigValue = Big.Low->getValue(); 9898 9899 // Check that there is only one bit different. 9900 APInt CommonBit = BigValue ^ SmallValue; 9901 if (CommonBit.isPowerOf2()) { 9902 SDValue CondLHS = getValue(Cond); 9903 EVT VT = CondLHS.getValueType(); 9904 SDLoc DL = getCurSDLoc(); 9905 9906 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9907 DAG.getConstant(CommonBit, DL, VT)); 9908 SDValue Cond = DAG.getSetCC( 9909 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9910 ISD::SETEQ); 9911 9912 // Update successor info. 9913 // Both Small and Big will jump to Small.BB, so we sum up the 9914 // probabilities. 9915 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9916 if (BPI) 9917 addSuccessorWithProb( 9918 SwitchMBB, DefaultMBB, 9919 // The default destination is the first successor in IR. 9920 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9921 else 9922 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9923 9924 // Insert the true branch. 9925 SDValue BrCond = 9926 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9927 DAG.getBasicBlock(Small.MBB)); 9928 // Insert the false branch. 9929 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9930 DAG.getBasicBlock(DefaultMBB)); 9931 9932 DAG.setRoot(BrCond); 9933 return; 9934 } 9935 } 9936 } 9937 9938 if (TM.getOptLevel() != CodeGenOpt::None) { 9939 // Here, we order cases by probability so the most likely case will be 9940 // checked first. However, two clusters can have the same probability in 9941 // which case their relative ordering is non-deterministic. So we use Low 9942 // as a tie-breaker as clusters are guaranteed to never overlap. 9943 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9944 [](const CaseCluster &a, const CaseCluster &b) { 9945 return a.Prob != b.Prob ? 9946 a.Prob > b.Prob : 9947 a.Low->getValue().slt(b.Low->getValue()); 9948 }); 9949 9950 // Rearrange the case blocks so that the last one falls through if possible 9951 // without changing the order of probabilities. 9952 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9953 --I; 9954 if (I->Prob > W.LastCluster->Prob) 9955 break; 9956 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9957 std::swap(*I, *W.LastCluster); 9958 break; 9959 } 9960 } 9961 } 9962 9963 // Compute total probability. 9964 BranchProbability DefaultProb = W.DefaultProb; 9965 BranchProbability UnhandledProbs = DefaultProb; 9966 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9967 UnhandledProbs += I->Prob; 9968 9969 MachineBasicBlock *CurMBB = W.MBB; 9970 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9971 MachineBasicBlock *Fallthrough; 9972 if (I == W.LastCluster) { 9973 // For the last cluster, fall through to the default destination. 9974 Fallthrough = DefaultMBB; 9975 } else { 9976 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9977 CurMF->insert(BBI, Fallthrough); 9978 // Put Cond in a virtual register to make it available from the new blocks. 9979 ExportFromCurrentBlock(Cond); 9980 } 9981 UnhandledProbs -= I->Prob; 9982 9983 switch (I->Kind) { 9984 case CC_JumpTable: { 9985 // FIXME: Optimize away range check based on pivot comparisons. 9986 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9987 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9988 9989 // The jump block hasn't been inserted yet; insert it here. 9990 MachineBasicBlock *JumpMBB = JT->MBB; 9991 CurMF->insert(BBI, JumpMBB); 9992 9993 auto JumpProb = I->Prob; 9994 auto FallthroughProb = UnhandledProbs; 9995 9996 // If the default statement is a target of the jump table, we evenly 9997 // distribute the default probability to successors of CurMBB. Also 9998 // update the probability on the edge from JumpMBB to Fallthrough. 9999 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10000 SE = JumpMBB->succ_end(); 10001 SI != SE; ++SI) { 10002 if (*SI == DefaultMBB) { 10003 JumpProb += DefaultProb / 2; 10004 FallthroughProb -= DefaultProb / 2; 10005 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10006 JumpMBB->normalizeSuccProbs(); 10007 break; 10008 } 10009 } 10010 10011 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10012 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10013 CurMBB->normalizeSuccProbs(); 10014 10015 // The jump table header will be inserted in our current block, do the 10016 // range check, and fall through to our fallthrough block. 10017 JTH->HeaderBB = CurMBB; 10018 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10019 10020 // If we're in the right place, emit the jump table header right now. 10021 if (CurMBB == SwitchMBB) { 10022 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10023 JTH->Emitted = true; 10024 } 10025 break; 10026 } 10027 case CC_BitTests: { 10028 // FIXME: Optimize away range check based on pivot comparisons. 10029 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10030 10031 // The bit test blocks haven't been inserted yet; insert them here. 10032 for (BitTestCase &BTC : BTB->Cases) 10033 CurMF->insert(BBI, BTC.ThisBB); 10034 10035 // Fill in fields of the BitTestBlock. 10036 BTB->Parent = CurMBB; 10037 BTB->Default = Fallthrough; 10038 10039 BTB->DefaultProb = UnhandledProbs; 10040 // If the cases in bit test don't form a contiguous range, we evenly 10041 // distribute the probability on the edge to Fallthrough to two 10042 // successors of CurMBB. 10043 if (!BTB->ContiguousRange) { 10044 BTB->Prob += DefaultProb / 2; 10045 BTB->DefaultProb -= DefaultProb / 2; 10046 } 10047 10048 // If we're in the right place, emit the bit test header right now. 10049 if (CurMBB == SwitchMBB) { 10050 visitBitTestHeader(*BTB, SwitchMBB); 10051 BTB->Emitted = true; 10052 } 10053 break; 10054 } 10055 case CC_Range: { 10056 const Value *RHS, *LHS, *MHS; 10057 ISD::CondCode CC; 10058 if (I->Low == I->High) { 10059 // Check Cond == I->Low. 10060 CC = ISD::SETEQ; 10061 LHS = Cond; 10062 RHS=I->Low; 10063 MHS = nullptr; 10064 } else { 10065 // Check I->Low <= Cond <= I->High. 10066 CC = ISD::SETLE; 10067 LHS = I->Low; 10068 MHS = Cond; 10069 RHS = I->High; 10070 } 10071 10072 // The false probability is the sum of all unhandled cases. 10073 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10074 getCurSDLoc(), I->Prob, UnhandledProbs); 10075 10076 if (CurMBB == SwitchMBB) 10077 visitSwitchCase(CB, SwitchMBB); 10078 else 10079 SwitchCases.push_back(CB); 10080 10081 break; 10082 } 10083 } 10084 CurMBB = Fallthrough; 10085 } 10086 } 10087 10088 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10089 CaseClusterIt First, 10090 CaseClusterIt Last) { 10091 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10092 if (X.Prob != CC.Prob) 10093 return X.Prob > CC.Prob; 10094 10095 // Ties are broken by comparing the case value. 10096 return X.Low->getValue().slt(CC.Low->getValue()); 10097 }); 10098 } 10099 10100 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10101 const SwitchWorkListItem &W, 10102 Value *Cond, 10103 MachineBasicBlock *SwitchMBB) { 10104 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10105 "Clusters not sorted?"); 10106 10107 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10108 10109 // Balance the tree based on branch probabilities to create a near-optimal (in 10110 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10111 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10112 CaseClusterIt LastLeft = W.FirstCluster; 10113 CaseClusterIt FirstRight = W.LastCluster; 10114 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10115 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10116 10117 // Move LastLeft and FirstRight towards each other from opposite directions to 10118 // find a partitioning of the clusters which balances the probability on both 10119 // sides. If LeftProb and RightProb are equal, alternate which side is 10120 // taken to ensure 0-probability nodes are distributed evenly. 10121 unsigned I = 0; 10122 while (LastLeft + 1 < FirstRight) { 10123 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10124 LeftProb += (++LastLeft)->Prob; 10125 else 10126 RightProb += (--FirstRight)->Prob; 10127 I++; 10128 } 10129 10130 while (true) { 10131 // Our binary search tree differs from a typical BST in that ours can have up 10132 // to three values in each leaf. The pivot selection above doesn't take that 10133 // into account, which means the tree might require more nodes and be less 10134 // efficient. We compensate for this here. 10135 10136 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10137 unsigned NumRight = W.LastCluster - FirstRight + 1; 10138 10139 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10140 // If one side has less than 3 clusters, and the other has more than 3, 10141 // consider taking a cluster from the other side. 10142 10143 if (NumLeft < NumRight) { 10144 // Consider moving the first cluster on the right to the left side. 10145 CaseCluster &CC = *FirstRight; 10146 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10147 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10148 if (LeftSideRank <= RightSideRank) { 10149 // Moving the cluster to the left does not demote it. 10150 ++LastLeft; 10151 ++FirstRight; 10152 continue; 10153 } 10154 } else { 10155 assert(NumRight < NumLeft); 10156 // Consider moving the last element on the left to the right side. 10157 CaseCluster &CC = *LastLeft; 10158 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10159 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10160 if (RightSideRank <= LeftSideRank) { 10161 // Moving the cluster to the right does not demot it. 10162 --LastLeft; 10163 --FirstRight; 10164 continue; 10165 } 10166 } 10167 } 10168 break; 10169 } 10170 10171 assert(LastLeft + 1 == FirstRight); 10172 assert(LastLeft >= W.FirstCluster); 10173 assert(FirstRight <= W.LastCluster); 10174 10175 // Use the first element on the right as pivot since we will make less-than 10176 // comparisons against it. 10177 CaseClusterIt PivotCluster = FirstRight; 10178 assert(PivotCluster > W.FirstCluster); 10179 assert(PivotCluster <= W.LastCluster); 10180 10181 CaseClusterIt FirstLeft = W.FirstCluster; 10182 CaseClusterIt LastRight = W.LastCluster; 10183 10184 const ConstantInt *Pivot = PivotCluster->Low; 10185 10186 // New blocks will be inserted immediately after the current one. 10187 MachineFunction::iterator BBI(W.MBB); 10188 ++BBI; 10189 10190 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10191 // we can branch to its destination directly if it's squeezed exactly in 10192 // between the known lower bound and Pivot - 1. 10193 MachineBasicBlock *LeftMBB; 10194 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10195 FirstLeft->Low == W.GE && 10196 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10197 LeftMBB = FirstLeft->MBB; 10198 } else { 10199 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10200 FuncInfo.MF->insert(BBI, LeftMBB); 10201 WorkList.push_back( 10202 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10203 // Put Cond in a virtual register to make it available from the new blocks. 10204 ExportFromCurrentBlock(Cond); 10205 } 10206 10207 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10208 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10209 // directly if RHS.High equals the current upper bound. 10210 MachineBasicBlock *RightMBB; 10211 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10212 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10213 RightMBB = FirstRight->MBB; 10214 } else { 10215 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10216 FuncInfo.MF->insert(BBI, RightMBB); 10217 WorkList.push_back( 10218 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10219 // Put Cond in a virtual register to make it available from the new blocks. 10220 ExportFromCurrentBlock(Cond); 10221 } 10222 10223 // Create the CaseBlock record that will be used to lower the branch. 10224 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10225 getCurSDLoc(), LeftProb, RightProb); 10226 10227 if (W.MBB == SwitchMBB) 10228 visitSwitchCase(CB, SwitchMBB); 10229 else 10230 SwitchCases.push_back(CB); 10231 } 10232 10233 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10234 // from the swith statement. 10235 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10236 BranchProbability PeeledCaseProb) { 10237 if (PeeledCaseProb == BranchProbability::getOne()) 10238 return BranchProbability::getZero(); 10239 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10240 10241 uint32_t Numerator = CaseProb.getNumerator(); 10242 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10243 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10244 } 10245 10246 // Try to peel the top probability case if it exceeds the threshold. 10247 // Return current MachineBasicBlock for the switch statement if the peeling 10248 // does not occur. 10249 // If the peeling is performed, return the newly created MachineBasicBlock 10250 // for the peeled switch statement. Also update Clusters to remove the peeled 10251 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10252 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10253 const SwitchInst &SI, CaseClusterVector &Clusters, 10254 BranchProbability &PeeledCaseProb) { 10255 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10256 // Don't perform if there is only one cluster or optimizing for size. 10257 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10258 TM.getOptLevel() == CodeGenOpt::None || 10259 SwitchMBB->getParent()->getFunction().optForMinSize()) 10260 return SwitchMBB; 10261 10262 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10263 unsigned PeeledCaseIndex = 0; 10264 bool SwitchPeeled = false; 10265 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10266 CaseCluster &CC = Clusters[Index]; 10267 if (CC.Prob < TopCaseProb) 10268 continue; 10269 TopCaseProb = CC.Prob; 10270 PeeledCaseIndex = Index; 10271 SwitchPeeled = true; 10272 } 10273 if (!SwitchPeeled) 10274 return SwitchMBB; 10275 10276 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10277 << TopCaseProb << "\n"); 10278 10279 // Record the MBB for the peeled switch statement. 10280 MachineFunction::iterator BBI(SwitchMBB); 10281 ++BBI; 10282 MachineBasicBlock *PeeledSwitchMBB = 10283 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10284 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10285 10286 ExportFromCurrentBlock(SI.getCondition()); 10287 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10288 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10289 nullptr, nullptr, TopCaseProb.getCompl()}; 10290 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10291 10292 Clusters.erase(PeeledCaseIt); 10293 for (CaseCluster &CC : Clusters) { 10294 LLVM_DEBUG( 10295 dbgs() << "Scale the probablity for one cluster, before scaling: " 10296 << CC.Prob << "\n"); 10297 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10298 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10299 } 10300 PeeledCaseProb = TopCaseProb; 10301 return PeeledSwitchMBB; 10302 } 10303 10304 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10305 // Extract cases from the switch. 10306 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10307 CaseClusterVector Clusters; 10308 Clusters.reserve(SI.getNumCases()); 10309 for (auto I : SI.cases()) { 10310 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10311 const ConstantInt *CaseVal = I.getCaseValue(); 10312 BranchProbability Prob = 10313 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10314 : BranchProbability(1, SI.getNumCases() + 1); 10315 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10316 } 10317 10318 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10319 10320 // Cluster adjacent cases with the same destination. We do this at all 10321 // optimization levels because it's cheap to do and will make codegen faster 10322 // if there are many clusters. 10323 sortAndRangeify(Clusters); 10324 10325 if (TM.getOptLevel() != CodeGenOpt::None) { 10326 // Replace an unreachable default with the most popular destination. 10327 // FIXME: Exploit unreachable default more aggressively. 10328 bool UnreachableDefault = 10329 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10330 if (UnreachableDefault && !Clusters.empty()) { 10331 DenseMap<const BasicBlock *, unsigned> Popularity; 10332 unsigned MaxPop = 0; 10333 const BasicBlock *MaxBB = nullptr; 10334 for (auto I : SI.cases()) { 10335 const BasicBlock *BB = I.getCaseSuccessor(); 10336 if (++Popularity[BB] > MaxPop) { 10337 MaxPop = Popularity[BB]; 10338 MaxBB = BB; 10339 } 10340 } 10341 // Set new default. 10342 assert(MaxPop > 0 && MaxBB); 10343 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10344 10345 // Remove cases that were pointing to the destination that is now the 10346 // default. 10347 CaseClusterVector New; 10348 New.reserve(Clusters.size()); 10349 for (CaseCluster &CC : Clusters) { 10350 if (CC.MBB != DefaultMBB) 10351 New.push_back(CC); 10352 } 10353 Clusters = std::move(New); 10354 } 10355 } 10356 10357 // The branch probablity of the peeled case. 10358 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10359 MachineBasicBlock *PeeledSwitchMBB = 10360 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10361 10362 // If there is only the default destination, jump there directly. 10363 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10364 if (Clusters.empty()) { 10365 assert(PeeledSwitchMBB == SwitchMBB); 10366 SwitchMBB->addSuccessor(DefaultMBB); 10367 if (DefaultMBB != NextBlock(SwitchMBB)) { 10368 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10369 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10370 } 10371 return; 10372 } 10373 10374 findJumpTables(Clusters, &SI, DefaultMBB); 10375 findBitTestClusters(Clusters, &SI); 10376 10377 LLVM_DEBUG({ 10378 dbgs() << "Case clusters: "; 10379 for (const CaseCluster &C : Clusters) { 10380 if (C.Kind == CC_JumpTable) 10381 dbgs() << "JT:"; 10382 if (C.Kind == CC_BitTests) 10383 dbgs() << "BT:"; 10384 10385 C.Low->getValue().print(dbgs(), true); 10386 if (C.Low != C.High) { 10387 dbgs() << '-'; 10388 C.High->getValue().print(dbgs(), true); 10389 } 10390 dbgs() << ' '; 10391 } 10392 dbgs() << '\n'; 10393 }); 10394 10395 assert(!Clusters.empty()); 10396 SwitchWorkList WorkList; 10397 CaseClusterIt First = Clusters.begin(); 10398 CaseClusterIt Last = Clusters.end() - 1; 10399 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10400 // Scale the branchprobability for DefaultMBB if the peel occurs and 10401 // DefaultMBB is not replaced. 10402 if (PeeledCaseProb != BranchProbability::getZero() && 10403 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10404 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10405 WorkList.push_back( 10406 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10407 10408 while (!WorkList.empty()) { 10409 SwitchWorkListItem W = WorkList.back(); 10410 WorkList.pop_back(); 10411 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10412 10413 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10414 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10415 // For optimized builds, lower large range as a balanced binary tree. 10416 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10417 continue; 10418 } 10419 10420 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10421 } 10422 } 10423