1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 using namespace PatternMatch; 125 126 #define DEBUG_TYPE "isel" 127 128 /// LimitFloatPrecision - Generate low-precision inline sequences for 129 /// some float libcalls (6, 8 or 12 bits). 130 static unsigned LimitFloatPrecision; 131 132 static cl::opt<unsigned, true> 133 LimitFPPrecision("limit-float-precision", 134 cl::desc("Generate low-precision inline sequences " 135 "for some float libcalls"), 136 cl::location(LimitFloatPrecision), cl::Hidden, 137 cl::init(0)); 138 139 static cl::opt<unsigned> SwitchPeelThreshold( 140 "switch-peel-threshold", cl::Hidden, cl::init(66), 141 cl::desc("Set the case probability threshold for peeling the case from a " 142 "switch statement. A value greater than 100 will void this " 143 "optimization")); 144 145 // Limit the width of DAG chains. This is important in general to prevent 146 // DAG-based analysis from blowing up. For example, alias analysis and 147 // load clustering may not complete in reasonable time. It is difficult to 148 // recognize and avoid this situation within each individual analysis, and 149 // future analyses are likely to have the same behavior. Limiting DAG width is 150 // the safe approach and will be especially important with global DAGs. 151 // 152 // MaxParallelChains default is arbitrarily high to avoid affecting 153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 154 // sequence over this should have been converted to llvm.memcpy by the 155 // frontend. It is easy to induce this behavior with .ll code such as: 156 // %buffer = alloca [4096 x i8] 157 // %data = load [4096 x i8]* %argPtr 158 // store [4096 x i8] %data, [4096 x i8]* %buffer 159 static const unsigned MaxParallelChains = 64; 160 161 // Return the calling convention if the Value passed requires ABI mangling as it 162 // is a parameter to a function or a return value from a function which is not 163 // an intrinsic. 164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 165 if (auto *R = dyn_cast<ReturnInst>(V)) 166 return R->getParent()->getParent()->getCallingConv(); 167 168 if (auto *CI = dyn_cast<CallInst>(V)) { 169 const bool IsInlineAsm = CI->isInlineAsm(); 170 const bool IsIndirectFunctionCall = 171 !IsInlineAsm && !CI->getCalledFunction(); 172 173 // It is possible that the call instruction is an inline asm statement or an 174 // indirect function call in which case the return value of 175 // getCalledFunction() would be nullptr. 176 const bool IsInstrinsicCall = 177 !IsInlineAsm && !IsIndirectFunctionCall && 178 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 179 180 if (!IsInlineAsm && !IsInstrinsicCall) 181 return CI->getCallingConv(); 182 } 183 184 return None; 185 } 186 187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 188 const SDValue *Parts, unsigned NumParts, 189 MVT PartVT, EVT ValueVT, const Value *V, 190 Optional<CallingConv::ID> CC); 191 192 /// getCopyFromParts - Create a value that contains the specified legal parts 193 /// combined into the value they represent. If the parts combine to a type 194 /// larger than ValueVT then AssertOp can be used to specify whether the extra 195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 196 /// (ISD::AssertSext). 197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 198 const SDValue *Parts, unsigned NumParts, 199 MVT PartVT, EVT ValueVT, const Value *V, 200 Optional<CallingConv::ID> CC = None, 201 Optional<ISD::NodeType> AssertOp = None) { 202 if (ValueVT.isVector()) 203 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 204 CC); 205 206 assert(NumParts > 0 && "No parts to assemble!"); 207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 208 SDValue Val = Parts[0]; 209 210 if (NumParts > 1) { 211 // Assemble the value from multiple parts. 212 if (ValueVT.isInteger()) { 213 unsigned PartBits = PartVT.getSizeInBits(); 214 unsigned ValueBits = ValueVT.getSizeInBits(); 215 216 // Assemble the power of 2 part. 217 unsigned RoundParts = NumParts & (NumParts - 1) ? 218 1 << Log2_32(NumParts) : NumParts; 219 unsigned RoundBits = PartBits * RoundParts; 220 EVT RoundVT = RoundBits == ValueBits ? 221 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 222 SDValue Lo, Hi; 223 224 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 225 226 if (RoundParts > 2) { 227 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 228 PartVT, HalfVT, V); 229 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 230 RoundParts / 2, PartVT, HalfVT, V); 231 } else { 232 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 233 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 234 } 235 236 if (DAG.getDataLayout().isBigEndian()) 237 std::swap(Lo, Hi); 238 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 240 241 if (RoundParts < NumParts) { 242 // Assemble the trailing non-power-of-2 part. 243 unsigned OddParts = NumParts - RoundParts; 244 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 246 OddVT, V, CC); 247 248 // Combine the round and odd parts. 249 Lo = Val; 250 if (DAG.getDataLayout().isBigEndian()) 251 std::swap(Lo, Hi); 252 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 253 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 254 Hi = 255 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 256 DAG.getConstant(Lo.getValueSizeInBits(), DL, 257 TLI.getPointerTy(DAG.getDataLayout()))); 258 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 259 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 260 } 261 } else if (PartVT.isFloatingPoint()) { 262 // FP split into multiple FP parts (for ppcf128) 263 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 264 "Unexpected split"); 265 SDValue Lo, Hi; 266 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 267 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 268 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 269 std::swap(Lo, Hi); 270 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 271 } else { 272 // FP split into integer parts (soft fp) 273 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 274 !PartVT.isVector() && "Unexpected split"); 275 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 276 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 277 } 278 } 279 280 // There is now one part, held in Val. Correct it to match ValueVT. 281 // PartEVT is the type of the register class that holds the value. 282 // ValueVT is the type of the inline asm operation. 283 EVT PartEVT = Val.getValueType(); 284 285 if (PartEVT == ValueVT) 286 return Val; 287 288 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 289 ValueVT.bitsLT(PartEVT)) { 290 // For an FP value in an integer part, we need to truncate to the right 291 // width first. 292 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 293 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 294 } 295 296 // Handle types that have the same size. 297 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 298 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 299 300 // Handle types with different sizes. 301 if (PartEVT.isInteger() && ValueVT.isInteger()) { 302 if (ValueVT.bitsLT(PartEVT)) { 303 // For a truncate, see if we have any information to 304 // indicate whether the truncated bits will always be 305 // zero or sign-extension. 306 if (AssertOp.hasValue()) 307 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 308 DAG.getValueType(ValueVT)); 309 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 310 } 311 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 312 } 313 314 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 315 // FP_ROUND's are always exact here. 316 if (ValueVT.bitsLT(Val.getValueType())) 317 return DAG.getNode( 318 ISD::FP_ROUND, DL, ValueVT, Val, 319 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 320 321 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 322 } 323 324 llvm_unreachable("Unknown mismatch!"); 325 } 326 327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 328 const Twine &ErrMsg) { 329 const Instruction *I = dyn_cast_or_null<Instruction>(V); 330 if (!V) 331 return Ctx.emitError(ErrMsg); 332 333 const char *AsmError = ", possible invalid constraint for vector type"; 334 if (const CallInst *CI = dyn_cast<CallInst>(I)) 335 if (isa<InlineAsm>(CI->getCalledValue())) 336 return Ctx.emitError(I, ErrMsg + AsmError); 337 338 return Ctx.emitError(I, ErrMsg); 339 } 340 341 /// getCopyFromPartsVector - Create a value that contains the specified legal 342 /// parts combined into the value they represent. If the parts combine to a 343 /// type larger than ValueVT then AssertOp can be used to specify whether the 344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 345 /// ValueVT (ISD::AssertSext). 346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 347 const SDValue *Parts, unsigned NumParts, 348 MVT PartVT, EVT ValueVT, const Value *V, 349 Optional<CallingConv::ID> CallConv) { 350 assert(ValueVT.isVector() && "Not a vector value"); 351 assert(NumParts > 0 && "No parts to assemble!"); 352 const bool IsABIRegCopy = CallConv.hasValue(); 353 354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 355 SDValue Val = Parts[0]; 356 357 // Handle a multi-element vector. 358 if (NumParts > 1) { 359 EVT IntermediateVT; 360 MVT RegisterVT; 361 unsigned NumIntermediates; 362 unsigned NumRegs; 363 364 if (IsABIRegCopy) { 365 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 366 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 367 NumIntermediates, RegisterVT); 368 } else { 369 NumRegs = 370 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } 373 374 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 375 NumParts = NumRegs; // Silence a compiler warning. 376 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 377 assert(RegisterVT.getSizeInBits() == 378 Parts[0].getSimpleValueType().getSizeInBits() && 379 "Part type sizes don't match!"); 380 381 // Assemble the parts into intermediate operands. 382 SmallVector<SDValue, 8> Ops(NumIntermediates); 383 if (NumIntermediates == NumParts) { 384 // If the register was not expanded, truncate or copy the value, 385 // as appropriate. 386 for (unsigned i = 0; i != NumParts; ++i) 387 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 388 PartVT, IntermediateVT, V); 389 } else if (NumParts > 0) { 390 // If the intermediate type was expanded, build the intermediate 391 // operands from the parts. 392 assert(NumParts % NumIntermediates == 0 && 393 "Must expand into a divisible number of parts!"); 394 unsigned Factor = NumParts / NumIntermediates; 395 for (unsigned i = 0; i != NumIntermediates; ++i) 396 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 397 PartVT, IntermediateVT, V); 398 } 399 400 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 401 // intermediate operands. 402 EVT BuiltVectorTy = 403 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 404 (IntermediateVT.isVector() 405 ? IntermediateVT.getVectorNumElements() * NumParts 406 : NumIntermediates)); 407 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 408 : ISD::BUILD_VECTOR, 409 DL, BuiltVectorTy, Ops); 410 } 411 412 // There is now one part, held in Val. Correct it to match ValueVT. 413 EVT PartEVT = Val.getValueType(); 414 415 if (PartEVT == ValueVT) 416 return Val; 417 418 if (PartEVT.isVector()) { 419 // If the element type of the source/dest vectors are the same, but the 420 // parts vector has more elements than the value vector, then we have a 421 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 422 // elements we want. 423 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 424 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 425 "Cannot narrow, it would be a lossy transformation"); 426 return DAG.getNode( 427 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 428 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 429 } 430 431 // Vector/Vector bitcast. 432 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 436 "Cannot handle this kind of promotion"); 437 // Promoted vector extract 438 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 439 440 } 441 442 // Trivial bitcast if the types are the same size and the destination 443 // vector type is legal. 444 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 445 TLI.isTypeLegal(ValueVT)) 446 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 447 448 if (ValueVT.getVectorNumElements() != 1) { 449 // Certain ABIs require that vectors are passed as integers. For vectors 450 // are the same size, this is an obvious bitcast. 451 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 454 // Bitcast Val back the original type and extract the corresponding 455 // vector we want. 456 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 457 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 458 ValueVT.getVectorElementType(), Elts); 459 Val = DAG.getBitcast(WiderVecType, Val); 460 return DAG.getNode( 461 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 462 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 473 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 474 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 Optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 488 SDValue *Parts, unsigned NumParts, MVT PartVT, 489 const Value *V, 490 Optional<CallingConv::ID> CallConv = None, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getIntPtrConstant(RoundBits, DL)); 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, 619 SDValue Val, const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 unsigned PartNumElts = PartVT.getVectorNumElements(); 625 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 626 if (PartNumElts > ValueNumElts && 627 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 628 EVT ElementVT = PartVT.getVectorElementType(); 629 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 630 // undef elements. 631 SmallVector<SDValue, 16> Ops; 632 DAG.ExtractVectorElements(Val, Ops); 633 SDValue EltUndef = DAG.getUNDEF(ElementVT); 634 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 635 Ops.push_back(EltUndef); 636 637 // FIXME: Use CONCAT for 2x -> 4x. 638 return DAG.getBuildVector(PartVT, DL, Ops); 639 } 640 641 return SDValue(); 642 } 643 644 /// getCopyToPartsVector - Create a series of nodes that contain the specified 645 /// value split into legal parts. 646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 647 SDValue Val, SDValue *Parts, unsigned NumParts, 648 MVT PartVT, const Value *V, 649 Optional<CallingConv::ID> CallConv) { 650 EVT ValueVT = Val.getValueType(); 651 assert(ValueVT.isVector() && "Not a vector"); 652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 653 const bool IsABIRegCopy = CallConv.hasValue(); 654 655 if (NumParts == 1) { 656 EVT PartEVT = PartVT; 657 if (PartEVT == ValueVT) { 658 // Nothing to do. 659 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 660 // Bitconvert vector->vector case. 661 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 662 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 663 Val = Widened; 664 } else if (PartVT.isVector() && 665 PartEVT.getVectorElementType().bitsGE( 666 ValueVT.getVectorElementType()) && 667 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 668 669 // Promoted vector extract 670 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 671 } else { 672 if (ValueVT.getVectorNumElements() == 1) { 673 Val = DAG.getNode( 674 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 675 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 676 } else { 677 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 678 "lossy conversion of vector to scalar type"); 679 EVT IntermediateType = 680 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 681 Val = DAG.getBitcast(IntermediateType, Val); 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } 684 } 685 686 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 687 Parts[0] = Val; 688 return; 689 } 690 691 // Handle a multi-element vector. 692 EVT IntermediateVT; 693 MVT RegisterVT; 694 unsigned NumIntermediates; 695 unsigned NumRegs; 696 if (IsABIRegCopy) { 697 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 698 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 699 NumIntermediates, RegisterVT); 700 } else { 701 NumRegs = 702 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 703 NumIntermediates, RegisterVT); 704 } 705 706 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 707 NumParts = NumRegs; // Silence a compiler warning. 708 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 709 710 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 711 IntermediateVT.getVectorNumElements() : 1; 712 713 // Convert the vector to the appropiate type if necessary. 714 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 715 716 EVT BuiltVectorTy = EVT::getVectorVT( 717 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 718 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 719 if (ValueVT != BuiltVectorTy) { 720 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 721 Val = Widened; 722 723 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 724 } 725 726 // Split the vector into intermediate operands. 727 SmallVector<SDValue, 8> Ops(NumIntermediates); 728 for (unsigned i = 0; i != NumIntermediates; ++i) { 729 if (IntermediateVT.isVector()) { 730 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 731 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 732 } else { 733 Ops[i] = DAG.getNode( 734 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 735 DAG.getConstant(i, DL, IdxVT)); 736 } 737 } 738 739 // Split the intermediate operands into legal parts. 740 if (NumParts == NumIntermediates) { 741 // If the register was not expanded, promote or copy the value, 742 // as appropriate. 743 for (unsigned i = 0; i != NumParts; ++i) 744 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 745 } else if (NumParts > 0) { 746 // If the intermediate type was expanded, split each the value into 747 // legal parts. 748 assert(NumIntermediates != 0 && "division by zero"); 749 assert(NumParts % NumIntermediates == 0 && 750 "Must expand into a divisible number of parts!"); 751 unsigned Factor = NumParts / NumIntermediates; 752 for (unsigned i = 0; i != NumIntermediates; ++i) 753 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 754 CallConv); 755 } 756 } 757 758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 759 EVT valuevt, Optional<CallingConv::ID> CC) 760 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 761 RegCount(1, regs.size()), CallConv(CC) {} 762 763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 764 const DataLayout &DL, unsigned Reg, Type *Ty, 765 Optional<CallingConv::ID> CC) { 766 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 767 768 CallConv = CC; 769 770 for (EVT ValueVT : ValueVTs) { 771 unsigned NumRegs = 772 isABIMangled() 773 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 774 : TLI.getNumRegisters(Context, ValueVT); 775 MVT RegisterVT = 776 isABIMangled() 777 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 778 : TLI.getRegisterType(Context, ValueVT); 779 for (unsigned i = 0; i != NumRegs; ++i) 780 Regs.push_back(Reg + i); 781 RegVTs.push_back(RegisterVT); 782 RegCount.push_back(NumRegs); 783 Reg += NumRegs; 784 } 785 } 786 787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 788 FunctionLoweringInfo &FuncInfo, 789 const SDLoc &dl, SDValue &Chain, 790 SDValue *Flag, const Value *V) const { 791 // A Value with type {} or [0 x %t] needs no registers. 792 if (ValueVTs.empty()) 793 return SDValue(); 794 795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 796 797 // Assemble the legal parts into the final values. 798 SmallVector<SDValue, 4> Values(ValueVTs.size()); 799 SmallVector<SDValue, 8> Parts; 800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 801 // Copy the legal parts from the registers. 802 EVT ValueVT = ValueVTs[Value]; 803 unsigned NumRegs = RegCount[Value]; 804 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 805 *DAG.getContext(), 806 CallConv.getValue(), RegVTs[Value]) 807 : RegVTs[Value]; 808 809 Parts.resize(NumRegs); 810 for (unsigned i = 0; i != NumRegs; ++i) { 811 SDValue P; 812 if (!Flag) { 813 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 814 } else { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 816 *Flag = P.getValue(2); 817 } 818 819 Chain = P.getValue(1); 820 Parts[i] = P; 821 822 // If the source register was virtual and if we know something about it, 823 // add an assert node. 824 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 825 !RegisterVT.isInteger()) 826 continue; 827 828 const FunctionLoweringInfo::LiveOutInfo *LOI = 829 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 830 if (!LOI) 831 continue; 832 833 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 834 unsigned NumSignBits = LOI->NumSignBits; 835 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 836 837 if (NumZeroBits == RegSize) { 838 // The current value is a zero. 839 // Explicitly express that as it would be easier for 840 // optimizations to kick in. 841 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 842 continue; 843 } 844 845 // FIXME: We capture more information than the dag can represent. For 846 // now, just use the tightest assertzext/assertsext possible. 847 bool isSExt; 848 EVT FromVT(MVT::Other); 849 if (NumZeroBits) { 850 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 851 isSExt = false; 852 } else if (NumSignBits > 1) { 853 FromVT = 854 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 855 isSExt = true; 856 } else { 857 continue; 858 } 859 // Add an assertion node. 860 assert(FromVT != MVT::Other); 861 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 862 RegisterVT, P, DAG.getValueType(FromVT)); 863 } 864 865 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 866 RegisterVT, ValueVT, V, CallConv); 867 Part += NumRegs; 868 Parts.clear(); 869 } 870 871 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 872 } 873 874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 875 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 876 const Value *V, 877 ISD::NodeType PreferredExtendType) const { 878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 879 ISD::NodeType ExtendKind = PreferredExtendType; 880 881 // Get the list of the values's legal parts. 882 unsigned NumRegs = Regs.size(); 883 SmallVector<SDValue, 8> Parts(NumRegs); 884 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 885 unsigned NumParts = RegCount[Value]; 886 887 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 888 *DAG.getContext(), 889 CallConv.getValue(), RegVTs[Value]) 890 : RegVTs[Value]; 891 892 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 893 ExtendKind = ISD::ZERO_EXTEND; 894 895 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 896 NumParts, RegisterVT, V, CallConv, ExtendKind); 897 Part += NumParts; 898 } 899 900 // Copy the parts into the registers. 901 SmallVector<SDValue, 8> Chains(NumRegs); 902 for (unsigned i = 0; i != NumRegs; ++i) { 903 SDValue Part; 904 if (!Flag) { 905 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 906 } else { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 908 *Flag = Part.getValue(1); 909 } 910 911 Chains[i] = Part.getValue(0); 912 } 913 914 if (NumRegs == 1 || Flag) 915 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 916 // flagged to it. That is the CopyToReg nodes and the user are considered 917 // a single scheduling unit. If we create a TokenFactor and return it as 918 // chain, then the TokenFactor is both a predecessor (operand) of the 919 // user as well as a successor (the TF operands are flagged to the user). 920 // c1, f1 = CopyToReg 921 // c2, f2 = CopyToReg 922 // c3 = TokenFactor c1, c2 923 // ... 924 // = op c3, ..., f2 925 Chain = Chains[NumRegs-1]; 926 else 927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 928 } 929 930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 931 unsigned MatchingIdx, const SDLoc &dl, 932 SelectionDAG &DAG, 933 std::vector<SDValue> &Ops) const { 934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 935 936 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 937 if (HasMatching) 938 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 939 else if (!Regs.empty() && 940 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, unsigned>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 unsigned RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 } 1006 1007 void SelectionDAGBuilder::clear() { 1008 NodeMap.clear(); 1009 UnusedArgNodeMap.clear(); 1010 PendingLoads.clear(); 1011 PendingExports.clear(); 1012 CurInst = nullptr; 1013 HasTailCall = false; 1014 SDNodeOrder = LowestSDNodeOrder; 1015 StatepointLowering.clear(); 1016 } 1017 1018 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1019 DanglingDebugInfoMap.clear(); 1020 } 1021 1022 SDValue SelectionDAGBuilder::getRoot() { 1023 if (PendingLoads.empty()) 1024 return DAG.getRoot(); 1025 1026 if (PendingLoads.size() == 1) { 1027 SDValue Root = PendingLoads[0]; 1028 DAG.setRoot(Root); 1029 PendingLoads.clear(); 1030 return Root; 1031 } 1032 1033 // Otherwise, we have to make a token factor node. 1034 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1035 PendingLoads.clear(); 1036 DAG.setRoot(Root); 1037 return Root; 1038 } 1039 1040 SDValue SelectionDAGBuilder::getControlRoot() { 1041 SDValue Root = DAG.getRoot(); 1042 1043 if (PendingExports.empty()) 1044 return Root; 1045 1046 // Turn all of the CopyToReg chains into one factored node. 1047 if (Root.getOpcode() != ISD::EntryToken) { 1048 unsigned i = 0, e = PendingExports.size(); 1049 for (; i != e; ++i) { 1050 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1051 if (PendingExports[i].getNode()->getOperand(0) == Root) 1052 break; // Don't add the root if we already indirectly depend on it. 1053 } 1054 1055 if (i == e) 1056 PendingExports.push_back(Root); 1057 } 1058 1059 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1060 PendingExports); 1061 PendingExports.clear(); 1062 DAG.setRoot(Root); 1063 return Root; 1064 } 1065 1066 void SelectionDAGBuilder::visit(const Instruction &I) { 1067 // Set up outgoing PHI node register values before emitting the terminator. 1068 if (I.isTerminator()) { 1069 HandlePHINodesInSuccessorBlocks(I.getParent()); 1070 } 1071 1072 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1073 if (!isa<DbgInfoIntrinsic>(I)) 1074 ++SDNodeOrder; 1075 1076 CurInst = &I; 1077 1078 visit(I.getOpcode(), I); 1079 1080 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1081 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1082 // maps to this instruction. 1083 // TODO: We could handle all flags (nsw, etc) here. 1084 // TODO: If an IR instruction maps to >1 node, only the final node will have 1085 // flags set. 1086 if (SDNode *Node = getNodeForIRValue(&I)) { 1087 SDNodeFlags IncomingFlags; 1088 IncomingFlags.copyFMF(*FPMO); 1089 if (!Node->getFlags().isDefined()) 1090 Node->setFlags(IncomingFlags); 1091 else 1092 Node->intersectFlagsWith(IncomingFlags); 1093 } 1094 } 1095 1096 if (!I.isTerminator() && !HasTailCall && 1097 !isStatepoint(&I)) // statepoints handle their exports internally 1098 CopyToExportRegsIfNeeded(&I); 1099 1100 CurInst = nullptr; 1101 } 1102 1103 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1104 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1105 } 1106 1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1108 // Note: this doesn't use InstVisitor, because it has to work with 1109 // ConstantExpr's in addition to instructions. 1110 switch (Opcode) { 1111 default: llvm_unreachable("Unknown instruction type encountered!"); 1112 // Build the switch statement using the Instruction.def file. 1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1114 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1115 #include "llvm/IR/Instruction.def" 1116 } 1117 } 1118 1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1120 const DIExpression *Expr) { 1121 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1122 const DbgValueInst *DI = DDI.getDI(); 1123 DIVariable *DanglingVariable = DI->getVariable(); 1124 DIExpression *DanglingExpr = DI->getExpression(); 1125 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1126 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1127 return true; 1128 } 1129 return false; 1130 }; 1131 1132 for (auto &DDIMI : DanglingDebugInfoMap) { 1133 DanglingDebugInfoVector &DDIV = DDIMI.second; 1134 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1135 } 1136 } 1137 1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1139 // generate the debug data structures now that we've seen its definition. 1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1141 SDValue Val) { 1142 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1143 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1144 return; 1145 1146 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1147 for (auto &DDI : DDIV) { 1148 const DbgValueInst *DI = DDI.getDI(); 1149 assert(DI && "Ill-formed DanglingDebugInfo"); 1150 DebugLoc dl = DDI.getdl(); 1151 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1152 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1153 DILocalVariable *Variable = DI->getVariable(); 1154 DIExpression *Expr = DI->getExpression(); 1155 assert(Variable->isValidLocationForIntrinsic(dl) && 1156 "Expected inlined-at fields to agree"); 1157 SDDbgValue *SDV; 1158 if (Val.getNode()) { 1159 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1160 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1161 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1162 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1163 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1164 // inserted after the definition of Val when emitting the instructions 1165 // after ISel. An alternative could be to teach 1166 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1167 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1168 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1169 << ValSDNodeOrder << "\n"); 1170 SDV = getDbgValue(Val, Variable, Expr, dl, 1171 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1172 DAG.AddDbgValue(SDV, Val.getNode(), false); 1173 } else 1174 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1175 << "in EmitFuncArgumentDbgValue\n"); 1176 } else 1177 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1178 } 1179 DDIV.clear(); 1180 } 1181 1182 /// getCopyFromRegs - If there was virtual register allocated for the value V 1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1185 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1186 SDValue Result; 1187 1188 if (It != FuncInfo.ValueMap.end()) { 1189 unsigned InReg = It->second; 1190 1191 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1192 DAG.getDataLayout(), InReg, Ty, 1193 None); // This is not an ABI copy. 1194 SDValue Chain = DAG.getEntryNode(); 1195 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1196 V); 1197 resolveDanglingDebugInfo(V, Result); 1198 } 1199 1200 return Result; 1201 } 1202 1203 /// getValue - Return an SDValue for the given Value. 1204 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1205 // If we already have an SDValue for this value, use it. It's important 1206 // to do this first, so that we don't create a CopyFromReg if we already 1207 // have a regular SDValue. 1208 SDValue &N = NodeMap[V]; 1209 if (N.getNode()) return N; 1210 1211 // If there's a virtual register allocated and initialized for this 1212 // value, use it. 1213 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1214 return copyFromReg; 1215 1216 // Otherwise create a new SDValue and remember it. 1217 SDValue Val = getValueImpl(V); 1218 NodeMap[V] = Val; 1219 resolveDanglingDebugInfo(V, Val); 1220 return Val; 1221 } 1222 1223 // Return true if SDValue exists for the given Value 1224 bool SelectionDAGBuilder::findValue(const Value *V) const { 1225 return (NodeMap.find(V) != NodeMap.end()) || 1226 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1227 } 1228 1229 /// getNonRegisterValue - Return an SDValue for the given Value, but 1230 /// don't look in FuncInfo.ValueMap for a virtual register. 1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1232 // If we already have an SDValue for this value, use it. 1233 SDValue &N = NodeMap[V]; 1234 if (N.getNode()) { 1235 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1236 // Remove the debug location from the node as the node is about to be used 1237 // in a location which may differ from the original debug location. This 1238 // is relevant to Constant and ConstantFP nodes because they can appear 1239 // as constant expressions inside PHI nodes. 1240 N->setDebugLoc(DebugLoc()); 1241 } 1242 return N; 1243 } 1244 1245 // Otherwise create a new SDValue and remember it. 1246 SDValue Val = getValueImpl(V); 1247 NodeMap[V] = Val; 1248 resolveDanglingDebugInfo(V, Val); 1249 return Val; 1250 } 1251 1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1253 /// Create an SDValue for the given value. 1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1256 1257 if (const Constant *C = dyn_cast<Constant>(V)) { 1258 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1259 1260 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1261 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1262 1263 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1264 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1265 1266 if (isa<ConstantPointerNull>(C)) { 1267 unsigned AS = V->getType()->getPointerAddressSpace(); 1268 return DAG.getConstant(0, getCurSDLoc(), 1269 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1270 } 1271 1272 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1273 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1274 1275 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1276 return DAG.getUNDEF(VT); 1277 1278 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1279 visit(CE->getOpcode(), *CE); 1280 SDValue N1 = NodeMap[V]; 1281 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1282 return N1; 1283 } 1284 1285 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1286 SmallVector<SDValue, 4> Constants; 1287 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1288 OI != OE; ++OI) { 1289 SDNode *Val = getValue(*OI).getNode(); 1290 // If the operand is an empty aggregate, there are no values. 1291 if (!Val) continue; 1292 // Add each leaf value from the operand to the Constants list 1293 // to form a flattened list of all the values. 1294 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1295 Constants.push_back(SDValue(Val, i)); 1296 } 1297 1298 return DAG.getMergeValues(Constants, getCurSDLoc()); 1299 } 1300 1301 if (const ConstantDataSequential *CDS = 1302 dyn_cast<ConstantDataSequential>(C)) { 1303 SmallVector<SDValue, 4> Ops; 1304 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1305 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1306 // Add each leaf value from the operand to the Constants list 1307 // to form a flattened list of all the values. 1308 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1309 Ops.push_back(SDValue(Val, i)); 1310 } 1311 1312 if (isa<ArrayType>(CDS->getType())) 1313 return DAG.getMergeValues(Ops, getCurSDLoc()); 1314 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1315 } 1316 1317 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1318 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1319 "Unknown struct or array constant!"); 1320 1321 SmallVector<EVT, 4> ValueVTs; 1322 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1323 unsigned NumElts = ValueVTs.size(); 1324 if (NumElts == 0) 1325 return SDValue(); // empty struct 1326 SmallVector<SDValue, 4> Constants(NumElts); 1327 for (unsigned i = 0; i != NumElts; ++i) { 1328 EVT EltVT = ValueVTs[i]; 1329 if (isa<UndefValue>(C)) 1330 Constants[i] = DAG.getUNDEF(EltVT); 1331 else if (EltVT.isFloatingPoint()) 1332 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1333 else 1334 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1335 } 1336 1337 return DAG.getMergeValues(Constants, getCurSDLoc()); 1338 } 1339 1340 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1341 return DAG.getBlockAddress(BA, VT); 1342 1343 VectorType *VecTy = cast<VectorType>(V->getType()); 1344 unsigned NumElements = VecTy->getNumElements(); 1345 1346 // Now that we know the number and type of the elements, get that number of 1347 // elements into the Ops array based on what kind of constant it is. 1348 SmallVector<SDValue, 16> Ops; 1349 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1350 for (unsigned i = 0; i != NumElements; ++i) 1351 Ops.push_back(getValue(CV->getOperand(i))); 1352 } else { 1353 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1354 EVT EltVT = 1355 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1356 1357 SDValue Op; 1358 if (EltVT.isFloatingPoint()) 1359 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1360 else 1361 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1362 Ops.assign(NumElements, Op); 1363 } 1364 1365 // Create a BUILD_VECTOR node. 1366 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1367 } 1368 1369 // If this is a static alloca, generate it as the frameindex instead of 1370 // computation. 1371 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1372 DenseMap<const AllocaInst*, int>::iterator SI = 1373 FuncInfo.StaticAllocaMap.find(AI); 1374 if (SI != FuncInfo.StaticAllocaMap.end()) 1375 return DAG.getFrameIndex(SI->second, 1376 TLI.getFrameIndexTy(DAG.getDataLayout())); 1377 } 1378 1379 // If this is an instruction which fast-isel has deferred, select it now. 1380 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1381 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1382 1383 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1384 Inst->getType(), getABIRegCopyCC(V)); 1385 SDValue Chain = DAG.getEntryNode(); 1386 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1387 } 1388 1389 llvm_unreachable("Can't get register for value!"); 1390 } 1391 1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1393 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1394 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1395 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1396 bool IsSEH = isAsynchronousEHPersonality(Pers); 1397 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1398 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1399 if (!IsSEH) 1400 CatchPadMBB->setIsEHScopeEntry(); 1401 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1402 if (IsMSVCCXX || IsCoreCLR) 1403 CatchPadMBB->setIsEHFuncletEntry(); 1404 // Wasm does not need catchpads anymore 1405 if (!IsWasmCXX) 1406 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1407 getControlRoot())); 1408 } 1409 1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1411 // Update machine-CFG edge. 1412 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1413 FuncInfo.MBB->addSuccessor(TargetMBB); 1414 1415 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1416 bool IsSEH = isAsynchronousEHPersonality(Pers); 1417 if (IsSEH) { 1418 // If this is not a fall-through branch or optimizations are switched off, 1419 // emit the branch. 1420 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1421 TM.getOptLevel() == CodeGenOpt::None) 1422 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1423 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1424 return; 1425 } 1426 1427 // Figure out the funclet membership for the catchret's successor. 1428 // This will be used by the FuncletLayout pass to determine how to order the 1429 // BB's. 1430 // A 'catchret' returns to the outer scope's color. 1431 Value *ParentPad = I.getCatchSwitchParentPad(); 1432 const BasicBlock *SuccessorColor; 1433 if (isa<ConstantTokenNone>(ParentPad)) 1434 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1435 else 1436 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1437 assert(SuccessorColor && "No parent funclet for catchret!"); 1438 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1439 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1440 1441 // Create the terminator node. 1442 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1443 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1444 DAG.getBasicBlock(SuccessorColorMBB)); 1445 DAG.setRoot(Ret); 1446 } 1447 1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1449 // Don't emit any special code for the cleanuppad instruction. It just marks 1450 // the start of an EH scope/funclet. 1451 FuncInfo.MBB->setIsEHScopeEntry(); 1452 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1453 if (Pers != EHPersonality::Wasm_CXX) { 1454 FuncInfo.MBB->setIsEHFuncletEntry(); 1455 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1456 } 1457 } 1458 1459 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1460 // the control flow always stops at the single catch pad, as it does for a 1461 // cleanup pad. In case the exception caught is not of the types the catch pad 1462 // catches, it will be rethrown by a rethrow. 1463 static void findWasmUnwindDestinations( 1464 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1465 BranchProbability Prob, 1466 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1467 &UnwindDests) { 1468 while (EHPadBB) { 1469 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1470 if (isa<CleanupPadInst>(Pad)) { 1471 // Stop on cleanup pads. 1472 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1473 UnwindDests.back().first->setIsEHScopeEntry(); 1474 break; 1475 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1476 // Add the catchpad handlers to the possible destinations. We don't 1477 // continue to the unwind destination of the catchswitch for wasm. 1478 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1479 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1480 UnwindDests.back().first->setIsEHScopeEntry(); 1481 } 1482 break; 1483 } else { 1484 continue; 1485 } 1486 } 1487 } 1488 1489 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1490 /// many places it could ultimately go. In the IR, we have a single unwind 1491 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1492 /// This function skips over imaginary basic blocks that hold catchswitch 1493 /// instructions, and finds all the "real" machine 1494 /// basic block destinations. As those destinations may not be successors of 1495 /// EHPadBB, here we also calculate the edge probability to those destinations. 1496 /// The passed-in Prob is the edge probability to EHPadBB. 1497 static void findUnwindDestinations( 1498 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1499 BranchProbability Prob, 1500 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1501 &UnwindDests) { 1502 EHPersonality Personality = 1503 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1504 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1505 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1506 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1507 bool IsSEH = isAsynchronousEHPersonality(Personality); 1508 1509 if (IsWasmCXX) { 1510 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1511 return; 1512 } 1513 1514 while (EHPadBB) { 1515 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1516 BasicBlock *NewEHPadBB = nullptr; 1517 if (isa<LandingPadInst>(Pad)) { 1518 // Stop on landingpads. They are not funclets. 1519 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1520 break; 1521 } else if (isa<CleanupPadInst>(Pad)) { 1522 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1523 // personalities. 1524 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1525 UnwindDests.back().first->setIsEHScopeEntry(); 1526 UnwindDests.back().first->setIsEHFuncletEntry(); 1527 break; 1528 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1529 // Add the catchpad handlers to the possible destinations. 1530 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1531 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1532 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1533 if (IsMSVCCXX || IsCoreCLR) 1534 UnwindDests.back().first->setIsEHFuncletEntry(); 1535 if (!IsSEH) 1536 UnwindDests.back().first->setIsEHScopeEntry(); 1537 } 1538 NewEHPadBB = CatchSwitch->getUnwindDest(); 1539 } else { 1540 continue; 1541 } 1542 1543 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1544 if (BPI && NewEHPadBB) 1545 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1546 EHPadBB = NewEHPadBB; 1547 } 1548 } 1549 1550 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1551 // Update successor info. 1552 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1553 auto UnwindDest = I.getUnwindDest(); 1554 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1555 BranchProbability UnwindDestProb = 1556 (BPI && UnwindDest) 1557 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1558 : BranchProbability::getZero(); 1559 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1560 for (auto &UnwindDest : UnwindDests) { 1561 UnwindDest.first->setIsEHPad(); 1562 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1563 } 1564 FuncInfo.MBB->normalizeSuccProbs(); 1565 1566 // Create the terminator node. 1567 SDValue Ret = 1568 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1569 DAG.setRoot(Ret); 1570 } 1571 1572 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1573 report_fatal_error("visitCatchSwitch not yet implemented!"); 1574 } 1575 1576 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1578 auto &DL = DAG.getDataLayout(); 1579 SDValue Chain = getControlRoot(); 1580 SmallVector<ISD::OutputArg, 8> Outs; 1581 SmallVector<SDValue, 8> OutVals; 1582 1583 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1584 // lower 1585 // 1586 // %val = call <ty> @llvm.experimental.deoptimize() 1587 // ret <ty> %val 1588 // 1589 // differently. 1590 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1591 LowerDeoptimizingReturn(); 1592 return; 1593 } 1594 1595 if (!FuncInfo.CanLowerReturn) { 1596 unsigned DemoteReg = FuncInfo.DemoteRegister; 1597 const Function *F = I.getParent()->getParent(); 1598 1599 // Emit a store of the return value through the virtual register. 1600 // Leave Outs empty so that LowerReturn won't try to load return 1601 // registers the usual way. 1602 SmallVector<EVT, 1> PtrValueVTs; 1603 ComputeValueVTs(TLI, DL, 1604 F->getReturnType()->getPointerTo( 1605 DAG.getDataLayout().getAllocaAddrSpace()), 1606 PtrValueVTs); 1607 1608 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1609 DemoteReg, PtrValueVTs[0]); 1610 SDValue RetOp = getValue(I.getOperand(0)); 1611 1612 SmallVector<EVT, 4> ValueVTs; 1613 SmallVector<uint64_t, 4> Offsets; 1614 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1615 unsigned NumValues = ValueVTs.size(); 1616 1617 SmallVector<SDValue, 4> Chains(NumValues); 1618 for (unsigned i = 0; i != NumValues; ++i) { 1619 // An aggregate return value cannot wrap around the address space, so 1620 // offsets to its parts don't wrap either. 1621 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1622 Chains[i] = DAG.getStore( 1623 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1624 // FIXME: better loc info would be nice. 1625 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1626 } 1627 1628 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1629 MVT::Other, Chains); 1630 } else if (I.getNumOperands() != 0) { 1631 SmallVector<EVT, 4> ValueVTs; 1632 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1633 unsigned NumValues = ValueVTs.size(); 1634 if (NumValues) { 1635 SDValue RetOp = getValue(I.getOperand(0)); 1636 1637 const Function *F = I.getParent()->getParent(); 1638 1639 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1640 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1641 Attribute::SExt)) 1642 ExtendKind = ISD::SIGN_EXTEND; 1643 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1644 Attribute::ZExt)) 1645 ExtendKind = ISD::ZERO_EXTEND; 1646 1647 LLVMContext &Context = F->getContext(); 1648 bool RetInReg = F->getAttributes().hasAttribute( 1649 AttributeList::ReturnIndex, Attribute::InReg); 1650 1651 for (unsigned j = 0; j != NumValues; ++j) { 1652 EVT VT = ValueVTs[j]; 1653 1654 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1655 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1656 1657 CallingConv::ID CC = F->getCallingConv(); 1658 1659 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1660 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1661 SmallVector<SDValue, 4> Parts(NumParts); 1662 getCopyToParts(DAG, getCurSDLoc(), 1663 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1664 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1665 1666 // 'inreg' on function refers to return value 1667 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1668 if (RetInReg) 1669 Flags.setInReg(); 1670 1671 // Propagate extension type if any 1672 if (ExtendKind == ISD::SIGN_EXTEND) 1673 Flags.setSExt(); 1674 else if (ExtendKind == ISD::ZERO_EXTEND) 1675 Flags.setZExt(); 1676 1677 for (unsigned i = 0; i < NumParts; ++i) { 1678 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1679 VT, /*isfixed=*/true, 0, 0)); 1680 OutVals.push_back(Parts[i]); 1681 } 1682 } 1683 } 1684 } 1685 1686 // Push in swifterror virtual register as the last element of Outs. This makes 1687 // sure swifterror virtual register will be returned in the swifterror 1688 // physical register. 1689 const Function *F = I.getParent()->getParent(); 1690 if (TLI.supportSwiftError() && 1691 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1692 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1693 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1694 Flags.setSwiftError(); 1695 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1696 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1697 true /*isfixed*/, 1 /*origidx*/, 1698 0 /*partOffs*/)); 1699 // Create SDNode for the swifterror virtual register. 1700 OutVals.push_back( 1701 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1702 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1703 EVT(TLI.getPointerTy(DL)))); 1704 } 1705 1706 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1707 CallingConv::ID CallConv = 1708 DAG.getMachineFunction().getFunction().getCallingConv(); 1709 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1710 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1711 1712 // Verify that the target's LowerReturn behaved as expected. 1713 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1714 "LowerReturn didn't return a valid chain!"); 1715 1716 // Update the DAG with the new chain value resulting from return lowering. 1717 DAG.setRoot(Chain); 1718 } 1719 1720 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1721 /// created for it, emit nodes to copy the value into the virtual 1722 /// registers. 1723 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1724 // Skip empty types 1725 if (V->getType()->isEmptyTy()) 1726 return; 1727 1728 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1729 if (VMI != FuncInfo.ValueMap.end()) { 1730 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1731 CopyValueToVirtualRegister(V, VMI->second); 1732 } 1733 } 1734 1735 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1736 /// the current basic block, add it to ValueMap now so that we'll get a 1737 /// CopyTo/FromReg. 1738 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1739 // No need to export constants. 1740 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1741 1742 // Already exported? 1743 if (FuncInfo.isExportedInst(V)) return; 1744 1745 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1746 CopyValueToVirtualRegister(V, Reg); 1747 } 1748 1749 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1750 const BasicBlock *FromBB) { 1751 // The operands of the setcc have to be in this block. We don't know 1752 // how to export them from some other block. 1753 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1754 // Can export from current BB. 1755 if (VI->getParent() == FromBB) 1756 return true; 1757 1758 // Is already exported, noop. 1759 return FuncInfo.isExportedInst(V); 1760 } 1761 1762 // If this is an argument, we can export it if the BB is the entry block or 1763 // if it is already exported. 1764 if (isa<Argument>(V)) { 1765 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1766 return true; 1767 1768 // Otherwise, can only export this if it is already exported. 1769 return FuncInfo.isExportedInst(V); 1770 } 1771 1772 // Otherwise, constants can always be exported. 1773 return true; 1774 } 1775 1776 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1777 BranchProbability 1778 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1779 const MachineBasicBlock *Dst) const { 1780 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1781 const BasicBlock *SrcBB = Src->getBasicBlock(); 1782 const BasicBlock *DstBB = Dst->getBasicBlock(); 1783 if (!BPI) { 1784 // If BPI is not available, set the default probability as 1 / N, where N is 1785 // the number of successors. 1786 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1787 return BranchProbability(1, SuccSize); 1788 } 1789 return BPI->getEdgeProbability(SrcBB, DstBB); 1790 } 1791 1792 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1793 MachineBasicBlock *Dst, 1794 BranchProbability Prob) { 1795 if (!FuncInfo.BPI) 1796 Src->addSuccessorWithoutProb(Dst); 1797 else { 1798 if (Prob.isUnknown()) 1799 Prob = getEdgeProbability(Src, Dst); 1800 Src->addSuccessor(Dst, Prob); 1801 } 1802 } 1803 1804 static bool InBlock(const Value *V, const BasicBlock *BB) { 1805 if (const Instruction *I = dyn_cast<Instruction>(V)) 1806 return I->getParent() == BB; 1807 return true; 1808 } 1809 1810 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1811 /// This function emits a branch and is used at the leaves of an OR or an 1812 /// AND operator tree. 1813 void 1814 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1815 MachineBasicBlock *TBB, 1816 MachineBasicBlock *FBB, 1817 MachineBasicBlock *CurBB, 1818 MachineBasicBlock *SwitchBB, 1819 BranchProbability TProb, 1820 BranchProbability FProb, 1821 bool InvertCond) { 1822 const BasicBlock *BB = CurBB->getBasicBlock(); 1823 1824 // If the leaf of the tree is a comparison, merge the condition into 1825 // the caseblock. 1826 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1827 // The operands of the cmp have to be in this block. We don't know 1828 // how to export them from some other block. If this is the first block 1829 // of the sequence, no exporting is needed. 1830 if (CurBB == SwitchBB || 1831 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1832 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1833 ISD::CondCode Condition; 1834 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1835 ICmpInst::Predicate Pred = 1836 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1837 Condition = getICmpCondCode(Pred); 1838 } else { 1839 const FCmpInst *FC = cast<FCmpInst>(Cond); 1840 FCmpInst::Predicate Pred = 1841 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1842 Condition = getFCmpCondCode(Pred); 1843 if (TM.Options.NoNaNsFPMath) 1844 Condition = getFCmpCodeWithoutNaN(Condition); 1845 } 1846 1847 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1848 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1849 SwitchCases.push_back(CB); 1850 return; 1851 } 1852 } 1853 1854 // Create a CaseBlock record representing this branch. 1855 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1856 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1857 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1858 SwitchCases.push_back(CB); 1859 } 1860 1861 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1862 MachineBasicBlock *TBB, 1863 MachineBasicBlock *FBB, 1864 MachineBasicBlock *CurBB, 1865 MachineBasicBlock *SwitchBB, 1866 Instruction::BinaryOps Opc, 1867 BranchProbability TProb, 1868 BranchProbability FProb, 1869 bool InvertCond) { 1870 // Skip over not part of the tree and remember to invert op and operands at 1871 // next level. 1872 Value *NotCond; 1873 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1874 InBlock(NotCond, CurBB->getBasicBlock())) { 1875 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1876 !InvertCond); 1877 return; 1878 } 1879 1880 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1881 // Compute the effective opcode for Cond, taking into account whether it needs 1882 // to be inverted, e.g. 1883 // and (not (or A, B)), C 1884 // gets lowered as 1885 // and (and (not A, not B), C) 1886 unsigned BOpc = 0; 1887 if (BOp) { 1888 BOpc = BOp->getOpcode(); 1889 if (InvertCond) { 1890 if (BOpc == Instruction::And) 1891 BOpc = Instruction::Or; 1892 else if (BOpc == Instruction::Or) 1893 BOpc = Instruction::And; 1894 } 1895 } 1896 1897 // If this node is not part of the or/and tree, emit it as a branch. 1898 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1899 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1900 BOp->getParent() != CurBB->getBasicBlock() || 1901 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1902 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1903 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1904 TProb, FProb, InvertCond); 1905 return; 1906 } 1907 1908 // Create TmpBB after CurBB. 1909 MachineFunction::iterator BBI(CurBB); 1910 MachineFunction &MF = DAG.getMachineFunction(); 1911 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1912 CurBB->getParent()->insert(++BBI, TmpBB); 1913 1914 if (Opc == Instruction::Or) { 1915 // Codegen X | Y as: 1916 // BB1: 1917 // jmp_if_X TBB 1918 // jmp TmpBB 1919 // TmpBB: 1920 // jmp_if_Y TBB 1921 // jmp FBB 1922 // 1923 1924 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1925 // The requirement is that 1926 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1927 // = TrueProb for original BB. 1928 // Assuming the original probabilities are A and B, one choice is to set 1929 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1930 // A/(1+B) and 2B/(1+B). This choice assumes that 1931 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1932 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1933 // TmpBB, but the math is more complicated. 1934 1935 auto NewTrueProb = TProb / 2; 1936 auto NewFalseProb = TProb / 2 + FProb; 1937 // Emit the LHS condition. 1938 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1939 NewTrueProb, NewFalseProb, InvertCond); 1940 1941 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1942 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 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 } else { 1948 assert(Opc == Instruction::And && "Unknown merge op!"); 1949 // Codegen X & Y as: 1950 // BB1: 1951 // jmp_if_X TmpBB 1952 // jmp FBB 1953 // TmpBB: 1954 // jmp_if_Y TBB 1955 // jmp FBB 1956 // 1957 // This requires creation of TmpBB after CurBB. 1958 1959 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1960 // The requirement is that 1961 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1962 // = FalseProb for original BB. 1963 // Assuming the original probabilities are A and B, one choice is to set 1964 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1965 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1966 // TrueProb for BB1 * FalseProb for TmpBB. 1967 1968 auto NewTrueProb = TProb + FProb / 2; 1969 auto NewFalseProb = FProb / 2; 1970 // Emit the LHS condition. 1971 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1972 NewTrueProb, NewFalseProb, InvertCond); 1973 1974 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1975 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1976 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1977 // Emit the RHS condition into TmpBB. 1978 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1979 Probs[0], Probs[1], InvertCond); 1980 } 1981 } 1982 1983 /// If the set of cases should be emitted as a series of branches, return true. 1984 /// If we should emit this as a bunch of and/or'd together conditions, return 1985 /// false. 1986 bool 1987 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1988 if (Cases.size() != 2) return true; 1989 1990 // If this is two comparisons of the same values or'd or and'd together, they 1991 // will get folded into a single comparison, so don't emit two blocks. 1992 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1993 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1994 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1995 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1996 return false; 1997 } 1998 1999 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2000 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2001 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2002 Cases[0].CC == Cases[1].CC && 2003 isa<Constant>(Cases[0].CmpRHS) && 2004 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2005 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2006 return false; 2007 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2008 return false; 2009 } 2010 2011 return true; 2012 } 2013 2014 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2015 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2016 2017 // Update machine-CFG edges. 2018 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2019 2020 if (I.isUnconditional()) { 2021 // Update machine-CFG edges. 2022 BrMBB->addSuccessor(Succ0MBB); 2023 2024 // If this is not a fall-through branch or optimizations are switched off, 2025 // emit the branch. 2026 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2027 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2028 MVT::Other, getControlRoot(), 2029 DAG.getBasicBlock(Succ0MBB))); 2030 2031 return; 2032 } 2033 2034 // If this condition is one of the special cases we handle, do special stuff 2035 // now. 2036 const Value *CondVal = I.getCondition(); 2037 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2038 2039 // If this is a series of conditions that are or'd or and'd together, emit 2040 // this as a sequence of branches instead of setcc's with and/or operations. 2041 // As long as jumps are not expensive, this should improve performance. 2042 // For example, instead of something like: 2043 // cmp A, B 2044 // C = seteq 2045 // cmp D, E 2046 // F = setle 2047 // or C, F 2048 // jnz foo 2049 // Emit: 2050 // cmp A, B 2051 // je foo 2052 // cmp D, E 2053 // jle foo 2054 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2055 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2056 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2057 !I.getMetadata(LLVMContext::MD_unpredictable) && 2058 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2059 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2060 Opcode, 2061 getEdgeProbability(BrMBB, Succ0MBB), 2062 getEdgeProbability(BrMBB, Succ1MBB), 2063 /*InvertCond=*/false); 2064 // If the compares in later blocks need to use values not currently 2065 // exported from this block, export them now. This block should always 2066 // be the first entry. 2067 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2068 2069 // Allow some cases to be rejected. 2070 if (ShouldEmitAsBranches(SwitchCases)) { 2071 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2072 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2073 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2074 } 2075 2076 // Emit the branch for this block. 2077 visitSwitchCase(SwitchCases[0], BrMBB); 2078 SwitchCases.erase(SwitchCases.begin()); 2079 return; 2080 } 2081 2082 // Okay, we decided not to do this, remove any inserted MBB's and clear 2083 // SwitchCases. 2084 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2085 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2086 2087 SwitchCases.clear(); 2088 } 2089 } 2090 2091 // Create a CaseBlock record representing this branch. 2092 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2093 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2094 2095 // Use visitSwitchCase to actually insert the fast branch sequence for this 2096 // cond branch. 2097 visitSwitchCase(CB, BrMBB); 2098 } 2099 2100 /// visitSwitchCase - Emits the necessary code to represent a single node in 2101 /// the binary search tree resulting from lowering a switch instruction. 2102 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2103 MachineBasicBlock *SwitchBB) { 2104 SDValue Cond; 2105 SDValue CondLHS = getValue(CB.CmpLHS); 2106 SDLoc dl = CB.DL; 2107 2108 // Build the setcc now. 2109 if (!CB.CmpMHS) { 2110 // Fold "(X == true)" to X and "(X == false)" to !X to 2111 // handle common cases produced by branch lowering. 2112 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2113 CB.CC == ISD::SETEQ) 2114 Cond = CondLHS; 2115 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2116 CB.CC == ISD::SETEQ) { 2117 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2118 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2119 } else 2120 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2121 } else { 2122 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2123 2124 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2125 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2126 2127 SDValue CmpOp = getValue(CB.CmpMHS); 2128 EVT VT = CmpOp.getValueType(); 2129 2130 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2131 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2132 ISD::SETLE); 2133 } else { 2134 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2135 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2136 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2137 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2138 } 2139 } 2140 2141 // Update successor info 2142 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2143 // TrueBB and FalseBB are always different unless the incoming IR is 2144 // degenerate. This only happens when running llc on weird IR. 2145 if (CB.TrueBB != CB.FalseBB) 2146 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2147 SwitchBB->normalizeSuccProbs(); 2148 2149 // If the lhs block is the next block, invert the condition so that we can 2150 // fall through to the lhs instead of the rhs block. 2151 if (CB.TrueBB == NextBlock(SwitchBB)) { 2152 std::swap(CB.TrueBB, CB.FalseBB); 2153 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2154 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2155 } 2156 2157 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2158 MVT::Other, getControlRoot(), Cond, 2159 DAG.getBasicBlock(CB.TrueBB)); 2160 2161 // Insert the false branch. Do this even if it's a fall through branch, 2162 // this makes it easier to do DAG optimizations which require inverting 2163 // the branch condition. 2164 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2165 DAG.getBasicBlock(CB.FalseBB)); 2166 2167 DAG.setRoot(BrCond); 2168 } 2169 2170 /// visitJumpTable - Emit JumpTable node in the current MBB 2171 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2172 // Emit the code for the jump table 2173 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2174 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2175 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2176 JT.Reg, PTy); 2177 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2178 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2179 MVT::Other, Index.getValue(1), 2180 Table, Index); 2181 DAG.setRoot(BrJumpTable); 2182 } 2183 2184 /// visitJumpTableHeader - This function emits necessary code to produce index 2185 /// in the JumpTable from switch case. 2186 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2187 JumpTableHeader &JTH, 2188 MachineBasicBlock *SwitchBB) { 2189 SDLoc dl = getCurSDLoc(); 2190 2191 // Subtract the lowest switch case value from the value being switched on and 2192 // conditional branch to default mbb if the result is greater than the 2193 // difference between smallest and largest cases. 2194 SDValue SwitchOp = getValue(JTH.SValue); 2195 EVT VT = SwitchOp.getValueType(); 2196 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2197 DAG.getConstant(JTH.First, dl, VT)); 2198 2199 // The SDNode we just created, which holds the value being switched on minus 2200 // the smallest case value, needs to be copied to a virtual register so it 2201 // can be used as an index into the jump table in a subsequent basic block. 2202 // This value may be smaller or larger than the target's pointer type, and 2203 // therefore require extension or truncating. 2204 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2205 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2206 2207 unsigned JumpTableReg = 2208 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2209 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2210 JumpTableReg, SwitchOp); 2211 JT.Reg = JumpTableReg; 2212 2213 // Emit the range check for the jump table, and branch to the default block 2214 // for the switch statement if the value being switched on exceeds the largest 2215 // case in the switch. 2216 SDValue CMP = DAG.getSetCC( 2217 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2218 Sub.getValueType()), 2219 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2220 2221 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2222 MVT::Other, CopyTo, CMP, 2223 DAG.getBasicBlock(JT.Default)); 2224 2225 // Avoid emitting unnecessary branches to the next block. 2226 if (JT.MBB != NextBlock(SwitchBB)) 2227 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2228 DAG.getBasicBlock(JT.MBB)); 2229 2230 DAG.setRoot(BrCond); 2231 } 2232 2233 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2234 /// variable if there exists one. 2235 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2236 SDValue &Chain) { 2237 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2238 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2239 MachineFunction &MF = DAG.getMachineFunction(); 2240 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2241 MachineSDNode *Node = 2242 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2243 if (Global) { 2244 MachinePointerInfo MPInfo(Global); 2245 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2246 MachineMemOperand::MODereferenceable; 2247 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2248 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2249 DAG.setNodeMemRefs(Node, {MemRef}); 2250 } 2251 return SDValue(Node, 0); 2252 } 2253 2254 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2255 /// tail spliced into a stack protector check success bb. 2256 /// 2257 /// For a high level explanation of how this fits into the stack protector 2258 /// generation see the comment on the declaration of class 2259 /// StackProtectorDescriptor. 2260 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2261 MachineBasicBlock *ParentBB) { 2262 2263 // First create the loads to the guard/stack slot for the comparison. 2264 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2265 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2266 2267 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2268 int FI = MFI.getStackProtectorIndex(); 2269 2270 SDValue Guard; 2271 SDLoc dl = getCurSDLoc(); 2272 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2273 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2274 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2275 2276 // Generate code to load the content of the guard slot. 2277 SDValue GuardVal = DAG.getLoad( 2278 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2279 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2280 MachineMemOperand::MOVolatile); 2281 2282 if (TLI.useStackGuardXorFP()) 2283 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2284 2285 // Retrieve guard check function, nullptr if instrumentation is inlined. 2286 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2287 // The target provides a guard check function to validate the guard value. 2288 // Generate a call to that function with the content of the guard slot as 2289 // argument. 2290 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2291 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2292 2293 TargetLowering::ArgListTy Args; 2294 TargetLowering::ArgListEntry Entry; 2295 Entry.Node = GuardVal; 2296 Entry.Ty = FnTy->getParamType(0); 2297 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2298 Entry.IsInReg = true; 2299 Args.push_back(Entry); 2300 2301 TargetLowering::CallLoweringInfo CLI(DAG); 2302 CLI.setDebugLoc(getCurSDLoc()) 2303 .setChain(DAG.getEntryNode()) 2304 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2305 getValue(GuardCheckFn), std::move(Args)); 2306 2307 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2308 DAG.setRoot(Result.second); 2309 return; 2310 } 2311 2312 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2313 // Otherwise, emit a volatile load to retrieve the stack guard value. 2314 SDValue Chain = DAG.getEntryNode(); 2315 if (TLI.useLoadStackGuardNode()) { 2316 Guard = getLoadStackGuard(DAG, dl, Chain); 2317 } else { 2318 const Value *IRGuard = TLI.getSDagStackGuard(M); 2319 SDValue GuardPtr = getValue(IRGuard); 2320 2321 Guard = 2322 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2323 Align, MachineMemOperand::MOVolatile); 2324 } 2325 2326 // Perform the comparison via a subtract/getsetcc. 2327 EVT VT = Guard.getValueType(); 2328 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2329 2330 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2331 *DAG.getContext(), 2332 Sub.getValueType()), 2333 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2334 2335 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2336 // branch to failure MBB. 2337 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2338 MVT::Other, GuardVal.getOperand(0), 2339 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2340 // Otherwise branch to success MBB. 2341 SDValue Br = DAG.getNode(ISD::BR, dl, 2342 MVT::Other, BrCond, 2343 DAG.getBasicBlock(SPD.getSuccessMBB())); 2344 2345 DAG.setRoot(Br); 2346 } 2347 2348 /// Codegen the failure basic block for a stack protector check. 2349 /// 2350 /// A failure stack protector machine basic block consists simply of a call to 2351 /// __stack_chk_fail(). 2352 /// 2353 /// For a high level explanation of how this fits into the stack protector 2354 /// generation see the comment on the declaration of class 2355 /// StackProtectorDescriptor. 2356 void 2357 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2359 SDValue Chain = 2360 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2361 None, false, getCurSDLoc(), false, false).second; 2362 DAG.setRoot(Chain); 2363 } 2364 2365 /// visitBitTestHeader - This function emits necessary code to produce value 2366 /// suitable for "bit tests" 2367 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2368 MachineBasicBlock *SwitchBB) { 2369 SDLoc dl = getCurSDLoc(); 2370 2371 // Subtract the minimum value 2372 SDValue SwitchOp = getValue(B.SValue); 2373 EVT VT = SwitchOp.getValueType(); 2374 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2375 DAG.getConstant(B.First, dl, VT)); 2376 2377 // Check range 2378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2379 SDValue RangeCmp = DAG.getSetCC( 2380 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2381 Sub.getValueType()), 2382 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2383 2384 // Determine the type of the test operands. 2385 bool UsePtrType = false; 2386 if (!TLI.isTypeLegal(VT)) 2387 UsePtrType = true; 2388 else { 2389 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2390 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2391 // Switch table case range are encoded into series of masks. 2392 // Just use pointer type, it's guaranteed to fit. 2393 UsePtrType = true; 2394 break; 2395 } 2396 } 2397 if (UsePtrType) { 2398 VT = TLI.getPointerTy(DAG.getDataLayout()); 2399 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2400 } 2401 2402 B.RegVT = VT.getSimpleVT(); 2403 B.Reg = FuncInfo.CreateReg(B.RegVT); 2404 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2405 2406 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2407 2408 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2409 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2410 SwitchBB->normalizeSuccProbs(); 2411 2412 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2413 MVT::Other, CopyTo, RangeCmp, 2414 DAG.getBasicBlock(B.Default)); 2415 2416 // Avoid emitting unnecessary branches to the next block. 2417 if (MBB != NextBlock(SwitchBB)) 2418 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2419 DAG.getBasicBlock(MBB)); 2420 2421 DAG.setRoot(BrRange); 2422 } 2423 2424 /// visitBitTestCase - this function produces one "bit test" 2425 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2426 MachineBasicBlock* NextMBB, 2427 BranchProbability BranchProbToNext, 2428 unsigned Reg, 2429 BitTestCase &B, 2430 MachineBasicBlock *SwitchBB) { 2431 SDLoc dl = getCurSDLoc(); 2432 MVT VT = BB.RegVT; 2433 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2434 SDValue Cmp; 2435 unsigned PopCount = countPopulation(B.Mask); 2436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2437 if (PopCount == 1) { 2438 // Testing for a single bit; just compare the shift count with what it 2439 // would need to be to shift a 1 bit in that position. 2440 Cmp = DAG.getSetCC( 2441 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2442 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2443 ISD::SETEQ); 2444 } else if (PopCount == BB.Range) { 2445 // There is only one zero bit in the range, test for it directly. 2446 Cmp = DAG.getSetCC( 2447 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2448 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2449 ISD::SETNE); 2450 } else { 2451 // Make desired shift 2452 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2453 DAG.getConstant(1, dl, VT), ShiftOp); 2454 2455 // Emit bit tests and jumps 2456 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2457 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2458 Cmp = DAG.getSetCC( 2459 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2460 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2461 } 2462 2463 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2464 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2465 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2466 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2467 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2468 // one as they are relative probabilities (and thus work more like weights), 2469 // and hence we need to normalize them to let the sum of them become one. 2470 SwitchBB->normalizeSuccProbs(); 2471 2472 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2473 MVT::Other, getControlRoot(), 2474 Cmp, DAG.getBasicBlock(B.TargetBB)); 2475 2476 // Avoid emitting unnecessary branches to the next block. 2477 if (NextMBB != NextBlock(SwitchBB)) 2478 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2479 DAG.getBasicBlock(NextMBB)); 2480 2481 DAG.setRoot(BrAnd); 2482 } 2483 2484 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2485 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2486 2487 // Retrieve successors. Look through artificial IR level blocks like 2488 // catchswitch for successors. 2489 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2490 const BasicBlock *EHPadBB = I.getSuccessor(1); 2491 2492 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2493 // have to do anything here to lower funclet bundles. 2494 assert(!I.hasOperandBundlesOtherThan( 2495 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2496 "Cannot lower invokes with arbitrary operand bundles yet!"); 2497 2498 const Value *Callee(I.getCalledValue()); 2499 const Function *Fn = dyn_cast<Function>(Callee); 2500 if (isa<InlineAsm>(Callee)) 2501 visitInlineAsm(&I); 2502 else if (Fn && Fn->isIntrinsic()) { 2503 switch (Fn->getIntrinsicID()) { 2504 default: 2505 llvm_unreachable("Cannot invoke this intrinsic"); 2506 case Intrinsic::donothing: 2507 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2508 break; 2509 case Intrinsic::experimental_patchpoint_void: 2510 case Intrinsic::experimental_patchpoint_i64: 2511 visitPatchpoint(&I, EHPadBB); 2512 break; 2513 case Intrinsic::experimental_gc_statepoint: 2514 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2515 break; 2516 } 2517 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2518 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2519 // Eventually we will support lowering the @llvm.experimental.deoptimize 2520 // intrinsic, and right now there are no plans to support other intrinsics 2521 // with deopt state. 2522 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2523 } else { 2524 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2525 } 2526 2527 // If the value of the invoke is used outside of its defining block, make it 2528 // available as a virtual register. 2529 // We already took care of the exported value for the statepoint instruction 2530 // during call to the LowerStatepoint. 2531 if (!isStatepoint(I)) { 2532 CopyToExportRegsIfNeeded(&I); 2533 } 2534 2535 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2536 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2537 BranchProbability EHPadBBProb = 2538 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2539 : BranchProbability::getZero(); 2540 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2541 2542 // Update successor info. 2543 addSuccessorWithProb(InvokeMBB, Return); 2544 for (auto &UnwindDest : UnwindDests) { 2545 UnwindDest.first->setIsEHPad(); 2546 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2547 } 2548 InvokeMBB->normalizeSuccProbs(); 2549 2550 // Drop into normal successor. 2551 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2552 MVT::Other, getControlRoot(), 2553 DAG.getBasicBlock(Return))); 2554 } 2555 2556 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2557 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2558 } 2559 2560 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2561 assert(FuncInfo.MBB->isEHPad() && 2562 "Call to landingpad not in landing pad!"); 2563 2564 // If there aren't registers to copy the values into (e.g., during SjLj 2565 // exceptions), then don't bother to create these DAG nodes. 2566 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2567 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2568 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2569 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2570 return; 2571 2572 // If landingpad's return type is token type, we don't create DAG nodes 2573 // for its exception pointer and selector value. The extraction of exception 2574 // pointer or selector value from token type landingpads is not currently 2575 // supported. 2576 if (LP.getType()->isTokenTy()) 2577 return; 2578 2579 SmallVector<EVT, 2> ValueVTs; 2580 SDLoc dl = getCurSDLoc(); 2581 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2582 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2583 2584 // Get the two live-in registers as SDValues. The physregs have already been 2585 // copied into virtual registers. 2586 SDValue Ops[2]; 2587 if (FuncInfo.ExceptionPointerVirtReg) { 2588 Ops[0] = DAG.getZExtOrTrunc( 2589 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2590 FuncInfo.ExceptionPointerVirtReg, 2591 TLI.getPointerTy(DAG.getDataLayout())), 2592 dl, ValueVTs[0]); 2593 } else { 2594 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2595 } 2596 Ops[1] = DAG.getZExtOrTrunc( 2597 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2598 FuncInfo.ExceptionSelectorVirtReg, 2599 TLI.getPointerTy(DAG.getDataLayout())), 2600 dl, ValueVTs[1]); 2601 2602 // Merge into one. 2603 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2604 DAG.getVTList(ValueVTs), Ops); 2605 setValue(&LP, Res); 2606 } 2607 2608 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2609 #ifndef NDEBUG 2610 for (const CaseCluster &CC : Clusters) 2611 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2612 #endif 2613 2614 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2615 return a.Low->getValue().slt(b.Low->getValue()); 2616 }); 2617 2618 // Merge adjacent clusters with the same destination. 2619 const unsigned N = Clusters.size(); 2620 unsigned DstIndex = 0; 2621 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2622 CaseCluster &CC = Clusters[SrcIndex]; 2623 const ConstantInt *CaseVal = CC.Low; 2624 MachineBasicBlock *Succ = CC.MBB; 2625 2626 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2627 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2628 // If this case has the same successor and is a neighbour, merge it into 2629 // the previous cluster. 2630 Clusters[DstIndex - 1].High = CaseVal; 2631 Clusters[DstIndex - 1].Prob += CC.Prob; 2632 } else { 2633 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2634 sizeof(Clusters[SrcIndex])); 2635 } 2636 } 2637 Clusters.resize(DstIndex); 2638 } 2639 2640 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2641 MachineBasicBlock *Last) { 2642 // Update JTCases. 2643 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2644 if (JTCases[i].first.HeaderBB == First) 2645 JTCases[i].first.HeaderBB = Last; 2646 2647 // Update BitTestCases. 2648 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2649 if (BitTestCases[i].Parent == First) 2650 BitTestCases[i].Parent = Last; 2651 } 2652 2653 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2654 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2655 2656 // Update machine-CFG edges with unique successors. 2657 SmallSet<BasicBlock*, 32> Done; 2658 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2659 BasicBlock *BB = I.getSuccessor(i); 2660 bool Inserted = Done.insert(BB).second; 2661 if (!Inserted) 2662 continue; 2663 2664 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2665 addSuccessorWithProb(IndirectBrMBB, Succ); 2666 } 2667 IndirectBrMBB->normalizeSuccProbs(); 2668 2669 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2670 MVT::Other, getControlRoot(), 2671 getValue(I.getAddress()))); 2672 } 2673 2674 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2675 if (!DAG.getTarget().Options.TrapUnreachable) 2676 return; 2677 2678 // We may be able to ignore unreachable behind a noreturn call. 2679 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2680 const BasicBlock &BB = *I.getParent(); 2681 if (&I != &BB.front()) { 2682 BasicBlock::const_iterator PredI = 2683 std::prev(BasicBlock::const_iterator(&I)); 2684 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2685 if (Call->doesNotReturn()) 2686 return; 2687 } 2688 } 2689 } 2690 2691 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2692 } 2693 2694 void SelectionDAGBuilder::visitFSub(const User &I) { 2695 // -0.0 - X --> fneg 2696 Type *Ty = I.getType(); 2697 if (isa<Constant>(I.getOperand(0)) && 2698 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2699 SDValue Op2 = getValue(I.getOperand(1)); 2700 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2701 Op2.getValueType(), Op2)); 2702 return; 2703 } 2704 2705 visitBinary(I, ISD::FSUB); 2706 } 2707 2708 /// Checks if the given instruction performs a vector reduction, in which case 2709 /// we have the freedom to alter the elements in the result as long as the 2710 /// reduction of them stays unchanged. 2711 static bool isVectorReductionOp(const User *I) { 2712 const Instruction *Inst = dyn_cast<Instruction>(I); 2713 if (!Inst || !Inst->getType()->isVectorTy()) 2714 return false; 2715 2716 auto OpCode = Inst->getOpcode(); 2717 switch (OpCode) { 2718 case Instruction::Add: 2719 case Instruction::Mul: 2720 case Instruction::And: 2721 case Instruction::Or: 2722 case Instruction::Xor: 2723 break; 2724 case Instruction::FAdd: 2725 case Instruction::FMul: 2726 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2727 if (FPOp->getFastMathFlags().isFast()) 2728 break; 2729 LLVM_FALLTHROUGH; 2730 default: 2731 return false; 2732 } 2733 2734 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2735 // Ensure the reduction size is a power of 2. 2736 if (!isPowerOf2_32(ElemNum)) 2737 return false; 2738 2739 unsigned ElemNumToReduce = ElemNum; 2740 2741 // Do DFS search on the def-use chain from the given instruction. We only 2742 // allow four kinds of operations during the search until we reach the 2743 // instruction that extracts the first element from the vector: 2744 // 2745 // 1. The reduction operation of the same opcode as the given instruction. 2746 // 2747 // 2. PHI node. 2748 // 2749 // 3. ShuffleVector instruction together with a reduction operation that 2750 // does a partial reduction. 2751 // 2752 // 4. ExtractElement that extracts the first element from the vector, and we 2753 // stop searching the def-use chain here. 2754 // 2755 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2756 // from 1-3 to the stack to continue the DFS. The given instruction is not 2757 // a reduction operation if we meet any other instructions other than those 2758 // listed above. 2759 2760 SmallVector<const User *, 16> UsersToVisit{Inst}; 2761 SmallPtrSet<const User *, 16> Visited; 2762 bool ReduxExtracted = false; 2763 2764 while (!UsersToVisit.empty()) { 2765 auto User = UsersToVisit.back(); 2766 UsersToVisit.pop_back(); 2767 if (!Visited.insert(User).second) 2768 continue; 2769 2770 for (const auto &U : User->users()) { 2771 auto Inst = dyn_cast<Instruction>(U); 2772 if (!Inst) 2773 return false; 2774 2775 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2776 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2777 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2778 return false; 2779 UsersToVisit.push_back(U); 2780 } else if (const ShuffleVectorInst *ShufInst = 2781 dyn_cast<ShuffleVectorInst>(U)) { 2782 // Detect the following pattern: A ShuffleVector instruction together 2783 // with a reduction that do partial reduction on the first and second 2784 // ElemNumToReduce / 2 elements, and store the result in 2785 // ElemNumToReduce / 2 elements in another vector. 2786 2787 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2788 if (ResultElements < ElemNum) 2789 return false; 2790 2791 if (ElemNumToReduce == 1) 2792 return false; 2793 if (!isa<UndefValue>(U->getOperand(1))) 2794 return false; 2795 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2796 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2797 return false; 2798 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2799 if (ShufInst->getMaskValue(i) != -1) 2800 return false; 2801 2802 // There is only one user of this ShuffleVector instruction, which 2803 // must be a reduction operation. 2804 if (!U->hasOneUse()) 2805 return false; 2806 2807 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2808 if (!U2 || U2->getOpcode() != OpCode) 2809 return false; 2810 2811 // Check operands of the reduction operation. 2812 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2813 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2814 UsersToVisit.push_back(U2); 2815 ElemNumToReduce /= 2; 2816 } else 2817 return false; 2818 } else if (isa<ExtractElementInst>(U)) { 2819 // At this moment we should have reduced all elements in the vector. 2820 if (ElemNumToReduce != 1) 2821 return false; 2822 2823 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2824 if (!Val || !Val->isZero()) 2825 return false; 2826 2827 ReduxExtracted = true; 2828 } else 2829 return false; 2830 } 2831 } 2832 return ReduxExtracted; 2833 } 2834 2835 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2836 SDNodeFlags Flags; 2837 2838 SDValue Op = getValue(I.getOperand(0)); 2839 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2840 Op, Flags); 2841 setValue(&I, UnNodeValue); 2842 } 2843 2844 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2845 SDNodeFlags Flags; 2846 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2847 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2848 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2849 } 2850 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2851 Flags.setExact(ExactOp->isExact()); 2852 } 2853 if (isVectorReductionOp(&I)) { 2854 Flags.setVectorReduction(true); 2855 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2856 } 2857 2858 SDValue Op1 = getValue(I.getOperand(0)); 2859 SDValue Op2 = getValue(I.getOperand(1)); 2860 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2861 Op1, Op2, Flags); 2862 setValue(&I, BinNodeValue); 2863 } 2864 2865 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2866 SDValue Op1 = getValue(I.getOperand(0)); 2867 SDValue Op2 = getValue(I.getOperand(1)); 2868 2869 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2870 Op1.getValueType(), DAG.getDataLayout()); 2871 2872 // Coerce the shift amount to the right type if we can. 2873 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2874 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2875 unsigned Op2Size = Op2.getValueSizeInBits(); 2876 SDLoc DL = getCurSDLoc(); 2877 2878 // If the operand is smaller than the shift count type, promote it. 2879 if (ShiftSize > Op2Size) 2880 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2881 2882 // If the operand is larger than the shift count type but the shift 2883 // count type has enough bits to represent any shift value, truncate 2884 // it now. This is a common case and it exposes the truncate to 2885 // optimization early. 2886 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2887 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2888 // Otherwise we'll need to temporarily settle for some other convenient 2889 // type. Type legalization will make adjustments once the shiftee is split. 2890 else 2891 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2892 } 2893 2894 bool nuw = false; 2895 bool nsw = false; 2896 bool exact = false; 2897 2898 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2899 2900 if (const OverflowingBinaryOperator *OFBinOp = 2901 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2902 nuw = OFBinOp->hasNoUnsignedWrap(); 2903 nsw = OFBinOp->hasNoSignedWrap(); 2904 } 2905 if (const PossiblyExactOperator *ExactOp = 2906 dyn_cast<const PossiblyExactOperator>(&I)) 2907 exact = ExactOp->isExact(); 2908 } 2909 SDNodeFlags Flags; 2910 Flags.setExact(exact); 2911 Flags.setNoSignedWrap(nsw); 2912 Flags.setNoUnsignedWrap(nuw); 2913 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2914 Flags); 2915 setValue(&I, Res); 2916 } 2917 2918 void SelectionDAGBuilder::visitSDiv(const User &I) { 2919 SDValue Op1 = getValue(I.getOperand(0)); 2920 SDValue Op2 = getValue(I.getOperand(1)); 2921 2922 SDNodeFlags Flags; 2923 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2924 cast<PossiblyExactOperator>(&I)->isExact()); 2925 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2926 Op2, Flags)); 2927 } 2928 2929 void SelectionDAGBuilder::visitICmp(const User &I) { 2930 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2931 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2932 predicate = IC->getPredicate(); 2933 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2934 predicate = ICmpInst::Predicate(IC->getPredicate()); 2935 SDValue Op1 = getValue(I.getOperand(0)); 2936 SDValue Op2 = getValue(I.getOperand(1)); 2937 ISD::CondCode Opcode = getICmpCondCode(predicate); 2938 2939 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2940 I.getType()); 2941 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2942 } 2943 2944 void SelectionDAGBuilder::visitFCmp(const User &I) { 2945 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2946 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2947 predicate = FC->getPredicate(); 2948 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2949 predicate = FCmpInst::Predicate(FC->getPredicate()); 2950 SDValue Op1 = getValue(I.getOperand(0)); 2951 SDValue Op2 = getValue(I.getOperand(1)); 2952 2953 ISD::CondCode Condition = getFCmpCondCode(predicate); 2954 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2955 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2956 Condition = getFCmpCodeWithoutNaN(Condition); 2957 2958 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2959 I.getType()); 2960 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2961 } 2962 2963 // Check if the condition of the select has one use or two users that are both 2964 // selects with the same condition. 2965 static bool hasOnlySelectUsers(const Value *Cond) { 2966 return llvm::all_of(Cond->users(), [](const Value *V) { 2967 return isa<SelectInst>(V); 2968 }); 2969 } 2970 2971 void SelectionDAGBuilder::visitSelect(const User &I) { 2972 SmallVector<EVT, 4> ValueVTs; 2973 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2974 ValueVTs); 2975 unsigned NumValues = ValueVTs.size(); 2976 if (NumValues == 0) return; 2977 2978 SmallVector<SDValue, 4> Values(NumValues); 2979 SDValue Cond = getValue(I.getOperand(0)); 2980 SDValue LHSVal = getValue(I.getOperand(1)); 2981 SDValue RHSVal = getValue(I.getOperand(2)); 2982 auto BaseOps = {Cond}; 2983 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2984 ISD::VSELECT : ISD::SELECT; 2985 2986 // Min/max matching is only viable if all output VTs are the same. 2987 if (is_splat(ValueVTs)) { 2988 EVT VT = ValueVTs[0]; 2989 LLVMContext &Ctx = *DAG.getContext(); 2990 auto &TLI = DAG.getTargetLoweringInfo(); 2991 2992 // We care about the legality of the operation after it has been type 2993 // legalized. 2994 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2995 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2996 VT = TLI.getTypeToTransformTo(Ctx, VT); 2997 2998 // If the vselect is legal, assume we want to leave this as a vector setcc + 2999 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3000 // min/max is legal on the scalar type. 3001 bool UseScalarMinMax = VT.isVector() && 3002 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3003 3004 Value *LHS, *RHS; 3005 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3006 ISD::NodeType Opc = ISD::DELETED_NODE; 3007 switch (SPR.Flavor) { 3008 case SPF_UMAX: Opc = ISD::UMAX; break; 3009 case SPF_UMIN: Opc = ISD::UMIN; break; 3010 case SPF_SMAX: Opc = ISD::SMAX; break; 3011 case SPF_SMIN: Opc = ISD::SMIN; break; 3012 case SPF_FMINNUM: 3013 switch (SPR.NaNBehavior) { 3014 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3015 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3016 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3017 case SPNB_RETURNS_ANY: { 3018 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3019 Opc = ISD::FMINNUM; 3020 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3021 Opc = ISD::FMINIMUM; 3022 else if (UseScalarMinMax) 3023 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3024 ISD::FMINNUM : ISD::FMINIMUM; 3025 break; 3026 } 3027 } 3028 break; 3029 case SPF_FMAXNUM: 3030 switch (SPR.NaNBehavior) { 3031 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3032 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3033 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3034 case SPNB_RETURNS_ANY: 3035 3036 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3037 Opc = ISD::FMAXNUM; 3038 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3039 Opc = ISD::FMAXIMUM; 3040 else if (UseScalarMinMax) 3041 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3042 ISD::FMAXNUM : ISD::FMAXIMUM; 3043 break; 3044 } 3045 break; 3046 default: break; 3047 } 3048 3049 if (Opc != ISD::DELETED_NODE && 3050 (TLI.isOperationLegalOrCustom(Opc, VT) || 3051 (UseScalarMinMax && 3052 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3053 // If the underlying comparison instruction is used by any other 3054 // instruction, the consumed instructions won't be destroyed, so it is 3055 // not profitable to convert to a min/max. 3056 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3057 OpCode = Opc; 3058 LHSVal = getValue(LHS); 3059 RHSVal = getValue(RHS); 3060 BaseOps = {}; 3061 } 3062 } 3063 3064 for (unsigned i = 0; i != NumValues; ++i) { 3065 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3066 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3067 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3068 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3069 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3070 Ops); 3071 } 3072 3073 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3074 DAG.getVTList(ValueVTs), Values)); 3075 } 3076 3077 void SelectionDAGBuilder::visitTrunc(const User &I) { 3078 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3079 SDValue N = getValue(I.getOperand(0)); 3080 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3081 I.getType()); 3082 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3083 } 3084 3085 void SelectionDAGBuilder::visitZExt(const User &I) { 3086 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3087 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3088 SDValue N = getValue(I.getOperand(0)); 3089 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3090 I.getType()); 3091 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3092 } 3093 3094 void SelectionDAGBuilder::visitSExt(const User &I) { 3095 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3096 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3097 SDValue N = getValue(I.getOperand(0)); 3098 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3099 I.getType()); 3100 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3101 } 3102 3103 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3104 // FPTrunc is never a no-op cast, no need to check 3105 SDValue N = getValue(I.getOperand(0)); 3106 SDLoc dl = getCurSDLoc(); 3107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3108 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3109 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3110 DAG.getTargetConstant( 3111 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3112 } 3113 3114 void SelectionDAGBuilder::visitFPExt(const User &I) { 3115 // FPExt 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::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3120 } 3121 3122 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3123 // FPToUI is never a no-op cast, no need to check 3124 SDValue N = getValue(I.getOperand(0)); 3125 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3126 I.getType()); 3127 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3128 } 3129 3130 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3131 // FPToSI is never a no-op cast, no need to check 3132 SDValue N = getValue(I.getOperand(0)); 3133 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3134 I.getType()); 3135 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3136 } 3137 3138 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3139 // UIToFP is never a no-op cast, no need to check 3140 SDValue N = getValue(I.getOperand(0)); 3141 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3142 I.getType()); 3143 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3144 } 3145 3146 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3147 // SIToFP is never a no-op cast, no need to check 3148 SDValue N = getValue(I.getOperand(0)); 3149 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3150 I.getType()); 3151 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3152 } 3153 3154 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3155 // What to do depends on the size of the integer and the size of the pointer. 3156 // We can either truncate, zero extend, or no-op, accordingly. 3157 SDValue N = getValue(I.getOperand(0)); 3158 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3159 I.getType()); 3160 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3161 } 3162 3163 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3164 // What to do depends on the size of the integer and the size of the pointer. 3165 // We can either truncate, zero extend, or no-op, accordingly. 3166 SDValue N = getValue(I.getOperand(0)); 3167 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3168 I.getType()); 3169 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3170 } 3171 3172 void SelectionDAGBuilder::visitBitCast(const User &I) { 3173 SDValue N = getValue(I.getOperand(0)); 3174 SDLoc dl = getCurSDLoc(); 3175 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3176 I.getType()); 3177 3178 // BitCast assures us that source and destination are the same size so this is 3179 // either a BITCAST or a no-op. 3180 if (DestVT != N.getValueType()) 3181 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3182 DestVT, N)); // convert types. 3183 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3184 // might fold any kind of constant expression to an integer constant and that 3185 // is not what we are looking for. Only recognize a bitcast of a genuine 3186 // constant integer as an opaque constant. 3187 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3188 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3189 /*isOpaque*/true)); 3190 else 3191 setValue(&I, N); // noop cast. 3192 } 3193 3194 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3195 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3196 const Value *SV = I.getOperand(0); 3197 SDValue N = getValue(SV); 3198 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3199 3200 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3201 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3202 3203 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3204 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3205 3206 setValue(&I, N); 3207 } 3208 3209 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3211 SDValue InVec = getValue(I.getOperand(0)); 3212 SDValue InVal = getValue(I.getOperand(1)); 3213 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3214 TLI.getVectorIdxTy(DAG.getDataLayout())); 3215 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3216 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3217 InVec, InVal, InIdx)); 3218 } 3219 3220 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3221 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3222 SDValue InVec = getValue(I.getOperand(0)); 3223 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3224 TLI.getVectorIdxTy(DAG.getDataLayout())); 3225 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3226 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3227 InVec, InIdx)); 3228 } 3229 3230 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3231 SDValue Src1 = getValue(I.getOperand(0)); 3232 SDValue Src2 = getValue(I.getOperand(1)); 3233 SDLoc DL = getCurSDLoc(); 3234 3235 SmallVector<int, 8> Mask; 3236 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3237 unsigned MaskNumElts = Mask.size(); 3238 3239 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3240 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3241 EVT SrcVT = Src1.getValueType(); 3242 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3243 3244 if (SrcNumElts == MaskNumElts) { 3245 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3246 return; 3247 } 3248 3249 // Normalize the shuffle vector since mask and vector length don't match. 3250 if (SrcNumElts < MaskNumElts) { 3251 // Mask is longer than the source vectors. We can use concatenate vector to 3252 // make the mask and vectors lengths match. 3253 3254 if (MaskNumElts % SrcNumElts == 0) { 3255 // Mask length is a multiple of the source vector length. 3256 // Check if the shuffle is some kind of concatenation of the input 3257 // vectors. 3258 unsigned NumConcat = MaskNumElts / SrcNumElts; 3259 bool IsConcat = true; 3260 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3261 for (unsigned i = 0; i != MaskNumElts; ++i) { 3262 int Idx = Mask[i]; 3263 if (Idx < 0) 3264 continue; 3265 // Ensure the indices in each SrcVT sized piece are sequential and that 3266 // the same source is used for the whole piece. 3267 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3268 (ConcatSrcs[i / SrcNumElts] >= 0 && 3269 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3270 IsConcat = false; 3271 break; 3272 } 3273 // Remember which source this index came from. 3274 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3275 } 3276 3277 // The shuffle is concatenating multiple vectors together. Just emit 3278 // a CONCAT_VECTORS operation. 3279 if (IsConcat) { 3280 SmallVector<SDValue, 8> ConcatOps; 3281 for (auto Src : ConcatSrcs) { 3282 if (Src < 0) 3283 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3284 else if (Src == 0) 3285 ConcatOps.push_back(Src1); 3286 else 3287 ConcatOps.push_back(Src2); 3288 } 3289 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3290 return; 3291 } 3292 } 3293 3294 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3295 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3296 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3297 PaddedMaskNumElts); 3298 3299 // Pad both vectors with undefs to make them the same length as the mask. 3300 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3301 3302 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3303 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3304 MOps1[0] = Src1; 3305 MOps2[0] = Src2; 3306 3307 Src1 = Src1.isUndef() 3308 ? DAG.getUNDEF(PaddedVT) 3309 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3310 Src2 = Src2.isUndef() 3311 ? DAG.getUNDEF(PaddedVT) 3312 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3313 3314 // Readjust mask for new input vector length. 3315 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3316 for (unsigned i = 0; i != MaskNumElts; ++i) { 3317 int Idx = Mask[i]; 3318 if (Idx >= (int)SrcNumElts) 3319 Idx -= SrcNumElts - PaddedMaskNumElts; 3320 MappedOps[i] = Idx; 3321 } 3322 3323 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3324 3325 // If the concatenated vector was padded, extract a subvector with the 3326 // correct number of elements. 3327 if (MaskNumElts != PaddedMaskNumElts) 3328 Result = DAG.getNode( 3329 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3330 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3331 3332 setValue(&I, Result); 3333 return; 3334 } 3335 3336 if (SrcNumElts > MaskNumElts) { 3337 // Analyze the access pattern of the vector to see if we can extract 3338 // two subvectors and do the shuffle. 3339 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3340 bool CanExtract = true; 3341 for (int Idx : Mask) { 3342 unsigned Input = 0; 3343 if (Idx < 0) 3344 continue; 3345 3346 if (Idx >= (int)SrcNumElts) { 3347 Input = 1; 3348 Idx -= SrcNumElts; 3349 } 3350 3351 // If all the indices come from the same MaskNumElts sized portion of 3352 // the sources we can use extract. Also make sure the extract wouldn't 3353 // extract past the end of the source. 3354 int NewStartIdx = alignDown(Idx, MaskNumElts); 3355 if (NewStartIdx + MaskNumElts > SrcNumElts || 3356 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3357 CanExtract = false; 3358 // Make sure we always update StartIdx as we use it to track if all 3359 // elements are undef. 3360 StartIdx[Input] = NewStartIdx; 3361 } 3362 3363 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3364 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3365 return; 3366 } 3367 if (CanExtract) { 3368 // Extract appropriate subvector and generate a vector shuffle 3369 for (unsigned Input = 0; Input < 2; ++Input) { 3370 SDValue &Src = Input == 0 ? Src1 : Src2; 3371 if (StartIdx[Input] < 0) 3372 Src = DAG.getUNDEF(VT); 3373 else { 3374 Src = DAG.getNode( 3375 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3376 DAG.getConstant(StartIdx[Input], DL, 3377 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3378 } 3379 } 3380 3381 // Calculate new mask. 3382 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3383 for (int &Idx : MappedOps) { 3384 if (Idx >= (int)SrcNumElts) 3385 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3386 else if (Idx >= 0) 3387 Idx -= StartIdx[0]; 3388 } 3389 3390 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3391 return; 3392 } 3393 } 3394 3395 // We can't use either concat vectors or extract subvectors so fall back to 3396 // replacing the shuffle with extract and build vector. 3397 // to insert and build vector. 3398 EVT EltVT = VT.getVectorElementType(); 3399 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3400 SmallVector<SDValue,8> Ops; 3401 for (int Idx : Mask) { 3402 SDValue Res; 3403 3404 if (Idx < 0) { 3405 Res = DAG.getUNDEF(EltVT); 3406 } else { 3407 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3408 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3409 3410 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3411 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3412 } 3413 3414 Ops.push_back(Res); 3415 } 3416 3417 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3418 } 3419 3420 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3421 ArrayRef<unsigned> Indices; 3422 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3423 Indices = IV->getIndices(); 3424 else 3425 Indices = cast<ConstantExpr>(&I)->getIndices(); 3426 3427 const Value *Op0 = I.getOperand(0); 3428 const Value *Op1 = I.getOperand(1); 3429 Type *AggTy = I.getType(); 3430 Type *ValTy = Op1->getType(); 3431 bool IntoUndef = isa<UndefValue>(Op0); 3432 bool FromUndef = isa<UndefValue>(Op1); 3433 3434 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3435 3436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3437 SmallVector<EVT, 4> AggValueVTs; 3438 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3439 SmallVector<EVT, 4> ValValueVTs; 3440 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3441 3442 unsigned NumAggValues = AggValueVTs.size(); 3443 unsigned NumValValues = ValValueVTs.size(); 3444 SmallVector<SDValue, 4> Values(NumAggValues); 3445 3446 // Ignore an insertvalue that produces an empty object 3447 if (!NumAggValues) { 3448 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3449 return; 3450 } 3451 3452 SDValue Agg = getValue(Op0); 3453 unsigned i = 0; 3454 // Copy the beginning value(s) from the original aggregate. 3455 for (; i != LinearIndex; ++i) 3456 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3457 SDValue(Agg.getNode(), Agg.getResNo() + i); 3458 // Copy values from the inserted value(s). 3459 if (NumValValues) { 3460 SDValue Val = getValue(Op1); 3461 for (; i != LinearIndex + NumValValues; ++i) 3462 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3463 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3464 } 3465 // Copy remaining value(s) from the original aggregate. 3466 for (; i != NumAggValues; ++i) 3467 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3468 SDValue(Agg.getNode(), Agg.getResNo() + i); 3469 3470 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3471 DAG.getVTList(AggValueVTs), Values)); 3472 } 3473 3474 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3475 ArrayRef<unsigned> Indices; 3476 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3477 Indices = EV->getIndices(); 3478 else 3479 Indices = cast<ConstantExpr>(&I)->getIndices(); 3480 3481 const Value *Op0 = I.getOperand(0); 3482 Type *AggTy = Op0->getType(); 3483 Type *ValTy = I.getType(); 3484 bool OutOfUndef = isa<UndefValue>(Op0); 3485 3486 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3487 3488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3489 SmallVector<EVT, 4> ValValueVTs; 3490 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3491 3492 unsigned NumValValues = ValValueVTs.size(); 3493 3494 // Ignore a extractvalue that produces an empty object 3495 if (!NumValValues) { 3496 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3497 return; 3498 } 3499 3500 SmallVector<SDValue, 4> Values(NumValValues); 3501 3502 SDValue Agg = getValue(Op0); 3503 // Copy out the selected value(s). 3504 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3505 Values[i - LinearIndex] = 3506 OutOfUndef ? 3507 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3508 SDValue(Agg.getNode(), Agg.getResNo() + i); 3509 3510 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3511 DAG.getVTList(ValValueVTs), Values)); 3512 } 3513 3514 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3515 Value *Op0 = I.getOperand(0); 3516 // Note that the pointer operand may be a vector of pointers. Take the scalar 3517 // element which holds a pointer. 3518 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3519 SDValue N = getValue(Op0); 3520 SDLoc dl = getCurSDLoc(); 3521 3522 // Normalize Vector GEP - all scalar operands should be converted to the 3523 // splat vector. 3524 unsigned VectorWidth = I.getType()->isVectorTy() ? 3525 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3526 3527 if (VectorWidth && !N.getValueType().isVector()) { 3528 LLVMContext &Context = *DAG.getContext(); 3529 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3530 N = DAG.getSplatBuildVector(VT, dl, N); 3531 } 3532 3533 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3534 GTI != E; ++GTI) { 3535 const Value *Idx = GTI.getOperand(); 3536 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3537 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3538 if (Field) { 3539 // N = N + Offset 3540 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3541 3542 // In an inbounds GEP with an offset that is nonnegative even when 3543 // interpreted as signed, assume there is no unsigned overflow. 3544 SDNodeFlags Flags; 3545 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3546 Flags.setNoUnsignedWrap(true); 3547 3548 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3549 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3550 } 3551 } else { 3552 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3553 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3554 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3555 3556 // If this is a scalar constant or a splat vector of constants, 3557 // handle it quickly. 3558 const auto *CI = dyn_cast<ConstantInt>(Idx); 3559 if (!CI && isa<ConstantDataVector>(Idx) && 3560 cast<ConstantDataVector>(Idx)->getSplatValue()) 3561 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3562 3563 if (CI) { 3564 if (CI->isZero()) 3565 continue; 3566 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3567 LLVMContext &Context = *DAG.getContext(); 3568 SDValue OffsVal = VectorWidth ? 3569 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3570 DAG.getConstant(Offs, dl, IdxTy); 3571 3572 // In an inbouds GEP with an offset that is nonnegative even when 3573 // interpreted as signed, assume there is no unsigned overflow. 3574 SDNodeFlags Flags; 3575 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3576 Flags.setNoUnsignedWrap(true); 3577 3578 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3579 continue; 3580 } 3581 3582 // N = N + Idx * ElementSize; 3583 SDValue IdxN = getValue(Idx); 3584 3585 if (!IdxN.getValueType().isVector() && VectorWidth) { 3586 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3587 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3588 } 3589 3590 // If the index is smaller or larger than intptr_t, truncate or extend 3591 // it. 3592 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3593 3594 // If this is a multiply by a power of two, turn it into a shl 3595 // immediately. This is a very common case. 3596 if (ElementSize != 1) { 3597 if (ElementSize.isPowerOf2()) { 3598 unsigned Amt = ElementSize.logBase2(); 3599 IdxN = DAG.getNode(ISD::SHL, dl, 3600 N.getValueType(), IdxN, 3601 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3602 } else { 3603 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3604 IdxN = DAG.getNode(ISD::MUL, dl, 3605 N.getValueType(), IdxN, Scale); 3606 } 3607 } 3608 3609 N = DAG.getNode(ISD::ADD, dl, 3610 N.getValueType(), N, IdxN); 3611 } 3612 } 3613 3614 setValue(&I, N); 3615 } 3616 3617 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3618 // If this is a fixed sized alloca in the entry block of the function, 3619 // allocate it statically on the stack. 3620 if (FuncInfo.StaticAllocaMap.count(&I)) 3621 return; // getValue will auto-populate this. 3622 3623 SDLoc dl = getCurSDLoc(); 3624 Type *Ty = I.getAllocatedType(); 3625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3626 auto &DL = DAG.getDataLayout(); 3627 uint64_t TySize = DL.getTypeAllocSize(Ty); 3628 unsigned Align = 3629 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3630 3631 SDValue AllocSize = getValue(I.getArraySize()); 3632 3633 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3634 if (AllocSize.getValueType() != IntPtr) 3635 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3636 3637 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3638 AllocSize, 3639 DAG.getConstant(TySize, dl, IntPtr)); 3640 3641 // Handle alignment. If the requested alignment is less than or equal to 3642 // the stack alignment, ignore it. If the size is greater than or equal to 3643 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3644 unsigned StackAlign = 3645 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3646 if (Align <= StackAlign) 3647 Align = 0; 3648 3649 // Round the size of the allocation up to the stack alignment size 3650 // by add SA-1 to the size. This doesn't overflow because we're computing 3651 // an address inside an alloca. 3652 SDNodeFlags Flags; 3653 Flags.setNoUnsignedWrap(true); 3654 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3655 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3656 3657 // Mask out the low bits for alignment purposes. 3658 AllocSize = 3659 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3660 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3661 3662 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3663 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3664 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3665 setValue(&I, DSA); 3666 DAG.setRoot(DSA.getValue(1)); 3667 3668 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3669 } 3670 3671 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3672 if (I.isAtomic()) 3673 return visitAtomicLoad(I); 3674 3675 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3676 const Value *SV = I.getOperand(0); 3677 if (TLI.supportSwiftError()) { 3678 // Swifterror values can come from either a function parameter with 3679 // swifterror attribute or an alloca with swifterror attribute. 3680 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3681 if (Arg->hasSwiftErrorAttr()) 3682 return visitLoadFromSwiftError(I); 3683 } 3684 3685 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3686 if (Alloca->isSwiftError()) 3687 return visitLoadFromSwiftError(I); 3688 } 3689 } 3690 3691 SDValue Ptr = getValue(SV); 3692 3693 Type *Ty = I.getType(); 3694 3695 bool isVolatile = I.isVolatile(); 3696 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3697 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3698 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3699 unsigned Alignment = I.getAlignment(); 3700 3701 AAMDNodes AAInfo; 3702 I.getAAMetadata(AAInfo); 3703 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3704 3705 SmallVector<EVT, 4> ValueVTs; 3706 SmallVector<uint64_t, 4> Offsets; 3707 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3708 unsigned NumValues = ValueVTs.size(); 3709 if (NumValues == 0) 3710 return; 3711 3712 SDValue Root; 3713 bool ConstantMemory = false; 3714 if (isVolatile || NumValues > MaxParallelChains) 3715 // Serialize volatile loads with other side effects. 3716 Root = getRoot(); 3717 else if (AA && 3718 AA->pointsToConstantMemory(MemoryLocation( 3719 SV, 3720 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3721 AAInfo))) { 3722 // Do not serialize (non-volatile) loads of constant memory with anything. 3723 Root = DAG.getEntryNode(); 3724 ConstantMemory = true; 3725 } else { 3726 // Do not serialize non-volatile loads against each other. 3727 Root = DAG.getRoot(); 3728 } 3729 3730 SDLoc dl = getCurSDLoc(); 3731 3732 if (isVolatile) 3733 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3734 3735 // An aggregate load cannot wrap around the address space, so offsets to its 3736 // parts don't wrap either. 3737 SDNodeFlags Flags; 3738 Flags.setNoUnsignedWrap(true); 3739 3740 SmallVector<SDValue, 4> Values(NumValues); 3741 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3742 EVT PtrVT = Ptr.getValueType(); 3743 unsigned ChainI = 0; 3744 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3745 // Serializing loads here may result in excessive register pressure, and 3746 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3747 // could recover a bit by hoisting nodes upward in the chain by recognizing 3748 // they are side-effect free or do not alias. The optimizer should really 3749 // avoid this case by converting large object/array copies to llvm.memcpy 3750 // (MaxParallelChains should always remain as failsafe). 3751 if (ChainI == MaxParallelChains) { 3752 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3753 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3754 makeArrayRef(Chains.data(), ChainI)); 3755 Root = Chain; 3756 ChainI = 0; 3757 } 3758 SDValue A = DAG.getNode(ISD::ADD, dl, 3759 PtrVT, Ptr, 3760 DAG.getConstant(Offsets[i], dl, PtrVT), 3761 Flags); 3762 auto MMOFlags = MachineMemOperand::MONone; 3763 if (isVolatile) 3764 MMOFlags |= MachineMemOperand::MOVolatile; 3765 if (isNonTemporal) 3766 MMOFlags |= MachineMemOperand::MONonTemporal; 3767 if (isInvariant) 3768 MMOFlags |= MachineMemOperand::MOInvariant; 3769 if (isDereferenceable) 3770 MMOFlags |= MachineMemOperand::MODereferenceable; 3771 MMOFlags |= TLI.getMMOFlags(I); 3772 3773 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3774 MachinePointerInfo(SV, Offsets[i]), Alignment, 3775 MMOFlags, AAInfo, Ranges); 3776 3777 Values[i] = L; 3778 Chains[ChainI] = L.getValue(1); 3779 } 3780 3781 if (!ConstantMemory) { 3782 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3783 makeArrayRef(Chains.data(), ChainI)); 3784 if (isVolatile) 3785 DAG.setRoot(Chain); 3786 else 3787 PendingLoads.push_back(Chain); 3788 } 3789 3790 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3791 DAG.getVTList(ValueVTs), Values)); 3792 } 3793 3794 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3795 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3796 "call visitStoreToSwiftError when backend supports swifterror"); 3797 3798 SmallVector<EVT, 4> ValueVTs; 3799 SmallVector<uint64_t, 4> Offsets; 3800 const Value *SrcV = I.getOperand(0); 3801 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3802 SrcV->getType(), ValueVTs, &Offsets); 3803 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3804 "expect a single EVT for swifterror"); 3805 3806 SDValue Src = getValue(SrcV); 3807 // Create a virtual register, then update the virtual register. 3808 unsigned VReg; bool CreatedVReg; 3809 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3810 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3811 // Chain can be getRoot or getControlRoot. 3812 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3813 SDValue(Src.getNode(), Src.getResNo())); 3814 DAG.setRoot(CopyNode); 3815 if (CreatedVReg) 3816 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3817 } 3818 3819 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3820 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3821 "call visitLoadFromSwiftError when backend supports swifterror"); 3822 3823 assert(!I.isVolatile() && 3824 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3825 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3826 "Support volatile, non temporal, invariant for load_from_swift_error"); 3827 3828 const Value *SV = I.getOperand(0); 3829 Type *Ty = I.getType(); 3830 AAMDNodes AAInfo; 3831 I.getAAMetadata(AAInfo); 3832 assert( 3833 (!AA || 3834 !AA->pointsToConstantMemory(MemoryLocation( 3835 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3836 AAInfo))) && 3837 "load_from_swift_error should not be constant memory"); 3838 3839 SmallVector<EVT, 4> ValueVTs; 3840 SmallVector<uint64_t, 4> Offsets; 3841 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3842 ValueVTs, &Offsets); 3843 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3844 "expect a single EVT for swifterror"); 3845 3846 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3847 SDValue L = DAG.getCopyFromReg( 3848 getRoot(), getCurSDLoc(), 3849 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3850 ValueVTs[0]); 3851 3852 setValue(&I, L); 3853 } 3854 3855 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3856 if (I.isAtomic()) 3857 return visitAtomicStore(I); 3858 3859 const Value *SrcV = I.getOperand(0); 3860 const Value *PtrV = I.getOperand(1); 3861 3862 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3863 if (TLI.supportSwiftError()) { 3864 // Swifterror values can come from either a function parameter with 3865 // swifterror attribute or an alloca with swifterror attribute. 3866 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3867 if (Arg->hasSwiftErrorAttr()) 3868 return visitStoreToSwiftError(I); 3869 } 3870 3871 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3872 if (Alloca->isSwiftError()) 3873 return visitStoreToSwiftError(I); 3874 } 3875 } 3876 3877 SmallVector<EVT, 4> ValueVTs; 3878 SmallVector<uint64_t, 4> Offsets; 3879 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3880 SrcV->getType(), ValueVTs, &Offsets); 3881 unsigned NumValues = ValueVTs.size(); 3882 if (NumValues == 0) 3883 return; 3884 3885 // Get the lowered operands. Note that we do this after 3886 // checking if NumResults is zero, because with zero results 3887 // the operands won't have values in the map. 3888 SDValue Src = getValue(SrcV); 3889 SDValue Ptr = getValue(PtrV); 3890 3891 SDValue Root = getRoot(); 3892 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3893 SDLoc dl = getCurSDLoc(); 3894 EVT PtrVT = Ptr.getValueType(); 3895 unsigned Alignment = I.getAlignment(); 3896 AAMDNodes AAInfo; 3897 I.getAAMetadata(AAInfo); 3898 3899 auto MMOFlags = MachineMemOperand::MONone; 3900 if (I.isVolatile()) 3901 MMOFlags |= MachineMemOperand::MOVolatile; 3902 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3903 MMOFlags |= MachineMemOperand::MONonTemporal; 3904 MMOFlags |= TLI.getMMOFlags(I); 3905 3906 // An aggregate load cannot wrap around the address space, so offsets to its 3907 // parts don't wrap either. 3908 SDNodeFlags Flags; 3909 Flags.setNoUnsignedWrap(true); 3910 3911 unsigned ChainI = 0; 3912 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3913 // See visitLoad comments. 3914 if (ChainI == MaxParallelChains) { 3915 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3916 makeArrayRef(Chains.data(), ChainI)); 3917 Root = Chain; 3918 ChainI = 0; 3919 } 3920 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3921 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3922 SDValue St = DAG.getStore( 3923 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3924 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3925 Chains[ChainI] = St; 3926 } 3927 3928 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3929 makeArrayRef(Chains.data(), ChainI)); 3930 DAG.setRoot(StoreNode); 3931 } 3932 3933 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3934 bool IsCompressing) { 3935 SDLoc sdl = getCurSDLoc(); 3936 3937 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3938 unsigned& Alignment) { 3939 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3940 Src0 = I.getArgOperand(0); 3941 Ptr = I.getArgOperand(1); 3942 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3943 Mask = I.getArgOperand(3); 3944 }; 3945 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3946 unsigned& Alignment) { 3947 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3948 Src0 = I.getArgOperand(0); 3949 Ptr = I.getArgOperand(1); 3950 Mask = I.getArgOperand(2); 3951 Alignment = 0; 3952 }; 3953 3954 Value *PtrOperand, *MaskOperand, *Src0Operand; 3955 unsigned Alignment; 3956 if (IsCompressing) 3957 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3958 else 3959 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3960 3961 SDValue Ptr = getValue(PtrOperand); 3962 SDValue Src0 = getValue(Src0Operand); 3963 SDValue Mask = getValue(MaskOperand); 3964 3965 EVT VT = Src0.getValueType(); 3966 if (!Alignment) 3967 Alignment = DAG.getEVTAlignment(VT); 3968 3969 AAMDNodes AAInfo; 3970 I.getAAMetadata(AAInfo); 3971 3972 MachineMemOperand *MMO = 3973 DAG.getMachineFunction(). 3974 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3975 MachineMemOperand::MOStore, VT.getStoreSize(), 3976 Alignment, AAInfo); 3977 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3978 MMO, false /* Truncating */, 3979 IsCompressing); 3980 DAG.setRoot(StoreNode); 3981 setValue(&I, StoreNode); 3982 } 3983 3984 // Get a uniform base for the Gather/Scatter intrinsic. 3985 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3986 // We try to represent it as a base pointer + vector of indices. 3987 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3988 // The first operand of the GEP may be a single pointer or a vector of pointers 3989 // Example: 3990 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3991 // or 3992 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3993 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3994 // 3995 // When the first GEP operand is a single pointer - it is the uniform base we 3996 // are looking for. If first operand of the GEP is a splat vector - we 3997 // extract the splat value and use it as a uniform base. 3998 // In all other cases the function returns 'false'. 3999 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4000 SDValue &Scale, SelectionDAGBuilder* SDB) { 4001 SelectionDAG& DAG = SDB->DAG; 4002 LLVMContext &Context = *DAG.getContext(); 4003 4004 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4005 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4006 if (!GEP) 4007 return false; 4008 4009 const Value *GEPPtr = GEP->getPointerOperand(); 4010 if (!GEPPtr->getType()->isVectorTy()) 4011 Ptr = GEPPtr; 4012 else if (!(Ptr = getSplatValue(GEPPtr))) 4013 return false; 4014 4015 unsigned FinalIndex = GEP->getNumOperands() - 1; 4016 Value *IndexVal = GEP->getOperand(FinalIndex); 4017 4018 // Ensure all the other indices are 0. 4019 for (unsigned i = 1; i < FinalIndex; ++i) { 4020 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4021 if (!C || !C->isZero()) 4022 return false; 4023 } 4024 4025 // The operands of the GEP may be defined in another basic block. 4026 // In this case we'll not find nodes for the operands. 4027 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4028 return false; 4029 4030 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4031 const DataLayout &DL = DAG.getDataLayout(); 4032 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4033 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4034 Base = SDB->getValue(Ptr); 4035 Index = SDB->getValue(IndexVal); 4036 4037 if (!Index.getValueType().isVector()) { 4038 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4039 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4040 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4041 } 4042 return true; 4043 } 4044 4045 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4046 SDLoc sdl = getCurSDLoc(); 4047 4048 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4049 const Value *Ptr = I.getArgOperand(1); 4050 SDValue Src0 = getValue(I.getArgOperand(0)); 4051 SDValue Mask = getValue(I.getArgOperand(3)); 4052 EVT VT = Src0.getValueType(); 4053 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4054 if (!Alignment) 4055 Alignment = DAG.getEVTAlignment(VT); 4056 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4057 4058 AAMDNodes AAInfo; 4059 I.getAAMetadata(AAInfo); 4060 4061 SDValue Base; 4062 SDValue Index; 4063 SDValue Scale; 4064 const Value *BasePtr = Ptr; 4065 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4066 4067 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4068 MachineMemOperand *MMO = DAG.getMachineFunction(). 4069 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4070 MachineMemOperand::MOStore, VT.getStoreSize(), 4071 Alignment, AAInfo); 4072 if (!UniformBase) { 4073 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4074 Index = getValue(Ptr); 4075 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4076 } 4077 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4078 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4079 Ops, MMO); 4080 DAG.setRoot(Scatter); 4081 setValue(&I, Scatter); 4082 } 4083 4084 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4085 SDLoc sdl = getCurSDLoc(); 4086 4087 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4088 unsigned& Alignment) { 4089 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4090 Ptr = I.getArgOperand(0); 4091 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4092 Mask = I.getArgOperand(2); 4093 Src0 = I.getArgOperand(3); 4094 }; 4095 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4096 unsigned& Alignment) { 4097 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4098 Ptr = I.getArgOperand(0); 4099 Alignment = 0; 4100 Mask = I.getArgOperand(1); 4101 Src0 = I.getArgOperand(2); 4102 }; 4103 4104 Value *PtrOperand, *MaskOperand, *Src0Operand; 4105 unsigned Alignment; 4106 if (IsExpanding) 4107 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4108 else 4109 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4110 4111 SDValue Ptr = getValue(PtrOperand); 4112 SDValue Src0 = getValue(Src0Operand); 4113 SDValue Mask = getValue(MaskOperand); 4114 4115 EVT VT = Src0.getValueType(); 4116 if (!Alignment) 4117 Alignment = DAG.getEVTAlignment(VT); 4118 4119 AAMDNodes AAInfo; 4120 I.getAAMetadata(AAInfo); 4121 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4122 4123 // Do not serialize masked loads of constant memory with anything. 4124 bool AddToChain = 4125 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4126 PtrOperand, 4127 LocationSize::precise( 4128 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4129 AAInfo)); 4130 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4131 4132 MachineMemOperand *MMO = 4133 DAG.getMachineFunction(). 4134 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4135 MachineMemOperand::MOLoad, VT.getStoreSize(), 4136 Alignment, AAInfo, Ranges); 4137 4138 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4139 ISD::NON_EXTLOAD, IsExpanding); 4140 if (AddToChain) 4141 PendingLoads.push_back(Load.getValue(1)); 4142 setValue(&I, Load); 4143 } 4144 4145 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4146 SDLoc sdl = getCurSDLoc(); 4147 4148 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4149 const Value *Ptr = I.getArgOperand(0); 4150 SDValue Src0 = getValue(I.getArgOperand(3)); 4151 SDValue Mask = getValue(I.getArgOperand(2)); 4152 4153 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4154 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4155 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4156 if (!Alignment) 4157 Alignment = DAG.getEVTAlignment(VT); 4158 4159 AAMDNodes AAInfo; 4160 I.getAAMetadata(AAInfo); 4161 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4162 4163 SDValue Root = DAG.getRoot(); 4164 SDValue Base; 4165 SDValue Index; 4166 SDValue Scale; 4167 const Value *BasePtr = Ptr; 4168 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4169 bool ConstantMemory = false; 4170 if (UniformBase && AA && 4171 AA->pointsToConstantMemory( 4172 MemoryLocation(BasePtr, 4173 LocationSize::precise( 4174 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4175 AAInfo))) { 4176 // Do not serialize (non-volatile) loads of constant memory with anything. 4177 Root = DAG.getEntryNode(); 4178 ConstantMemory = true; 4179 } 4180 4181 MachineMemOperand *MMO = 4182 DAG.getMachineFunction(). 4183 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4184 MachineMemOperand::MOLoad, VT.getStoreSize(), 4185 Alignment, AAInfo, Ranges); 4186 4187 if (!UniformBase) { 4188 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4189 Index = getValue(Ptr); 4190 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4191 } 4192 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4193 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4194 Ops, MMO); 4195 4196 SDValue OutChain = Gather.getValue(1); 4197 if (!ConstantMemory) 4198 PendingLoads.push_back(OutChain); 4199 setValue(&I, Gather); 4200 } 4201 4202 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4203 SDLoc dl = getCurSDLoc(); 4204 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4205 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4206 SyncScope::ID SSID = I.getSyncScopeID(); 4207 4208 SDValue InChain = getRoot(); 4209 4210 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4211 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4212 SDValue L = DAG.getAtomicCmpSwap( 4213 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4214 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4215 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4216 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4217 4218 SDValue OutChain = L.getValue(2); 4219 4220 setValue(&I, L); 4221 DAG.setRoot(OutChain); 4222 } 4223 4224 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4225 SDLoc dl = getCurSDLoc(); 4226 ISD::NodeType NT; 4227 switch (I.getOperation()) { 4228 default: llvm_unreachable("Unknown atomicrmw operation"); 4229 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4230 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4231 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4232 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4233 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4234 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4235 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4236 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4237 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4238 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4239 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4240 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4241 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4242 } 4243 AtomicOrdering Order = I.getOrdering(); 4244 SyncScope::ID SSID = I.getSyncScopeID(); 4245 4246 SDValue InChain = getRoot(); 4247 4248 SDValue L = 4249 DAG.getAtomic(NT, dl, 4250 getValue(I.getValOperand()).getSimpleValueType(), 4251 InChain, 4252 getValue(I.getPointerOperand()), 4253 getValue(I.getValOperand()), 4254 I.getPointerOperand(), 4255 /* Alignment=*/ 0, Order, SSID); 4256 4257 SDValue OutChain = L.getValue(1); 4258 4259 setValue(&I, L); 4260 DAG.setRoot(OutChain); 4261 } 4262 4263 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4264 SDLoc dl = getCurSDLoc(); 4265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4266 SDValue Ops[3]; 4267 Ops[0] = getRoot(); 4268 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4269 TLI.getFenceOperandTy(DAG.getDataLayout())); 4270 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4271 TLI.getFenceOperandTy(DAG.getDataLayout())); 4272 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4273 } 4274 4275 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4276 SDLoc dl = getCurSDLoc(); 4277 AtomicOrdering Order = I.getOrdering(); 4278 SyncScope::ID SSID = I.getSyncScopeID(); 4279 4280 SDValue InChain = getRoot(); 4281 4282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4283 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4284 4285 if (!TLI.supportsUnalignedAtomics() && 4286 I.getAlignment() < VT.getStoreSize()) 4287 report_fatal_error("Cannot generate unaligned atomic load"); 4288 4289 MachineMemOperand *MMO = 4290 DAG.getMachineFunction(). 4291 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4292 MachineMemOperand::MOVolatile | 4293 MachineMemOperand::MOLoad, 4294 VT.getStoreSize(), 4295 I.getAlignment() ? I.getAlignment() : 4296 DAG.getEVTAlignment(VT), 4297 AAMDNodes(), nullptr, SSID, Order); 4298 4299 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4300 SDValue L = 4301 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4302 getValue(I.getPointerOperand()), MMO); 4303 4304 SDValue OutChain = L.getValue(1); 4305 4306 setValue(&I, L); 4307 DAG.setRoot(OutChain); 4308 } 4309 4310 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4311 SDLoc dl = getCurSDLoc(); 4312 4313 AtomicOrdering Order = I.getOrdering(); 4314 SyncScope::ID SSID = I.getSyncScopeID(); 4315 4316 SDValue InChain = getRoot(); 4317 4318 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4319 EVT VT = 4320 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4321 4322 if (I.getAlignment() < VT.getStoreSize()) 4323 report_fatal_error("Cannot generate unaligned atomic store"); 4324 4325 SDValue OutChain = 4326 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4327 InChain, 4328 getValue(I.getPointerOperand()), 4329 getValue(I.getValueOperand()), 4330 I.getPointerOperand(), I.getAlignment(), 4331 Order, SSID); 4332 4333 DAG.setRoot(OutChain); 4334 } 4335 4336 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4337 /// node. 4338 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4339 unsigned Intrinsic) { 4340 // Ignore the callsite's attributes. A specific call site may be marked with 4341 // readnone, but the lowering code will expect the chain based on the 4342 // definition. 4343 const Function *F = I.getCalledFunction(); 4344 bool HasChain = !F->doesNotAccessMemory(); 4345 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4346 4347 // Build the operand list. 4348 SmallVector<SDValue, 8> Ops; 4349 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4350 if (OnlyLoad) { 4351 // We don't need to serialize loads against other loads. 4352 Ops.push_back(DAG.getRoot()); 4353 } else { 4354 Ops.push_back(getRoot()); 4355 } 4356 } 4357 4358 // Info is set by getTgtMemInstrinsic 4359 TargetLowering::IntrinsicInfo Info; 4360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4361 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4362 DAG.getMachineFunction(), 4363 Intrinsic); 4364 4365 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4366 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4367 Info.opc == ISD::INTRINSIC_W_CHAIN) 4368 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4369 TLI.getPointerTy(DAG.getDataLayout()))); 4370 4371 // Add all operands of the call to the operand list. 4372 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4373 SDValue Op = getValue(I.getArgOperand(i)); 4374 Ops.push_back(Op); 4375 } 4376 4377 SmallVector<EVT, 4> ValueVTs; 4378 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4379 4380 if (HasChain) 4381 ValueVTs.push_back(MVT::Other); 4382 4383 SDVTList VTs = DAG.getVTList(ValueVTs); 4384 4385 // Create the node. 4386 SDValue Result; 4387 if (IsTgtIntrinsic) { 4388 // This is target intrinsic that touches memory 4389 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4390 Ops, Info.memVT, 4391 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4392 Info.flags, Info.size); 4393 } else if (!HasChain) { 4394 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4395 } else if (!I.getType()->isVoidTy()) { 4396 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4397 } else { 4398 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4399 } 4400 4401 if (HasChain) { 4402 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4403 if (OnlyLoad) 4404 PendingLoads.push_back(Chain); 4405 else 4406 DAG.setRoot(Chain); 4407 } 4408 4409 if (!I.getType()->isVoidTy()) { 4410 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4411 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4412 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4413 } else 4414 Result = lowerRangeToAssertZExt(DAG, I, Result); 4415 4416 setValue(&I, Result); 4417 } 4418 } 4419 4420 /// GetSignificand - Get the significand and build it into a floating-point 4421 /// number with exponent of 1: 4422 /// 4423 /// Op = (Op & 0x007fffff) | 0x3f800000; 4424 /// 4425 /// where Op is the hexadecimal representation of floating point value. 4426 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4427 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4428 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4429 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4430 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4431 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4432 } 4433 4434 /// GetExponent - Get the exponent: 4435 /// 4436 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4437 /// 4438 /// where Op is the hexadecimal representation of floating point value. 4439 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4440 const TargetLowering &TLI, const SDLoc &dl) { 4441 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4442 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4443 SDValue t1 = DAG.getNode( 4444 ISD::SRL, dl, MVT::i32, t0, 4445 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4446 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4447 DAG.getConstant(127, dl, MVT::i32)); 4448 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4449 } 4450 4451 /// getF32Constant - Get 32-bit floating point constant. 4452 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4453 const SDLoc &dl) { 4454 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4455 MVT::f32); 4456 } 4457 4458 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4459 SelectionDAG &DAG) { 4460 // TODO: What fast-math-flags should be set on the floating-point nodes? 4461 4462 // IntegerPartOfX = ((int32_t)(t0); 4463 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4464 4465 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4466 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4467 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4468 4469 // IntegerPartOfX <<= 23; 4470 IntegerPartOfX = DAG.getNode( 4471 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4472 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4473 DAG.getDataLayout()))); 4474 4475 SDValue TwoToFractionalPartOfX; 4476 if (LimitFloatPrecision <= 6) { 4477 // For floating-point precision of 6: 4478 // 4479 // TwoToFractionalPartOfX = 4480 // 0.997535578f + 4481 // (0.735607626f + 0.252464424f * x) * x; 4482 // 4483 // error 0.0144103317, which is 6 bits 4484 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4485 getF32Constant(DAG, 0x3e814304, dl)); 4486 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4487 getF32Constant(DAG, 0x3f3c50c8, dl)); 4488 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4489 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4490 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4491 } else if (LimitFloatPrecision <= 12) { 4492 // For floating-point precision of 12: 4493 // 4494 // TwoToFractionalPartOfX = 4495 // 0.999892986f + 4496 // (0.696457318f + 4497 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4498 // 4499 // error 0.000107046256, which is 13 to 14 bits 4500 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4501 getF32Constant(DAG, 0x3da235e3, dl)); 4502 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4503 getF32Constant(DAG, 0x3e65b8f3, dl)); 4504 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4505 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4506 getF32Constant(DAG, 0x3f324b07, dl)); 4507 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4508 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4509 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4510 } else { // LimitFloatPrecision <= 18 4511 // For floating-point precision of 18: 4512 // 4513 // TwoToFractionalPartOfX = 4514 // 0.999999982f + 4515 // (0.693148872f + 4516 // (0.240227044f + 4517 // (0.554906021e-1f + 4518 // (0.961591928e-2f + 4519 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4520 // error 2.47208000*10^(-7), which is better than 18 bits 4521 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4522 getF32Constant(DAG, 0x3924b03e, dl)); 4523 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4524 getF32Constant(DAG, 0x3ab24b87, dl)); 4525 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4526 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4527 getF32Constant(DAG, 0x3c1d8c17, dl)); 4528 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4529 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4530 getF32Constant(DAG, 0x3d634a1d, dl)); 4531 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4532 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4533 getF32Constant(DAG, 0x3e75fe14, dl)); 4534 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4535 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4536 getF32Constant(DAG, 0x3f317234, dl)); 4537 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4538 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4539 getF32Constant(DAG, 0x3f800000, dl)); 4540 } 4541 4542 // Add the exponent into the result in integer domain. 4543 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4544 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4545 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4546 } 4547 4548 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4549 /// limited-precision mode. 4550 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4551 const TargetLowering &TLI) { 4552 if (Op.getValueType() == MVT::f32 && 4553 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4554 4555 // Put the exponent in the right bit position for later addition to the 4556 // final result: 4557 // 4558 // #define LOG2OFe 1.4426950f 4559 // t0 = Op * LOG2OFe 4560 4561 // TODO: What fast-math-flags should be set here? 4562 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4563 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4564 return getLimitedPrecisionExp2(t0, dl, DAG); 4565 } 4566 4567 // No special expansion. 4568 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4569 } 4570 4571 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4572 /// limited-precision mode. 4573 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4574 const TargetLowering &TLI) { 4575 // TODO: What fast-math-flags should be set on the floating-point nodes? 4576 4577 if (Op.getValueType() == MVT::f32 && 4578 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4579 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4580 4581 // Scale the exponent by log(2) [0.69314718f]. 4582 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4583 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4584 getF32Constant(DAG, 0x3f317218, dl)); 4585 4586 // Get the significand and build it into a floating-point number with 4587 // exponent of 1. 4588 SDValue X = GetSignificand(DAG, Op1, dl); 4589 4590 SDValue LogOfMantissa; 4591 if (LimitFloatPrecision <= 6) { 4592 // For floating-point precision of 6: 4593 // 4594 // LogofMantissa = 4595 // -1.1609546f + 4596 // (1.4034025f - 0.23903021f * x) * x; 4597 // 4598 // error 0.0034276066, which is better than 8 bits 4599 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4600 getF32Constant(DAG, 0xbe74c456, dl)); 4601 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4602 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4603 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4604 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4605 getF32Constant(DAG, 0x3f949a29, dl)); 4606 } else if (LimitFloatPrecision <= 12) { 4607 // For floating-point precision of 12: 4608 // 4609 // LogOfMantissa = 4610 // -1.7417939f + 4611 // (2.8212026f + 4612 // (-1.4699568f + 4613 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4614 // 4615 // error 0.000061011436, which is 14 bits 4616 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4617 getF32Constant(DAG, 0xbd67b6d6, dl)); 4618 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4619 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4620 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4621 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4622 getF32Constant(DAG, 0x3fbc278b, dl)); 4623 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4624 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4625 getF32Constant(DAG, 0x40348e95, dl)); 4626 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4627 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4628 getF32Constant(DAG, 0x3fdef31a, dl)); 4629 } else { // LimitFloatPrecision <= 18 4630 // For floating-point precision of 18: 4631 // 4632 // LogOfMantissa = 4633 // -2.1072184f + 4634 // (4.2372794f + 4635 // (-3.7029485f + 4636 // (2.2781945f + 4637 // (-0.87823314f + 4638 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4639 // 4640 // error 0.0000023660568, which is better than 18 bits 4641 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4642 getF32Constant(DAG, 0xbc91e5ac, dl)); 4643 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4644 getF32Constant(DAG, 0x3e4350aa, dl)); 4645 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4646 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4647 getF32Constant(DAG, 0x3f60d3e3, dl)); 4648 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4649 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4650 getF32Constant(DAG, 0x4011cdf0, dl)); 4651 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4652 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4653 getF32Constant(DAG, 0x406cfd1c, dl)); 4654 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4655 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4656 getF32Constant(DAG, 0x408797cb, dl)); 4657 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4658 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4659 getF32Constant(DAG, 0x4006dcab, dl)); 4660 } 4661 4662 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4663 } 4664 4665 // No special expansion. 4666 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4667 } 4668 4669 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4670 /// limited-precision mode. 4671 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4672 const TargetLowering &TLI) { 4673 // TODO: What fast-math-flags should be set on the floating-point nodes? 4674 4675 if (Op.getValueType() == MVT::f32 && 4676 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4677 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4678 4679 // Get the exponent. 4680 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4681 4682 // Get the significand and build it into a floating-point number with 4683 // exponent of 1. 4684 SDValue X = GetSignificand(DAG, Op1, dl); 4685 4686 // Different possible minimax approximations of significand in 4687 // floating-point for various degrees of accuracy over [1,2]. 4688 SDValue Log2ofMantissa; 4689 if (LimitFloatPrecision <= 6) { 4690 // For floating-point precision of 6: 4691 // 4692 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4693 // 4694 // error 0.0049451742, which is more than 7 bits 4695 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4696 getF32Constant(DAG, 0xbeb08fe0, dl)); 4697 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4698 getF32Constant(DAG, 0x40019463, dl)); 4699 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4700 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4701 getF32Constant(DAG, 0x3fd6633d, dl)); 4702 } else if (LimitFloatPrecision <= 12) { 4703 // For floating-point precision of 12: 4704 // 4705 // Log2ofMantissa = 4706 // -2.51285454f + 4707 // (4.07009056f + 4708 // (-2.12067489f + 4709 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4710 // 4711 // error 0.0000876136000, which is better than 13 bits 4712 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4713 getF32Constant(DAG, 0xbda7262e, dl)); 4714 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4715 getF32Constant(DAG, 0x3f25280b, dl)); 4716 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4717 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4718 getF32Constant(DAG, 0x4007b923, dl)); 4719 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4720 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4721 getF32Constant(DAG, 0x40823e2f, dl)); 4722 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4723 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4724 getF32Constant(DAG, 0x4020d29c, dl)); 4725 } else { // LimitFloatPrecision <= 18 4726 // For floating-point precision of 18: 4727 // 4728 // Log2ofMantissa = 4729 // -3.0400495f + 4730 // (6.1129976f + 4731 // (-5.3420409f + 4732 // (3.2865683f + 4733 // (-1.2669343f + 4734 // (0.27515199f - 4735 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4736 // 4737 // error 0.0000018516, which is better than 18 bits 4738 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4739 getF32Constant(DAG, 0xbcd2769e, dl)); 4740 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4741 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4742 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4743 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4744 getF32Constant(DAG, 0x3fa22ae7, dl)); 4745 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4746 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4747 getF32Constant(DAG, 0x40525723, dl)); 4748 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4749 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4750 getF32Constant(DAG, 0x40aaf200, dl)); 4751 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4752 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4753 getF32Constant(DAG, 0x40c39dad, dl)); 4754 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4755 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4756 getF32Constant(DAG, 0x4042902c, dl)); 4757 } 4758 4759 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4760 } 4761 4762 // No special expansion. 4763 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4764 } 4765 4766 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4767 /// limited-precision mode. 4768 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4769 const TargetLowering &TLI) { 4770 // TODO: What fast-math-flags should be set on the floating-point nodes? 4771 4772 if (Op.getValueType() == MVT::f32 && 4773 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4774 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4775 4776 // Scale the exponent by log10(2) [0.30102999f]. 4777 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4778 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4779 getF32Constant(DAG, 0x3e9a209a, dl)); 4780 4781 // Get the significand and build it into a floating-point number with 4782 // exponent of 1. 4783 SDValue X = GetSignificand(DAG, Op1, dl); 4784 4785 SDValue Log10ofMantissa; 4786 if (LimitFloatPrecision <= 6) { 4787 // For floating-point precision of 6: 4788 // 4789 // Log10ofMantissa = 4790 // -0.50419619f + 4791 // (0.60948995f - 0.10380950f * x) * x; 4792 // 4793 // error 0.0014886165, which is 6 bits 4794 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4795 getF32Constant(DAG, 0xbdd49a13, dl)); 4796 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4797 getF32Constant(DAG, 0x3f1c0789, dl)); 4798 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4799 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4800 getF32Constant(DAG, 0x3f011300, dl)); 4801 } else if (LimitFloatPrecision <= 12) { 4802 // For floating-point precision of 12: 4803 // 4804 // Log10ofMantissa = 4805 // -0.64831180f + 4806 // (0.91751397f + 4807 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4808 // 4809 // error 0.00019228036, which is better than 12 bits 4810 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4811 getF32Constant(DAG, 0x3d431f31, dl)); 4812 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4813 getF32Constant(DAG, 0x3ea21fb2, dl)); 4814 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4815 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4816 getF32Constant(DAG, 0x3f6ae232, dl)); 4817 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4818 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4819 getF32Constant(DAG, 0x3f25f7c3, dl)); 4820 } else { // LimitFloatPrecision <= 18 4821 // For floating-point precision of 18: 4822 // 4823 // Log10ofMantissa = 4824 // -0.84299375f + 4825 // (1.5327582f + 4826 // (-1.0688956f + 4827 // (0.49102474f + 4828 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4829 // 4830 // error 0.0000037995730, which is better than 18 bits 4831 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4832 getF32Constant(DAG, 0x3c5d51ce, dl)); 4833 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4834 getF32Constant(DAG, 0x3e00685a, dl)); 4835 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4836 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4837 getF32Constant(DAG, 0x3efb6798, dl)); 4838 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4839 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4840 getF32Constant(DAG, 0x3f88d192, dl)); 4841 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4842 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4843 getF32Constant(DAG, 0x3fc4316c, dl)); 4844 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4845 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4846 getF32Constant(DAG, 0x3f57ce70, dl)); 4847 } 4848 4849 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4850 } 4851 4852 // No special expansion. 4853 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4854 } 4855 4856 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4857 /// limited-precision mode. 4858 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4859 const TargetLowering &TLI) { 4860 if (Op.getValueType() == MVT::f32 && 4861 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4862 return getLimitedPrecisionExp2(Op, dl, DAG); 4863 4864 // No special expansion. 4865 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4866 } 4867 4868 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4869 /// limited-precision mode with x == 10.0f. 4870 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4871 SelectionDAG &DAG, const TargetLowering &TLI) { 4872 bool IsExp10 = false; 4873 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4874 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4875 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4876 APFloat Ten(10.0f); 4877 IsExp10 = LHSC->isExactlyValue(Ten); 4878 } 4879 } 4880 4881 // TODO: What fast-math-flags should be set on the FMUL node? 4882 if (IsExp10) { 4883 // Put the exponent in the right bit position for later addition to the 4884 // final result: 4885 // 4886 // #define LOG2OF10 3.3219281f 4887 // t0 = Op * LOG2OF10; 4888 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4889 getF32Constant(DAG, 0x40549a78, dl)); 4890 return getLimitedPrecisionExp2(t0, dl, DAG); 4891 } 4892 4893 // No special expansion. 4894 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4895 } 4896 4897 /// ExpandPowI - Expand a llvm.powi intrinsic. 4898 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4899 SelectionDAG &DAG) { 4900 // If RHS is a constant, we can expand this out to a multiplication tree, 4901 // otherwise we end up lowering to a call to __powidf2 (for example). When 4902 // optimizing for size, we only want to do this if the expansion would produce 4903 // a small number of multiplies, otherwise we do the full expansion. 4904 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4905 // Get the exponent as a positive value. 4906 unsigned Val = RHSC->getSExtValue(); 4907 if ((int)Val < 0) Val = -Val; 4908 4909 // powi(x, 0) -> 1.0 4910 if (Val == 0) 4911 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4912 4913 const Function &F = DAG.getMachineFunction().getFunction(); 4914 if (!F.optForSize() || 4915 // If optimizing for size, don't insert too many multiplies. 4916 // This inserts up to 5 multiplies. 4917 countPopulation(Val) + Log2_32(Val) < 7) { 4918 // We use the simple binary decomposition method to generate the multiply 4919 // sequence. There are more optimal ways to do this (for example, 4920 // powi(x,15) generates one more multiply than it should), but this has 4921 // the benefit of being both really simple and much better than a libcall. 4922 SDValue Res; // Logically starts equal to 1.0 4923 SDValue CurSquare = LHS; 4924 // TODO: Intrinsics should have fast-math-flags that propagate to these 4925 // nodes. 4926 while (Val) { 4927 if (Val & 1) { 4928 if (Res.getNode()) 4929 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4930 else 4931 Res = CurSquare; // 1.0*CurSquare. 4932 } 4933 4934 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4935 CurSquare, CurSquare); 4936 Val >>= 1; 4937 } 4938 4939 // If the original was negative, invert the result, producing 1/(x*x*x). 4940 if (RHSC->getSExtValue() < 0) 4941 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4942 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4943 return Res; 4944 } 4945 } 4946 4947 // Otherwise, expand to a libcall. 4948 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4949 } 4950 4951 // getUnderlyingArgReg - Find underlying register used for a truncated or 4952 // bitcasted argument. 4953 static unsigned getUnderlyingArgReg(const SDValue &N) { 4954 switch (N.getOpcode()) { 4955 case ISD::CopyFromReg: 4956 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4957 case ISD::BITCAST: 4958 case ISD::AssertZext: 4959 case ISD::AssertSext: 4960 case ISD::TRUNCATE: 4961 return getUnderlyingArgReg(N.getOperand(0)); 4962 default: 4963 return 0; 4964 } 4965 } 4966 4967 /// If the DbgValueInst is a dbg_value of a function argument, create the 4968 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4969 /// instruction selection, they will be inserted to the entry BB. 4970 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4971 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4972 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4973 const Argument *Arg = dyn_cast<Argument>(V); 4974 if (!Arg) 4975 return false; 4976 4977 MachineFunction &MF = DAG.getMachineFunction(); 4978 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4979 4980 bool IsIndirect = false; 4981 Optional<MachineOperand> Op; 4982 // Some arguments' frame index is recorded during argument lowering. 4983 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4984 if (FI != std::numeric_limits<int>::max()) 4985 Op = MachineOperand::CreateFI(FI); 4986 4987 if (!Op && N.getNode()) { 4988 unsigned Reg = getUnderlyingArgReg(N); 4989 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4990 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4991 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4992 if (PR) 4993 Reg = PR; 4994 } 4995 if (Reg) { 4996 Op = MachineOperand::CreateReg(Reg, false); 4997 IsIndirect = IsDbgDeclare; 4998 } 4999 } 5000 5001 if (!Op && N.getNode()) 5002 // Check if frame index is available. 5003 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 5004 if (FrameIndexSDNode *FINode = 5005 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5006 Op = MachineOperand::CreateFI(FINode->getIndex()); 5007 5008 if (!Op) { 5009 // Check if ValueMap has reg number. 5010 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5011 if (VMI != FuncInfo.ValueMap.end()) { 5012 const auto &TLI = DAG.getTargetLoweringInfo(); 5013 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5014 V->getType(), getABIRegCopyCC(V)); 5015 if (RFV.occupiesMultipleRegs()) { 5016 unsigned Offset = 0; 5017 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5018 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5019 auto FragmentExpr = DIExpression::createFragmentExpression( 5020 Expr, Offset, RegAndSize.second); 5021 if (!FragmentExpr) 5022 continue; 5023 FuncInfo.ArgDbgValues.push_back( 5024 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5025 Op->getReg(), Variable, *FragmentExpr)); 5026 Offset += RegAndSize.second; 5027 } 5028 return true; 5029 } 5030 Op = MachineOperand::CreateReg(VMI->second, false); 5031 IsIndirect = IsDbgDeclare; 5032 } 5033 } 5034 5035 if (!Op) 5036 return false; 5037 5038 assert(Variable->isValidLocationForIntrinsic(DL) && 5039 "Expected inlined-at fields to agree"); 5040 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5041 FuncInfo.ArgDbgValues.push_back( 5042 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5043 *Op, Variable, Expr)); 5044 5045 return true; 5046 } 5047 5048 /// Return the appropriate SDDbgValue based on N. 5049 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5050 DILocalVariable *Variable, 5051 DIExpression *Expr, 5052 const DebugLoc &dl, 5053 unsigned DbgSDNodeOrder) { 5054 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5055 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5056 // stack slot locations. 5057 // 5058 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5059 // debug values here after optimization: 5060 // 5061 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5062 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5063 // 5064 // Both describe the direct values of their associated variables. 5065 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5066 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5067 } 5068 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5069 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5070 } 5071 5072 // VisualStudio defines setjmp as _setjmp 5073 #if defined(_MSC_VER) && defined(setjmp) && \ 5074 !defined(setjmp_undefined_for_msvc) 5075 # pragma push_macro("setjmp") 5076 # undef setjmp 5077 # define setjmp_undefined_for_msvc 5078 #endif 5079 5080 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5081 switch (Intrinsic) { 5082 case Intrinsic::smul_fix: 5083 return ISD::SMULFIX; 5084 case Intrinsic::umul_fix: 5085 return ISD::UMULFIX; 5086 default: 5087 llvm_unreachable("Unhandled fixed point intrinsic"); 5088 } 5089 } 5090 5091 /// Lower the call to the specified intrinsic function. If we want to emit this 5092 /// as a call to a named external function, return the name. Otherwise, lower it 5093 /// and return null. 5094 const char * 5095 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5096 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5097 SDLoc sdl = getCurSDLoc(); 5098 DebugLoc dl = getCurDebugLoc(); 5099 SDValue Res; 5100 5101 switch (Intrinsic) { 5102 default: 5103 // By default, turn this into a target intrinsic node. 5104 visitTargetIntrinsic(I, Intrinsic); 5105 return nullptr; 5106 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5107 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5108 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5109 case Intrinsic::returnaddress: 5110 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5111 TLI.getPointerTy(DAG.getDataLayout()), 5112 getValue(I.getArgOperand(0)))); 5113 return nullptr; 5114 case Intrinsic::addressofreturnaddress: 5115 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5116 TLI.getPointerTy(DAG.getDataLayout()))); 5117 return nullptr; 5118 case Intrinsic::sponentry: 5119 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5120 TLI.getPointerTy(DAG.getDataLayout()))); 5121 return nullptr; 5122 case Intrinsic::frameaddress: 5123 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5124 TLI.getPointerTy(DAG.getDataLayout()), 5125 getValue(I.getArgOperand(0)))); 5126 return nullptr; 5127 case Intrinsic::read_register: { 5128 Value *Reg = I.getArgOperand(0); 5129 SDValue Chain = getRoot(); 5130 SDValue RegName = 5131 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5132 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5133 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5134 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5135 setValue(&I, Res); 5136 DAG.setRoot(Res.getValue(1)); 5137 return nullptr; 5138 } 5139 case Intrinsic::write_register: { 5140 Value *Reg = I.getArgOperand(0); 5141 Value *RegValue = I.getArgOperand(1); 5142 SDValue Chain = getRoot(); 5143 SDValue RegName = 5144 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5145 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5146 RegName, getValue(RegValue))); 5147 return nullptr; 5148 } 5149 case Intrinsic::setjmp: 5150 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5151 case Intrinsic::longjmp: 5152 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5153 case Intrinsic::memcpy: { 5154 const auto &MCI = cast<MemCpyInst>(I); 5155 SDValue Op1 = getValue(I.getArgOperand(0)); 5156 SDValue Op2 = getValue(I.getArgOperand(1)); 5157 SDValue Op3 = getValue(I.getArgOperand(2)); 5158 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5159 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5160 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5161 unsigned Align = MinAlign(DstAlign, SrcAlign); 5162 bool isVol = MCI.isVolatile(); 5163 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5164 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5165 // node. 5166 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5167 false, isTC, 5168 MachinePointerInfo(I.getArgOperand(0)), 5169 MachinePointerInfo(I.getArgOperand(1))); 5170 updateDAGForMaybeTailCall(MC); 5171 return nullptr; 5172 } 5173 case Intrinsic::memset: { 5174 const auto &MSI = cast<MemSetInst>(I); 5175 SDValue Op1 = getValue(I.getArgOperand(0)); 5176 SDValue Op2 = getValue(I.getArgOperand(1)); 5177 SDValue Op3 = getValue(I.getArgOperand(2)); 5178 // @llvm.memset defines 0 and 1 to both mean no alignment. 5179 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5180 bool isVol = MSI.isVolatile(); 5181 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5182 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5183 isTC, MachinePointerInfo(I.getArgOperand(0))); 5184 updateDAGForMaybeTailCall(MS); 5185 return nullptr; 5186 } 5187 case Intrinsic::memmove: { 5188 const auto &MMI = cast<MemMoveInst>(I); 5189 SDValue Op1 = getValue(I.getArgOperand(0)); 5190 SDValue Op2 = getValue(I.getArgOperand(1)); 5191 SDValue Op3 = getValue(I.getArgOperand(2)); 5192 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5193 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5194 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5195 unsigned Align = MinAlign(DstAlign, SrcAlign); 5196 bool isVol = MMI.isVolatile(); 5197 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5198 // FIXME: Support passing different dest/src alignments to the memmove DAG 5199 // node. 5200 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5201 isTC, MachinePointerInfo(I.getArgOperand(0)), 5202 MachinePointerInfo(I.getArgOperand(1))); 5203 updateDAGForMaybeTailCall(MM); 5204 return nullptr; 5205 } 5206 case Intrinsic::memcpy_element_unordered_atomic: { 5207 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5208 SDValue Dst = getValue(MI.getRawDest()); 5209 SDValue Src = getValue(MI.getRawSource()); 5210 SDValue Length = getValue(MI.getLength()); 5211 5212 unsigned DstAlign = MI.getDestAlignment(); 5213 unsigned SrcAlign = MI.getSourceAlignment(); 5214 Type *LengthTy = MI.getLength()->getType(); 5215 unsigned ElemSz = MI.getElementSizeInBytes(); 5216 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5217 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5218 SrcAlign, Length, LengthTy, ElemSz, isTC, 5219 MachinePointerInfo(MI.getRawDest()), 5220 MachinePointerInfo(MI.getRawSource())); 5221 updateDAGForMaybeTailCall(MC); 5222 return nullptr; 5223 } 5224 case Intrinsic::memmove_element_unordered_atomic: { 5225 auto &MI = cast<AtomicMemMoveInst>(I); 5226 SDValue Dst = getValue(MI.getRawDest()); 5227 SDValue Src = getValue(MI.getRawSource()); 5228 SDValue Length = getValue(MI.getLength()); 5229 5230 unsigned DstAlign = MI.getDestAlignment(); 5231 unsigned SrcAlign = MI.getSourceAlignment(); 5232 Type *LengthTy = MI.getLength()->getType(); 5233 unsigned ElemSz = MI.getElementSizeInBytes(); 5234 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5235 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5236 SrcAlign, Length, LengthTy, ElemSz, isTC, 5237 MachinePointerInfo(MI.getRawDest()), 5238 MachinePointerInfo(MI.getRawSource())); 5239 updateDAGForMaybeTailCall(MC); 5240 return nullptr; 5241 } 5242 case Intrinsic::memset_element_unordered_atomic: { 5243 auto &MI = cast<AtomicMemSetInst>(I); 5244 SDValue Dst = getValue(MI.getRawDest()); 5245 SDValue Val = getValue(MI.getValue()); 5246 SDValue Length = getValue(MI.getLength()); 5247 5248 unsigned DstAlign = MI.getDestAlignment(); 5249 Type *LengthTy = MI.getLength()->getType(); 5250 unsigned ElemSz = MI.getElementSizeInBytes(); 5251 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5252 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5253 LengthTy, ElemSz, isTC, 5254 MachinePointerInfo(MI.getRawDest())); 5255 updateDAGForMaybeTailCall(MC); 5256 return nullptr; 5257 } 5258 case Intrinsic::dbg_addr: 5259 case Intrinsic::dbg_declare: { 5260 const auto &DI = cast<DbgVariableIntrinsic>(I); 5261 DILocalVariable *Variable = DI.getVariable(); 5262 DIExpression *Expression = DI.getExpression(); 5263 dropDanglingDebugInfo(Variable, Expression); 5264 assert(Variable && "Missing variable"); 5265 5266 // Check if address has undef value. 5267 const Value *Address = DI.getVariableLocation(); 5268 if (!Address || isa<UndefValue>(Address) || 5269 (Address->use_empty() && !isa<Argument>(Address))) { 5270 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5271 return nullptr; 5272 } 5273 5274 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5275 5276 // Check if this variable can be described by a frame index, typically 5277 // either as a static alloca or a byval parameter. 5278 int FI = std::numeric_limits<int>::max(); 5279 if (const auto *AI = 5280 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5281 if (AI->isStaticAlloca()) { 5282 auto I = FuncInfo.StaticAllocaMap.find(AI); 5283 if (I != FuncInfo.StaticAllocaMap.end()) 5284 FI = I->second; 5285 } 5286 } else if (const auto *Arg = dyn_cast<Argument>( 5287 Address->stripInBoundsConstantOffsets())) { 5288 FI = FuncInfo.getArgumentFrameIndex(Arg); 5289 } 5290 5291 // llvm.dbg.addr is control dependent and always generates indirect 5292 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5293 // the MachineFunction variable table. 5294 if (FI != std::numeric_limits<int>::max()) { 5295 if (Intrinsic == Intrinsic::dbg_addr) { 5296 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5297 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5298 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5299 } 5300 return nullptr; 5301 } 5302 5303 SDValue &N = NodeMap[Address]; 5304 if (!N.getNode() && isa<Argument>(Address)) 5305 // Check unused arguments map. 5306 N = UnusedArgNodeMap[Address]; 5307 SDDbgValue *SDV; 5308 if (N.getNode()) { 5309 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5310 Address = BCI->getOperand(0); 5311 // Parameters are handled specially. 5312 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5313 if (isParameter && FINode) { 5314 // Byval parameter. We have a frame index at this point. 5315 SDV = 5316 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5317 /*IsIndirect*/ true, dl, SDNodeOrder); 5318 } else if (isa<Argument>(Address)) { 5319 // Address is an argument, so try to emit its dbg value using 5320 // virtual register info from the FuncInfo.ValueMap. 5321 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5322 return nullptr; 5323 } else { 5324 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5325 true, dl, SDNodeOrder); 5326 } 5327 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5328 } else { 5329 // If Address is an argument then try to emit its dbg value using 5330 // virtual register info from the FuncInfo.ValueMap. 5331 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5332 N)) { 5333 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5334 } 5335 } 5336 return nullptr; 5337 } 5338 case Intrinsic::dbg_label: { 5339 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5340 DILabel *Label = DI.getLabel(); 5341 assert(Label && "Missing label"); 5342 5343 SDDbgLabel *SDV; 5344 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5345 DAG.AddDbgLabel(SDV); 5346 return nullptr; 5347 } 5348 case Intrinsic::dbg_value: { 5349 const DbgValueInst &DI = cast<DbgValueInst>(I); 5350 assert(DI.getVariable() && "Missing variable"); 5351 5352 DILocalVariable *Variable = DI.getVariable(); 5353 DIExpression *Expression = DI.getExpression(); 5354 dropDanglingDebugInfo(Variable, Expression); 5355 const Value *V = DI.getValue(); 5356 if (!V) 5357 return nullptr; 5358 5359 SDDbgValue *SDV; 5360 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5361 isa<ConstantPointerNull>(V)) { 5362 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5363 DAG.AddDbgValue(SDV, nullptr, false); 5364 return nullptr; 5365 } 5366 5367 // If the Value is a frame index, we can create a FrameIndex debug value 5368 // without relying on the DAG at all. 5369 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 5370 auto SI = FuncInfo.StaticAllocaMap.find(AI); 5371 if (SI != FuncInfo.StaticAllocaMap.end()) { 5372 auto SDV = 5373 DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 5374 /*IsIndirect*/ false, dl, SDNodeOrder); 5375 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 5376 // is still available even if the SDNode gets optimized out. 5377 DAG.AddDbgValue(SDV, nullptr, false); 5378 return nullptr; 5379 } 5380 } 5381 5382 // Do not use getValue() in here; we don't want to generate code at 5383 // this point if it hasn't been done yet. 5384 SDValue N = NodeMap[V]; 5385 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5386 N = UnusedArgNodeMap[V]; 5387 if (N.getNode()) { 5388 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5389 return nullptr; 5390 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5391 DAG.AddDbgValue(SDV, N.getNode(), false); 5392 return nullptr; 5393 } 5394 5395 // The value is not used in this block yet (or it would have an SDNode). 5396 // We still want the value to appear for the user if possible -- if it has 5397 // an associated VReg, we can refer to that instead. 5398 if (!isa<Argument>(V)) { 5399 auto VMI = FuncInfo.ValueMap.find(V); 5400 if (VMI != FuncInfo.ValueMap.end()) { 5401 unsigned Reg = VMI->second; 5402 // If this is a PHI node, it may be split up into several MI PHI nodes 5403 // (in FunctionLoweringInfo::set). 5404 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5405 V->getType(), None); 5406 if (RFV.occupiesMultipleRegs()) { 5407 unsigned Offset = 0; 5408 unsigned BitsToDescribe = 0; 5409 if (auto VarSize = Variable->getSizeInBits()) 5410 BitsToDescribe = *VarSize; 5411 if (auto Fragment = Expression->getFragmentInfo()) 5412 BitsToDescribe = Fragment->SizeInBits; 5413 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5414 unsigned RegisterSize = RegAndSize.second; 5415 // Bail out if all bits are described already. 5416 if (Offset >= BitsToDescribe) 5417 break; 5418 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5419 ? BitsToDescribe - Offset 5420 : RegisterSize; 5421 auto FragmentExpr = DIExpression::createFragmentExpression( 5422 Expression, Offset, FragmentSize); 5423 if (!FragmentExpr) 5424 continue; 5425 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5426 false, dl, SDNodeOrder); 5427 DAG.AddDbgValue(SDV, nullptr, false); 5428 Offset += RegisterSize; 5429 } 5430 } else { 5431 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5432 SDNodeOrder); 5433 DAG.AddDbgValue(SDV, nullptr, false); 5434 } 5435 return nullptr; 5436 } 5437 } 5438 5439 // TODO: When we get here we will either drop the dbg.value completely, or 5440 // we try to move it forward by letting it dangle for awhile. So we should 5441 // probably add an extra DbgValue to the DAG here, with a reference to 5442 // "noreg", to indicate that we have lost the debug location for the 5443 // variable. 5444 5445 if (!V->use_empty() ) { 5446 // Do not call getValue(V) yet, as we don't want to generate code. 5447 // Remember it for later. 5448 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5449 return nullptr; 5450 } 5451 5452 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5453 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5454 return nullptr; 5455 } 5456 5457 case Intrinsic::eh_typeid_for: { 5458 // Find the type id for the given typeinfo. 5459 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5460 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5461 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5462 setValue(&I, Res); 5463 return nullptr; 5464 } 5465 5466 case Intrinsic::eh_return_i32: 5467 case Intrinsic::eh_return_i64: 5468 DAG.getMachineFunction().setCallsEHReturn(true); 5469 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5470 MVT::Other, 5471 getControlRoot(), 5472 getValue(I.getArgOperand(0)), 5473 getValue(I.getArgOperand(1)))); 5474 return nullptr; 5475 case Intrinsic::eh_unwind_init: 5476 DAG.getMachineFunction().setCallsUnwindInit(true); 5477 return nullptr; 5478 case Intrinsic::eh_dwarf_cfa: 5479 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5480 TLI.getPointerTy(DAG.getDataLayout()), 5481 getValue(I.getArgOperand(0)))); 5482 return nullptr; 5483 case Intrinsic::eh_sjlj_callsite: { 5484 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5485 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5486 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5487 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5488 5489 MMI.setCurrentCallSite(CI->getZExtValue()); 5490 return nullptr; 5491 } 5492 case Intrinsic::eh_sjlj_functioncontext: { 5493 // Get and store the index of the function context. 5494 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5495 AllocaInst *FnCtx = 5496 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5497 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5498 MFI.setFunctionContextIndex(FI); 5499 return nullptr; 5500 } 5501 case Intrinsic::eh_sjlj_setjmp: { 5502 SDValue Ops[2]; 5503 Ops[0] = getRoot(); 5504 Ops[1] = getValue(I.getArgOperand(0)); 5505 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5506 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5507 setValue(&I, Op.getValue(0)); 5508 DAG.setRoot(Op.getValue(1)); 5509 return nullptr; 5510 } 5511 case Intrinsic::eh_sjlj_longjmp: 5512 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5513 getRoot(), getValue(I.getArgOperand(0)))); 5514 return nullptr; 5515 case Intrinsic::eh_sjlj_setup_dispatch: 5516 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5517 getRoot())); 5518 return nullptr; 5519 case Intrinsic::masked_gather: 5520 visitMaskedGather(I); 5521 return nullptr; 5522 case Intrinsic::masked_load: 5523 visitMaskedLoad(I); 5524 return nullptr; 5525 case Intrinsic::masked_scatter: 5526 visitMaskedScatter(I); 5527 return nullptr; 5528 case Intrinsic::masked_store: 5529 visitMaskedStore(I); 5530 return nullptr; 5531 case Intrinsic::masked_expandload: 5532 visitMaskedLoad(I, true /* IsExpanding */); 5533 return nullptr; 5534 case Intrinsic::masked_compressstore: 5535 visitMaskedStore(I, true /* IsCompressing */); 5536 return nullptr; 5537 case Intrinsic::x86_mmx_pslli_w: 5538 case Intrinsic::x86_mmx_pslli_d: 5539 case Intrinsic::x86_mmx_pslli_q: 5540 case Intrinsic::x86_mmx_psrli_w: 5541 case Intrinsic::x86_mmx_psrli_d: 5542 case Intrinsic::x86_mmx_psrli_q: 5543 case Intrinsic::x86_mmx_psrai_w: 5544 case Intrinsic::x86_mmx_psrai_d: { 5545 SDValue ShAmt = getValue(I.getArgOperand(1)); 5546 if (isa<ConstantSDNode>(ShAmt)) { 5547 visitTargetIntrinsic(I, Intrinsic); 5548 return nullptr; 5549 } 5550 unsigned NewIntrinsic = 0; 5551 EVT ShAmtVT = MVT::v2i32; 5552 switch (Intrinsic) { 5553 case Intrinsic::x86_mmx_pslli_w: 5554 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5555 break; 5556 case Intrinsic::x86_mmx_pslli_d: 5557 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5558 break; 5559 case Intrinsic::x86_mmx_pslli_q: 5560 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5561 break; 5562 case Intrinsic::x86_mmx_psrli_w: 5563 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5564 break; 5565 case Intrinsic::x86_mmx_psrli_d: 5566 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5567 break; 5568 case Intrinsic::x86_mmx_psrli_q: 5569 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5570 break; 5571 case Intrinsic::x86_mmx_psrai_w: 5572 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5573 break; 5574 case Intrinsic::x86_mmx_psrai_d: 5575 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5576 break; 5577 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5578 } 5579 5580 // The vector shift intrinsics with scalars uses 32b shift amounts but 5581 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5582 // to be zero. 5583 // We must do this early because v2i32 is not a legal type. 5584 SDValue ShOps[2]; 5585 ShOps[0] = ShAmt; 5586 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5587 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5588 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5589 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5590 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5591 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5592 getValue(I.getArgOperand(0)), ShAmt); 5593 setValue(&I, Res); 5594 return nullptr; 5595 } 5596 case Intrinsic::powi: 5597 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5598 getValue(I.getArgOperand(1)), DAG)); 5599 return nullptr; 5600 case Intrinsic::log: 5601 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5602 return nullptr; 5603 case Intrinsic::log2: 5604 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5605 return nullptr; 5606 case Intrinsic::log10: 5607 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5608 return nullptr; 5609 case Intrinsic::exp: 5610 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5611 return nullptr; 5612 case Intrinsic::exp2: 5613 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5614 return nullptr; 5615 case Intrinsic::pow: 5616 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5617 getValue(I.getArgOperand(1)), DAG, TLI)); 5618 return nullptr; 5619 case Intrinsic::sqrt: 5620 case Intrinsic::fabs: 5621 case Intrinsic::sin: 5622 case Intrinsic::cos: 5623 case Intrinsic::floor: 5624 case Intrinsic::ceil: 5625 case Intrinsic::trunc: 5626 case Intrinsic::rint: 5627 case Intrinsic::nearbyint: 5628 case Intrinsic::round: 5629 case Intrinsic::canonicalize: { 5630 unsigned Opcode; 5631 switch (Intrinsic) { 5632 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5633 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5634 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5635 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5636 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5637 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5638 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5639 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5640 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5641 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5642 case Intrinsic::round: Opcode = ISD::FROUND; break; 5643 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5644 } 5645 5646 setValue(&I, DAG.getNode(Opcode, sdl, 5647 getValue(I.getArgOperand(0)).getValueType(), 5648 getValue(I.getArgOperand(0)))); 5649 return nullptr; 5650 } 5651 case Intrinsic::minnum: { 5652 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5653 unsigned Opc = 5654 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5655 ? ISD::FMINIMUM 5656 : ISD::FMINNUM; 5657 setValue(&I, DAG.getNode(Opc, sdl, VT, 5658 getValue(I.getArgOperand(0)), 5659 getValue(I.getArgOperand(1)))); 5660 return nullptr; 5661 } 5662 case Intrinsic::maxnum: { 5663 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5664 unsigned Opc = 5665 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5666 ? ISD::FMAXIMUM 5667 : ISD::FMAXNUM; 5668 setValue(&I, DAG.getNode(Opc, sdl, VT, 5669 getValue(I.getArgOperand(0)), 5670 getValue(I.getArgOperand(1)))); 5671 return nullptr; 5672 } 5673 case Intrinsic::minimum: 5674 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5675 getValue(I.getArgOperand(0)).getValueType(), 5676 getValue(I.getArgOperand(0)), 5677 getValue(I.getArgOperand(1)))); 5678 return nullptr; 5679 case Intrinsic::maximum: 5680 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5681 getValue(I.getArgOperand(0)).getValueType(), 5682 getValue(I.getArgOperand(0)), 5683 getValue(I.getArgOperand(1)))); 5684 return nullptr; 5685 case Intrinsic::copysign: 5686 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5687 getValue(I.getArgOperand(0)).getValueType(), 5688 getValue(I.getArgOperand(0)), 5689 getValue(I.getArgOperand(1)))); 5690 return nullptr; 5691 case Intrinsic::fma: 5692 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5693 getValue(I.getArgOperand(0)).getValueType(), 5694 getValue(I.getArgOperand(0)), 5695 getValue(I.getArgOperand(1)), 5696 getValue(I.getArgOperand(2)))); 5697 return nullptr; 5698 case Intrinsic::experimental_constrained_fadd: 5699 case Intrinsic::experimental_constrained_fsub: 5700 case Intrinsic::experimental_constrained_fmul: 5701 case Intrinsic::experimental_constrained_fdiv: 5702 case Intrinsic::experimental_constrained_frem: 5703 case Intrinsic::experimental_constrained_fma: 5704 case Intrinsic::experimental_constrained_sqrt: 5705 case Intrinsic::experimental_constrained_pow: 5706 case Intrinsic::experimental_constrained_powi: 5707 case Intrinsic::experimental_constrained_sin: 5708 case Intrinsic::experimental_constrained_cos: 5709 case Intrinsic::experimental_constrained_exp: 5710 case Intrinsic::experimental_constrained_exp2: 5711 case Intrinsic::experimental_constrained_log: 5712 case Intrinsic::experimental_constrained_log10: 5713 case Intrinsic::experimental_constrained_log2: 5714 case Intrinsic::experimental_constrained_rint: 5715 case Intrinsic::experimental_constrained_nearbyint: 5716 case Intrinsic::experimental_constrained_maxnum: 5717 case Intrinsic::experimental_constrained_minnum: 5718 case Intrinsic::experimental_constrained_ceil: 5719 case Intrinsic::experimental_constrained_floor: 5720 case Intrinsic::experimental_constrained_round: 5721 case Intrinsic::experimental_constrained_trunc: 5722 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5723 return nullptr; 5724 case Intrinsic::fmuladd: { 5725 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5726 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5727 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5728 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5729 getValue(I.getArgOperand(0)).getValueType(), 5730 getValue(I.getArgOperand(0)), 5731 getValue(I.getArgOperand(1)), 5732 getValue(I.getArgOperand(2)))); 5733 } else { 5734 // TODO: Intrinsic calls should have fast-math-flags. 5735 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5736 getValue(I.getArgOperand(0)).getValueType(), 5737 getValue(I.getArgOperand(0)), 5738 getValue(I.getArgOperand(1))); 5739 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5740 getValue(I.getArgOperand(0)).getValueType(), 5741 Mul, 5742 getValue(I.getArgOperand(2))); 5743 setValue(&I, Add); 5744 } 5745 return nullptr; 5746 } 5747 case Intrinsic::convert_to_fp16: 5748 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5749 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5750 getValue(I.getArgOperand(0)), 5751 DAG.getTargetConstant(0, sdl, 5752 MVT::i32)))); 5753 return nullptr; 5754 case Intrinsic::convert_from_fp16: 5755 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5756 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5757 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5758 getValue(I.getArgOperand(0))))); 5759 return nullptr; 5760 case Intrinsic::pcmarker: { 5761 SDValue Tmp = getValue(I.getArgOperand(0)); 5762 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5763 return nullptr; 5764 } 5765 case Intrinsic::readcyclecounter: { 5766 SDValue Op = getRoot(); 5767 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5768 DAG.getVTList(MVT::i64, MVT::Other), Op); 5769 setValue(&I, Res); 5770 DAG.setRoot(Res.getValue(1)); 5771 return nullptr; 5772 } 5773 case Intrinsic::bitreverse: 5774 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5775 getValue(I.getArgOperand(0)).getValueType(), 5776 getValue(I.getArgOperand(0)))); 5777 return nullptr; 5778 case Intrinsic::bswap: 5779 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5780 getValue(I.getArgOperand(0)).getValueType(), 5781 getValue(I.getArgOperand(0)))); 5782 return nullptr; 5783 case Intrinsic::cttz: { 5784 SDValue Arg = getValue(I.getArgOperand(0)); 5785 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5786 EVT Ty = Arg.getValueType(); 5787 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5788 sdl, Ty, Arg)); 5789 return nullptr; 5790 } 5791 case Intrinsic::ctlz: { 5792 SDValue Arg = getValue(I.getArgOperand(0)); 5793 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5794 EVT Ty = Arg.getValueType(); 5795 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5796 sdl, Ty, Arg)); 5797 return nullptr; 5798 } 5799 case Intrinsic::ctpop: { 5800 SDValue Arg = getValue(I.getArgOperand(0)); 5801 EVT Ty = Arg.getValueType(); 5802 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5803 return nullptr; 5804 } 5805 case Intrinsic::fshl: 5806 case Intrinsic::fshr: { 5807 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5808 SDValue X = getValue(I.getArgOperand(0)); 5809 SDValue Y = getValue(I.getArgOperand(1)); 5810 SDValue Z = getValue(I.getArgOperand(2)); 5811 EVT VT = X.getValueType(); 5812 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5813 SDValue Zero = DAG.getConstant(0, sdl, VT); 5814 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5815 5816 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5817 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5818 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5819 return nullptr; 5820 } 5821 5822 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5823 // avoid the select that is necessary in the general case to filter out 5824 // the 0-shift possibility that leads to UB. 5825 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5826 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5827 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5828 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5829 return nullptr; 5830 } 5831 5832 // Some targets only rotate one way. Try the opposite direction. 5833 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5834 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5835 // Negate the shift amount because it is safe to ignore the high bits. 5836 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5837 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5838 return nullptr; 5839 } 5840 5841 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5842 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5843 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5844 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5845 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5846 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5847 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5848 return nullptr; 5849 } 5850 5851 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5852 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5853 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5854 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5855 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5856 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5857 5858 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5859 // and that is undefined. We must compare and select to avoid UB. 5860 EVT CCVT = MVT::i1; 5861 if (VT.isVector()) 5862 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5863 5864 // For fshl, 0-shift returns the 1st arg (X). 5865 // For fshr, 0-shift returns the 2nd arg (Y). 5866 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5867 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5868 return nullptr; 5869 } 5870 case Intrinsic::sadd_sat: { 5871 SDValue Op1 = getValue(I.getArgOperand(0)); 5872 SDValue Op2 = getValue(I.getArgOperand(1)); 5873 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5874 return nullptr; 5875 } 5876 case Intrinsic::uadd_sat: { 5877 SDValue Op1 = getValue(I.getArgOperand(0)); 5878 SDValue Op2 = getValue(I.getArgOperand(1)); 5879 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5880 return nullptr; 5881 } 5882 case Intrinsic::ssub_sat: { 5883 SDValue Op1 = getValue(I.getArgOperand(0)); 5884 SDValue Op2 = getValue(I.getArgOperand(1)); 5885 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5886 return nullptr; 5887 } 5888 case Intrinsic::usub_sat: { 5889 SDValue Op1 = getValue(I.getArgOperand(0)); 5890 SDValue Op2 = getValue(I.getArgOperand(1)); 5891 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5892 return nullptr; 5893 } 5894 case Intrinsic::smul_fix: 5895 case Intrinsic::umul_fix: { 5896 SDValue Op1 = getValue(I.getArgOperand(0)); 5897 SDValue Op2 = getValue(I.getArgOperand(1)); 5898 SDValue Op3 = getValue(I.getArgOperand(2)); 5899 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 5900 Op1.getValueType(), Op1, Op2, Op3)); 5901 return nullptr; 5902 } 5903 case Intrinsic::stacksave: { 5904 SDValue Op = getRoot(); 5905 Res = DAG.getNode( 5906 ISD::STACKSAVE, sdl, 5907 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5908 setValue(&I, Res); 5909 DAG.setRoot(Res.getValue(1)); 5910 return nullptr; 5911 } 5912 case Intrinsic::stackrestore: 5913 Res = getValue(I.getArgOperand(0)); 5914 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5915 return nullptr; 5916 case Intrinsic::get_dynamic_area_offset: { 5917 SDValue Op = getRoot(); 5918 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5919 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5920 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5921 // target. 5922 if (PtrTy != ResTy) 5923 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5924 " intrinsic!"); 5925 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5926 Op); 5927 DAG.setRoot(Op); 5928 setValue(&I, Res); 5929 return nullptr; 5930 } 5931 case Intrinsic::stackguard: { 5932 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5933 MachineFunction &MF = DAG.getMachineFunction(); 5934 const Module &M = *MF.getFunction().getParent(); 5935 SDValue Chain = getRoot(); 5936 if (TLI.useLoadStackGuardNode()) { 5937 Res = getLoadStackGuard(DAG, sdl, Chain); 5938 } else { 5939 const Value *Global = TLI.getSDagStackGuard(M); 5940 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5941 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5942 MachinePointerInfo(Global, 0), Align, 5943 MachineMemOperand::MOVolatile); 5944 } 5945 if (TLI.useStackGuardXorFP()) 5946 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5947 DAG.setRoot(Chain); 5948 setValue(&I, Res); 5949 return nullptr; 5950 } 5951 case Intrinsic::stackprotector: { 5952 // Emit code into the DAG to store the stack guard onto the stack. 5953 MachineFunction &MF = DAG.getMachineFunction(); 5954 MachineFrameInfo &MFI = MF.getFrameInfo(); 5955 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5956 SDValue Src, Chain = getRoot(); 5957 5958 if (TLI.useLoadStackGuardNode()) 5959 Src = getLoadStackGuard(DAG, sdl, Chain); 5960 else 5961 Src = getValue(I.getArgOperand(0)); // The guard's value. 5962 5963 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5964 5965 int FI = FuncInfo.StaticAllocaMap[Slot]; 5966 MFI.setStackProtectorIndex(FI); 5967 5968 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5969 5970 // Store the stack protector onto the stack. 5971 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5972 DAG.getMachineFunction(), FI), 5973 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5974 setValue(&I, Res); 5975 DAG.setRoot(Res); 5976 return nullptr; 5977 } 5978 case Intrinsic::objectsize: { 5979 // If we don't know by now, we're never going to know. 5980 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5981 5982 assert(CI && "Non-constant type in __builtin_object_size?"); 5983 5984 SDValue Arg = getValue(I.getCalledValue()); 5985 EVT Ty = Arg.getValueType(); 5986 5987 if (CI->isZero()) 5988 Res = DAG.getConstant(-1ULL, sdl, Ty); 5989 else 5990 Res = DAG.getConstant(0, sdl, Ty); 5991 5992 setValue(&I, Res); 5993 return nullptr; 5994 } 5995 5996 case Intrinsic::is_constant: 5997 // If this wasn't constant-folded away by now, then it's not a 5998 // constant. 5999 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6000 return nullptr; 6001 6002 case Intrinsic::annotation: 6003 case Intrinsic::ptr_annotation: 6004 case Intrinsic::launder_invariant_group: 6005 case Intrinsic::strip_invariant_group: 6006 // Drop the intrinsic, but forward the value 6007 setValue(&I, getValue(I.getOperand(0))); 6008 return nullptr; 6009 case Intrinsic::assume: 6010 case Intrinsic::var_annotation: 6011 case Intrinsic::sideeffect: 6012 // Discard annotate attributes, assumptions, and artificial side-effects. 6013 return nullptr; 6014 6015 case Intrinsic::codeview_annotation: { 6016 // Emit a label associated with this metadata. 6017 MachineFunction &MF = DAG.getMachineFunction(); 6018 MCSymbol *Label = 6019 MF.getMMI().getContext().createTempSymbol("annotation", true); 6020 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6021 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6022 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6023 DAG.setRoot(Res); 6024 return nullptr; 6025 } 6026 6027 case Intrinsic::init_trampoline: { 6028 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6029 6030 SDValue Ops[6]; 6031 Ops[0] = getRoot(); 6032 Ops[1] = getValue(I.getArgOperand(0)); 6033 Ops[2] = getValue(I.getArgOperand(1)); 6034 Ops[3] = getValue(I.getArgOperand(2)); 6035 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6036 Ops[5] = DAG.getSrcValue(F); 6037 6038 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6039 6040 DAG.setRoot(Res); 6041 return nullptr; 6042 } 6043 case Intrinsic::adjust_trampoline: 6044 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6045 TLI.getPointerTy(DAG.getDataLayout()), 6046 getValue(I.getArgOperand(0)))); 6047 return nullptr; 6048 case Intrinsic::gcroot: { 6049 assert(DAG.getMachineFunction().getFunction().hasGC() && 6050 "only valid in functions with gc specified, enforced by Verifier"); 6051 assert(GFI && "implied by previous"); 6052 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6053 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6054 6055 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6056 GFI->addStackRoot(FI->getIndex(), TypeMap); 6057 return nullptr; 6058 } 6059 case Intrinsic::gcread: 6060 case Intrinsic::gcwrite: 6061 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6062 case Intrinsic::flt_rounds: 6063 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6064 return nullptr; 6065 6066 case Intrinsic::expect: 6067 // Just replace __builtin_expect(exp, c) with EXP. 6068 setValue(&I, getValue(I.getArgOperand(0))); 6069 return nullptr; 6070 6071 case Intrinsic::debugtrap: 6072 case Intrinsic::trap: { 6073 StringRef TrapFuncName = 6074 I.getAttributes() 6075 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6076 .getValueAsString(); 6077 if (TrapFuncName.empty()) { 6078 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6079 ISD::TRAP : ISD::DEBUGTRAP; 6080 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6081 return nullptr; 6082 } 6083 TargetLowering::ArgListTy Args; 6084 6085 TargetLowering::CallLoweringInfo CLI(DAG); 6086 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6087 CallingConv::C, I.getType(), 6088 DAG.getExternalSymbol(TrapFuncName.data(), 6089 TLI.getPointerTy(DAG.getDataLayout())), 6090 std::move(Args)); 6091 6092 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6093 DAG.setRoot(Result.second); 6094 return nullptr; 6095 } 6096 6097 case Intrinsic::uadd_with_overflow: 6098 case Intrinsic::sadd_with_overflow: 6099 case Intrinsic::usub_with_overflow: 6100 case Intrinsic::ssub_with_overflow: 6101 case Intrinsic::umul_with_overflow: 6102 case Intrinsic::smul_with_overflow: { 6103 ISD::NodeType Op; 6104 switch (Intrinsic) { 6105 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6106 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6107 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6108 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6109 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6110 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6111 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6112 } 6113 SDValue Op1 = getValue(I.getArgOperand(0)); 6114 SDValue Op2 = getValue(I.getArgOperand(1)); 6115 6116 EVT ResultVT = Op1.getValueType(); 6117 EVT OverflowVT = MVT::i1; 6118 if (ResultVT.isVector()) 6119 OverflowVT = EVT::getVectorVT( 6120 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6121 6122 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6123 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6124 return nullptr; 6125 } 6126 case Intrinsic::prefetch: { 6127 SDValue Ops[5]; 6128 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6129 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6130 Ops[0] = DAG.getRoot(); 6131 Ops[1] = getValue(I.getArgOperand(0)); 6132 Ops[2] = getValue(I.getArgOperand(1)); 6133 Ops[3] = getValue(I.getArgOperand(2)); 6134 Ops[4] = getValue(I.getArgOperand(3)); 6135 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6136 DAG.getVTList(MVT::Other), Ops, 6137 EVT::getIntegerVT(*Context, 8), 6138 MachinePointerInfo(I.getArgOperand(0)), 6139 0, /* align */ 6140 Flags); 6141 6142 // Chain the prefetch in parallell with any pending loads, to stay out of 6143 // the way of later optimizations. 6144 PendingLoads.push_back(Result); 6145 Result = getRoot(); 6146 DAG.setRoot(Result); 6147 return nullptr; 6148 } 6149 case Intrinsic::lifetime_start: 6150 case Intrinsic::lifetime_end: { 6151 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6152 // Stack coloring is not enabled in O0, discard region information. 6153 if (TM.getOptLevel() == CodeGenOpt::None) 6154 return nullptr; 6155 6156 SmallVector<Value *, 4> Allocas; 6157 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6158 6159 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6160 E = Allocas.end(); Object != E; ++Object) { 6161 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6162 6163 // Could not find an Alloca. 6164 if (!LifetimeObject) 6165 continue; 6166 6167 // First check that the Alloca is static, otherwise it won't have a 6168 // valid frame index. 6169 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6170 if (SI == FuncInfo.StaticAllocaMap.end()) 6171 return nullptr; 6172 6173 int FI = SI->second; 6174 6175 SDValue Ops[2]; 6176 Ops[0] = getRoot(); 6177 Ops[1] = 6178 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6179 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6180 6181 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6182 DAG.setRoot(Res); 6183 } 6184 return nullptr; 6185 } 6186 case Intrinsic::invariant_start: 6187 // Discard region information. 6188 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6189 return nullptr; 6190 case Intrinsic::invariant_end: 6191 // Discard region information. 6192 return nullptr; 6193 case Intrinsic::clear_cache: 6194 return TLI.getClearCacheBuiltinName(); 6195 case Intrinsic::donothing: 6196 // ignore 6197 return nullptr; 6198 case Intrinsic::experimental_stackmap: 6199 visitStackmap(I); 6200 return nullptr; 6201 case Intrinsic::experimental_patchpoint_void: 6202 case Intrinsic::experimental_patchpoint_i64: 6203 visitPatchpoint(&I); 6204 return nullptr; 6205 case Intrinsic::experimental_gc_statepoint: 6206 LowerStatepoint(ImmutableStatepoint(&I)); 6207 return nullptr; 6208 case Intrinsic::experimental_gc_result: 6209 visitGCResult(cast<GCResultInst>(I)); 6210 return nullptr; 6211 case Intrinsic::experimental_gc_relocate: 6212 visitGCRelocate(cast<GCRelocateInst>(I)); 6213 return nullptr; 6214 case Intrinsic::instrprof_increment: 6215 llvm_unreachable("instrprof failed to lower an increment"); 6216 case Intrinsic::instrprof_value_profile: 6217 llvm_unreachable("instrprof failed to lower a value profiling call"); 6218 case Intrinsic::localescape: { 6219 MachineFunction &MF = DAG.getMachineFunction(); 6220 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6221 6222 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6223 // is the same on all targets. 6224 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6225 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6226 if (isa<ConstantPointerNull>(Arg)) 6227 continue; // Skip null pointers. They represent a hole in index space. 6228 AllocaInst *Slot = cast<AllocaInst>(Arg); 6229 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6230 "can only escape static allocas"); 6231 int FI = FuncInfo.StaticAllocaMap[Slot]; 6232 MCSymbol *FrameAllocSym = 6233 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6234 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6235 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6236 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6237 .addSym(FrameAllocSym) 6238 .addFrameIndex(FI); 6239 } 6240 6241 return nullptr; 6242 } 6243 6244 case Intrinsic::localrecover: { 6245 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6246 MachineFunction &MF = DAG.getMachineFunction(); 6247 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6248 6249 // Get the symbol that defines the frame offset. 6250 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6251 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6252 unsigned IdxVal = 6253 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6254 MCSymbol *FrameAllocSym = 6255 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6256 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6257 6258 // Create a MCSymbol for the label to avoid any target lowering 6259 // that would make this PC relative. 6260 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6261 SDValue OffsetVal = 6262 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6263 6264 // Add the offset to the FP. 6265 Value *FP = I.getArgOperand(1); 6266 SDValue FPVal = getValue(FP); 6267 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6268 setValue(&I, Add); 6269 6270 return nullptr; 6271 } 6272 6273 case Intrinsic::eh_exceptionpointer: 6274 case Intrinsic::eh_exceptioncode: { 6275 // Get the exception pointer vreg, copy from it, and resize it to fit. 6276 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6277 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6278 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6279 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6280 SDValue N = 6281 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6282 if (Intrinsic == Intrinsic::eh_exceptioncode) 6283 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6284 setValue(&I, N); 6285 return nullptr; 6286 } 6287 case Intrinsic::xray_customevent: { 6288 // Here we want to make sure that the intrinsic behaves as if it has a 6289 // specific calling convention, and only for x86_64. 6290 // FIXME: Support other platforms later. 6291 const auto &Triple = DAG.getTarget().getTargetTriple(); 6292 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6293 return nullptr; 6294 6295 SDLoc DL = getCurSDLoc(); 6296 SmallVector<SDValue, 8> Ops; 6297 6298 // We want to say that we always want the arguments in registers. 6299 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6300 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6301 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6302 SDValue Chain = getRoot(); 6303 Ops.push_back(LogEntryVal); 6304 Ops.push_back(StrSizeVal); 6305 Ops.push_back(Chain); 6306 6307 // We need to enforce the calling convention for the callsite, so that 6308 // argument ordering is enforced correctly, and that register allocation can 6309 // see that some registers may be assumed clobbered and have to preserve 6310 // them across calls to the intrinsic. 6311 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6312 DL, NodeTys, Ops); 6313 SDValue patchableNode = SDValue(MN, 0); 6314 DAG.setRoot(patchableNode); 6315 setValue(&I, patchableNode); 6316 return nullptr; 6317 } 6318 case Intrinsic::xray_typedevent: { 6319 // Here we want to make sure that the intrinsic behaves as if it has a 6320 // specific calling convention, and only for x86_64. 6321 // FIXME: Support other platforms later. 6322 const auto &Triple = DAG.getTarget().getTargetTriple(); 6323 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6324 return nullptr; 6325 6326 SDLoc DL = getCurSDLoc(); 6327 SmallVector<SDValue, 8> Ops; 6328 6329 // We want to say that we always want the arguments in registers. 6330 // It's unclear to me how manipulating the selection DAG here forces callers 6331 // to provide arguments in registers instead of on the stack. 6332 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6333 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6334 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6335 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6336 SDValue Chain = getRoot(); 6337 Ops.push_back(LogTypeId); 6338 Ops.push_back(LogEntryVal); 6339 Ops.push_back(StrSizeVal); 6340 Ops.push_back(Chain); 6341 6342 // We need to enforce the calling convention for the callsite, so that 6343 // argument ordering is enforced correctly, and that register allocation can 6344 // see that some registers may be assumed clobbered and have to preserve 6345 // them across calls to the intrinsic. 6346 MachineSDNode *MN = DAG.getMachineNode( 6347 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6348 SDValue patchableNode = SDValue(MN, 0); 6349 DAG.setRoot(patchableNode); 6350 setValue(&I, patchableNode); 6351 return nullptr; 6352 } 6353 case Intrinsic::experimental_deoptimize: 6354 LowerDeoptimizeCall(&I); 6355 return nullptr; 6356 6357 case Intrinsic::experimental_vector_reduce_fadd: 6358 case Intrinsic::experimental_vector_reduce_fmul: 6359 case Intrinsic::experimental_vector_reduce_add: 6360 case Intrinsic::experimental_vector_reduce_mul: 6361 case Intrinsic::experimental_vector_reduce_and: 6362 case Intrinsic::experimental_vector_reduce_or: 6363 case Intrinsic::experimental_vector_reduce_xor: 6364 case Intrinsic::experimental_vector_reduce_smax: 6365 case Intrinsic::experimental_vector_reduce_smin: 6366 case Intrinsic::experimental_vector_reduce_umax: 6367 case Intrinsic::experimental_vector_reduce_umin: 6368 case Intrinsic::experimental_vector_reduce_fmax: 6369 case Intrinsic::experimental_vector_reduce_fmin: 6370 visitVectorReduce(I, Intrinsic); 6371 return nullptr; 6372 6373 case Intrinsic::icall_branch_funnel: { 6374 SmallVector<SDValue, 16> Ops; 6375 Ops.push_back(DAG.getRoot()); 6376 Ops.push_back(getValue(I.getArgOperand(0))); 6377 6378 int64_t Offset; 6379 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6380 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6381 if (!Base) 6382 report_fatal_error( 6383 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6384 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6385 6386 struct BranchFunnelTarget { 6387 int64_t Offset; 6388 SDValue Target; 6389 }; 6390 SmallVector<BranchFunnelTarget, 8> Targets; 6391 6392 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6393 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6394 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6395 if (ElemBase != Base) 6396 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6397 "to the same GlobalValue"); 6398 6399 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6400 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6401 if (!GA) 6402 report_fatal_error( 6403 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6404 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6405 GA->getGlobal(), getCurSDLoc(), 6406 Val.getValueType(), GA->getOffset())}); 6407 } 6408 llvm::sort(Targets, 6409 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6410 return T1.Offset < T2.Offset; 6411 }); 6412 6413 for (auto &T : Targets) { 6414 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6415 Ops.push_back(T.Target); 6416 } 6417 6418 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6419 getCurSDLoc(), MVT::Other, Ops), 6420 0); 6421 DAG.setRoot(N); 6422 setValue(&I, N); 6423 HasTailCall = true; 6424 return nullptr; 6425 } 6426 6427 case Intrinsic::wasm_landingpad_index: 6428 // Information this intrinsic contained has been transferred to 6429 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6430 // delete it now. 6431 return nullptr; 6432 } 6433 } 6434 6435 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6436 const ConstrainedFPIntrinsic &FPI) { 6437 SDLoc sdl = getCurSDLoc(); 6438 unsigned Opcode; 6439 switch (FPI.getIntrinsicID()) { 6440 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6441 case Intrinsic::experimental_constrained_fadd: 6442 Opcode = ISD::STRICT_FADD; 6443 break; 6444 case Intrinsic::experimental_constrained_fsub: 6445 Opcode = ISD::STRICT_FSUB; 6446 break; 6447 case Intrinsic::experimental_constrained_fmul: 6448 Opcode = ISD::STRICT_FMUL; 6449 break; 6450 case Intrinsic::experimental_constrained_fdiv: 6451 Opcode = ISD::STRICT_FDIV; 6452 break; 6453 case Intrinsic::experimental_constrained_frem: 6454 Opcode = ISD::STRICT_FREM; 6455 break; 6456 case Intrinsic::experimental_constrained_fma: 6457 Opcode = ISD::STRICT_FMA; 6458 break; 6459 case Intrinsic::experimental_constrained_sqrt: 6460 Opcode = ISD::STRICT_FSQRT; 6461 break; 6462 case Intrinsic::experimental_constrained_pow: 6463 Opcode = ISD::STRICT_FPOW; 6464 break; 6465 case Intrinsic::experimental_constrained_powi: 6466 Opcode = ISD::STRICT_FPOWI; 6467 break; 6468 case Intrinsic::experimental_constrained_sin: 6469 Opcode = ISD::STRICT_FSIN; 6470 break; 6471 case Intrinsic::experimental_constrained_cos: 6472 Opcode = ISD::STRICT_FCOS; 6473 break; 6474 case Intrinsic::experimental_constrained_exp: 6475 Opcode = ISD::STRICT_FEXP; 6476 break; 6477 case Intrinsic::experimental_constrained_exp2: 6478 Opcode = ISD::STRICT_FEXP2; 6479 break; 6480 case Intrinsic::experimental_constrained_log: 6481 Opcode = ISD::STRICT_FLOG; 6482 break; 6483 case Intrinsic::experimental_constrained_log10: 6484 Opcode = ISD::STRICT_FLOG10; 6485 break; 6486 case Intrinsic::experimental_constrained_log2: 6487 Opcode = ISD::STRICT_FLOG2; 6488 break; 6489 case Intrinsic::experimental_constrained_rint: 6490 Opcode = ISD::STRICT_FRINT; 6491 break; 6492 case Intrinsic::experimental_constrained_nearbyint: 6493 Opcode = ISD::STRICT_FNEARBYINT; 6494 break; 6495 case Intrinsic::experimental_constrained_maxnum: 6496 Opcode = ISD::STRICT_FMAXNUM; 6497 break; 6498 case Intrinsic::experimental_constrained_minnum: 6499 Opcode = ISD::STRICT_FMINNUM; 6500 break; 6501 case Intrinsic::experimental_constrained_ceil: 6502 Opcode = ISD::STRICT_FCEIL; 6503 break; 6504 case Intrinsic::experimental_constrained_floor: 6505 Opcode = ISD::STRICT_FFLOOR; 6506 break; 6507 case Intrinsic::experimental_constrained_round: 6508 Opcode = ISD::STRICT_FROUND; 6509 break; 6510 case Intrinsic::experimental_constrained_trunc: 6511 Opcode = ISD::STRICT_FTRUNC; 6512 break; 6513 } 6514 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6515 SDValue Chain = getRoot(); 6516 SmallVector<EVT, 4> ValueVTs; 6517 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6518 ValueVTs.push_back(MVT::Other); // Out chain 6519 6520 SDVTList VTs = DAG.getVTList(ValueVTs); 6521 SDValue Result; 6522 if (FPI.isUnaryOp()) 6523 Result = DAG.getNode(Opcode, sdl, VTs, 6524 { Chain, getValue(FPI.getArgOperand(0)) }); 6525 else if (FPI.isTernaryOp()) 6526 Result = DAG.getNode(Opcode, sdl, VTs, 6527 { Chain, getValue(FPI.getArgOperand(0)), 6528 getValue(FPI.getArgOperand(1)), 6529 getValue(FPI.getArgOperand(2)) }); 6530 else 6531 Result = DAG.getNode(Opcode, sdl, VTs, 6532 { Chain, getValue(FPI.getArgOperand(0)), 6533 getValue(FPI.getArgOperand(1)) }); 6534 6535 assert(Result.getNode()->getNumValues() == 2); 6536 SDValue OutChain = Result.getValue(1); 6537 DAG.setRoot(OutChain); 6538 SDValue FPResult = Result.getValue(0); 6539 setValue(&FPI, FPResult); 6540 } 6541 6542 std::pair<SDValue, SDValue> 6543 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6544 const BasicBlock *EHPadBB) { 6545 MachineFunction &MF = DAG.getMachineFunction(); 6546 MachineModuleInfo &MMI = MF.getMMI(); 6547 MCSymbol *BeginLabel = nullptr; 6548 6549 if (EHPadBB) { 6550 // Insert a label before the invoke call to mark the try range. This can be 6551 // used to detect deletion of the invoke via the MachineModuleInfo. 6552 BeginLabel = MMI.getContext().createTempSymbol(); 6553 6554 // For SjLj, keep track of which landing pads go with which invokes 6555 // so as to maintain the ordering of pads in the LSDA. 6556 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6557 if (CallSiteIndex) { 6558 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6559 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6560 6561 // Now that the call site is handled, stop tracking it. 6562 MMI.setCurrentCallSite(0); 6563 } 6564 6565 // Both PendingLoads and PendingExports must be flushed here; 6566 // this call might not return. 6567 (void)getRoot(); 6568 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6569 6570 CLI.setChain(getRoot()); 6571 } 6572 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6573 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6574 6575 assert((CLI.IsTailCall || Result.second.getNode()) && 6576 "Non-null chain expected with non-tail call!"); 6577 assert((Result.second.getNode() || !Result.first.getNode()) && 6578 "Null value expected with tail call!"); 6579 6580 if (!Result.second.getNode()) { 6581 // As a special case, a null chain means that a tail call has been emitted 6582 // and the DAG root is already updated. 6583 HasTailCall = true; 6584 6585 // Since there's no actual continuation from this block, nothing can be 6586 // relying on us setting vregs for them. 6587 PendingExports.clear(); 6588 } else { 6589 DAG.setRoot(Result.second); 6590 } 6591 6592 if (EHPadBB) { 6593 // Insert a label at the end of the invoke call to mark the try range. This 6594 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6595 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6596 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6597 6598 // Inform MachineModuleInfo of range. 6599 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6600 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6601 // actually use outlined funclets and their LSDA info style. 6602 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6603 assert(CLI.CS); 6604 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6605 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6606 BeginLabel, EndLabel); 6607 } else if (!isScopedEHPersonality(Pers)) { 6608 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6609 } 6610 } 6611 6612 return Result; 6613 } 6614 6615 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6616 bool isTailCall, 6617 const BasicBlock *EHPadBB) { 6618 auto &DL = DAG.getDataLayout(); 6619 FunctionType *FTy = CS.getFunctionType(); 6620 Type *RetTy = CS.getType(); 6621 6622 TargetLowering::ArgListTy Args; 6623 Args.reserve(CS.arg_size()); 6624 6625 const Value *SwiftErrorVal = nullptr; 6626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6627 6628 // We can't tail call inside a function with a swifterror argument. Lowering 6629 // does not support this yet. It would have to move into the swifterror 6630 // register before the call. 6631 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6632 if (TLI.supportSwiftError() && 6633 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6634 isTailCall = false; 6635 6636 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6637 i != e; ++i) { 6638 TargetLowering::ArgListEntry Entry; 6639 const Value *V = *i; 6640 6641 // Skip empty types 6642 if (V->getType()->isEmptyTy()) 6643 continue; 6644 6645 SDValue ArgNode = getValue(V); 6646 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6647 6648 Entry.setAttributes(&CS, i - CS.arg_begin()); 6649 6650 // Use swifterror virtual register as input to the call. 6651 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6652 SwiftErrorVal = V; 6653 // We find the virtual register for the actual swifterror argument. 6654 // Instead of using the Value, we use the virtual register instead. 6655 Entry.Node = DAG.getRegister(FuncInfo 6656 .getOrCreateSwiftErrorVRegUseAt( 6657 CS.getInstruction(), FuncInfo.MBB, V) 6658 .first, 6659 EVT(TLI.getPointerTy(DL))); 6660 } 6661 6662 Args.push_back(Entry); 6663 6664 // If we have an explicit sret argument that is an Instruction, (i.e., it 6665 // might point to function-local memory), we can't meaningfully tail-call. 6666 if (Entry.IsSRet && isa<Instruction>(V)) 6667 isTailCall = false; 6668 } 6669 6670 // Check if target-independent constraints permit a tail call here. 6671 // Target-dependent constraints are checked within TLI->LowerCallTo. 6672 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6673 isTailCall = false; 6674 6675 // Disable tail calls if there is an swifterror argument. Targets have not 6676 // been updated to support tail calls. 6677 if (TLI.supportSwiftError() && SwiftErrorVal) 6678 isTailCall = false; 6679 6680 TargetLowering::CallLoweringInfo CLI(DAG); 6681 CLI.setDebugLoc(getCurSDLoc()) 6682 .setChain(getRoot()) 6683 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6684 .setTailCall(isTailCall) 6685 .setConvergent(CS.isConvergent()); 6686 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6687 6688 if (Result.first.getNode()) { 6689 const Instruction *Inst = CS.getInstruction(); 6690 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6691 setValue(Inst, Result.first); 6692 } 6693 6694 // The last element of CLI.InVals has the SDValue for swifterror return. 6695 // Here we copy it to a virtual register and update SwiftErrorMap for 6696 // book-keeping. 6697 if (SwiftErrorVal && TLI.supportSwiftError()) { 6698 // Get the last element of InVals. 6699 SDValue Src = CLI.InVals.back(); 6700 unsigned VReg; bool CreatedVReg; 6701 std::tie(VReg, CreatedVReg) = 6702 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6703 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6704 // We update the virtual register for the actual swifterror argument. 6705 if (CreatedVReg) 6706 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6707 DAG.setRoot(CopyNode); 6708 } 6709 } 6710 6711 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6712 SelectionDAGBuilder &Builder) { 6713 // Check to see if this load can be trivially constant folded, e.g. if the 6714 // input is from a string literal. 6715 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6716 // Cast pointer to the type we really want to load. 6717 Type *LoadTy = 6718 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6719 if (LoadVT.isVector()) 6720 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6721 6722 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6723 PointerType::getUnqual(LoadTy)); 6724 6725 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6726 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6727 return Builder.getValue(LoadCst); 6728 } 6729 6730 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6731 // still constant memory, the input chain can be the entry node. 6732 SDValue Root; 6733 bool ConstantMemory = false; 6734 6735 // Do not serialize (non-volatile) loads of constant memory with anything. 6736 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6737 Root = Builder.DAG.getEntryNode(); 6738 ConstantMemory = true; 6739 } else { 6740 // Do not serialize non-volatile loads against each other. 6741 Root = Builder.DAG.getRoot(); 6742 } 6743 6744 SDValue Ptr = Builder.getValue(PtrVal); 6745 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6746 Ptr, MachinePointerInfo(PtrVal), 6747 /* Alignment = */ 1); 6748 6749 if (!ConstantMemory) 6750 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6751 return LoadVal; 6752 } 6753 6754 /// Record the value for an instruction that produces an integer result, 6755 /// converting the type where necessary. 6756 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6757 SDValue Value, 6758 bool IsSigned) { 6759 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6760 I.getType(), true); 6761 if (IsSigned) 6762 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6763 else 6764 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6765 setValue(&I, Value); 6766 } 6767 6768 /// See if we can lower a memcmp call into an optimized form. If so, return 6769 /// true and lower it. Otherwise return false, and it will be lowered like a 6770 /// normal call. 6771 /// The caller already checked that \p I calls the appropriate LibFunc with a 6772 /// correct prototype. 6773 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6774 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6775 const Value *Size = I.getArgOperand(2); 6776 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6777 if (CSize && CSize->getZExtValue() == 0) { 6778 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6779 I.getType(), true); 6780 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6781 return true; 6782 } 6783 6784 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6785 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6786 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6787 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6788 if (Res.first.getNode()) { 6789 processIntegerCallValue(I, Res.first, true); 6790 PendingLoads.push_back(Res.second); 6791 return true; 6792 } 6793 6794 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6795 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6796 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6797 return false; 6798 6799 // If the target has a fast compare for the given size, it will return a 6800 // preferred load type for that size. Require that the load VT is legal and 6801 // that the target supports unaligned loads of that type. Otherwise, return 6802 // INVALID. 6803 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6804 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6805 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6806 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6807 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6808 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6809 // TODO: Check alignment of src and dest ptrs. 6810 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6811 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6812 if (!TLI.isTypeLegal(LVT) || 6813 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6814 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6815 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6816 } 6817 6818 return LVT; 6819 }; 6820 6821 // This turns into unaligned loads. We only do this if the target natively 6822 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6823 // we'll only produce a small number of byte loads. 6824 MVT LoadVT; 6825 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6826 switch (NumBitsToCompare) { 6827 default: 6828 return false; 6829 case 16: 6830 LoadVT = MVT::i16; 6831 break; 6832 case 32: 6833 LoadVT = MVT::i32; 6834 break; 6835 case 64: 6836 case 128: 6837 case 256: 6838 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6839 break; 6840 } 6841 6842 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6843 return false; 6844 6845 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6846 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6847 6848 // Bitcast to a wide integer type if the loads are vectors. 6849 if (LoadVT.isVector()) { 6850 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6851 LoadL = DAG.getBitcast(CmpVT, LoadL); 6852 LoadR = DAG.getBitcast(CmpVT, LoadR); 6853 } 6854 6855 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6856 processIntegerCallValue(I, Cmp, false); 6857 return true; 6858 } 6859 6860 /// See if we can lower a memchr call into an optimized form. If so, return 6861 /// true and lower it. Otherwise return false, and it will be lowered like a 6862 /// normal call. 6863 /// The caller already checked that \p I calls the appropriate LibFunc with a 6864 /// correct prototype. 6865 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6866 const Value *Src = I.getArgOperand(0); 6867 const Value *Char = I.getArgOperand(1); 6868 const Value *Length = I.getArgOperand(2); 6869 6870 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6871 std::pair<SDValue, SDValue> Res = 6872 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6873 getValue(Src), getValue(Char), getValue(Length), 6874 MachinePointerInfo(Src)); 6875 if (Res.first.getNode()) { 6876 setValue(&I, Res.first); 6877 PendingLoads.push_back(Res.second); 6878 return true; 6879 } 6880 6881 return false; 6882 } 6883 6884 /// See if we can lower a mempcpy call into an optimized form. If so, return 6885 /// true and lower it. Otherwise return false, and it will be lowered like a 6886 /// normal call. 6887 /// The caller already checked that \p I calls the appropriate LibFunc with a 6888 /// correct prototype. 6889 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6890 SDValue Dst = getValue(I.getArgOperand(0)); 6891 SDValue Src = getValue(I.getArgOperand(1)); 6892 SDValue Size = getValue(I.getArgOperand(2)); 6893 6894 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6895 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6896 unsigned Align = std::min(DstAlign, SrcAlign); 6897 if (Align == 0) // Alignment of one or both could not be inferred. 6898 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6899 6900 bool isVol = false; 6901 SDLoc sdl = getCurSDLoc(); 6902 6903 // In the mempcpy context we need to pass in a false value for isTailCall 6904 // because the return pointer needs to be adjusted by the size of 6905 // the copied memory. 6906 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6907 false, /*isTailCall=*/false, 6908 MachinePointerInfo(I.getArgOperand(0)), 6909 MachinePointerInfo(I.getArgOperand(1))); 6910 assert(MC.getNode() != nullptr && 6911 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6912 DAG.setRoot(MC); 6913 6914 // Check if Size needs to be truncated or extended. 6915 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6916 6917 // Adjust return pointer to point just past the last dst byte. 6918 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6919 Dst, Size); 6920 setValue(&I, DstPlusSize); 6921 return true; 6922 } 6923 6924 /// See if we can lower a strcpy call into an optimized form. If so, return 6925 /// true and lower it, otherwise return false and it will be lowered like a 6926 /// normal call. 6927 /// The caller already checked that \p I calls the appropriate LibFunc with a 6928 /// correct prototype. 6929 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6930 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6931 6932 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6933 std::pair<SDValue, SDValue> Res = 6934 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6935 getValue(Arg0), getValue(Arg1), 6936 MachinePointerInfo(Arg0), 6937 MachinePointerInfo(Arg1), isStpcpy); 6938 if (Res.first.getNode()) { 6939 setValue(&I, Res.first); 6940 DAG.setRoot(Res.second); 6941 return true; 6942 } 6943 6944 return false; 6945 } 6946 6947 /// See if we can lower a strcmp call into an optimized form. If so, return 6948 /// true and lower it, otherwise return false and it will be lowered like a 6949 /// normal call. 6950 /// The caller already checked that \p I calls the appropriate LibFunc with a 6951 /// correct prototype. 6952 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6953 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6954 6955 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6956 std::pair<SDValue, SDValue> Res = 6957 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6958 getValue(Arg0), getValue(Arg1), 6959 MachinePointerInfo(Arg0), 6960 MachinePointerInfo(Arg1)); 6961 if (Res.first.getNode()) { 6962 processIntegerCallValue(I, Res.first, true); 6963 PendingLoads.push_back(Res.second); 6964 return true; 6965 } 6966 6967 return false; 6968 } 6969 6970 /// See if we can lower a strlen call into an optimized form. If so, return 6971 /// true and lower it, otherwise return false and it will be lowered like a 6972 /// normal call. 6973 /// The caller already checked that \p I calls the appropriate LibFunc with a 6974 /// correct prototype. 6975 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6976 const Value *Arg0 = I.getArgOperand(0); 6977 6978 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6979 std::pair<SDValue, SDValue> Res = 6980 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6981 getValue(Arg0), MachinePointerInfo(Arg0)); 6982 if (Res.first.getNode()) { 6983 processIntegerCallValue(I, Res.first, false); 6984 PendingLoads.push_back(Res.second); 6985 return true; 6986 } 6987 6988 return false; 6989 } 6990 6991 /// See if we can lower a strnlen call into an optimized form. If so, return 6992 /// true and lower it, otherwise return false and it will be lowered like a 6993 /// normal call. 6994 /// The caller already checked that \p I calls the appropriate LibFunc with a 6995 /// correct prototype. 6996 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6997 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6998 6999 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7000 std::pair<SDValue, SDValue> Res = 7001 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7002 getValue(Arg0), getValue(Arg1), 7003 MachinePointerInfo(Arg0)); 7004 if (Res.first.getNode()) { 7005 processIntegerCallValue(I, Res.first, false); 7006 PendingLoads.push_back(Res.second); 7007 return true; 7008 } 7009 7010 return false; 7011 } 7012 7013 /// See if we can lower a unary floating-point operation into an SDNode with 7014 /// the specified Opcode. If so, return true and lower it, otherwise return 7015 /// false and it will be lowered like a normal call. 7016 /// The caller already checked that \p I calls the appropriate LibFunc with a 7017 /// correct prototype. 7018 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7019 unsigned Opcode) { 7020 // We already checked this call's prototype; verify it doesn't modify errno. 7021 if (!I.onlyReadsMemory()) 7022 return false; 7023 7024 SDValue Tmp = getValue(I.getArgOperand(0)); 7025 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7026 return true; 7027 } 7028 7029 /// See if we can lower a binary floating-point operation into an SDNode with 7030 /// the specified Opcode. If so, return true and lower it. Otherwise return 7031 /// false, and it will be lowered like a normal call. 7032 /// The caller already checked that \p I calls the appropriate LibFunc with a 7033 /// correct prototype. 7034 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7035 unsigned Opcode) { 7036 // We already checked this call's prototype; verify it doesn't modify errno. 7037 if (!I.onlyReadsMemory()) 7038 return false; 7039 7040 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7041 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7042 EVT VT = Tmp0.getValueType(); 7043 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7044 return true; 7045 } 7046 7047 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7048 // Handle inline assembly differently. 7049 if (isa<InlineAsm>(I.getCalledValue())) { 7050 visitInlineAsm(&I); 7051 return; 7052 } 7053 7054 const char *RenameFn = nullptr; 7055 if (Function *F = I.getCalledFunction()) { 7056 if (F->isDeclaration()) { 7057 // Is this an LLVM intrinsic or a target-specific intrinsic? 7058 unsigned IID = F->getIntrinsicID(); 7059 if (!IID) 7060 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7061 IID = II->getIntrinsicID(F); 7062 7063 if (IID) { 7064 RenameFn = visitIntrinsicCall(I, IID); 7065 if (!RenameFn) 7066 return; 7067 } 7068 } 7069 7070 // Check for well-known libc/libm calls. If the function is internal, it 7071 // can't be a library call. Don't do the check if marked as nobuiltin for 7072 // some reason or the call site requires strict floating point semantics. 7073 LibFunc Func; 7074 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7075 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7076 LibInfo->hasOptimizedCodeGen(Func)) { 7077 switch (Func) { 7078 default: break; 7079 case LibFunc_copysign: 7080 case LibFunc_copysignf: 7081 case LibFunc_copysignl: 7082 // We already checked this call's prototype; verify it doesn't modify 7083 // errno. 7084 if (I.onlyReadsMemory()) { 7085 SDValue LHS = getValue(I.getArgOperand(0)); 7086 SDValue RHS = getValue(I.getArgOperand(1)); 7087 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7088 LHS.getValueType(), LHS, RHS)); 7089 return; 7090 } 7091 break; 7092 case LibFunc_fabs: 7093 case LibFunc_fabsf: 7094 case LibFunc_fabsl: 7095 if (visitUnaryFloatCall(I, ISD::FABS)) 7096 return; 7097 break; 7098 case LibFunc_fmin: 7099 case LibFunc_fminf: 7100 case LibFunc_fminl: 7101 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7102 return; 7103 break; 7104 case LibFunc_fmax: 7105 case LibFunc_fmaxf: 7106 case LibFunc_fmaxl: 7107 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7108 return; 7109 break; 7110 case LibFunc_sin: 7111 case LibFunc_sinf: 7112 case LibFunc_sinl: 7113 if (visitUnaryFloatCall(I, ISD::FSIN)) 7114 return; 7115 break; 7116 case LibFunc_cos: 7117 case LibFunc_cosf: 7118 case LibFunc_cosl: 7119 if (visitUnaryFloatCall(I, ISD::FCOS)) 7120 return; 7121 break; 7122 case LibFunc_sqrt: 7123 case LibFunc_sqrtf: 7124 case LibFunc_sqrtl: 7125 case LibFunc_sqrt_finite: 7126 case LibFunc_sqrtf_finite: 7127 case LibFunc_sqrtl_finite: 7128 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7129 return; 7130 break; 7131 case LibFunc_floor: 7132 case LibFunc_floorf: 7133 case LibFunc_floorl: 7134 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7135 return; 7136 break; 7137 case LibFunc_nearbyint: 7138 case LibFunc_nearbyintf: 7139 case LibFunc_nearbyintl: 7140 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7141 return; 7142 break; 7143 case LibFunc_ceil: 7144 case LibFunc_ceilf: 7145 case LibFunc_ceill: 7146 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7147 return; 7148 break; 7149 case LibFunc_rint: 7150 case LibFunc_rintf: 7151 case LibFunc_rintl: 7152 if (visitUnaryFloatCall(I, ISD::FRINT)) 7153 return; 7154 break; 7155 case LibFunc_round: 7156 case LibFunc_roundf: 7157 case LibFunc_roundl: 7158 if (visitUnaryFloatCall(I, ISD::FROUND)) 7159 return; 7160 break; 7161 case LibFunc_trunc: 7162 case LibFunc_truncf: 7163 case LibFunc_truncl: 7164 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7165 return; 7166 break; 7167 case LibFunc_log2: 7168 case LibFunc_log2f: 7169 case LibFunc_log2l: 7170 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7171 return; 7172 break; 7173 case LibFunc_exp2: 7174 case LibFunc_exp2f: 7175 case LibFunc_exp2l: 7176 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7177 return; 7178 break; 7179 case LibFunc_memcmp: 7180 if (visitMemCmpCall(I)) 7181 return; 7182 break; 7183 case LibFunc_mempcpy: 7184 if (visitMemPCpyCall(I)) 7185 return; 7186 break; 7187 case LibFunc_memchr: 7188 if (visitMemChrCall(I)) 7189 return; 7190 break; 7191 case LibFunc_strcpy: 7192 if (visitStrCpyCall(I, false)) 7193 return; 7194 break; 7195 case LibFunc_stpcpy: 7196 if (visitStrCpyCall(I, true)) 7197 return; 7198 break; 7199 case LibFunc_strcmp: 7200 if (visitStrCmpCall(I)) 7201 return; 7202 break; 7203 case LibFunc_strlen: 7204 if (visitStrLenCall(I)) 7205 return; 7206 break; 7207 case LibFunc_strnlen: 7208 if (visitStrNLenCall(I)) 7209 return; 7210 break; 7211 } 7212 } 7213 } 7214 7215 SDValue Callee; 7216 if (!RenameFn) 7217 Callee = getValue(I.getCalledValue()); 7218 else 7219 Callee = DAG.getExternalSymbol( 7220 RenameFn, 7221 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7222 7223 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7224 // have to do anything here to lower funclet bundles. 7225 assert(!I.hasOperandBundlesOtherThan( 7226 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7227 "Cannot lower calls with arbitrary operand bundles!"); 7228 7229 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7230 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7231 else 7232 // Check if we can potentially perform a tail call. More detailed checking 7233 // is be done within LowerCallTo, after more information about the call is 7234 // known. 7235 LowerCallTo(&I, Callee, I.isTailCall()); 7236 } 7237 7238 namespace { 7239 7240 /// AsmOperandInfo - This contains information for each constraint that we are 7241 /// lowering. 7242 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7243 public: 7244 /// CallOperand - If this is the result output operand or a clobber 7245 /// this is null, otherwise it is the incoming operand to the CallInst. 7246 /// This gets modified as the asm is processed. 7247 SDValue CallOperand; 7248 7249 /// AssignedRegs - If this is a register or register class operand, this 7250 /// contains the set of register corresponding to the operand. 7251 RegsForValue AssignedRegs; 7252 7253 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7254 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7255 } 7256 7257 /// Whether or not this operand accesses memory 7258 bool hasMemory(const TargetLowering &TLI) const { 7259 // Indirect operand accesses access memory. 7260 if (isIndirect) 7261 return true; 7262 7263 for (const auto &Code : Codes) 7264 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7265 return true; 7266 7267 return false; 7268 } 7269 7270 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7271 /// corresponds to. If there is no Value* for this operand, it returns 7272 /// MVT::Other. 7273 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7274 const DataLayout &DL) const { 7275 if (!CallOperandVal) return MVT::Other; 7276 7277 if (isa<BasicBlock>(CallOperandVal)) 7278 return TLI.getPointerTy(DL); 7279 7280 llvm::Type *OpTy = CallOperandVal->getType(); 7281 7282 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7283 // If this is an indirect operand, the operand is a pointer to the 7284 // accessed type. 7285 if (isIndirect) { 7286 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7287 if (!PtrTy) 7288 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7289 OpTy = PtrTy->getElementType(); 7290 } 7291 7292 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7293 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7294 if (STy->getNumElements() == 1) 7295 OpTy = STy->getElementType(0); 7296 7297 // If OpTy is not a single value, it may be a struct/union that we 7298 // can tile with integers. 7299 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7300 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7301 switch (BitSize) { 7302 default: break; 7303 case 1: 7304 case 8: 7305 case 16: 7306 case 32: 7307 case 64: 7308 case 128: 7309 OpTy = IntegerType::get(Context, BitSize); 7310 break; 7311 } 7312 } 7313 7314 return TLI.getValueType(DL, OpTy, true); 7315 } 7316 }; 7317 7318 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7319 7320 } // end anonymous namespace 7321 7322 /// Make sure that the output operand \p OpInfo and its corresponding input 7323 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7324 /// out). 7325 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7326 SDISelAsmOperandInfo &MatchingOpInfo, 7327 SelectionDAG &DAG) { 7328 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7329 return; 7330 7331 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7332 const auto &TLI = DAG.getTargetLoweringInfo(); 7333 7334 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7335 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7336 OpInfo.ConstraintVT); 7337 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7338 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7339 MatchingOpInfo.ConstraintVT); 7340 if ((OpInfo.ConstraintVT.isInteger() != 7341 MatchingOpInfo.ConstraintVT.isInteger()) || 7342 (MatchRC.second != InputRC.second)) { 7343 // FIXME: error out in a more elegant fashion 7344 report_fatal_error("Unsupported asm: input constraint" 7345 " with a matching output constraint of" 7346 " incompatible type!"); 7347 } 7348 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7349 } 7350 7351 /// Get a direct memory input to behave well as an indirect operand. 7352 /// This may introduce stores, hence the need for a \p Chain. 7353 /// \return The (possibly updated) chain. 7354 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7355 SDISelAsmOperandInfo &OpInfo, 7356 SelectionDAG &DAG) { 7357 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7358 7359 // If we don't have an indirect input, put it in the constpool if we can, 7360 // otherwise spill it to a stack slot. 7361 // TODO: This isn't quite right. We need to handle these according to 7362 // the addressing mode that the constraint wants. Also, this may take 7363 // an additional register for the computation and we don't want that 7364 // either. 7365 7366 // If the operand is a float, integer, or vector constant, spill to a 7367 // constant pool entry to get its address. 7368 const Value *OpVal = OpInfo.CallOperandVal; 7369 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7370 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7371 OpInfo.CallOperand = DAG.getConstantPool( 7372 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7373 return Chain; 7374 } 7375 7376 // Otherwise, create a stack slot and emit a store to it before the asm. 7377 Type *Ty = OpVal->getType(); 7378 auto &DL = DAG.getDataLayout(); 7379 uint64_t TySize = DL.getTypeAllocSize(Ty); 7380 unsigned Align = DL.getPrefTypeAlignment(Ty); 7381 MachineFunction &MF = DAG.getMachineFunction(); 7382 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7383 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7384 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7385 MachinePointerInfo::getFixedStack(MF, SSFI)); 7386 OpInfo.CallOperand = StackSlot; 7387 7388 return Chain; 7389 } 7390 7391 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7392 /// specified operand. We prefer to assign virtual registers, to allow the 7393 /// register allocator to handle the assignment process. However, if the asm 7394 /// uses features that we can't model on machineinstrs, we have SDISel do the 7395 /// allocation. This produces generally horrible, but correct, code. 7396 /// 7397 /// OpInfo describes the operand 7398 /// RefOpInfo describes the matching operand if any, the operand otherwise 7399 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7400 SDISelAsmOperandInfo &OpInfo, 7401 SDISelAsmOperandInfo &RefOpInfo) { 7402 LLVMContext &Context = *DAG.getContext(); 7403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7404 7405 MachineFunction &MF = DAG.getMachineFunction(); 7406 SmallVector<unsigned, 4> Regs; 7407 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7408 7409 // No work to do for memory operations. 7410 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7411 return; 7412 7413 // If this is a constraint for a single physreg, or a constraint for a 7414 // register class, find it. 7415 unsigned AssignedReg; 7416 const TargetRegisterClass *RC; 7417 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7418 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7419 // RC is unset only on failure. Return immediately. 7420 if (!RC) 7421 return; 7422 7423 // Get the actual register value type. This is important, because the user 7424 // may have asked for (e.g.) the AX register in i32 type. We need to 7425 // remember that AX is actually i16 to get the right extension. 7426 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7427 7428 if (OpInfo.ConstraintVT != MVT::Other) { 7429 // If this is an FP operand in an integer register (or visa versa), or more 7430 // generally if the operand value disagrees with the register class we plan 7431 // to stick it in, fix the operand type. 7432 // 7433 // If this is an input value, the bitcast to the new type is done now. 7434 // Bitcast for output value is done at the end of visitInlineAsm(). 7435 if ((OpInfo.Type == InlineAsm::isOutput || 7436 OpInfo.Type == InlineAsm::isInput) && 7437 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7438 // Try to convert to the first EVT that the reg class contains. If the 7439 // types are identical size, use a bitcast to convert (e.g. two differing 7440 // vector types). Note: output bitcast is done at the end of 7441 // visitInlineAsm(). 7442 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7443 // Exclude indirect inputs while they are unsupported because the code 7444 // to perform the load is missing and thus OpInfo.CallOperand still 7445 // refers to the input address rather than the pointed-to value. 7446 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7447 OpInfo.CallOperand = 7448 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7449 OpInfo.ConstraintVT = RegVT; 7450 // If the operand is an FP value and we want it in integer registers, 7451 // use the corresponding integer type. This turns an f64 value into 7452 // i64, which can be passed with two i32 values on a 32-bit machine. 7453 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7454 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7455 if (OpInfo.Type == InlineAsm::isInput) 7456 OpInfo.CallOperand = 7457 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7458 OpInfo.ConstraintVT = VT; 7459 } 7460 } 7461 } 7462 7463 // No need to allocate a matching input constraint since the constraint it's 7464 // matching to has already been allocated. 7465 if (OpInfo.isMatchingInputConstraint()) 7466 return; 7467 7468 EVT ValueVT = OpInfo.ConstraintVT; 7469 if (OpInfo.ConstraintVT == MVT::Other) 7470 ValueVT = RegVT; 7471 7472 // Initialize NumRegs. 7473 unsigned NumRegs = 1; 7474 if (OpInfo.ConstraintVT != MVT::Other) 7475 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7476 7477 // If this is a constraint for a specific physical register, like {r17}, 7478 // assign it now. 7479 7480 // If this associated to a specific register, initialize iterator to correct 7481 // place. If virtual, make sure we have enough registers 7482 7483 // Initialize iterator if necessary 7484 TargetRegisterClass::iterator I = RC->begin(); 7485 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7486 7487 // Do not check for single registers. 7488 if (AssignedReg) { 7489 for (; *I != AssignedReg; ++I) 7490 assert(I != RC->end() && "AssignedReg should be member of RC"); 7491 } 7492 7493 for (; NumRegs; --NumRegs, ++I) { 7494 assert(I != RC->end() && "Ran out of registers to allocate!"); 7495 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7496 Regs.push_back(R); 7497 } 7498 7499 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7500 } 7501 7502 static unsigned 7503 findMatchingInlineAsmOperand(unsigned OperandNo, 7504 const std::vector<SDValue> &AsmNodeOperands) { 7505 // Scan until we find the definition we already emitted of this operand. 7506 unsigned CurOp = InlineAsm::Op_FirstOperand; 7507 for (; OperandNo; --OperandNo) { 7508 // Advance to the next operand. 7509 unsigned OpFlag = 7510 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7511 assert((InlineAsm::isRegDefKind(OpFlag) || 7512 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7513 InlineAsm::isMemKind(OpFlag)) && 7514 "Skipped past definitions?"); 7515 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7516 } 7517 return CurOp; 7518 } 7519 7520 namespace { 7521 7522 class ExtraFlags { 7523 unsigned Flags = 0; 7524 7525 public: 7526 explicit ExtraFlags(ImmutableCallSite CS) { 7527 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7528 if (IA->hasSideEffects()) 7529 Flags |= InlineAsm::Extra_HasSideEffects; 7530 if (IA->isAlignStack()) 7531 Flags |= InlineAsm::Extra_IsAlignStack; 7532 if (CS.isConvergent()) 7533 Flags |= InlineAsm::Extra_IsConvergent; 7534 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7535 } 7536 7537 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7538 // Ideally, we would only check against memory constraints. However, the 7539 // meaning of an Other constraint can be target-specific and we can't easily 7540 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7541 // for Other constraints as well. 7542 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7543 OpInfo.ConstraintType == TargetLowering::C_Other) { 7544 if (OpInfo.Type == InlineAsm::isInput) 7545 Flags |= InlineAsm::Extra_MayLoad; 7546 else if (OpInfo.Type == InlineAsm::isOutput) 7547 Flags |= InlineAsm::Extra_MayStore; 7548 else if (OpInfo.Type == InlineAsm::isClobber) 7549 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7550 } 7551 } 7552 7553 unsigned get() const { return Flags; } 7554 }; 7555 7556 } // end anonymous namespace 7557 7558 /// visitInlineAsm - Handle a call to an InlineAsm object. 7559 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7560 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7561 7562 /// ConstraintOperands - Information about all of the constraints. 7563 SDISelAsmOperandInfoVector ConstraintOperands; 7564 7565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7566 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7567 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7568 7569 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7570 // AsmDialect, MayLoad, MayStore). 7571 bool HasSideEffect = IA->hasSideEffects(); 7572 ExtraFlags ExtraInfo(CS); 7573 7574 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7575 unsigned ResNo = 0; // ResNo - The result number of the next output. 7576 for (auto &T : TargetConstraints) { 7577 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7578 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7579 7580 // Compute the value type for each operand. 7581 if (OpInfo.Type == InlineAsm::isInput || 7582 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7583 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7584 7585 // Process the call argument. BasicBlocks are labels, currently appearing 7586 // only in asm's. 7587 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7588 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7589 } else { 7590 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7591 } 7592 7593 OpInfo.ConstraintVT = 7594 OpInfo 7595 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7596 .getSimpleVT(); 7597 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7598 // The return value of the call is this value. As such, there is no 7599 // corresponding argument. 7600 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7601 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7602 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7603 DAG.getDataLayout(), STy->getElementType(ResNo)); 7604 } else { 7605 assert(ResNo == 0 && "Asm only has one result!"); 7606 OpInfo.ConstraintVT = 7607 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7608 } 7609 ++ResNo; 7610 } else { 7611 OpInfo.ConstraintVT = MVT::Other; 7612 } 7613 7614 if (!HasSideEffect) 7615 HasSideEffect = OpInfo.hasMemory(TLI); 7616 7617 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7618 // FIXME: Could we compute this on OpInfo rather than T? 7619 7620 // Compute the constraint code and ConstraintType to use. 7621 TLI.ComputeConstraintToUse(T, SDValue()); 7622 7623 ExtraInfo.update(T); 7624 } 7625 7626 // We won't need to flush pending loads if this asm doesn't touch 7627 // memory and is nonvolatile. 7628 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7629 7630 // Second pass over the constraints: compute which constraint option to use. 7631 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7632 // If this is an output operand with a matching input operand, look up the 7633 // matching input. If their types mismatch, e.g. one is an integer, the 7634 // other is floating point, or their sizes are different, flag it as an 7635 // error. 7636 if (OpInfo.hasMatchingInput()) { 7637 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7638 patchMatchingInput(OpInfo, Input, DAG); 7639 } 7640 7641 // Compute the constraint code and ConstraintType to use. 7642 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7643 7644 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7645 OpInfo.Type == InlineAsm::isClobber) 7646 continue; 7647 7648 // If this is a memory input, and if the operand is not indirect, do what we 7649 // need to provide an address for the memory input. 7650 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7651 !OpInfo.isIndirect) { 7652 assert((OpInfo.isMultipleAlternative || 7653 (OpInfo.Type == InlineAsm::isInput)) && 7654 "Can only indirectify direct input operands!"); 7655 7656 // Memory operands really want the address of the value. 7657 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7658 7659 // There is no longer a Value* corresponding to this operand. 7660 OpInfo.CallOperandVal = nullptr; 7661 7662 // It is now an indirect operand. 7663 OpInfo.isIndirect = true; 7664 } 7665 7666 } 7667 7668 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7669 std::vector<SDValue> AsmNodeOperands; 7670 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7671 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7672 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7673 7674 // If we have a !srcloc metadata node associated with it, we want to attach 7675 // this to the ultimately generated inline asm machineinstr. To do this, we 7676 // pass in the third operand as this (potentially null) inline asm MDNode. 7677 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7678 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7679 7680 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7681 // bits as operand 3. 7682 AsmNodeOperands.push_back(DAG.getTargetConstant( 7683 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7684 7685 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7686 // this, assign virtual and physical registers for inputs and otput. 7687 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7688 // Assign Registers. 7689 SDISelAsmOperandInfo &RefOpInfo = 7690 OpInfo.isMatchingInputConstraint() 7691 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7692 : OpInfo; 7693 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7694 7695 switch (OpInfo.Type) { 7696 case InlineAsm::isOutput: 7697 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7698 (OpInfo.ConstraintType == TargetLowering::C_Other && 7699 OpInfo.isIndirect)) { 7700 unsigned ConstraintID = 7701 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7702 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7703 "Failed to convert memory constraint code to constraint id."); 7704 7705 // Add information to the INLINEASM node to know about this output. 7706 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7707 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7708 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7709 MVT::i32)); 7710 AsmNodeOperands.push_back(OpInfo.CallOperand); 7711 break; 7712 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 7713 !OpInfo.isIndirect) || 7714 OpInfo.ConstraintType == TargetLowering::C_Register || 7715 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7716 // Otherwise, this outputs to a register (directly for C_Register / 7717 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 7718 // register that we can use. 7719 if (OpInfo.AssignedRegs.Regs.empty()) { 7720 emitInlineAsmError( 7721 CS, "couldn't allocate output register for constraint '" + 7722 Twine(OpInfo.ConstraintCode) + "'"); 7723 return; 7724 } 7725 7726 // Add information to the INLINEASM node to know that this register is 7727 // set. 7728 OpInfo.AssignedRegs.AddInlineAsmOperands( 7729 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7730 : InlineAsm::Kind_RegDef, 7731 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7732 } 7733 break; 7734 7735 case InlineAsm::isInput: { 7736 SDValue InOperandVal = OpInfo.CallOperand; 7737 7738 if (OpInfo.isMatchingInputConstraint()) { 7739 // If this is required to match an output register we have already set, 7740 // just use its register. 7741 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7742 AsmNodeOperands); 7743 unsigned OpFlag = 7744 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7745 if (InlineAsm::isRegDefKind(OpFlag) || 7746 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7747 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7748 if (OpInfo.isIndirect) { 7749 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7750 emitInlineAsmError(CS, "inline asm not supported yet:" 7751 " don't know how to handle tied " 7752 "indirect register inputs"); 7753 return; 7754 } 7755 7756 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7757 SmallVector<unsigned, 4> Regs; 7758 7759 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7760 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7761 MachineRegisterInfo &RegInfo = 7762 DAG.getMachineFunction().getRegInfo(); 7763 for (unsigned i = 0; i != NumRegs; ++i) 7764 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7765 } else { 7766 emitInlineAsmError(CS, "inline asm error: This value type register " 7767 "class is not natively supported!"); 7768 return; 7769 } 7770 7771 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7772 7773 SDLoc dl = getCurSDLoc(); 7774 // Use the produced MatchedRegs object to 7775 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7776 CS.getInstruction()); 7777 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7778 true, OpInfo.getMatchedOperand(), dl, 7779 DAG, AsmNodeOperands); 7780 break; 7781 } 7782 7783 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7784 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7785 "Unexpected number of operands"); 7786 // Add information to the INLINEASM node to know about this input. 7787 // See InlineAsm.h isUseOperandTiedToDef. 7788 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7789 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7790 OpInfo.getMatchedOperand()); 7791 AsmNodeOperands.push_back(DAG.getTargetConstant( 7792 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7793 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7794 break; 7795 } 7796 7797 // Treat indirect 'X' constraint as memory. 7798 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7799 OpInfo.isIndirect) 7800 OpInfo.ConstraintType = TargetLowering::C_Memory; 7801 7802 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7803 std::vector<SDValue> Ops; 7804 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7805 Ops, DAG); 7806 if (Ops.empty()) { 7807 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7808 Twine(OpInfo.ConstraintCode) + "'"); 7809 return; 7810 } 7811 7812 // Add information to the INLINEASM node to know about this input. 7813 unsigned ResOpType = 7814 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7815 AsmNodeOperands.push_back(DAG.getTargetConstant( 7816 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7817 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7818 break; 7819 } 7820 7821 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7822 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7823 assert(InOperandVal.getValueType() == 7824 TLI.getPointerTy(DAG.getDataLayout()) && 7825 "Memory operands expect pointer values"); 7826 7827 unsigned ConstraintID = 7828 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7829 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7830 "Failed to convert memory constraint code to constraint id."); 7831 7832 // Add information to the INLINEASM node to know about this input. 7833 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7834 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7835 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7836 getCurSDLoc(), 7837 MVT::i32)); 7838 AsmNodeOperands.push_back(InOperandVal); 7839 break; 7840 } 7841 7842 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7843 OpInfo.ConstraintType == TargetLowering::C_Register) && 7844 "Unknown constraint type!"); 7845 7846 // TODO: Support this. 7847 if (OpInfo.isIndirect) { 7848 emitInlineAsmError( 7849 CS, "Don't know how to handle indirect register inputs yet " 7850 "for constraint '" + 7851 Twine(OpInfo.ConstraintCode) + "'"); 7852 return; 7853 } 7854 7855 // Copy the input into the appropriate registers. 7856 if (OpInfo.AssignedRegs.Regs.empty()) { 7857 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7858 Twine(OpInfo.ConstraintCode) + "'"); 7859 return; 7860 } 7861 7862 SDLoc dl = getCurSDLoc(); 7863 7864 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7865 Chain, &Flag, CS.getInstruction()); 7866 7867 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7868 dl, DAG, AsmNodeOperands); 7869 break; 7870 } 7871 case InlineAsm::isClobber: 7872 // Add the clobbered value to the operand list, so that the register 7873 // allocator is aware that the physreg got clobbered. 7874 if (!OpInfo.AssignedRegs.Regs.empty()) 7875 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7876 false, 0, getCurSDLoc(), DAG, 7877 AsmNodeOperands); 7878 break; 7879 } 7880 } 7881 7882 // Finish up input operands. Set the input chain and add the flag last. 7883 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7884 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7885 7886 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7887 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7888 Flag = Chain.getValue(1); 7889 7890 // Do additional work to generate outputs. 7891 7892 SmallVector<EVT, 1> ResultVTs; 7893 SmallVector<SDValue, 1> ResultValues; 7894 SmallVector<SDValue, 8> OutChains; 7895 7896 llvm::Type *CSResultType = CS.getType(); 7897 ArrayRef<Type *> ResultTypes; 7898 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 7899 ResultTypes = StructResult->elements(); 7900 else if (!CSResultType->isVoidTy()) 7901 ResultTypes = makeArrayRef(CSResultType); 7902 7903 auto CurResultType = ResultTypes.begin(); 7904 auto handleRegAssign = [&](SDValue V) { 7905 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7906 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7907 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7908 ++CurResultType; 7909 // If the type of the inline asm call site return value is different but has 7910 // same size as the type of the asm output bitcast it. One example of this 7911 // is for vectors with different width / number of elements. This can 7912 // happen for register classes that can contain multiple different value 7913 // types. The preg or vreg allocated may not have the same VT as was 7914 // expected. 7915 // 7916 // This can also happen for a return value that disagrees with the register 7917 // class it is put in, eg. a double in a general-purpose register on a 7918 // 32-bit machine. 7919 if (ResultVT != V.getValueType() && 7920 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7921 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7922 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7923 V.getValueType().isInteger()) { 7924 // If a result value was tied to an input value, the computed result 7925 // may have a wider width than the expected result. Extract the 7926 // relevant portion. 7927 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7928 } 7929 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7930 ResultVTs.push_back(ResultVT); 7931 ResultValues.push_back(V); 7932 }; 7933 7934 // Deal with output operands. 7935 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7936 if (OpInfo.Type == InlineAsm::isOutput) { 7937 SDValue Val; 7938 // Skip trivial output operands. 7939 if (OpInfo.AssignedRegs.Regs.empty()) 7940 continue; 7941 7942 switch (OpInfo.ConstraintType) { 7943 case TargetLowering::C_Register: 7944 case TargetLowering::C_RegisterClass: 7945 Val = OpInfo.AssignedRegs.getCopyFromRegs( 7946 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7947 break; 7948 case TargetLowering::C_Other: 7949 Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(), 7950 OpInfo, DAG); 7951 break; 7952 case TargetLowering::C_Memory: 7953 break; // Already handled. 7954 case TargetLowering::C_Unknown: 7955 assert(false && "Unexpected unknown constraint"); 7956 } 7957 7958 // Indirect output manifest as stores. Record output chains. 7959 if (OpInfo.isIndirect) { 7960 7961 const Value *Ptr = OpInfo.CallOperandVal; 7962 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 7963 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 7964 MachinePointerInfo(Ptr)); 7965 OutChains.push_back(Store); 7966 } else { 7967 // generate CopyFromRegs to associated registers. 7968 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7969 if (Val.getOpcode() == ISD::MERGE_VALUES) { 7970 for (const SDValue &V : Val->op_values()) 7971 handleRegAssign(V); 7972 } else 7973 handleRegAssign(Val); 7974 } 7975 } 7976 } 7977 7978 // Set results. 7979 if (!ResultValues.empty()) { 7980 assert(CurResultType == ResultTypes.end() && 7981 "Mismatch in number of ResultTypes"); 7982 assert(ResultValues.size() == ResultTypes.size() && 7983 "Mismatch in number of output operands in asm result"); 7984 7985 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7986 DAG.getVTList(ResultVTs), ResultValues); 7987 setValue(CS.getInstruction(), V); 7988 } 7989 7990 // Collect store chains. 7991 if (!OutChains.empty()) 7992 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7993 7994 // Only Update Root if inline assembly has a memory effect. 7995 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 7996 DAG.setRoot(Chain); 7997 } 7998 7999 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8000 const Twine &Message) { 8001 LLVMContext &Ctx = *DAG.getContext(); 8002 Ctx.emitError(CS.getInstruction(), Message); 8003 8004 // Make sure we leave the DAG in a valid state 8005 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8006 SmallVector<EVT, 1> ValueVTs; 8007 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8008 8009 if (ValueVTs.empty()) 8010 return; 8011 8012 SmallVector<SDValue, 1> Ops; 8013 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8014 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8015 8016 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8017 } 8018 8019 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8020 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8021 MVT::Other, getRoot(), 8022 getValue(I.getArgOperand(0)), 8023 DAG.getSrcValue(I.getArgOperand(0)))); 8024 } 8025 8026 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8027 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8028 const DataLayout &DL = DAG.getDataLayout(); 8029 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 8030 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 8031 DAG.getSrcValue(I.getOperand(0)), 8032 DL.getABITypeAlignment(I.getType())); 8033 setValue(&I, V); 8034 DAG.setRoot(V.getValue(1)); 8035 } 8036 8037 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8038 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8039 MVT::Other, getRoot(), 8040 getValue(I.getArgOperand(0)), 8041 DAG.getSrcValue(I.getArgOperand(0)))); 8042 } 8043 8044 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8045 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8046 MVT::Other, getRoot(), 8047 getValue(I.getArgOperand(0)), 8048 getValue(I.getArgOperand(1)), 8049 DAG.getSrcValue(I.getArgOperand(0)), 8050 DAG.getSrcValue(I.getArgOperand(1)))); 8051 } 8052 8053 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8054 const Instruction &I, 8055 SDValue Op) { 8056 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8057 if (!Range) 8058 return Op; 8059 8060 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8061 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8062 return Op; 8063 8064 APInt Lo = CR.getUnsignedMin(); 8065 if (!Lo.isMinValue()) 8066 return Op; 8067 8068 APInt Hi = CR.getUnsignedMax(); 8069 unsigned Bits = std::max(Hi.getActiveBits(), 8070 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8071 8072 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8073 8074 SDLoc SL = getCurSDLoc(); 8075 8076 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8077 DAG.getValueType(SmallVT)); 8078 unsigned NumVals = Op.getNode()->getNumValues(); 8079 if (NumVals == 1) 8080 return ZExt; 8081 8082 SmallVector<SDValue, 4> Ops; 8083 8084 Ops.push_back(ZExt); 8085 for (unsigned I = 1; I != NumVals; ++I) 8086 Ops.push_back(Op.getValue(I)); 8087 8088 return DAG.getMergeValues(Ops, SL); 8089 } 8090 8091 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8092 /// the call being lowered. 8093 /// 8094 /// This is a helper for lowering intrinsics that follow a target calling 8095 /// convention or require stack pointer adjustment. Only a subset of the 8096 /// intrinsic's operands need to participate in the calling convention. 8097 void SelectionDAGBuilder::populateCallLoweringInfo( 8098 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8099 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8100 bool IsPatchPoint) { 8101 TargetLowering::ArgListTy Args; 8102 Args.reserve(NumArgs); 8103 8104 // Populate the argument list. 8105 // Attributes for args start at offset 1, after the return attribute. 8106 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8107 ArgI != ArgE; ++ArgI) { 8108 const Value *V = CS->getOperand(ArgI); 8109 8110 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8111 8112 TargetLowering::ArgListEntry Entry; 8113 Entry.Node = getValue(V); 8114 Entry.Ty = V->getType(); 8115 Entry.setAttributes(&CS, ArgI); 8116 Args.push_back(Entry); 8117 } 8118 8119 CLI.setDebugLoc(getCurSDLoc()) 8120 .setChain(getRoot()) 8121 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8122 .setDiscardResult(CS->use_empty()) 8123 .setIsPatchPoint(IsPatchPoint); 8124 } 8125 8126 /// Add a stack map intrinsic call's live variable operands to a stackmap 8127 /// or patchpoint target node's operand list. 8128 /// 8129 /// Constants are converted to TargetConstants purely as an optimization to 8130 /// avoid constant materialization and register allocation. 8131 /// 8132 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8133 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8134 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8135 /// address materialization and register allocation, but may also be required 8136 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8137 /// alloca in the entry block, then the runtime may assume that the alloca's 8138 /// StackMap location can be read immediately after compilation and that the 8139 /// location is valid at any point during execution (this is similar to the 8140 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8141 /// only available in a register, then the runtime would need to trap when 8142 /// execution reaches the StackMap in order to read the alloca's location. 8143 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8144 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8145 SelectionDAGBuilder &Builder) { 8146 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8147 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8149 Ops.push_back( 8150 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8151 Ops.push_back( 8152 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8153 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8154 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8155 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8156 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8157 } else 8158 Ops.push_back(OpVal); 8159 } 8160 } 8161 8162 /// Lower llvm.experimental.stackmap directly to its target opcode. 8163 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8164 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8165 // [live variables...]) 8166 8167 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8168 8169 SDValue Chain, InFlag, Callee, NullPtr; 8170 SmallVector<SDValue, 32> Ops; 8171 8172 SDLoc DL = getCurSDLoc(); 8173 Callee = getValue(CI.getCalledValue()); 8174 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8175 8176 // The stackmap intrinsic only records the live variables (the arguemnts 8177 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8178 // intrinsic, this won't be lowered to a function call. This means we don't 8179 // have to worry about calling conventions and target specific lowering code. 8180 // Instead we perform the call lowering right here. 8181 // 8182 // chain, flag = CALLSEQ_START(chain, 0, 0) 8183 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8184 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8185 // 8186 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8187 InFlag = Chain.getValue(1); 8188 8189 // Add the <id> and <numBytes> constants. 8190 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8191 Ops.push_back(DAG.getTargetConstant( 8192 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8193 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8194 Ops.push_back(DAG.getTargetConstant( 8195 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8196 MVT::i32)); 8197 8198 // Push live variables for the stack map. 8199 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8200 8201 // We are not pushing any register mask info here on the operands list, 8202 // because the stackmap doesn't clobber anything. 8203 8204 // Push the chain and the glue flag. 8205 Ops.push_back(Chain); 8206 Ops.push_back(InFlag); 8207 8208 // Create the STACKMAP node. 8209 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8210 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8211 Chain = SDValue(SM, 0); 8212 InFlag = Chain.getValue(1); 8213 8214 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8215 8216 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8217 8218 // Set the root to the target-lowered call chain. 8219 DAG.setRoot(Chain); 8220 8221 // Inform the Frame Information that we have a stackmap in this function. 8222 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8223 } 8224 8225 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8226 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8227 const BasicBlock *EHPadBB) { 8228 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8229 // i32 <numBytes>, 8230 // i8* <target>, 8231 // i32 <numArgs>, 8232 // [Args...], 8233 // [live variables...]) 8234 8235 CallingConv::ID CC = CS.getCallingConv(); 8236 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8237 bool HasDef = !CS->getType()->isVoidTy(); 8238 SDLoc dl = getCurSDLoc(); 8239 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8240 8241 // Handle immediate and symbolic callees. 8242 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8243 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8244 /*isTarget=*/true); 8245 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8246 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8247 SDLoc(SymbolicCallee), 8248 SymbolicCallee->getValueType(0)); 8249 8250 // Get the real number of arguments participating in the call <numArgs> 8251 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8252 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8253 8254 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8255 // Intrinsics include all meta-operands up to but not including CC. 8256 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8257 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8258 "Not enough arguments provided to the patchpoint intrinsic"); 8259 8260 // For AnyRegCC the arguments are lowered later on manually. 8261 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8262 Type *ReturnTy = 8263 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8264 8265 TargetLowering::CallLoweringInfo CLI(DAG); 8266 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8267 true); 8268 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8269 8270 SDNode *CallEnd = Result.second.getNode(); 8271 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8272 CallEnd = CallEnd->getOperand(0).getNode(); 8273 8274 /// Get a call instruction from the call sequence chain. 8275 /// Tail calls are not allowed. 8276 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8277 "Expected a callseq node."); 8278 SDNode *Call = CallEnd->getOperand(0).getNode(); 8279 bool HasGlue = Call->getGluedNode(); 8280 8281 // Replace the target specific call node with the patchable intrinsic. 8282 SmallVector<SDValue, 8> Ops; 8283 8284 // Add the <id> and <numBytes> constants. 8285 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8286 Ops.push_back(DAG.getTargetConstant( 8287 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8288 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8289 Ops.push_back(DAG.getTargetConstant( 8290 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8291 MVT::i32)); 8292 8293 // Add the callee. 8294 Ops.push_back(Callee); 8295 8296 // Adjust <numArgs> to account for any arguments that have been passed on the 8297 // stack instead. 8298 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8299 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8300 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8301 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8302 8303 // Add the calling convention 8304 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8305 8306 // Add the arguments we omitted previously. The register allocator should 8307 // place these in any free register. 8308 if (IsAnyRegCC) 8309 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8310 Ops.push_back(getValue(CS.getArgument(i))); 8311 8312 // Push the arguments from the call instruction up to the register mask. 8313 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8314 Ops.append(Call->op_begin() + 2, e); 8315 8316 // Push live variables for the stack map. 8317 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8318 8319 // Push the register mask info. 8320 if (HasGlue) 8321 Ops.push_back(*(Call->op_end()-2)); 8322 else 8323 Ops.push_back(*(Call->op_end()-1)); 8324 8325 // Push the chain (this is originally the first operand of the call, but 8326 // becomes now the last or second to last operand). 8327 Ops.push_back(*(Call->op_begin())); 8328 8329 // Push the glue flag (last operand). 8330 if (HasGlue) 8331 Ops.push_back(*(Call->op_end()-1)); 8332 8333 SDVTList NodeTys; 8334 if (IsAnyRegCC && HasDef) { 8335 // Create the return types based on the intrinsic definition 8336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8337 SmallVector<EVT, 3> ValueVTs; 8338 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8339 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8340 8341 // There is always a chain and a glue type at the end 8342 ValueVTs.push_back(MVT::Other); 8343 ValueVTs.push_back(MVT::Glue); 8344 NodeTys = DAG.getVTList(ValueVTs); 8345 } else 8346 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8347 8348 // Replace the target specific call node with a PATCHPOINT node. 8349 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8350 dl, NodeTys, Ops); 8351 8352 // Update the NodeMap. 8353 if (HasDef) { 8354 if (IsAnyRegCC) 8355 setValue(CS.getInstruction(), SDValue(MN, 0)); 8356 else 8357 setValue(CS.getInstruction(), Result.first); 8358 } 8359 8360 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8361 // call sequence. Furthermore the location of the chain and glue can change 8362 // when the AnyReg calling convention is used and the intrinsic returns a 8363 // value. 8364 if (IsAnyRegCC && HasDef) { 8365 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8366 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8367 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8368 } else 8369 DAG.ReplaceAllUsesWith(Call, MN); 8370 DAG.DeleteNode(Call); 8371 8372 // Inform the Frame Information that we have a patchpoint in this function. 8373 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8374 } 8375 8376 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8377 unsigned Intrinsic) { 8378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8379 SDValue Op1 = getValue(I.getArgOperand(0)); 8380 SDValue Op2; 8381 if (I.getNumArgOperands() > 1) 8382 Op2 = getValue(I.getArgOperand(1)); 8383 SDLoc dl = getCurSDLoc(); 8384 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8385 SDValue Res; 8386 FastMathFlags FMF; 8387 if (isa<FPMathOperator>(I)) 8388 FMF = I.getFastMathFlags(); 8389 8390 switch (Intrinsic) { 8391 case Intrinsic::experimental_vector_reduce_fadd: 8392 if (FMF.isFast()) 8393 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8394 else 8395 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8396 break; 8397 case Intrinsic::experimental_vector_reduce_fmul: 8398 if (FMF.isFast()) 8399 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8400 else 8401 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8402 break; 8403 case Intrinsic::experimental_vector_reduce_add: 8404 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8405 break; 8406 case Intrinsic::experimental_vector_reduce_mul: 8407 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8408 break; 8409 case Intrinsic::experimental_vector_reduce_and: 8410 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8411 break; 8412 case Intrinsic::experimental_vector_reduce_or: 8413 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8414 break; 8415 case Intrinsic::experimental_vector_reduce_xor: 8416 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8417 break; 8418 case Intrinsic::experimental_vector_reduce_smax: 8419 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8420 break; 8421 case Intrinsic::experimental_vector_reduce_smin: 8422 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8423 break; 8424 case Intrinsic::experimental_vector_reduce_umax: 8425 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8426 break; 8427 case Intrinsic::experimental_vector_reduce_umin: 8428 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8429 break; 8430 case Intrinsic::experimental_vector_reduce_fmax: 8431 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8432 break; 8433 case Intrinsic::experimental_vector_reduce_fmin: 8434 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8435 break; 8436 default: 8437 llvm_unreachable("Unhandled vector reduce intrinsic"); 8438 } 8439 setValue(&I, Res); 8440 } 8441 8442 /// Returns an AttributeList representing the attributes applied to the return 8443 /// value of the given call. 8444 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8445 SmallVector<Attribute::AttrKind, 2> Attrs; 8446 if (CLI.RetSExt) 8447 Attrs.push_back(Attribute::SExt); 8448 if (CLI.RetZExt) 8449 Attrs.push_back(Attribute::ZExt); 8450 if (CLI.IsInReg) 8451 Attrs.push_back(Attribute::InReg); 8452 8453 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8454 Attrs); 8455 } 8456 8457 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8458 /// implementation, which just calls LowerCall. 8459 /// FIXME: When all targets are 8460 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8461 std::pair<SDValue, SDValue> 8462 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8463 // Handle the incoming return values from the call. 8464 CLI.Ins.clear(); 8465 Type *OrigRetTy = CLI.RetTy; 8466 SmallVector<EVT, 4> RetTys; 8467 SmallVector<uint64_t, 4> Offsets; 8468 auto &DL = CLI.DAG.getDataLayout(); 8469 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8470 8471 if (CLI.IsPostTypeLegalization) { 8472 // If we are lowering a libcall after legalization, split the return type. 8473 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8474 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8475 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8476 EVT RetVT = OldRetTys[i]; 8477 uint64_t Offset = OldOffsets[i]; 8478 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8479 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8480 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8481 RetTys.append(NumRegs, RegisterVT); 8482 for (unsigned j = 0; j != NumRegs; ++j) 8483 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8484 } 8485 } 8486 8487 SmallVector<ISD::OutputArg, 4> Outs; 8488 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8489 8490 bool CanLowerReturn = 8491 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8492 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8493 8494 SDValue DemoteStackSlot; 8495 int DemoteStackIdx = -100; 8496 if (!CanLowerReturn) { 8497 // FIXME: equivalent assert? 8498 // assert(!CS.hasInAllocaArgument() && 8499 // "sret demotion is incompatible with inalloca"); 8500 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8501 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8502 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8503 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8504 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8505 DL.getAllocaAddrSpace()); 8506 8507 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8508 ArgListEntry Entry; 8509 Entry.Node = DemoteStackSlot; 8510 Entry.Ty = StackSlotPtrType; 8511 Entry.IsSExt = false; 8512 Entry.IsZExt = false; 8513 Entry.IsInReg = false; 8514 Entry.IsSRet = true; 8515 Entry.IsNest = false; 8516 Entry.IsByVal = false; 8517 Entry.IsReturned = false; 8518 Entry.IsSwiftSelf = false; 8519 Entry.IsSwiftError = false; 8520 Entry.Alignment = Align; 8521 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8522 CLI.NumFixedArgs += 1; 8523 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8524 8525 // sret demotion isn't compatible with tail-calls, since the sret argument 8526 // points into the callers stack frame. 8527 CLI.IsTailCall = false; 8528 } else { 8529 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8530 EVT VT = RetTys[I]; 8531 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8532 CLI.CallConv, VT); 8533 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8534 CLI.CallConv, VT); 8535 for (unsigned i = 0; i != NumRegs; ++i) { 8536 ISD::InputArg MyFlags; 8537 MyFlags.VT = RegisterVT; 8538 MyFlags.ArgVT = VT; 8539 MyFlags.Used = CLI.IsReturnValueUsed; 8540 if (CLI.RetSExt) 8541 MyFlags.Flags.setSExt(); 8542 if (CLI.RetZExt) 8543 MyFlags.Flags.setZExt(); 8544 if (CLI.IsInReg) 8545 MyFlags.Flags.setInReg(); 8546 CLI.Ins.push_back(MyFlags); 8547 } 8548 } 8549 } 8550 8551 // We push in swifterror return as the last element of CLI.Ins. 8552 ArgListTy &Args = CLI.getArgs(); 8553 if (supportSwiftError()) { 8554 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8555 if (Args[i].IsSwiftError) { 8556 ISD::InputArg MyFlags; 8557 MyFlags.VT = getPointerTy(DL); 8558 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8559 MyFlags.Flags.setSwiftError(); 8560 CLI.Ins.push_back(MyFlags); 8561 } 8562 } 8563 } 8564 8565 // Handle all of the outgoing arguments. 8566 CLI.Outs.clear(); 8567 CLI.OutVals.clear(); 8568 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8569 SmallVector<EVT, 4> ValueVTs; 8570 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8571 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8572 Type *FinalType = Args[i].Ty; 8573 if (Args[i].IsByVal) 8574 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8575 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8576 FinalType, CLI.CallConv, CLI.IsVarArg); 8577 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8578 ++Value) { 8579 EVT VT = ValueVTs[Value]; 8580 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8581 SDValue Op = SDValue(Args[i].Node.getNode(), 8582 Args[i].Node.getResNo() + Value); 8583 ISD::ArgFlagsTy Flags; 8584 8585 // Certain targets (such as MIPS), may have a different ABI alignment 8586 // for a type depending on the context. Give the target a chance to 8587 // specify the alignment it wants. 8588 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8589 8590 if (Args[i].IsZExt) 8591 Flags.setZExt(); 8592 if (Args[i].IsSExt) 8593 Flags.setSExt(); 8594 if (Args[i].IsInReg) { 8595 // If we are using vectorcall calling convention, a structure that is 8596 // passed InReg - is surely an HVA 8597 if (CLI.CallConv == CallingConv::X86_VectorCall && 8598 isa<StructType>(FinalType)) { 8599 // The first value of a structure is marked 8600 if (0 == Value) 8601 Flags.setHvaStart(); 8602 Flags.setHva(); 8603 } 8604 // Set InReg Flag 8605 Flags.setInReg(); 8606 } 8607 if (Args[i].IsSRet) 8608 Flags.setSRet(); 8609 if (Args[i].IsSwiftSelf) 8610 Flags.setSwiftSelf(); 8611 if (Args[i].IsSwiftError) 8612 Flags.setSwiftError(); 8613 if (Args[i].IsByVal) 8614 Flags.setByVal(); 8615 if (Args[i].IsInAlloca) { 8616 Flags.setInAlloca(); 8617 // Set the byval flag for CCAssignFn callbacks that don't know about 8618 // inalloca. This way we can know how many bytes we should've allocated 8619 // and how many bytes a callee cleanup function will pop. If we port 8620 // inalloca to more targets, we'll have to add custom inalloca handling 8621 // in the various CC lowering callbacks. 8622 Flags.setByVal(); 8623 } 8624 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8625 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8626 Type *ElementTy = Ty->getElementType(); 8627 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8628 // For ByVal, alignment should come from FE. BE will guess if this 8629 // info is not there but there are cases it cannot get right. 8630 unsigned FrameAlign; 8631 if (Args[i].Alignment) 8632 FrameAlign = Args[i].Alignment; 8633 else 8634 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8635 Flags.setByValAlign(FrameAlign); 8636 } 8637 if (Args[i].IsNest) 8638 Flags.setNest(); 8639 if (NeedsRegBlock) 8640 Flags.setInConsecutiveRegs(); 8641 Flags.setOrigAlign(OriginalAlignment); 8642 8643 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8644 CLI.CallConv, VT); 8645 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8646 CLI.CallConv, VT); 8647 SmallVector<SDValue, 4> Parts(NumParts); 8648 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8649 8650 if (Args[i].IsSExt) 8651 ExtendKind = ISD::SIGN_EXTEND; 8652 else if (Args[i].IsZExt) 8653 ExtendKind = ISD::ZERO_EXTEND; 8654 8655 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8656 // for now. 8657 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8658 CanLowerReturn) { 8659 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8660 "unexpected use of 'returned'"); 8661 // Before passing 'returned' to the target lowering code, ensure that 8662 // either the register MVT and the actual EVT are the same size or that 8663 // the return value and argument are extended in the same way; in these 8664 // cases it's safe to pass the argument register value unchanged as the 8665 // return register value (although it's at the target's option whether 8666 // to do so) 8667 // TODO: allow code generation to take advantage of partially preserved 8668 // registers rather than clobbering the entire register when the 8669 // parameter extension method is not compatible with the return 8670 // extension method 8671 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8672 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8673 CLI.RetZExt == Args[i].IsZExt)) 8674 Flags.setReturned(); 8675 } 8676 8677 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8678 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8679 8680 for (unsigned j = 0; j != NumParts; ++j) { 8681 // if it isn't first piece, alignment must be 1 8682 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8683 i < CLI.NumFixedArgs, 8684 i, j*Parts[j].getValueType().getStoreSize()); 8685 if (NumParts > 1 && j == 0) 8686 MyFlags.Flags.setSplit(); 8687 else if (j != 0) { 8688 MyFlags.Flags.setOrigAlign(1); 8689 if (j == NumParts - 1) 8690 MyFlags.Flags.setSplitEnd(); 8691 } 8692 8693 CLI.Outs.push_back(MyFlags); 8694 CLI.OutVals.push_back(Parts[j]); 8695 } 8696 8697 if (NeedsRegBlock && Value == NumValues - 1) 8698 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8699 } 8700 } 8701 8702 SmallVector<SDValue, 4> InVals; 8703 CLI.Chain = LowerCall(CLI, InVals); 8704 8705 // Update CLI.InVals to use outside of this function. 8706 CLI.InVals = InVals; 8707 8708 // Verify that the target's LowerCall behaved as expected. 8709 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8710 "LowerCall didn't return a valid chain!"); 8711 assert((!CLI.IsTailCall || InVals.empty()) && 8712 "LowerCall emitted a return value for a tail call!"); 8713 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8714 "LowerCall didn't emit the correct number of values!"); 8715 8716 // For a tail call, the return value is merely live-out and there aren't 8717 // any nodes in the DAG representing it. Return a special value to 8718 // indicate that a tail call has been emitted and no more Instructions 8719 // should be processed in the current block. 8720 if (CLI.IsTailCall) { 8721 CLI.DAG.setRoot(CLI.Chain); 8722 return std::make_pair(SDValue(), SDValue()); 8723 } 8724 8725 #ifndef NDEBUG 8726 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8727 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8728 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8729 "LowerCall emitted a value with the wrong type!"); 8730 } 8731 #endif 8732 8733 SmallVector<SDValue, 4> ReturnValues; 8734 if (!CanLowerReturn) { 8735 // The instruction result is the result of loading from the 8736 // hidden sret parameter. 8737 SmallVector<EVT, 1> PVTs; 8738 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8739 8740 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8741 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8742 EVT PtrVT = PVTs[0]; 8743 8744 unsigned NumValues = RetTys.size(); 8745 ReturnValues.resize(NumValues); 8746 SmallVector<SDValue, 4> Chains(NumValues); 8747 8748 // An aggregate return value cannot wrap around the address space, so 8749 // offsets to its parts don't wrap either. 8750 SDNodeFlags Flags; 8751 Flags.setNoUnsignedWrap(true); 8752 8753 for (unsigned i = 0; i < NumValues; ++i) { 8754 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8755 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8756 PtrVT), Flags); 8757 SDValue L = CLI.DAG.getLoad( 8758 RetTys[i], CLI.DL, CLI.Chain, Add, 8759 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8760 DemoteStackIdx, Offsets[i]), 8761 /* Alignment = */ 1); 8762 ReturnValues[i] = L; 8763 Chains[i] = L.getValue(1); 8764 } 8765 8766 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8767 } else { 8768 // Collect the legal value parts into potentially illegal values 8769 // that correspond to the original function's return values. 8770 Optional<ISD::NodeType> AssertOp; 8771 if (CLI.RetSExt) 8772 AssertOp = ISD::AssertSext; 8773 else if (CLI.RetZExt) 8774 AssertOp = ISD::AssertZext; 8775 unsigned CurReg = 0; 8776 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8777 EVT VT = RetTys[I]; 8778 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8779 CLI.CallConv, VT); 8780 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8781 CLI.CallConv, VT); 8782 8783 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8784 NumRegs, RegisterVT, VT, nullptr, 8785 CLI.CallConv, AssertOp)); 8786 CurReg += NumRegs; 8787 } 8788 8789 // For a function returning void, there is no return value. We can't create 8790 // such a node, so we just return a null return value in that case. In 8791 // that case, nothing will actually look at the value. 8792 if (ReturnValues.empty()) 8793 return std::make_pair(SDValue(), CLI.Chain); 8794 } 8795 8796 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8797 CLI.DAG.getVTList(RetTys), ReturnValues); 8798 return std::make_pair(Res, CLI.Chain); 8799 } 8800 8801 void TargetLowering::LowerOperationWrapper(SDNode *N, 8802 SmallVectorImpl<SDValue> &Results, 8803 SelectionDAG &DAG) const { 8804 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8805 Results.push_back(Res); 8806 } 8807 8808 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8809 llvm_unreachable("LowerOperation not implemented for this target!"); 8810 } 8811 8812 void 8813 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8814 SDValue Op = getNonRegisterValue(V); 8815 assert((Op.getOpcode() != ISD::CopyFromReg || 8816 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8817 "Copy from a reg to the same reg!"); 8818 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8819 8820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8821 // If this is an InlineAsm we have to match the registers required, not the 8822 // notional registers required by the type. 8823 8824 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8825 None); // This is not an ABI copy. 8826 SDValue Chain = DAG.getEntryNode(); 8827 8828 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8829 FuncInfo.PreferredExtendType.end()) 8830 ? ISD::ANY_EXTEND 8831 : FuncInfo.PreferredExtendType[V]; 8832 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8833 PendingExports.push_back(Chain); 8834 } 8835 8836 #include "llvm/CodeGen/SelectionDAGISel.h" 8837 8838 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8839 /// entry block, return true. This includes arguments used by switches, since 8840 /// the switch may expand into multiple basic blocks. 8841 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8842 // With FastISel active, we may be splitting blocks, so force creation 8843 // of virtual registers for all non-dead arguments. 8844 if (FastISel) 8845 return A->use_empty(); 8846 8847 const BasicBlock &Entry = A->getParent()->front(); 8848 for (const User *U : A->users()) 8849 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8850 return false; // Use not in entry block. 8851 8852 return true; 8853 } 8854 8855 using ArgCopyElisionMapTy = 8856 DenseMap<const Argument *, 8857 std::pair<const AllocaInst *, const StoreInst *>>; 8858 8859 /// Scan the entry block of the function in FuncInfo for arguments that look 8860 /// like copies into a local alloca. Record any copied arguments in 8861 /// ArgCopyElisionCandidates. 8862 static void 8863 findArgumentCopyElisionCandidates(const DataLayout &DL, 8864 FunctionLoweringInfo *FuncInfo, 8865 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8866 // Record the state of every static alloca used in the entry block. Argument 8867 // allocas are all used in the entry block, so we need approximately as many 8868 // entries as we have arguments. 8869 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8870 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8871 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8872 StaticAllocas.reserve(NumArgs * 2); 8873 8874 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8875 if (!V) 8876 return nullptr; 8877 V = V->stripPointerCasts(); 8878 const auto *AI = dyn_cast<AllocaInst>(V); 8879 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8880 return nullptr; 8881 auto Iter = StaticAllocas.insert({AI, Unknown}); 8882 return &Iter.first->second; 8883 }; 8884 8885 // Look for stores of arguments to static allocas. Look through bitcasts and 8886 // GEPs to handle type coercions, as long as the alloca is fully initialized 8887 // by the store. Any non-store use of an alloca escapes it and any subsequent 8888 // unanalyzed store might write it. 8889 // FIXME: Handle structs initialized with multiple stores. 8890 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8891 // Look for stores, and handle non-store uses conservatively. 8892 const auto *SI = dyn_cast<StoreInst>(&I); 8893 if (!SI) { 8894 // We will look through cast uses, so ignore them completely. 8895 if (I.isCast()) 8896 continue; 8897 // Ignore debug info intrinsics, they don't escape or store to allocas. 8898 if (isa<DbgInfoIntrinsic>(I)) 8899 continue; 8900 // This is an unknown instruction. Assume it escapes or writes to all 8901 // static alloca operands. 8902 for (const Use &U : I.operands()) { 8903 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8904 *Info = StaticAllocaInfo::Clobbered; 8905 } 8906 continue; 8907 } 8908 8909 // If the stored value is a static alloca, mark it as escaped. 8910 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8911 *Info = StaticAllocaInfo::Clobbered; 8912 8913 // Check if the destination is a static alloca. 8914 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8915 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8916 if (!Info) 8917 continue; 8918 const AllocaInst *AI = cast<AllocaInst>(Dst); 8919 8920 // Skip allocas that have been initialized or clobbered. 8921 if (*Info != StaticAllocaInfo::Unknown) 8922 continue; 8923 8924 // Check if the stored value is an argument, and that this store fully 8925 // initializes the alloca. Don't elide copies from the same argument twice. 8926 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8927 const auto *Arg = dyn_cast<Argument>(Val); 8928 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8929 Arg->getType()->isEmptyTy() || 8930 DL.getTypeStoreSize(Arg->getType()) != 8931 DL.getTypeAllocSize(AI->getAllocatedType()) || 8932 ArgCopyElisionCandidates.count(Arg)) { 8933 *Info = StaticAllocaInfo::Clobbered; 8934 continue; 8935 } 8936 8937 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8938 << '\n'); 8939 8940 // Mark this alloca and store for argument copy elision. 8941 *Info = StaticAllocaInfo::Elidable; 8942 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8943 8944 // Stop scanning if we've seen all arguments. This will happen early in -O0 8945 // builds, which is useful, because -O0 builds have large entry blocks and 8946 // many allocas. 8947 if (ArgCopyElisionCandidates.size() == NumArgs) 8948 break; 8949 } 8950 } 8951 8952 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8953 /// ArgVal is a load from a suitable fixed stack object. 8954 static void tryToElideArgumentCopy( 8955 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8956 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8957 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8958 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8959 SDValue ArgVal, bool &ArgHasUses) { 8960 // Check if this is a load from a fixed stack object. 8961 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8962 if (!LNode) 8963 return; 8964 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8965 if (!FINode) 8966 return; 8967 8968 // Check that the fixed stack object is the right size and alignment. 8969 // Look at the alignment that the user wrote on the alloca instead of looking 8970 // at the stack object. 8971 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8972 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8973 const AllocaInst *AI = ArgCopyIter->second.first; 8974 int FixedIndex = FINode->getIndex(); 8975 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8976 int OldIndex = AllocaIndex; 8977 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8978 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8979 LLVM_DEBUG( 8980 dbgs() << " argument copy elision failed due to bad fixed stack " 8981 "object size\n"); 8982 return; 8983 } 8984 unsigned RequiredAlignment = AI->getAlignment(); 8985 if (!RequiredAlignment) { 8986 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8987 AI->getAllocatedType()); 8988 } 8989 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8990 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8991 "greater than stack argument alignment (" 8992 << RequiredAlignment << " vs " 8993 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8994 return; 8995 } 8996 8997 // Perform the elision. Delete the old stack object and replace its only use 8998 // in the variable info map. Mark the stack object as mutable. 8999 LLVM_DEBUG({ 9000 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9001 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9002 << '\n'; 9003 }); 9004 MFI.RemoveStackObject(OldIndex); 9005 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9006 AllocaIndex = FixedIndex; 9007 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9008 Chains.push_back(ArgVal.getValue(1)); 9009 9010 // Avoid emitting code for the store implementing the copy. 9011 const StoreInst *SI = ArgCopyIter->second.second; 9012 ElidedArgCopyInstrs.insert(SI); 9013 9014 // Check for uses of the argument again so that we can avoid exporting ArgVal 9015 // if it is't used by anything other than the store. 9016 for (const Value *U : Arg.users()) { 9017 if (U != SI) { 9018 ArgHasUses = true; 9019 break; 9020 } 9021 } 9022 } 9023 9024 void SelectionDAGISel::LowerArguments(const Function &F) { 9025 SelectionDAG &DAG = SDB->DAG; 9026 SDLoc dl = SDB->getCurSDLoc(); 9027 const DataLayout &DL = DAG.getDataLayout(); 9028 SmallVector<ISD::InputArg, 16> Ins; 9029 9030 if (!FuncInfo->CanLowerReturn) { 9031 // Put in an sret pointer parameter before all the other parameters. 9032 SmallVector<EVT, 1> ValueVTs; 9033 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9034 F.getReturnType()->getPointerTo( 9035 DAG.getDataLayout().getAllocaAddrSpace()), 9036 ValueVTs); 9037 9038 // NOTE: Assuming that a pointer will never break down to more than one VT 9039 // or one register. 9040 ISD::ArgFlagsTy Flags; 9041 Flags.setSRet(); 9042 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9043 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9044 ISD::InputArg::NoArgIndex, 0); 9045 Ins.push_back(RetArg); 9046 } 9047 9048 // Look for stores of arguments to static allocas. Mark such arguments with a 9049 // flag to ask the target to give us the memory location of that argument if 9050 // available. 9051 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9052 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9053 9054 // Set up the incoming argument description vector. 9055 for (const Argument &Arg : F.args()) { 9056 unsigned ArgNo = Arg.getArgNo(); 9057 SmallVector<EVT, 4> ValueVTs; 9058 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9059 bool isArgValueUsed = !Arg.use_empty(); 9060 unsigned PartBase = 0; 9061 Type *FinalType = Arg.getType(); 9062 if (Arg.hasAttribute(Attribute::ByVal)) 9063 FinalType = cast<PointerType>(FinalType)->getElementType(); 9064 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9065 FinalType, F.getCallingConv(), F.isVarArg()); 9066 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9067 Value != NumValues; ++Value) { 9068 EVT VT = ValueVTs[Value]; 9069 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9070 ISD::ArgFlagsTy Flags; 9071 9072 // Certain targets (such as MIPS), may have a different ABI alignment 9073 // for a type depending on the context. Give the target a chance to 9074 // specify the alignment it wants. 9075 unsigned OriginalAlignment = 9076 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9077 9078 if (Arg.hasAttribute(Attribute::ZExt)) 9079 Flags.setZExt(); 9080 if (Arg.hasAttribute(Attribute::SExt)) 9081 Flags.setSExt(); 9082 if (Arg.hasAttribute(Attribute::InReg)) { 9083 // If we are using vectorcall calling convention, a structure that is 9084 // passed InReg - is surely an HVA 9085 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9086 isa<StructType>(Arg.getType())) { 9087 // The first value of a structure is marked 9088 if (0 == Value) 9089 Flags.setHvaStart(); 9090 Flags.setHva(); 9091 } 9092 // Set InReg Flag 9093 Flags.setInReg(); 9094 } 9095 if (Arg.hasAttribute(Attribute::StructRet)) 9096 Flags.setSRet(); 9097 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9098 Flags.setSwiftSelf(); 9099 if (Arg.hasAttribute(Attribute::SwiftError)) 9100 Flags.setSwiftError(); 9101 if (Arg.hasAttribute(Attribute::ByVal)) 9102 Flags.setByVal(); 9103 if (Arg.hasAttribute(Attribute::InAlloca)) { 9104 Flags.setInAlloca(); 9105 // Set the byval flag for CCAssignFn callbacks that don't know about 9106 // inalloca. This way we can know how many bytes we should've allocated 9107 // and how many bytes a callee cleanup function will pop. If we port 9108 // inalloca to more targets, we'll have to add custom inalloca handling 9109 // in the various CC lowering callbacks. 9110 Flags.setByVal(); 9111 } 9112 if (F.getCallingConv() == CallingConv::X86_INTR) { 9113 // IA Interrupt passes frame (1st parameter) by value in the stack. 9114 if (ArgNo == 0) 9115 Flags.setByVal(); 9116 } 9117 if (Flags.isByVal() || Flags.isInAlloca()) { 9118 PointerType *Ty = cast<PointerType>(Arg.getType()); 9119 Type *ElementTy = Ty->getElementType(); 9120 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9121 // For ByVal, alignment should be passed from FE. BE will guess if 9122 // this info is not there but there are cases it cannot get right. 9123 unsigned FrameAlign; 9124 if (Arg.getParamAlignment()) 9125 FrameAlign = Arg.getParamAlignment(); 9126 else 9127 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9128 Flags.setByValAlign(FrameAlign); 9129 } 9130 if (Arg.hasAttribute(Attribute::Nest)) 9131 Flags.setNest(); 9132 if (NeedsRegBlock) 9133 Flags.setInConsecutiveRegs(); 9134 Flags.setOrigAlign(OriginalAlignment); 9135 if (ArgCopyElisionCandidates.count(&Arg)) 9136 Flags.setCopyElisionCandidate(); 9137 9138 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9139 *CurDAG->getContext(), F.getCallingConv(), VT); 9140 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9141 *CurDAG->getContext(), F.getCallingConv(), VT); 9142 for (unsigned i = 0; i != NumRegs; ++i) { 9143 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9144 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9145 if (NumRegs > 1 && i == 0) 9146 MyFlags.Flags.setSplit(); 9147 // if it isn't first piece, alignment must be 1 9148 else if (i > 0) { 9149 MyFlags.Flags.setOrigAlign(1); 9150 if (i == NumRegs - 1) 9151 MyFlags.Flags.setSplitEnd(); 9152 } 9153 Ins.push_back(MyFlags); 9154 } 9155 if (NeedsRegBlock && Value == NumValues - 1) 9156 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9157 PartBase += VT.getStoreSize(); 9158 } 9159 } 9160 9161 // Call the target to set up the argument values. 9162 SmallVector<SDValue, 8> InVals; 9163 SDValue NewRoot = TLI->LowerFormalArguments( 9164 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9165 9166 // Verify that the target's LowerFormalArguments behaved as expected. 9167 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9168 "LowerFormalArguments didn't return a valid chain!"); 9169 assert(InVals.size() == Ins.size() && 9170 "LowerFormalArguments didn't emit the correct number of values!"); 9171 LLVM_DEBUG({ 9172 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9173 assert(InVals[i].getNode() && 9174 "LowerFormalArguments emitted a null value!"); 9175 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9176 "LowerFormalArguments emitted a value with the wrong type!"); 9177 } 9178 }); 9179 9180 // Update the DAG with the new chain value resulting from argument lowering. 9181 DAG.setRoot(NewRoot); 9182 9183 // Set up the argument values. 9184 unsigned i = 0; 9185 if (!FuncInfo->CanLowerReturn) { 9186 // Create a virtual register for the sret pointer, and put in a copy 9187 // from the sret argument into it. 9188 SmallVector<EVT, 1> ValueVTs; 9189 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9190 F.getReturnType()->getPointerTo( 9191 DAG.getDataLayout().getAllocaAddrSpace()), 9192 ValueVTs); 9193 MVT VT = ValueVTs[0].getSimpleVT(); 9194 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9195 Optional<ISD::NodeType> AssertOp = None; 9196 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9197 nullptr, F.getCallingConv(), AssertOp); 9198 9199 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9200 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9201 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9202 FuncInfo->DemoteRegister = SRetReg; 9203 NewRoot = 9204 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9205 DAG.setRoot(NewRoot); 9206 9207 // i indexes lowered arguments. Bump it past the hidden sret argument. 9208 ++i; 9209 } 9210 9211 SmallVector<SDValue, 4> Chains; 9212 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9213 for (const Argument &Arg : F.args()) { 9214 SmallVector<SDValue, 4> ArgValues; 9215 SmallVector<EVT, 4> ValueVTs; 9216 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9217 unsigned NumValues = ValueVTs.size(); 9218 if (NumValues == 0) 9219 continue; 9220 9221 bool ArgHasUses = !Arg.use_empty(); 9222 9223 // Elide the copying store if the target loaded this argument from a 9224 // suitable fixed stack object. 9225 if (Ins[i].Flags.isCopyElisionCandidate()) { 9226 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9227 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9228 InVals[i], ArgHasUses); 9229 } 9230 9231 // If this argument is unused then remember its value. It is used to generate 9232 // debugging information. 9233 bool isSwiftErrorArg = 9234 TLI->supportSwiftError() && 9235 Arg.hasAttribute(Attribute::SwiftError); 9236 if (!ArgHasUses && !isSwiftErrorArg) { 9237 SDB->setUnusedArgValue(&Arg, InVals[i]); 9238 9239 // Also remember any frame index for use in FastISel. 9240 if (FrameIndexSDNode *FI = 9241 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9242 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9243 } 9244 9245 for (unsigned Val = 0; Val != NumValues; ++Val) { 9246 EVT VT = ValueVTs[Val]; 9247 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9248 F.getCallingConv(), VT); 9249 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9250 *CurDAG->getContext(), F.getCallingConv(), VT); 9251 9252 // Even an apparant 'unused' swifterror argument needs to be returned. So 9253 // we do generate a copy for it that can be used on return from the 9254 // function. 9255 if (ArgHasUses || isSwiftErrorArg) { 9256 Optional<ISD::NodeType> AssertOp; 9257 if (Arg.hasAttribute(Attribute::SExt)) 9258 AssertOp = ISD::AssertSext; 9259 else if (Arg.hasAttribute(Attribute::ZExt)) 9260 AssertOp = ISD::AssertZext; 9261 9262 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9263 PartVT, VT, nullptr, 9264 F.getCallingConv(), AssertOp)); 9265 } 9266 9267 i += NumParts; 9268 } 9269 9270 // We don't need to do anything else for unused arguments. 9271 if (ArgValues.empty()) 9272 continue; 9273 9274 // Note down frame index. 9275 if (FrameIndexSDNode *FI = 9276 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9277 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9278 9279 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9280 SDB->getCurSDLoc()); 9281 9282 SDB->setValue(&Arg, Res); 9283 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9284 // We want to associate the argument with the frame index, among 9285 // involved operands, that correspond to the lowest address. The 9286 // getCopyFromParts function, called earlier, is swapping the order of 9287 // the operands to BUILD_PAIR depending on endianness. The result of 9288 // that swapping is that the least significant bits of the argument will 9289 // be in the first operand of the BUILD_PAIR node, and the most 9290 // significant bits will be in the second operand. 9291 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9292 if (LoadSDNode *LNode = 9293 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9294 if (FrameIndexSDNode *FI = 9295 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9296 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9297 } 9298 9299 // Update the SwiftErrorVRegDefMap. 9300 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9301 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9302 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9303 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9304 FuncInfo->SwiftErrorArg, Reg); 9305 } 9306 9307 // If this argument is live outside of the entry block, insert a copy from 9308 // wherever we got it to the vreg that other BB's will reference it as. 9309 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9310 // If we can, though, try to skip creating an unnecessary vreg. 9311 // FIXME: This isn't very clean... it would be nice to make this more 9312 // general. It's also subtly incompatible with the hacks FastISel 9313 // uses with vregs. 9314 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9315 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9316 FuncInfo->ValueMap[&Arg] = Reg; 9317 continue; 9318 } 9319 } 9320 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9321 FuncInfo->InitializeRegForValue(&Arg); 9322 SDB->CopyToExportRegsIfNeeded(&Arg); 9323 } 9324 } 9325 9326 if (!Chains.empty()) { 9327 Chains.push_back(NewRoot); 9328 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9329 } 9330 9331 DAG.setRoot(NewRoot); 9332 9333 assert(i == InVals.size() && "Argument register count mismatch!"); 9334 9335 // If any argument copy elisions occurred and we have debug info, update the 9336 // stale frame indices used in the dbg.declare variable info table. 9337 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9338 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9339 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9340 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9341 if (I != ArgCopyElisionFrameIndexMap.end()) 9342 VI.Slot = I->second; 9343 } 9344 } 9345 9346 // Finally, if the target has anything special to do, allow it to do so. 9347 EmitFunctionEntryCode(); 9348 } 9349 9350 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9351 /// ensure constants are generated when needed. Remember the virtual registers 9352 /// that need to be added to the Machine PHI nodes as input. We cannot just 9353 /// directly add them, because expansion might result in multiple MBB's for one 9354 /// BB. As such, the start of the BB might correspond to a different MBB than 9355 /// the end. 9356 void 9357 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9358 const Instruction *TI = LLVMBB->getTerminator(); 9359 9360 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9361 9362 // Check PHI nodes in successors that expect a value to be available from this 9363 // block. 9364 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9365 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9366 if (!isa<PHINode>(SuccBB->begin())) continue; 9367 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9368 9369 // If this terminator has multiple identical successors (common for 9370 // switches), only handle each succ once. 9371 if (!SuccsHandled.insert(SuccMBB).second) 9372 continue; 9373 9374 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9375 9376 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9377 // nodes and Machine PHI nodes, but the incoming operands have not been 9378 // emitted yet. 9379 for (const PHINode &PN : SuccBB->phis()) { 9380 // Ignore dead phi's. 9381 if (PN.use_empty()) 9382 continue; 9383 9384 // Skip empty types 9385 if (PN.getType()->isEmptyTy()) 9386 continue; 9387 9388 unsigned Reg; 9389 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9390 9391 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9392 unsigned &RegOut = ConstantsOut[C]; 9393 if (RegOut == 0) { 9394 RegOut = FuncInfo.CreateRegs(C->getType()); 9395 CopyValueToVirtualRegister(C, RegOut); 9396 } 9397 Reg = RegOut; 9398 } else { 9399 DenseMap<const Value *, unsigned>::iterator I = 9400 FuncInfo.ValueMap.find(PHIOp); 9401 if (I != FuncInfo.ValueMap.end()) 9402 Reg = I->second; 9403 else { 9404 assert(isa<AllocaInst>(PHIOp) && 9405 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9406 "Didn't codegen value into a register!??"); 9407 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9408 CopyValueToVirtualRegister(PHIOp, Reg); 9409 } 9410 } 9411 9412 // Remember that this register needs to added to the machine PHI node as 9413 // the input for this MBB. 9414 SmallVector<EVT, 4> ValueVTs; 9415 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9416 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9417 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9418 EVT VT = ValueVTs[vti]; 9419 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9420 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9421 FuncInfo.PHINodesToUpdate.push_back( 9422 std::make_pair(&*MBBI++, Reg + i)); 9423 Reg += NumRegisters; 9424 } 9425 } 9426 } 9427 9428 ConstantsOut.clear(); 9429 } 9430 9431 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9432 /// is 0. 9433 MachineBasicBlock * 9434 SelectionDAGBuilder::StackProtectorDescriptor:: 9435 AddSuccessorMBB(const BasicBlock *BB, 9436 MachineBasicBlock *ParentMBB, 9437 bool IsLikely, 9438 MachineBasicBlock *SuccMBB) { 9439 // If SuccBB has not been created yet, create it. 9440 if (!SuccMBB) { 9441 MachineFunction *MF = ParentMBB->getParent(); 9442 MachineFunction::iterator BBI(ParentMBB); 9443 SuccMBB = MF->CreateMachineBasicBlock(BB); 9444 MF->insert(++BBI, SuccMBB); 9445 } 9446 // Add it as a successor of ParentMBB. 9447 ParentMBB->addSuccessor( 9448 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9449 return SuccMBB; 9450 } 9451 9452 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9453 MachineFunction::iterator I(MBB); 9454 if (++I == FuncInfo.MF->end()) 9455 return nullptr; 9456 return &*I; 9457 } 9458 9459 /// During lowering new call nodes can be created (such as memset, etc.). 9460 /// Those will become new roots of the current DAG, but complications arise 9461 /// when they are tail calls. In such cases, the call lowering will update 9462 /// the root, but the builder still needs to know that a tail call has been 9463 /// lowered in order to avoid generating an additional return. 9464 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9465 // If the node is null, we do have a tail call. 9466 if (MaybeTC.getNode() != nullptr) 9467 DAG.setRoot(MaybeTC); 9468 else 9469 HasTailCall = true; 9470 } 9471 9472 uint64_t 9473 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9474 unsigned First, unsigned Last) const { 9475 assert(Last >= First); 9476 const APInt &LowCase = Clusters[First].Low->getValue(); 9477 const APInt &HighCase = Clusters[Last].High->getValue(); 9478 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9479 9480 // FIXME: A range of consecutive cases has 100% density, but only requires one 9481 // comparison to lower. We should discriminate against such consecutive ranges 9482 // in jump tables. 9483 9484 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9485 } 9486 9487 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9488 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9489 unsigned Last) const { 9490 assert(Last >= First); 9491 assert(TotalCases[Last] >= TotalCases[First]); 9492 uint64_t NumCases = 9493 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9494 return NumCases; 9495 } 9496 9497 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9498 unsigned First, unsigned Last, 9499 const SwitchInst *SI, 9500 MachineBasicBlock *DefaultMBB, 9501 CaseCluster &JTCluster) { 9502 assert(First <= Last); 9503 9504 auto Prob = BranchProbability::getZero(); 9505 unsigned NumCmps = 0; 9506 std::vector<MachineBasicBlock*> Table; 9507 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9508 9509 // Initialize probabilities in JTProbs. 9510 for (unsigned I = First; I <= Last; ++I) 9511 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9512 9513 for (unsigned I = First; I <= Last; ++I) { 9514 assert(Clusters[I].Kind == CC_Range); 9515 Prob += Clusters[I].Prob; 9516 const APInt &Low = Clusters[I].Low->getValue(); 9517 const APInt &High = Clusters[I].High->getValue(); 9518 NumCmps += (Low == High) ? 1 : 2; 9519 if (I != First) { 9520 // Fill the gap between this and the previous cluster. 9521 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9522 assert(PreviousHigh.slt(Low)); 9523 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9524 for (uint64_t J = 0; J < Gap; J++) 9525 Table.push_back(DefaultMBB); 9526 } 9527 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9528 for (uint64_t J = 0; J < ClusterSize; ++J) 9529 Table.push_back(Clusters[I].MBB); 9530 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9531 } 9532 9533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9534 unsigned NumDests = JTProbs.size(); 9535 if (TLI.isSuitableForBitTests( 9536 NumDests, NumCmps, Clusters[First].Low->getValue(), 9537 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9538 // Clusters[First..Last] should be lowered as bit tests instead. 9539 return false; 9540 } 9541 9542 // Create the MBB that will load from and jump through the table. 9543 // Note: We create it here, but it's not inserted into the function yet. 9544 MachineFunction *CurMF = FuncInfo.MF; 9545 MachineBasicBlock *JumpTableMBB = 9546 CurMF->CreateMachineBasicBlock(SI->getParent()); 9547 9548 // Add successors. Note: use table order for determinism. 9549 SmallPtrSet<MachineBasicBlock *, 8> Done; 9550 for (MachineBasicBlock *Succ : Table) { 9551 if (Done.count(Succ)) 9552 continue; 9553 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9554 Done.insert(Succ); 9555 } 9556 JumpTableMBB->normalizeSuccProbs(); 9557 9558 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9559 ->createJumpTableIndex(Table); 9560 9561 // Set up the jump table info. 9562 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9563 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9564 Clusters[Last].High->getValue(), SI->getCondition(), 9565 nullptr, false); 9566 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9567 9568 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9569 JTCases.size() - 1, Prob); 9570 return true; 9571 } 9572 9573 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9574 const SwitchInst *SI, 9575 MachineBasicBlock *DefaultMBB) { 9576 #ifndef NDEBUG 9577 // Clusters must be non-empty, sorted, and only contain Range clusters. 9578 assert(!Clusters.empty()); 9579 for (CaseCluster &C : Clusters) 9580 assert(C.Kind == CC_Range); 9581 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9582 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9583 #endif 9584 9585 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9586 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9587 return; 9588 9589 const int64_t N = Clusters.size(); 9590 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9591 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9592 9593 if (N < 2 || N < MinJumpTableEntries) 9594 return; 9595 9596 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9597 SmallVector<unsigned, 8> TotalCases(N); 9598 for (unsigned i = 0; i < N; ++i) { 9599 const APInt &Hi = Clusters[i].High->getValue(); 9600 const APInt &Lo = Clusters[i].Low->getValue(); 9601 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9602 if (i != 0) 9603 TotalCases[i] += TotalCases[i - 1]; 9604 } 9605 9606 // Cheap case: the whole range may be suitable for jump table. 9607 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9608 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9609 assert(NumCases < UINT64_MAX / 100); 9610 assert(Range >= NumCases); 9611 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9612 CaseCluster JTCluster; 9613 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9614 Clusters[0] = JTCluster; 9615 Clusters.resize(1); 9616 return; 9617 } 9618 } 9619 9620 // The algorithm below is not suitable for -O0. 9621 if (TM.getOptLevel() == CodeGenOpt::None) 9622 return; 9623 9624 // Split Clusters into minimum number of dense partitions. The algorithm uses 9625 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9626 // for the Case Statement'" (1994), but builds the MinPartitions array in 9627 // reverse order to make it easier to reconstruct the partitions in ascending 9628 // order. In the choice between two optimal partitionings, it picks the one 9629 // which yields more jump tables. 9630 9631 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9632 SmallVector<unsigned, 8> MinPartitions(N); 9633 // LastElement[i] is the last element of the partition starting at i. 9634 SmallVector<unsigned, 8> LastElement(N); 9635 // PartitionsScore[i] is used to break ties when choosing between two 9636 // partitionings resulting in the same number of partitions. 9637 SmallVector<unsigned, 8> PartitionsScore(N); 9638 // For PartitionsScore, a small number of comparisons is considered as good as 9639 // a jump table and a single comparison is considered better than a jump 9640 // table. 9641 enum PartitionScores : unsigned { 9642 NoTable = 0, 9643 Table = 1, 9644 FewCases = 1, 9645 SingleCase = 2 9646 }; 9647 9648 // Base case: There is only one way to partition Clusters[N-1]. 9649 MinPartitions[N - 1] = 1; 9650 LastElement[N - 1] = N - 1; 9651 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9652 9653 // Note: loop indexes are signed to avoid underflow. 9654 for (int64_t i = N - 2; i >= 0; i--) { 9655 // Find optimal partitioning of Clusters[i..N-1]. 9656 // Baseline: Put Clusters[i] into a partition on its own. 9657 MinPartitions[i] = MinPartitions[i + 1] + 1; 9658 LastElement[i] = i; 9659 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9660 9661 // Search for a solution that results in fewer partitions. 9662 for (int64_t j = N - 1; j > i; j--) { 9663 // Try building a partition from Clusters[i..j]. 9664 uint64_t Range = getJumpTableRange(Clusters, i, j); 9665 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9666 assert(NumCases < UINT64_MAX / 100); 9667 assert(Range >= NumCases); 9668 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9669 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9670 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9671 int64_t NumEntries = j - i + 1; 9672 9673 if (NumEntries == 1) 9674 Score += PartitionScores::SingleCase; 9675 else if (NumEntries <= SmallNumberOfEntries) 9676 Score += PartitionScores::FewCases; 9677 else if (NumEntries >= MinJumpTableEntries) 9678 Score += PartitionScores::Table; 9679 9680 // If this leads to fewer partitions, or to the same number of 9681 // partitions with better score, it is a better partitioning. 9682 if (NumPartitions < MinPartitions[i] || 9683 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9684 MinPartitions[i] = NumPartitions; 9685 LastElement[i] = j; 9686 PartitionsScore[i] = Score; 9687 } 9688 } 9689 } 9690 } 9691 9692 // Iterate over the partitions, replacing some with jump tables in-place. 9693 unsigned DstIndex = 0; 9694 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9695 Last = LastElement[First]; 9696 assert(Last >= First); 9697 assert(DstIndex <= First); 9698 unsigned NumClusters = Last - First + 1; 9699 9700 CaseCluster JTCluster; 9701 if (NumClusters >= MinJumpTableEntries && 9702 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9703 Clusters[DstIndex++] = JTCluster; 9704 } else { 9705 for (unsigned I = First; I <= Last; ++I) 9706 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9707 } 9708 } 9709 Clusters.resize(DstIndex); 9710 } 9711 9712 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9713 unsigned First, unsigned Last, 9714 const SwitchInst *SI, 9715 CaseCluster &BTCluster) { 9716 assert(First <= Last); 9717 if (First == Last) 9718 return false; 9719 9720 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9721 unsigned NumCmps = 0; 9722 for (int64_t I = First; I <= Last; ++I) { 9723 assert(Clusters[I].Kind == CC_Range); 9724 Dests.set(Clusters[I].MBB->getNumber()); 9725 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9726 } 9727 unsigned NumDests = Dests.count(); 9728 9729 APInt Low = Clusters[First].Low->getValue(); 9730 APInt High = Clusters[Last].High->getValue(); 9731 assert(Low.slt(High)); 9732 9733 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9734 const DataLayout &DL = DAG.getDataLayout(); 9735 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9736 return false; 9737 9738 APInt LowBound; 9739 APInt CmpRange; 9740 9741 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9742 assert(TLI.rangeFitsInWord(Low, High, DL) && 9743 "Case range must fit in bit mask!"); 9744 9745 // Check if the clusters cover a contiguous range such that no value in the 9746 // range will jump to the default statement. 9747 bool ContiguousRange = true; 9748 for (int64_t I = First + 1; I <= Last; ++I) { 9749 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9750 ContiguousRange = false; 9751 break; 9752 } 9753 } 9754 9755 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9756 // Optimize the case where all the case values fit in a word without having 9757 // to subtract minValue. In this case, we can optimize away the subtraction. 9758 LowBound = APInt::getNullValue(Low.getBitWidth()); 9759 CmpRange = High; 9760 ContiguousRange = false; 9761 } else { 9762 LowBound = Low; 9763 CmpRange = High - Low; 9764 } 9765 9766 CaseBitsVector CBV; 9767 auto TotalProb = BranchProbability::getZero(); 9768 for (unsigned i = First; i <= Last; ++i) { 9769 // Find the CaseBits for this destination. 9770 unsigned j; 9771 for (j = 0; j < CBV.size(); ++j) 9772 if (CBV[j].BB == Clusters[i].MBB) 9773 break; 9774 if (j == CBV.size()) 9775 CBV.push_back( 9776 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9777 CaseBits *CB = &CBV[j]; 9778 9779 // Update Mask, Bits and ExtraProb. 9780 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9781 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9782 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9783 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9784 CB->Bits += Hi - Lo + 1; 9785 CB->ExtraProb += Clusters[i].Prob; 9786 TotalProb += Clusters[i].Prob; 9787 } 9788 9789 BitTestInfo BTI; 9790 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9791 // Sort by probability first, number of bits second, bit mask third. 9792 if (a.ExtraProb != b.ExtraProb) 9793 return a.ExtraProb > b.ExtraProb; 9794 if (a.Bits != b.Bits) 9795 return a.Bits > b.Bits; 9796 return a.Mask < b.Mask; 9797 }); 9798 9799 for (auto &CB : CBV) { 9800 MachineBasicBlock *BitTestBB = 9801 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9802 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9803 } 9804 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9805 SI->getCondition(), -1U, MVT::Other, false, 9806 ContiguousRange, nullptr, nullptr, std::move(BTI), 9807 TotalProb); 9808 9809 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9810 BitTestCases.size() - 1, TotalProb); 9811 return true; 9812 } 9813 9814 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9815 const SwitchInst *SI) { 9816 // Partition Clusters into as few subsets as possible, where each subset has a 9817 // range that fits in a machine word and has <= 3 unique destinations. 9818 9819 #ifndef NDEBUG 9820 // Clusters must be sorted and contain Range or JumpTable clusters. 9821 assert(!Clusters.empty()); 9822 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9823 for (const CaseCluster &C : Clusters) 9824 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9825 for (unsigned i = 1; i < Clusters.size(); ++i) 9826 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9827 #endif 9828 9829 // The algorithm below is not suitable for -O0. 9830 if (TM.getOptLevel() == CodeGenOpt::None) 9831 return; 9832 9833 // If target does not have legal shift left, do not emit bit tests at all. 9834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9835 const DataLayout &DL = DAG.getDataLayout(); 9836 9837 EVT PTy = TLI.getPointerTy(DL); 9838 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9839 return; 9840 9841 int BitWidth = PTy.getSizeInBits(); 9842 const int64_t N = Clusters.size(); 9843 9844 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9845 SmallVector<unsigned, 8> MinPartitions(N); 9846 // LastElement[i] is the last element of the partition starting at i. 9847 SmallVector<unsigned, 8> LastElement(N); 9848 9849 // FIXME: This might not be the best algorithm for finding bit test clusters. 9850 9851 // Base case: There is only one way to partition Clusters[N-1]. 9852 MinPartitions[N - 1] = 1; 9853 LastElement[N - 1] = N - 1; 9854 9855 // Note: loop indexes are signed to avoid underflow. 9856 for (int64_t i = N - 2; i >= 0; --i) { 9857 // Find optimal partitioning of Clusters[i..N-1]. 9858 // Baseline: Put Clusters[i] into a partition on its own. 9859 MinPartitions[i] = MinPartitions[i + 1] + 1; 9860 LastElement[i] = i; 9861 9862 // Search for a solution that results in fewer partitions. 9863 // Note: the search is limited by BitWidth, reducing time complexity. 9864 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9865 // Try building a partition from Clusters[i..j]. 9866 9867 // Check the range. 9868 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9869 Clusters[j].High->getValue(), DL)) 9870 continue; 9871 9872 // Check nbr of destinations and cluster types. 9873 // FIXME: This works, but doesn't seem very efficient. 9874 bool RangesOnly = true; 9875 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9876 for (int64_t k = i; k <= j; k++) { 9877 if (Clusters[k].Kind != CC_Range) { 9878 RangesOnly = false; 9879 break; 9880 } 9881 Dests.set(Clusters[k].MBB->getNumber()); 9882 } 9883 if (!RangesOnly || Dests.count() > 3) 9884 break; 9885 9886 // Check if it's a better partition. 9887 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9888 if (NumPartitions < MinPartitions[i]) { 9889 // Found a better partition. 9890 MinPartitions[i] = NumPartitions; 9891 LastElement[i] = j; 9892 } 9893 } 9894 } 9895 9896 // Iterate over the partitions, replacing with bit-test clusters in-place. 9897 unsigned DstIndex = 0; 9898 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9899 Last = LastElement[First]; 9900 assert(First <= Last); 9901 assert(DstIndex <= First); 9902 9903 CaseCluster BitTestCluster; 9904 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9905 Clusters[DstIndex++] = BitTestCluster; 9906 } else { 9907 size_t NumClusters = Last - First + 1; 9908 std::memmove(&Clusters[DstIndex], &Clusters[First], 9909 sizeof(Clusters[0]) * NumClusters); 9910 DstIndex += NumClusters; 9911 } 9912 } 9913 Clusters.resize(DstIndex); 9914 } 9915 9916 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9917 MachineBasicBlock *SwitchMBB, 9918 MachineBasicBlock *DefaultMBB) { 9919 MachineFunction *CurMF = FuncInfo.MF; 9920 MachineBasicBlock *NextMBB = nullptr; 9921 MachineFunction::iterator BBI(W.MBB); 9922 if (++BBI != FuncInfo.MF->end()) 9923 NextMBB = &*BBI; 9924 9925 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9926 9927 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9928 9929 if (Size == 2 && W.MBB == SwitchMBB) { 9930 // If any two of the cases has the same destination, and if one value 9931 // is the same as the other, but has one bit unset that the other has set, 9932 // use bit manipulation to do two compares at once. For example: 9933 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9934 // TODO: This could be extended to merge any 2 cases in switches with 3 9935 // cases. 9936 // TODO: Handle cases where W.CaseBB != SwitchBB. 9937 CaseCluster &Small = *W.FirstCluster; 9938 CaseCluster &Big = *W.LastCluster; 9939 9940 if (Small.Low == Small.High && Big.Low == Big.High && 9941 Small.MBB == Big.MBB) { 9942 const APInt &SmallValue = Small.Low->getValue(); 9943 const APInt &BigValue = Big.Low->getValue(); 9944 9945 // Check that there is only one bit different. 9946 APInt CommonBit = BigValue ^ SmallValue; 9947 if (CommonBit.isPowerOf2()) { 9948 SDValue CondLHS = getValue(Cond); 9949 EVT VT = CondLHS.getValueType(); 9950 SDLoc DL = getCurSDLoc(); 9951 9952 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9953 DAG.getConstant(CommonBit, DL, VT)); 9954 SDValue Cond = DAG.getSetCC( 9955 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9956 ISD::SETEQ); 9957 9958 // Update successor info. 9959 // Both Small and Big will jump to Small.BB, so we sum up the 9960 // probabilities. 9961 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9962 if (BPI) 9963 addSuccessorWithProb( 9964 SwitchMBB, DefaultMBB, 9965 // The default destination is the first successor in IR. 9966 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9967 else 9968 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9969 9970 // Insert the true branch. 9971 SDValue BrCond = 9972 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9973 DAG.getBasicBlock(Small.MBB)); 9974 // Insert the false branch. 9975 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9976 DAG.getBasicBlock(DefaultMBB)); 9977 9978 DAG.setRoot(BrCond); 9979 return; 9980 } 9981 } 9982 } 9983 9984 if (TM.getOptLevel() != CodeGenOpt::None) { 9985 // Here, we order cases by probability so the most likely case will be 9986 // checked first. However, two clusters can have the same probability in 9987 // which case their relative ordering is non-deterministic. So we use Low 9988 // as a tie-breaker as clusters are guaranteed to never overlap. 9989 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9990 [](const CaseCluster &a, const CaseCluster &b) { 9991 return a.Prob != b.Prob ? 9992 a.Prob > b.Prob : 9993 a.Low->getValue().slt(b.Low->getValue()); 9994 }); 9995 9996 // Rearrange the case blocks so that the last one falls through if possible 9997 // without changing the order of probabilities. 9998 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9999 --I; 10000 if (I->Prob > W.LastCluster->Prob) 10001 break; 10002 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10003 std::swap(*I, *W.LastCluster); 10004 break; 10005 } 10006 } 10007 } 10008 10009 // Compute total probability. 10010 BranchProbability DefaultProb = W.DefaultProb; 10011 BranchProbability UnhandledProbs = DefaultProb; 10012 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10013 UnhandledProbs += I->Prob; 10014 10015 MachineBasicBlock *CurMBB = W.MBB; 10016 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10017 MachineBasicBlock *Fallthrough; 10018 if (I == W.LastCluster) { 10019 // For the last cluster, fall through to the default destination. 10020 Fallthrough = DefaultMBB; 10021 } else { 10022 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10023 CurMF->insert(BBI, Fallthrough); 10024 // Put Cond in a virtual register to make it available from the new blocks. 10025 ExportFromCurrentBlock(Cond); 10026 } 10027 UnhandledProbs -= I->Prob; 10028 10029 switch (I->Kind) { 10030 case CC_JumpTable: { 10031 // FIXME: Optimize away range check based on pivot comparisons. 10032 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10033 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10034 10035 // The jump block hasn't been inserted yet; insert it here. 10036 MachineBasicBlock *JumpMBB = JT->MBB; 10037 CurMF->insert(BBI, JumpMBB); 10038 10039 auto JumpProb = I->Prob; 10040 auto FallthroughProb = UnhandledProbs; 10041 10042 // If the default statement is a target of the jump table, we evenly 10043 // distribute the default probability to successors of CurMBB. Also 10044 // update the probability on the edge from JumpMBB to Fallthrough. 10045 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10046 SE = JumpMBB->succ_end(); 10047 SI != SE; ++SI) { 10048 if (*SI == DefaultMBB) { 10049 JumpProb += DefaultProb / 2; 10050 FallthroughProb -= DefaultProb / 2; 10051 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10052 JumpMBB->normalizeSuccProbs(); 10053 break; 10054 } 10055 } 10056 10057 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10058 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10059 CurMBB->normalizeSuccProbs(); 10060 10061 // The jump table header will be inserted in our current block, do the 10062 // range check, and fall through to our fallthrough block. 10063 JTH->HeaderBB = CurMBB; 10064 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10065 10066 // If we're in the right place, emit the jump table header right now. 10067 if (CurMBB == SwitchMBB) { 10068 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10069 JTH->Emitted = true; 10070 } 10071 break; 10072 } 10073 case CC_BitTests: { 10074 // FIXME: Optimize away range check based on pivot comparisons. 10075 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10076 10077 // The bit test blocks haven't been inserted yet; insert them here. 10078 for (BitTestCase &BTC : BTB->Cases) 10079 CurMF->insert(BBI, BTC.ThisBB); 10080 10081 // Fill in fields of the BitTestBlock. 10082 BTB->Parent = CurMBB; 10083 BTB->Default = Fallthrough; 10084 10085 BTB->DefaultProb = UnhandledProbs; 10086 // If the cases in bit test don't form a contiguous range, we evenly 10087 // distribute the probability on the edge to Fallthrough to two 10088 // successors of CurMBB. 10089 if (!BTB->ContiguousRange) { 10090 BTB->Prob += DefaultProb / 2; 10091 BTB->DefaultProb -= DefaultProb / 2; 10092 } 10093 10094 // If we're in the right place, emit the bit test header right now. 10095 if (CurMBB == SwitchMBB) { 10096 visitBitTestHeader(*BTB, SwitchMBB); 10097 BTB->Emitted = true; 10098 } 10099 break; 10100 } 10101 case CC_Range: { 10102 const Value *RHS, *LHS, *MHS; 10103 ISD::CondCode CC; 10104 if (I->Low == I->High) { 10105 // Check Cond == I->Low. 10106 CC = ISD::SETEQ; 10107 LHS = Cond; 10108 RHS=I->Low; 10109 MHS = nullptr; 10110 } else { 10111 // Check I->Low <= Cond <= I->High. 10112 CC = ISD::SETLE; 10113 LHS = I->Low; 10114 MHS = Cond; 10115 RHS = I->High; 10116 } 10117 10118 // The false probability is the sum of all unhandled cases. 10119 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10120 getCurSDLoc(), I->Prob, UnhandledProbs); 10121 10122 if (CurMBB == SwitchMBB) 10123 visitSwitchCase(CB, SwitchMBB); 10124 else 10125 SwitchCases.push_back(CB); 10126 10127 break; 10128 } 10129 } 10130 CurMBB = Fallthrough; 10131 } 10132 } 10133 10134 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10135 CaseClusterIt First, 10136 CaseClusterIt Last) { 10137 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10138 if (X.Prob != CC.Prob) 10139 return X.Prob > CC.Prob; 10140 10141 // Ties are broken by comparing the case value. 10142 return X.Low->getValue().slt(CC.Low->getValue()); 10143 }); 10144 } 10145 10146 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10147 const SwitchWorkListItem &W, 10148 Value *Cond, 10149 MachineBasicBlock *SwitchMBB) { 10150 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10151 "Clusters not sorted?"); 10152 10153 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10154 10155 // Balance the tree based on branch probabilities to create a near-optimal (in 10156 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10157 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10158 CaseClusterIt LastLeft = W.FirstCluster; 10159 CaseClusterIt FirstRight = W.LastCluster; 10160 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10161 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10162 10163 // Move LastLeft and FirstRight towards each other from opposite directions to 10164 // find a partitioning of the clusters which balances the probability on both 10165 // sides. If LeftProb and RightProb are equal, alternate which side is 10166 // taken to ensure 0-probability nodes are distributed evenly. 10167 unsigned I = 0; 10168 while (LastLeft + 1 < FirstRight) { 10169 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10170 LeftProb += (++LastLeft)->Prob; 10171 else 10172 RightProb += (--FirstRight)->Prob; 10173 I++; 10174 } 10175 10176 while (true) { 10177 // Our binary search tree differs from a typical BST in that ours can have up 10178 // to three values in each leaf. The pivot selection above doesn't take that 10179 // into account, which means the tree might require more nodes and be less 10180 // efficient. We compensate for this here. 10181 10182 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10183 unsigned NumRight = W.LastCluster - FirstRight + 1; 10184 10185 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10186 // If one side has less than 3 clusters, and the other has more than 3, 10187 // consider taking a cluster from the other side. 10188 10189 if (NumLeft < NumRight) { 10190 // Consider moving the first cluster on the right to the left side. 10191 CaseCluster &CC = *FirstRight; 10192 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10193 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10194 if (LeftSideRank <= RightSideRank) { 10195 // Moving the cluster to the left does not demote it. 10196 ++LastLeft; 10197 ++FirstRight; 10198 continue; 10199 } 10200 } else { 10201 assert(NumRight < NumLeft); 10202 // Consider moving the last element on the left to the right side. 10203 CaseCluster &CC = *LastLeft; 10204 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10205 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10206 if (RightSideRank <= LeftSideRank) { 10207 // Moving the cluster to the right does not demot it. 10208 --LastLeft; 10209 --FirstRight; 10210 continue; 10211 } 10212 } 10213 } 10214 break; 10215 } 10216 10217 assert(LastLeft + 1 == FirstRight); 10218 assert(LastLeft >= W.FirstCluster); 10219 assert(FirstRight <= W.LastCluster); 10220 10221 // Use the first element on the right as pivot since we will make less-than 10222 // comparisons against it. 10223 CaseClusterIt PivotCluster = FirstRight; 10224 assert(PivotCluster > W.FirstCluster); 10225 assert(PivotCluster <= W.LastCluster); 10226 10227 CaseClusterIt FirstLeft = W.FirstCluster; 10228 CaseClusterIt LastRight = W.LastCluster; 10229 10230 const ConstantInt *Pivot = PivotCluster->Low; 10231 10232 // New blocks will be inserted immediately after the current one. 10233 MachineFunction::iterator BBI(W.MBB); 10234 ++BBI; 10235 10236 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10237 // we can branch to its destination directly if it's squeezed exactly in 10238 // between the known lower bound and Pivot - 1. 10239 MachineBasicBlock *LeftMBB; 10240 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10241 FirstLeft->Low == W.GE && 10242 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10243 LeftMBB = FirstLeft->MBB; 10244 } else { 10245 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10246 FuncInfo.MF->insert(BBI, LeftMBB); 10247 WorkList.push_back( 10248 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10249 // Put Cond in a virtual register to make it available from the new blocks. 10250 ExportFromCurrentBlock(Cond); 10251 } 10252 10253 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10254 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10255 // directly if RHS.High equals the current upper bound. 10256 MachineBasicBlock *RightMBB; 10257 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10258 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10259 RightMBB = FirstRight->MBB; 10260 } else { 10261 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10262 FuncInfo.MF->insert(BBI, RightMBB); 10263 WorkList.push_back( 10264 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10265 // Put Cond in a virtual register to make it available from the new blocks. 10266 ExportFromCurrentBlock(Cond); 10267 } 10268 10269 // Create the CaseBlock record that will be used to lower the branch. 10270 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10271 getCurSDLoc(), LeftProb, RightProb); 10272 10273 if (W.MBB == SwitchMBB) 10274 visitSwitchCase(CB, SwitchMBB); 10275 else 10276 SwitchCases.push_back(CB); 10277 } 10278 10279 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10280 // from the swith statement. 10281 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10282 BranchProbability PeeledCaseProb) { 10283 if (PeeledCaseProb == BranchProbability::getOne()) 10284 return BranchProbability::getZero(); 10285 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10286 10287 uint32_t Numerator = CaseProb.getNumerator(); 10288 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10289 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10290 } 10291 10292 // Try to peel the top probability case if it exceeds the threshold. 10293 // Return current MachineBasicBlock for the switch statement if the peeling 10294 // does not occur. 10295 // If the peeling is performed, return the newly created MachineBasicBlock 10296 // for the peeled switch statement. Also update Clusters to remove the peeled 10297 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10298 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10299 const SwitchInst &SI, CaseClusterVector &Clusters, 10300 BranchProbability &PeeledCaseProb) { 10301 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10302 // Don't perform if there is only one cluster or optimizing for size. 10303 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10304 TM.getOptLevel() == CodeGenOpt::None || 10305 SwitchMBB->getParent()->getFunction().optForMinSize()) 10306 return SwitchMBB; 10307 10308 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10309 unsigned PeeledCaseIndex = 0; 10310 bool SwitchPeeled = false; 10311 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10312 CaseCluster &CC = Clusters[Index]; 10313 if (CC.Prob < TopCaseProb) 10314 continue; 10315 TopCaseProb = CC.Prob; 10316 PeeledCaseIndex = Index; 10317 SwitchPeeled = true; 10318 } 10319 if (!SwitchPeeled) 10320 return SwitchMBB; 10321 10322 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10323 << TopCaseProb << "\n"); 10324 10325 // Record the MBB for the peeled switch statement. 10326 MachineFunction::iterator BBI(SwitchMBB); 10327 ++BBI; 10328 MachineBasicBlock *PeeledSwitchMBB = 10329 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10330 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10331 10332 ExportFromCurrentBlock(SI.getCondition()); 10333 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10334 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10335 nullptr, nullptr, TopCaseProb.getCompl()}; 10336 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10337 10338 Clusters.erase(PeeledCaseIt); 10339 for (CaseCluster &CC : Clusters) { 10340 LLVM_DEBUG( 10341 dbgs() << "Scale the probablity for one cluster, before scaling: " 10342 << CC.Prob << "\n"); 10343 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10344 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10345 } 10346 PeeledCaseProb = TopCaseProb; 10347 return PeeledSwitchMBB; 10348 } 10349 10350 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10351 // Extract cases from the switch. 10352 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10353 CaseClusterVector Clusters; 10354 Clusters.reserve(SI.getNumCases()); 10355 for (auto I : SI.cases()) { 10356 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10357 const ConstantInt *CaseVal = I.getCaseValue(); 10358 BranchProbability Prob = 10359 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10360 : BranchProbability(1, SI.getNumCases() + 1); 10361 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10362 } 10363 10364 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10365 10366 // Cluster adjacent cases with the same destination. We do this at all 10367 // optimization levels because it's cheap to do and will make codegen faster 10368 // if there are many clusters. 10369 sortAndRangeify(Clusters); 10370 10371 if (TM.getOptLevel() != CodeGenOpt::None) { 10372 // Replace an unreachable default with the most popular destination. 10373 // FIXME: Exploit unreachable default more aggressively. 10374 bool UnreachableDefault = 10375 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10376 if (UnreachableDefault && !Clusters.empty()) { 10377 DenseMap<const BasicBlock *, unsigned> Popularity; 10378 unsigned MaxPop = 0; 10379 const BasicBlock *MaxBB = nullptr; 10380 for (auto I : SI.cases()) { 10381 const BasicBlock *BB = I.getCaseSuccessor(); 10382 if (++Popularity[BB] > MaxPop) { 10383 MaxPop = Popularity[BB]; 10384 MaxBB = BB; 10385 } 10386 } 10387 // Set new default. 10388 assert(MaxPop > 0 && MaxBB); 10389 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10390 10391 // Remove cases that were pointing to the destination that is now the 10392 // default. 10393 CaseClusterVector New; 10394 New.reserve(Clusters.size()); 10395 for (CaseCluster &CC : Clusters) { 10396 if (CC.MBB != DefaultMBB) 10397 New.push_back(CC); 10398 } 10399 Clusters = std::move(New); 10400 } 10401 } 10402 10403 // The branch probablity of the peeled case. 10404 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10405 MachineBasicBlock *PeeledSwitchMBB = 10406 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10407 10408 // If there is only the default destination, jump there directly. 10409 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10410 if (Clusters.empty()) { 10411 assert(PeeledSwitchMBB == SwitchMBB); 10412 SwitchMBB->addSuccessor(DefaultMBB); 10413 if (DefaultMBB != NextBlock(SwitchMBB)) { 10414 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10415 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10416 } 10417 return; 10418 } 10419 10420 findJumpTables(Clusters, &SI, DefaultMBB); 10421 findBitTestClusters(Clusters, &SI); 10422 10423 LLVM_DEBUG({ 10424 dbgs() << "Case clusters: "; 10425 for (const CaseCluster &C : Clusters) { 10426 if (C.Kind == CC_JumpTable) 10427 dbgs() << "JT:"; 10428 if (C.Kind == CC_BitTests) 10429 dbgs() << "BT:"; 10430 10431 C.Low->getValue().print(dbgs(), true); 10432 if (C.Low != C.High) { 10433 dbgs() << '-'; 10434 C.High->getValue().print(dbgs(), true); 10435 } 10436 dbgs() << ' '; 10437 } 10438 dbgs() << '\n'; 10439 }); 10440 10441 assert(!Clusters.empty()); 10442 SwitchWorkList WorkList; 10443 CaseClusterIt First = Clusters.begin(); 10444 CaseClusterIt Last = Clusters.end() - 1; 10445 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10446 // Scale the branchprobability for DefaultMBB if the peel occurs and 10447 // DefaultMBB is not replaced. 10448 if (PeeledCaseProb != BranchProbability::getZero() && 10449 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10450 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10451 WorkList.push_back( 10452 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10453 10454 while (!WorkList.empty()) { 10455 SwitchWorkListItem W = WorkList.back(); 10456 WorkList.pop_back(); 10457 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10458 10459 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10460 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10461 // For optimized builds, lower large range as a balanced binary tree. 10462 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10463 continue; 10464 } 10465 10466 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10467 } 10468 } 10469