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(), MVT::Other, getControlRoot(), 2552 DAG.getBasicBlock(Return))); 2553 } 2554 2555 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2556 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2557 2558 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2559 // have to do anything here to lower funclet bundles. 2560 assert(!I.hasOperandBundlesOtherThan( 2561 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2562 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2563 2564 assert(isa<InlineAsm>(I.getCalledValue()) && 2565 "Only know how to handle inlineasm callbr"); 2566 visitInlineAsm(&I); 2567 2568 // Retrieve successors. 2569 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2570 2571 // Update successor info. 2572 addSuccessorWithProb(CallBrMBB, Return); 2573 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2574 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2575 addSuccessorWithProb(CallBrMBB, Target); 2576 } 2577 CallBrMBB->normalizeSuccProbs(); 2578 2579 // Drop into default successor. 2580 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2581 MVT::Other, getControlRoot(), 2582 DAG.getBasicBlock(Return))); 2583 } 2584 2585 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2586 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2587 } 2588 2589 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2590 assert(FuncInfo.MBB->isEHPad() && 2591 "Call to landingpad not in landing pad!"); 2592 2593 // If there aren't registers to copy the values into (e.g., during SjLj 2594 // exceptions), then don't bother to create these DAG nodes. 2595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2596 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2597 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2598 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2599 return; 2600 2601 // If landingpad's return type is token type, we don't create DAG nodes 2602 // for its exception pointer and selector value. The extraction of exception 2603 // pointer or selector value from token type landingpads is not currently 2604 // supported. 2605 if (LP.getType()->isTokenTy()) 2606 return; 2607 2608 SmallVector<EVT, 2> ValueVTs; 2609 SDLoc dl = getCurSDLoc(); 2610 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2611 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2612 2613 // Get the two live-in registers as SDValues. The physregs have already been 2614 // copied into virtual registers. 2615 SDValue Ops[2]; 2616 if (FuncInfo.ExceptionPointerVirtReg) { 2617 Ops[0] = DAG.getZExtOrTrunc( 2618 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2619 FuncInfo.ExceptionPointerVirtReg, 2620 TLI.getPointerTy(DAG.getDataLayout())), 2621 dl, ValueVTs[0]); 2622 } else { 2623 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2624 } 2625 Ops[1] = DAG.getZExtOrTrunc( 2626 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2627 FuncInfo.ExceptionSelectorVirtReg, 2628 TLI.getPointerTy(DAG.getDataLayout())), 2629 dl, ValueVTs[1]); 2630 2631 // Merge into one. 2632 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2633 DAG.getVTList(ValueVTs), Ops); 2634 setValue(&LP, Res); 2635 } 2636 2637 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2638 #ifndef NDEBUG 2639 for (const CaseCluster &CC : Clusters) 2640 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2641 #endif 2642 2643 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2644 return a.Low->getValue().slt(b.Low->getValue()); 2645 }); 2646 2647 // Merge adjacent clusters with the same destination. 2648 const unsigned N = Clusters.size(); 2649 unsigned DstIndex = 0; 2650 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2651 CaseCluster &CC = Clusters[SrcIndex]; 2652 const ConstantInt *CaseVal = CC.Low; 2653 MachineBasicBlock *Succ = CC.MBB; 2654 2655 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2656 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2657 // If this case has the same successor and is a neighbour, merge it into 2658 // the previous cluster. 2659 Clusters[DstIndex - 1].High = CaseVal; 2660 Clusters[DstIndex - 1].Prob += CC.Prob; 2661 } else { 2662 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2663 sizeof(Clusters[SrcIndex])); 2664 } 2665 } 2666 Clusters.resize(DstIndex); 2667 } 2668 2669 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2670 MachineBasicBlock *Last) { 2671 // Update JTCases. 2672 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2673 if (JTCases[i].first.HeaderBB == First) 2674 JTCases[i].first.HeaderBB = Last; 2675 2676 // Update BitTestCases. 2677 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2678 if (BitTestCases[i].Parent == First) 2679 BitTestCases[i].Parent = Last; 2680 } 2681 2682 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2683 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2684 2685 // Update machine-CFG edges with unique successors. 2686 SmallSet<BasicBlock*, 32> Done; 2687 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2688 BasicBlock *BB = I.getSuccessor(i); 2689 bool Inserted = Done.insert(BB).second; 2690 if (!Inserted) 2691 continue; 2692 2693 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2694 addSuccessorWithProb(IndirectBrMBB, Succ); 2695 } 2696 IndirectBrMBB->normalizeSuccProbs(); 2697 2698 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2699 MVT::Other, getControlRoot(), 2700 getValue(I.getAddress()))); 2701 } 2702 2703 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2704 if (!DAG.getTarget().Options.TrapUnreachable) 2705 return; 2706 2707 // We may be able to ignore unreachable behind a noreturn call. 2708 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2709 const BasicBlock &BB = *I.getParent(); 2710 if (&I != &BB.front()) { 2711 BasicBlock::const_iterator PredI = 2712 std::prev(BasicBlock::const_iterator(&I)); 2713 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2714 if (Call->doesNotReturn()) 2715 return; 2716 } 2717 } 2718 } 2719 2720 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2721 } 2722 2723 void SelectionDAGBuilder::visitFSub(const User &I) { 2724 // -0.0 - X --> fneg 2725 Type *Ty = I.getType(); 2726 if (isa<Constant>(I.getOperand(0)) && 2727 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2728 SDValue Op2 = getValue(I.getOperand(1)); 2729 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2730 Op2.getValueType(), Op2)); 2731 return; 2732 } 2733 2734 visitBinary(I, ISD::FSUB); 2735 } 2736 2737 /// Checks if the given instruction performs a vector reduction, in which case 2738 /// we have the freedom to alter the elements in the result as long as the 2739 /// reduction of them stays unchanged. 2740 static bool isVectorReductionOp(const User *I) { 2741 const Instruction *Inst = dyn_cast<Instruction>(I); 2742 if (!Inst || !Inst->getType()->isVectorTy()) 2743 return false; 2744 2745 auto OpCode = Inst->getOpcode(); 2746 switch (OpCode) { 2747 case Instruction::Add: 2748 case Instruction::Mul: 2749 case Instruction::And: 2750 case Instruction::Or: 2751 case Instruction::Xor: 2752 break; 2753 case Instruction::FAdd: 2754 case Instruction::FMul: 2755 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2756 if (FPOp->getFastMathFlags().isFast()) 2757 break; 2758 LLVM_FALLTHROUGH; 2759 default: 2760 return false; 2761 } 2762 2763 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2764 // Ensure the reduction size is a power of 2. 2765 if (!isPowerOf2_32(ElemNum)) 2766 return false; 2767 2768 unsigned ElemNumToReduce = ElemNum; 2769 2770 // Do DFS search on the def-use chain from the given instruction. We only 2771 // allow four kinds of operations during the search until we reach the 2772 // instruction that extracts the first element from the vector: 2773 // 2774 // 1. The reduction operation of the same opcode as the given instruction. 2775 // 2776 // 2. PHI node. 2777 // 2778 // 3. ShuffleVector instruction together with a reduction operation that 2779 // does a partial reduction. 2780 // 2781 // 4. ExtractElement that extracts the first element from the vector, and we 2782 // stop searching the def-use chain here. 2783 // 2784 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2785 // from 1-3 to the stack to continue the DFS. The given instruction is not 2786 // a reduction operation if we meet any other instructions other than those 2787 // listed above. 2788 2789 SmallVector<const User *, 16> UsersToVisit{Inst}; 2790 SmallPtrSet<const User *, 16> Visited; 2791 bool ReduxExtracted = false; 2792 2793 while (!UsersToVisit.empty()) { 2794 auto User = UsersToVisit.back(); 2795 UsersToVisit.pop_back(); 2796 if (!Visited.insert(User).second) 2797 continue; 2798 2799 for (const auto &U : User->users()) { 2800 auto Inst = dyn_cast<Instruction>(U); 2801 if (!Inst) 2802 return false; 2803 2804 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2805 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2806 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2807 return false; 2808 UsersToVisit.push_back(U); 2809 } else if (const ShuffleVectorInst *ShufInst = 2810 dyn_cast<ShuffleVectorInst>(U)) { 2811 // Detect the following pattern: A ShuffleVector instruction together 2812 // with a reduction that do partial reduction on the first and second 2813 // ElemNumToReduce / 2 elements, and store the result in 2814 // ElemNumToReduce / 2 elements in another vector. 2815 2816 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2817 if (ResultElements < ElemNum) 2818 return false; 2819 2820 if (ElemNumToReduce == 1) 2821 return false; 2822 if (!isa<UndefValue>(U->getOperand(1))) 2823 return false; 2824 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2825 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2826 return false; 2827 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2828 if (ShufInst->getMaskValue(i) != -1) 2829 return false; 2830 2831 // There is only one user of this ShuffleVector instruction, which 2832 // must be a reduction operation. 2833 if (!U->hasOneUse()) 2834 return false; 2835 2836 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2837 if (!U2 || U2->getOpcode() != OpCode) 2838 return false; 2839 2840 // Check operands of the reduction operation. 2841 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2842 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2843 UsersToVisit.push_back(U2); 2844 ElemNumToReduce /= 2; 2845 } else 2846 return false; 2847 } else if (isa<ExtractElementInst>(U)) { 2848 // At this moment we should have reduced all elements in the vector. 2849 if (ElemNumToReduce != 1) 2850 return false; 2851 2852 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2853 if (!Val || !Val->isZero()) 2854 return false; 2855 2856 ReduxExtracted = true; 2857 } else 2858 return false; 2859 } 2860 } 2861 return ReduxExtracted; 2862 } 2863 2864 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2865 SDNodeFlags Flags; 2866 2867 SDValue Op = getValue(I.getOperand(0)); 2868 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2869 Op, Flags); 2870 setValue(&I, UnNodeValue); 2871 } 2872 2873 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2874 SDNodeFlags Flags; 2875 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2876 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2877 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2878 } 2879 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2880 Flags.setExact(ExactOp->isExact()); 2881 } 2882 if (isVectorReductionOp(&I)) { 2883 Flags.setVectorReduction(true); 2884 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2885 } 2886 2887 SDValue Op1 = getValue(I.getOperand(0)); 2888 SDValue Op2 = getValue(I.getOperand(1)); 2889 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2890 Op1, Op2, Flags); 2891 setValue(&I, BinNodeValue); 2892 } 2893 2894 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2895 SDValue Op1 = getValue(I.getOperand(0)); 2896 SDValue Op2 = getValue(I.getOperand(1)); 2897 2898 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2899 Op1.getValueType(), DAG.getDataLayout()); 2900 2901 // Coerce the shift amount to the right type if we can. 2902 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2903 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2904 unsigned Op2Size = Op2.getValueSizeInBits(); 2905 SDLoc DL = getCurSDLoc(); 2906 2907 // If the operand is smaller than the shift count type, promote it. 2908 if (ShiftSize > Op2Size) 2909 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2910 2911 // If the operand is larger than the shift count type but the shift 2912 // count type has enough bits to represent any shift value, truncate 2913 // it now. This is a common case and it exposes the truncate to 2914 // optimization early. 2915 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2916 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2917 // Otherwise we'll need to temporarily settle for some other convenient 2918 // type. Type legalization will make adjustments once the shiftee is split. 2919 else 2920 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2921 } 2922 2923 bool nuw = false; 2924 bool nsw = false; 2925 bool exact = false; 2926 2927 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2928 2929 if (const OverflowingBinaryOperator *OFBinOp = 2930 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2931 nuw = OFBinOp->hasNoUnsignedWrap(); 2932 nsw = OFBinOp->hasNoSignedWrap(); 2933 } 2934 if (const PossiblyExactOperator *ExactOp = 2935 dyn_cast<const PossiblyExactOperator>(&I)) 2936 exact = ExactOp->isExact(); 2937 } 2938 SDNodeFlags Flags; 2939 Flags.setExact(exact); 2940 Flags.setNoSignedWrap(nsw); 2941 Flags.setNoUnsignedWrap(nuw); 2942 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2943 Flags); 2944 setValue(&I, Res); 2945 } 2946 2947 void SelectionDAGBuilder::visitSDiv(const User &I) { 2948 SDValue Op1 = getValue(I.getOperand(0)); 2949 SDValue Op2 = getValue(I.getOperand(1)); 2950 2951 SDNodeFlags Flags; 2952 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2953 cast<PossiblyExactOperator>(&I)->isExact()); 2954 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2955 Op2, Flags)); 2956 } 2957 2958 void SelectionDAGBuilder::visitICmp(const User &I) { 2959 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2960 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2961 predicate = IC->getPredicate(); 2962 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2963 predicate = ICmpInst::Predicate(IC->getPredicate()); 2964 SDValue Op1 = getValue(I.getOperand(0)); 2965 SDValue Op2 = getValue(I.getOperand(1)); 2966 ISD::CondCode Opcode = getICmpCondCode(predicate); 2967 2968 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2969 I.getType()); 2970 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2971 } 2972 2973 void SelectionDAGBuilder::visitFCmp(const User &I) { 2974 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2975 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2976 predicate = FC->getPredicate(); 2977 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2978 predicate = FCmpInst::Predicate(FC->getPredicate()); 2979 SDValue Op1 = getValue(I.getOperand(0)); 2980 SDValue Op2 = getValue(I.getOperand(1)); 2981 2982 ISD::CondCode Condition = getFCmpCondCode(predicate); 2983 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2984 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2985 Condition = getFCmpCodeWithoutNaN(Condition); 2986 2987 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2988 I.getType()); 2989 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2990 } 2991 2992 // Check if the condition of the select has one use or two users that are both 2993 // selects with the same condition. 2994 static bool hasOnlySelectUsers(const Value *Cond) { 2995 return llvm::all_of(Cond->users(), [](const Value *V) { 2996 return isa<SelectInst>(V); 2997 }); 2998 } 2999 3000 void SelectionDAGBuilder::visitSelect(const User &I) { 3001 SmallVector<EVT, 4> ValueVTs; 3002 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3003 ValueVTs); 3004 unsigned NumValues = ValueVTs.size(); 3005 if (NumValues == 0) return; 3006 3007 SmallVector<SDValue, 4> Values(NumValues); 3008 SDValue Cond = getValue(I.getOperand(0)); 3009 SDValue LHSVal = getValue(I.getOperand(1)); 3010 SDValue RHSVal = getValue(I.getOperand(2)); 3011 auto BaseOps = {Cond}; 3012 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3013 ISD::VSELECT : ISD::SELECT; 3014 3015 // Min/max matching is only viable if all output VTs are the same. 3016 if (is_splat(ValueVTs)) { 3017 EVT VT = ValueVTs[0]; 3018 LLVMContext &Ctx = *DAG.getContext(); 3019 auto &TLI = DAG.getTargetLoweringInfo(); 3020 3021 // We care about the legality of the operation after it has been type 3022 // legalized. 3023 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 3024 VT != TLI.getTypeToTransformTo(Ctx, VT)) 3025 VT = TLI.getTypeToTransformTo(Ctx, VT); 3026 3027 // If the vselect is legal, assume we want to leave this as a vector setcc + 3028 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3029 // min/max is legal on the scalar type. 3030 bool UseScalarMinMax = VT.isVector() && 3031 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3032 3033 Value *LHS, *RHS; 3034 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3035 ISD::NodeType Opc = ISD::DELETED_NODE; 3036 switch (SPR.Flavor) { 3037 case SPF_UMAX: Opc = ISD::UMAX; break; 3038 case SPF_UMIN: Opc = ISD::UMIN; break; 3039 case SPF_SMAX: Opc = ISD::SMAX; break; 3040 case SPF_SMIN: Opc = ISD::SMIN; break; 3041 case SPF_FMINNUM: 3042 switch (SPR.NaNBehavior) { 3043 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3044 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3045 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3046 case SPNB_RETURNS_ANY: { 3047 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3048 Opc = ISD::FMINNUM; 3049 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3050 Opc = ISD::FMINIMUM; 3051 else if (UseScalarMinMax) 3052 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3053 ISD::FMINNUM : ISD::FMINIMUM; 3054 break; 3055 } 3056 } 3057 break; 3058 case SPF_FMAXNUM: 3059 switch (SPR.NaNBehavior) { 3060 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3061 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3062 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3063 case SPNB_RETURNS_ANY: 3064 3065 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3066 Opc = ISD::FMAXNUM; 3067 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3068 Opc = ISD::FMAXIMUM; 3069 else if (UseScalarMinMax) 3070 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3071 ISD::FMAXNUM : ISD::FMAXIMUM; 3072 break; 3073 } 3074 break; 3075 default: break; 3076 } 3077 3078 if (Opc != ISD::DELETED_NODE && 3079 (TLI.isOperationLegalOrCustom(Opc, VT) || 3080 (UseScalarMinMax && 3081 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3082 // If the underlying comparison instruction is used by any other 3083 // instruction, the consumed instructions won't be destroyed, so it is 3084 // not profitable to convert to a min/max. 3085 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3086 OpCode = Opc; 3087 LHSVal = getValue(LHS); 3088 RHSVal = getValue(RHS); 3089 BaseOps = {}; 3090 } 3091 } 3092 3093 for (unsigned i = 0; i != NumValues; ++i) { 3094 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3095 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3096 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3097 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3098 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3099 Ops); 3100 } 3101 3102 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3103 DAG.getVTList(ValueVTs), Values)); 3104 } 3105 3106 void SelectionDAGBuilder::visitTrunc(const User &I) { 3107 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3108 SDValue N = getValue(I.getOperand(0)); 3109 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3110 I.getType()); 3111 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3112 } 3113 3114 void SelectionDAGBuilder::visitZExt(const User &I) { 3115 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3116 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3117 SDValue N = getValue(I.getOperand(0)); 3118 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3119 I.getType()); 3120 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3121 } 3122 3123 void SelectionDAGBuilder::visitSExt(const User &I) { 3124 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3125 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3126 SDValue N = getValue(I.getOperand(0)); 3127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3128 I.getType()); 3129 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3130 } 3131 3132 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3133 // FPTrunc is never a no-op cast, no need to check 3134 SDValue N = getValue(I.getOperand(0)); 3135 SDLoc dl = getCurSDLoc(); 3136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3137 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3138 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3139 DAG.getTargetConstant( 3140 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3141 } 3142 3143 void SelectionDAGBuilder::visitFPExt(const User &I) { 3144 // FPExt is never a no-op cast, no need to check 3145 SDValue N = getValue(I.getOperand(0)); 3146 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3147 I.getType()); 3148 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3149 } 3150 3151 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3152 // FPToUI is never a no-op cast, no need to check 3153 SDValue N = getValue(I.getOperand(0)); 3154 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3155 I.getType()); 3156 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3157 } 3158 3159 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3160 // FPToSI is never a no-op cast, no need to check 3161 SDValue N = getValue(I.getOperand(0)); 3162 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3163 I.getType()); 3164 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3165 } 3166 3167 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3168 // UIToFP is never a no-op cast, no need to check 3169 SDValue N = getValue(I.getOperand(0)); 3170 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3171 I.getType()); 3172 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3173 } 3174 3175 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3176 // SIToFP is never a no-op cast, no need to check 3177 SDValue N = getValue(I.getOperand(0)); 3178 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3179 I.getType()); 3180 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3181 } 3182 3183 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3184 // What to do depends on the size of the integer and the size of the pointer. 3185 // We can either truncate, zero extend, or no-op, accordingly. 3186 SDValue N = getValue(I.getOperand(0)); 3187 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3188 I.getType()); 3189 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3190 } 3191 3192 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3193 // What to do depends on the size of the integer and the size of the pointer. 3194 // We can either truncate, zero extend, or no-op, accordingly. 3195 SDValue N = getValue(I.getOperand(0)); 3196 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3197 I.getType()); 3198 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3199 } 3200 3201 void SelectionDAGBuilder::visitBitCast(const User &I) { 3202 SDValue N = getValue(I.getOperand(0)); 3203 SDLoc dl = getCurSDLoc(); 3204 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3205 I.getType()); 3206 3207 // BitCast assures us that source and destination are the same size so this is 3208 // either a BITCAST or a no-op. 3209 if (DestVT != N.getValueType()) 3210 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3211 DestVT, N)); // convert types. 3212 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3213 // might fold any kind of constant expression to an integer constant and that 3214 // is not what we are looking for. Only recognize a bitcast of a genuine 3215 // constant integer as an opaque constant. 3216 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3217 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3218 /*isOpaque*/true)); 3219 else 3220 setValue(&I, N); // noop cast. 3221 } 3222 3223 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3224 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3225 const Value *SV = I.getOperand(0); 3226 SDValue N = getValue(SV); 3227 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3228 3229 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3230 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3231 3232 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3233 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3234 3235 setValue(&I, N); 3236 } 3237 3238 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3239 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3240 SDValue InVec = getValue(I.getOperand(0)); 3241 SDValue InVal = getValue(I.getOperand(1)); 3242 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3243 TLI.getVectorIdxTy(DAG.getDataLayout())); 3244 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3245 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3246 InVec, InVal, InIdx)); 3247 } 3248 3249 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3250 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3251 SDValue InVec = getValue(I.getOperand(0)); 3252 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3253 TLI.getVectorIdxTy(DAG.getDataLayout())); 3254 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3255 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3256 InVec, InIdx)); 3257 } 3258 3259 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3260 SDValue Src1 = getValue(I.getOperand(0)); 3261 SDValue Src2 = getValue(I.getOperand(1)); 3262 SDLoc DL = getCurSDLoc(); 3263 3264 SmallVector<int, 8> Mask; 3265 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3266 unsigned MaskNumElts = Mask.size(); 3267 3268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3269 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3270 EVT SrcVT = Src1.getValueType(); 3271 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3272 3273 if (SrcNumElts == MaskNumElts) { 3274 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3275 return; 3276 } 3277 3278 // Normalize the shuffle vector since mask and vector length don't match. 3279 if (SrcNumElts < MaskNumElts) { 3280 // Mask is longer than the source vectors. We can use concatenate vector to 3281 // make the mask and vectors lengths match. 3282 3283 if (MaskNumElts % SrcNumElts == 0) { 3284 // Mask length is a multiple of the source vector length. 3285 // Check if the shuffle is some kind of concatenation of the input 3286 // vectors. 3287 unsigned NumConcat = MaskNumElts / SrcNumElts; 3288 bool IsConcat = true; 3289 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3290 for (unsigned i = 0; i != MaskNumElts; ++i) { 3291 int Idx = Mask[i]; 3292 if (Idx < 0) 3293 continue; 3294 // Ensure the indices in each SrcVT sized piece are sequential and that 3295 // the same source is used for the whole piece. 3296 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3297 (ConcatSrcs[i / SrcNumElts] >= 0 && 3298 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3299 IsConcat = false; 3300 break; 3301 } 3302 // Remember which source this index came from. 3303 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3304 } 3305 3306 // The shuffle is concatenating multiple vectors together. Just emit 3307 // a CONCAT_VECTORS operation. 3308 if (IsConcat) { 3309 SmallVector<SDValue, 8> ConcatOps; 3310 for (auto Src : ConcatSrcs) { 3311 if (Src < 0) 3312 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3313 else if (Src == 0) 3314 ConcatOps.push_back(Src1); 3315 else 3316 ConcatOps.push_back(Src2); 3317 } 3318 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3319 return; 3320 } 3321 } 3322 3323 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3324 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3325 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3326 PaddedMaskNumElts); 3327 3328 // Pad both vectors with undefs to make them the same length as the mask. 3329 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3330 3331 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3332 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3333 MOps1[0] = Src1; 3334 MOps2[0] = Src2; 3335 3336 Src1 = Src1.isUndef() 3337 ? DAG.getUNDEF(PaddedVT) 3338 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3339 Src2 = Src2.isUndef() 3340 ? DAG.getUNDEF(PaddedVT) 3341 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3342 3343 // Readjust mask for new input vector length. 3344 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3345 for (unsigned i = 0; i != MaskNumElts; ++i) { 3346 int Idx = Mask[i]; 3347 if (Idx >= (int)SrcNumElts) 3348 Idx -= SrcNumElts - PaddedMaskNumElts; 3349 MappedOps[i] = Idx; 3350 } 3351 3352 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3353 3354 // If the concatenated vector was padded, extract a subvector with the 3355 // correct number of elements. 3356 if (MaskNumElts != PaddedMaskNumElts) 3357 Result = DAG.getNode( 3358 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3359 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3360 3361 setValue(&I, Result); 3362 return; 3363 } 3364 3365 if (SrcNumElts > MaskNumElts) { 3366 // Analyze the access pattern of the vector to see if we can extract 3367 // two subvectors and do the shuffle. 3368 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3369 bool CanExtract = true; 3370 for (int Idx : Mask) { 3371 unsigned Input = 0; 3372 if (Idx < 0) 3373 continue; 3374 3375 if (Idx >= (int)SrcNumElts) { 3376 Input = 1; 3377 Idx -= SrcNumElts; 3378 } 3379 3380 // If all the indices come from the same MaskNumElts sized portion of 3381 // the sources we can use extract. Also make sure the extract wouldn't 3382 // extract past the end of the source. 3383 int NewStartIdx = alignDown(Idx, MaskNumElts); 3384 if (NewStartIdx + MaskNumElts > SrcNumElts || 3385 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3386 CanExtract = false; 3387 // Make sure we always update StartIdx as we use it to track if all 3388 // elements are undef. 3389 StartIdx[Input] = NewStartIdx; 3390 } 3391 3392 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3393 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3394 return; 3395 } 3396 if (CanExtract) { 3397 // Extract appropriate subvector and generate a vector shuffle 3398 for (unsigned Input = 0; Input < 2; ++Input) { 3399 SDValue &Src = Input == 0 ? Src1 : Src2; 3400 if (StartIdx[Input] < 0) 3401 Src = DAG.getUNDEF(VT); 3402 else { 3403 Src = DAG.getNode( 3404 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3405 DAG.getConstant(StartIdx[Input], DL, 3406 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3407 } 3408 } 3409 3410 // Calculate new mask. 3411 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3412 for (int &Idx : MappedOps) { 3413 if (Idx >= (int)SrcNumElts) 3414 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3415 else if (Idx >= 0) 3416 Idx -= StartIdx[0]; 3417 } 3418 3419 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3420 return; 3421 } 3422 } 3423 3424 // We can't use either concat vectors or extract subvectors so fall back to 3425 // replacing the shuffle with extract and build vector. 3426 // to insert and build vector. 3427 EVT EltVT = VT.getVectorElementType(); 3428 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3429 SmallVector<SDValue,8> Ops; 3430 for (int Idx : Mask) { 3431 SDValue Res; 3432 3433 if (Idx < 0) { 3434 Res = DAG.getUNDEF(EltVT); 3435 } else { 3436 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3437 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3438 3439 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3440 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3441 } 3442 3443 Ops.push_back(Res); 3444 } 3445 3446 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3447 } 3448 3449 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3450 ArrayRef<unsigned> Indices; 3451 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3452 Indices = IV->getIndices(); 3453 else 3454 Indices = cast<ConstantExpr>(&I)->getIndices(); 3455 3456 const Value *Op0 = I.getOperand(0); 3457 const Value *Op1 = I.getOperand(1); 3458 Type *AggTy = I.getType(); 3459 Type *ValTy = Op1->getType(); 3460 bool IntoUndef = isa<UndefValue>(Op0); 3461 bool FromUndef = isa<UndefValue>(Op1); 3462 3463 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3464 3465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3466 SmallVector<EVT, 4> AggValueVTs; 3467 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3468 SmallVector<EVT, 4> ValValueVTs; 3469 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3470 3471 unsigned NumAggValues = AggValueVTs.size(); 3472 unsigned NumValValues = ValValueVTs.size(); 3473 SmallVector<SDValue, 4> Values(NumAggValues); 3474 3475 // Ignore an insertvalue that produces an empty object 3476 if (!NumAggValues) { 3477 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3478 return; 3479 } 3480 3481 SDValue Agg = getValue(Op0); 3482 unsigned i = 0; 3483 // Copy the beginning value(s) from the original aggregate. 3484 for (; i != LinearIndex; ++i) 3485 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3486 SDValue(Agg.getNode(), Agg.getResNo() + i); 3487 // Copy values from the inserted value(s). 3488 if (NumValValues) { 3489 SDValue Val = getValue(Op1); 3490 for (; i != LinearIndex + NumValValues; ++i) 3491 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3492 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3493 } 3494 // Copy remaining value(s) from the original aggregate. 3495 for (; i != NumAggValues; ++i) 3496 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3497 SDValue(Agg.getNode(), Agg.getResNo() + i); 3498 3499 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3500 DAG.getVTList(AggValueVTs), Values)); 3501 } 3502 3503 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3504 ArrayRef<unsigned> Indices; 3505 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3506 Indices = EV->getIndices(); 3507 else 3508 Indices = cast<ConstantExpr>(&I)->getIndices(); 3509 3510 const Value *Op0 = I.getOperand(0); 3511 Type *AggTy = Op0->getType(); 3512 Type *ValTy = I.getType(); 3513 bool OutOfUndef = isa<UndefValue>(Op0); 3514 3515 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3516 3517 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3518 SmallVector<EVT, 4> ValValueVTs; 3519 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3520 3521 unsigned NumValValues = ValValueVTs.size(); 3522 3523 // Ignore a extractvalue that produces an empty object 3524 if (!NumValValues) { 3525 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3526 return; 3527 } 3528 3529 SmallVector<SDValue, 4> Values(NumValValues); 3530 3531 SDValue Agg = getValue(Op0); 3532 // Copy out the selected value(s). 3533 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3534 Values[i - LinearIndex] = 3535 OutOfUndef ? 3536 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3537 SDValue(Agg.getNode(), Agg.getResNo() + i); 3538 3539 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3540 DAG.getVTList(ValValueVTs), Values)); 3541 } 3542 3543 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3544 Value *Op0 = I.getOperand(0); 3545 // Note that the pointer operand may be a vector of pointers. Take the scalar 3546 // element which holds a pointer. 3547 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3548 SDValue N = getValue(Op0); 3549 SDLoc dl = getCurSDLoc(); 3550 3551 // Normalize Vector GEP - all scalar operands should be converted to the 3552 // splat vector. 3553 unsigned VectorWidth = I.getType()->isVectorTy() ? 3554 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3555 3556 if (VectorWidth && !N.getValueType().isVector()) { 3557 LLVMContext &Context = *DAG.getContext(); 3558 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3559 N = DAG.getSplatBuildVector(VT, dl, N); 3560 } 3561 3562 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3563 GTI != E; ++GTI) { 3564 const Value *Idx = GTI.getOperand(); 3565 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3566 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3567 if (Field) { 3568 // N = N + Offset 3569 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3570 3571 // In an inbounds GEP with an offset that is nonnegative even when 3572 // interpreted as signed, assume there is no unsigned overflow. 3573 SDNodeFlags Flags; 3574 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3575 Flags.setNoUnsignedWrap(true); 3576 3577 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3578 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3579 } 3580 } else { 3581 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3582 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3583 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3584 3585 // If this is a scalar constant or a splat vector of constants, 3586 // handle it quickly. 3587 const auto *CI = dyn_cast<ConstantInt>(Idx); 3588 if (!CI && isa<ConstantDataVector>(Idx) && 3589 cast<ConstantDataVector>(Idx)->getSplatValue()) 3590 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3591 3592 if (CI) { 3593 if (CI->isZero()) 3594 continue; 3595 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3596 LLVMContext &Context = *DAG.getContext(); 3597 SDValue OffsVal = VectorWidth ? 3598 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3599 DAG.getConstant(Offs, dl, IdxTy); 3600 3601 // In an inbouds GEP with an offset that is nonnegative even when 3602 // interpreted as signed, assume there is no unsigned overflow. 3603 SDNodeFlags Flags; 3604 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3605 Flags.setNoUnsignedWrap(true); 3606 3607 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3608 continue; 3609 } 3610 3611 // N = N + Idx * ElementSize; 3612 SDValue IdxN = getValue(Idx); 3613 3614 if (!IdxN.getValueType().isVector() && VectorWidth) { 3615 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3616 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3617 } 3618 3619 // If the index is smaller or larger than intptr_t, truncate or extend 3620 // it. 3621 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3622 3623 // If this is a multiply by a power of two, turn it into a shl 3624 // immediately. This is a very common case. 3625 if (ElementSize != 1) { 3626 if (ElementSize.isPowerOf2()) { 3627 unsigned Amt = ElementSize.logBase2(); 3628 IdxN = DAG.getNode(ISD::SHL, dl, 3629 N.getValueType(), IdxN, 3630 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3631 } else { 3632 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3633 IdxN = DAG.getNode(ISD::MUL, dl, 3634 N.getValueType(), IdxN, Scale); 3635 } 3636 } 3637 3638 N = DAG.getNode(ISD::ADD, dl, 3639 N.getValueType(), N, IdxN); 3640 } 3641 } 3642 3643 setValue(&I, N); 3644 } 3645 3646 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3647 // If this is a fixed sized alloca in the entry block of the function, 3648 // allocate it statically on the stack. 3649 if (FuncInfo.StaticAllocaMap.count(&I)) 3650 return; // getValue will auto-populate this. 3651 3652 SDLoc dl = getCurSDLoc(); 3653 Type *Ty = I.getAllocatedType(); 3654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3655 auto &DL = DAG.getDataLayout(); 3656 uint64_t TySize = DL.getTypeAllocSize(Ty); 3657 unsigned Align = 3658 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3659 3660 SDValue AllocSize = getValue(I.getArraySize()); 3661 3662 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3663 if (AllocSize.getValueType() != IntPtr) 3664 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3665 3666 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3667 AllocSize, 3668 DAG.getConstant(TySize, dl, IntPtr)); 3669 3670 // Handle alignment. If the requested alignment is less than or equal to 3671 // the stack alignment, ignore it. If the size is greater than or equal to 3672 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3673 unsigned StackAlign = 3674 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3675 if (Align <= StackAlign) 3676 Align = 0; 3677 3678 // Round the size of the allocation up to the stack alignment size 3679 // by add SA-1 to the size. This doesn't overflow because we're computing 3680 // an address inside an alloca. 3681 SDNodeFlags Flags; 3682 Flags.setNoUnsignedWrap(true); 3683 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3684 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3685 3686 // Mask out the low bits for alignment purposes. 3687 AllocSize = 3688 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3689 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3690 3691 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3692 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3693 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3694 setValue(&I, DSA); 3695 DAG.setRoot(DSA.getValue(1)); 3696 3697 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3698 } 3699 3700 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3701 if (I.isAtomic()) 3702 return visitAtomicLoad(I); 3703 3704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3705 const Value *SV = I.getOperand(0); 3706 if (TLI.supportSwiftError()) { 3707 // Swifterror values can come from either a function parameter with 3708 // swifterror attribute or an alloca with swifterror attribute. 3709 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3710 if (Arg->hasSwiftErrorAttr()) 3711 return visitLoadFromSwiftError(I); 3712 } 3713 3714 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3715 if (Alloca->isSwiftError()) 3716 return visitLoadFromSwiftError(I); 3717 } 3718 } 3719 3720 SDValue Ptr = getValue(SV); 3721 3722 Type *Ty = I.getType(); 3723 3724 bool isVolatile = I.isVolatile(); 3725 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3726 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3727 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3728 unsigned Alignment = I.getAlignment(); 3729 3730 AAMDNodes AAInfo; 3731 I.getAAMetadata(AAInfo); 3732 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3733 3734 SmallVector<EVT, 4> ValueVTs; 3735 SmallVector<uint64_t, 4> Offsets; 3736 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3737 unsigned NumValues = ValueVTs.size(); 3738 if (NumValues == 0) 3739 return; 3740 3741 SDValue Root; 3742 bool ConstantMemory = false; 3743 if (isVolatile || NumValues > MaxParallelChains) 3744 // Serialize volatile loads with other side effects. 3745 Root = getRoot(); 3746 else if (AA && 3747 AA->pointsToConstantMemory(MemoryLocation( 3748 SV, 3749 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3750 AAInfo))) { 3751 // Do not serialize (non-volatile) loads of constant memory with anything. 3752 Root = DAG.getEntryNode(); 3753 ConstantMemory = true; 3754 } else { 3755 // Do not serialize non-volatile loads against each other. 3756 Root = DAG.getRoot(); 3757 } 3758 3759 SDLoc dl = getCurSDLoc(); 3760 3761 if (isVolatile) 3762 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3763 3764 // An aggregate load cannot wrap around the address space, so offsets to its 3765 // parts don't wrap either. 3766 SDNodeFlags Flags; 3767 Flags.setNoUnsignedWrap(true); 3768 3769 SmallVector<SDValue, 4> Values(NumValues); 3770 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3771 EVT PtrVT = Ptr.getValueType(); 3772 unsigned ChainI = 0; 3773 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3774 // Serializing loads here may result in excessive register pressure, and 3775 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3776 // could recover a bit by hoisting nodes upward in the chain by recognizing 3777 // they are side-effect free or do not alias. The optimizer should really 3778 // avoid this case by converting large object/array copies to llvm.memcpy 3779 // (MaxParallelChains should always remain as failsafe). 3780 if (ChainI == MaxParallelChains) { 3781 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3782 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3783 makeArrayRef(Chains.data(), ChainI)); 3784 Root = Chain; 3785 ChainI = 0; 3786 } 3787 SDValue A = DAG.getNode(ISD::ADD, dl, 3788 PtrVT, Ptr, 3789 DAG.getConstant(Offsets[i], dl, PtrVT), 3790 Flags); 3791 auto MMOFlags = MachineMemOperand::MONone; 3792 if (isVolatile) 3793 MMOFlags |= MachineMemOperand::MOVolatile; 3794 if (isNonTemporal) 3795 MMOFlags |= MachineMemOperand::MONonTemporal; 3796 if (isInvariant) 3797 MMOFlags |= MachineMemOperand::MOInvariant; 3798 if (isDereferenceable) 3799 MMOFlags |= MachineMemOperand::MODereferenceable; 3800 MMOFlags |= TLI.getMMOFlags(I); 3801 3802 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3803 MachinePointerInfo(SV, Offsets[i]), Alignment, 3804 MMOFlags, AAInfo, Ranges); 3805 3806 Values[i] = L; 3807 Chains[ChainI] = L.getValue(1); 3808 } 3809 3810 if (!ConstantMemory) { 3811 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3812 makeArrayRef(Chains.data(), ChainI)); 3813 if (isVolatile) 3814 DAG.setRoot(Chain); 3815 else 3816 PendingLoads.push_back(Chain); 3817 } 3818 3819 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3820 DAG.getVTList(ValueVTs), Values)); 3821 } 3822 3823 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3824 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3825 "call visitStoreToSwiftError when backend supports swifterror"); 3826 3827 SmallVector<EVT, 4> ValueVTs; 3828 SmallVector<uint64_t, 4> Offsets; 3829 const Value *SrcV = I.getOperand(0); 3830 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3831 SrcV->getType(), ValueVTs, &Offsets); 3832 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3833 "expect a single EVT for swifterror"); 3834 3835 SDValue Src = getValue(SrcV); 3836 // Create a virtual register, then update the virtual register. 3837 unsigned VReg; bool CreatedVReg; 3838 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3839 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3840 // Chain can be getRoot or getControlRoot. 3841 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3842 SDValue(Src.getNode(), Src.getResNo())); 3843 DAG.setRoot(CopyNode); 3844 if (CreatedVReg) 3845 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3846 } 3847 3848 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3849 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3850 "call visitLoadFromSwiftError when backend supports swifterror"); 3851 3852 assert(!I.isVolatile() && 3853 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3854 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3855 "Support volatile, non temporal, invariant for load_from_swift_error"); 3856 3857 const Value *SV = I.getOperand(0); 3858 Type *Ty = I.getType(); 3859 AAMDNodes AAInfo; 3860 I.getAAMetadata(AAInfo); 3861 assert( 3862 (!AA || 3863 !AA->pointsToConstantMemory(MemoryLocation( 3864 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3865 AAInfo))) && 3866 "load_from_swift_error should not be constant memory"); 3867 3868 SmallVector<EVT, 4> ValueVTs; 3869 SmallVector<uint64_t, 4> Offsets; 3870 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3871 ValueVTs, &Offsets); 3872 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3873 "expect a single EVT for swifterror"); 3874 3875 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3876 SDValue L = DAG.getCopyFromReg( 3877 getRoot(), getCurSDLoc(), 3878 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3879 ValueVTs[0]); 3880 3881 setValue(&I, L); 3882 } 3883 3884 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3885 if (I.isAtomic()) 3886 return visitAtomicStore(I); 3887 3888 const Value *SrcV = I.getOperand(0); 3889 const Value *PtrV = I.getOperand(1); 3890 3891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3892 if (TLI.supportSwiftError()) { 3893 // Swifterror values can come from either a function parameter with 3894 // swifterror attribute or an alloca with swifterror attribute. 3895 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3896 if (Arg->hasSwiftErrorAttr()) 3897 return visitStoreToSwiftError(I); 3898 } 3899 3900 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3901 if (Alloca->isSwiftError()) 3902 return visitStoreToSwiftError(I); 3903 } 3904 } 3905 3906 SmallVector<EVT, 4> ValueVTs; 3907 SmallVector<uint64_t, 4> Offsets; 3908 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3909 SrcV->getType(), ValueVTs, &Offsets); 3910 unsigned NumValues = ValueVTs.size(); 3911 if (NumValues == 0) 3912 return; 3913 3914 // Get the lowered operands. Note that we do this after 3915 // checking if NumResults is zero, because with zero results 3916 // the operands won't have values in the map. 3917 SDValue Src = getValue(SrcV); 3918 SDValue Ptr = getValue(PtrV); 3919 3920 SDValue Root = getRoot(); 3921 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3922 SDLoc dl = getCurSDLoc(); 3923 EVT PtrVT = Ptr.getValueType(); 3924 unsigned Alignment = I.getAlignment(); 3925 AAMDNodes AAInfo; 3926 I.getAAMetadata(AAInfo); 3927 3928 auto MMOFlags = MachineMemOperand::MONone; 3929 if (I.isVolatile()) 3930 MMOFlags |= MachineMemOperand::MOVolatile; 3931 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3932 MMOFlags |= MachineMemOperand::MONonTemporal; 3933 MMOFlags |= TLI.getMMOFlags(I); 3934 3935 // An aggregate load cannot wrap around the address space, so offsets to its 3936 // parts don't wrap either. 3937 SDNodeFlags Flags; 3938 Flags.setNoUnsignedWrap(true); 3939 3940 unsigned ChainI = 0; 3941 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3942 // See visitLoad comments. 3943 if (ChainI == MaxParallelChains) { 3944 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3945 makeArrayRef(Chains.data(), ChainI)); 3946 Root = Chain; 3947 ChainI = 0; 3948 } 3949 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3950 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3951 SDValue St = DAG.getStore( 3952 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3953 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3954 Chains[ChainI] = St; 3955 } 3956 3957 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3958 makeArrayRef(Chains.data(), ChainI)); 3959 DAG.setRoot(StoreNode); 3960 } 3961 3962 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3963 bool IsCompressing) { 3964 SDLoc sdl = getCurSDLoc(); 3965 3966 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3967 unsigned& Alignment) { 3968 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3969 Src0 = I.getArgOperand(0); 3970 Ptr = I.getArgOperand(1); 3971 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3972 Mask = I.getArgOperand(3); 3973 }; 3974 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3975 unsigned& Alignment) { 3976 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3977 Src0 = I.getArgOperand(0); 3978 Ptr = I.getArgOperand(1); 3979 Mask = I.getArgOperand(2); 3980 Alignment = 0; 3981 }; 3982 3983 Value *PtrOperand, *MaskOperand, *Src0Operand; 3984 unsigned Alignment; 3985 if (IsCompressing) 3986 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3987 else 3988 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3989 3990 SDValue Ptr = getValue(PtrOperand); 3991 SDValue Src0 = getValue(Src0Operand); 3992 SDValue Mask = getValue(MaskOperand); 3993 3994 EVT VT = Src0.getValueType(); 3995 if (!Alignment) 3996 Alignment = DAG.getEVTAlignment(VT); 3997 3998 AAMDNodes AAInfo; 3999 I.getAAMetadata(AAInfo); 4000 4001 MachineMemOperand *MMO = 4002 DAG.getMachineFunction(). 4003 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4004 MachineMemOperand::MOStore, VT.getStoreSize(), 4005 Alignment, AAInfo); 4006 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4007 MMO, false /* Truncating */, 4008 IsCompressing); 4009 DAG.setRoot(StoreNode); 4010 setValue(&I, StoreNode); 4011 } 4012 4013 // Get a uniform base for the Gather/Scatter intrinsic. 4014 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4015 // We try to represent it as a base pointer + vector of indices. 4016 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4017 // The first operand of the GEP may be a single pointer or a vector of pointers 4018 // Example: 4019 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4020 // or 4021 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4022 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4023 // 4024 // When the first GEP operand is a single pointer - it is the uniform base we 4025 // are looking for. If first operand of the GEP is a splat vector - we 4026 // extract the splat value and use it as a uniform base. 4027 // In all other cases the function returns 'false'. 4028 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4029 SDValue &Scale, SelectionDAGBuilder* SDB) { 4030 SelectionDAG& DAG = SDB->DAG; 4031 LLVMContext &Context = *DAG.getContext(); 4032 4033 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4034 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4035 if (!GEP) 4036 return false; 4037 4038 const Value *GEPPtr = GEP->getPointerOperand(); 4039 if (!GEPPtr->getType()->isVectorTy()) 4040 Ptr = GEPPtr; 4041 else if (!(Ptr = getSplatValue(GEPPtr))) 4042 return false; 4043 4044 unsigned FinalIndex = GEP->getNumOperands() - 1; 4045 Value *IndexVal = GEP->getOperand(FinalIndex); 4046 4047 // Ensure all the other indices are 0. 4048 for (unsigned i = 1; i < FinalIndex; ++i) { 4049 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4050 if (!C || !C->isZero()) 4051 return false; 4052 } 4053 4054 // The operands of the GEP may be defined in another basic block. 4055 // In this case we'll not find nodes for the operands. 4056 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4057 return false; 4058 4059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4060 const DataLayout &DL = DAG.getDataLayout(); 4061 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4062 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4063 Base = SDB->getValue(Ptr); 4064 Index = SDB->getValue(IndexVal); 4065 4066 if (!Index.getValueType().isVector()) { 4067 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4068 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4069 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4070 } 4071 return true; 4072 } 4073 4074 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4075 SDLoc sdl = getCurSDLoc(); 4076 4077 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4078 const Value *Ptr = I.getArgOperand(1); 4079 SDValue Src0 = getValue(I.getArgOperand(0)); 4080 SDValue Mask = getValue(I.getArgOperand(3)); 4081 EVT VT = Src0.getValueType(); 4082 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4083 if (!Alignment) 4084 Alignment = DAG.getEVTAlignment(VT); 4085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4086 4087 AAMDNodes AAInfo; 4088 I.getAAMetadata(AAInfo); 4089 4090 SDValue Base; 4091 SDValue Index; 4092 SDValue Scale; 4093 const Value *BasePtr = Ptr; 4094 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4095 4096 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4097 MachineMemOperand *MMO = DAG.getMachineFunction(). 4098 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4099 MachineMemOperand::MOStore, VT.getStoreSize(), 4100 Alignment, AAInfo); 4101 if (!UniformBase) { 4102 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4103 Index = getValue(Ptr); 4104 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4105 } 4106 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4107 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4108 Ops, MMO); 4109 DAG.setRoot(Scatter); 4110 setValue(&I, Scatter); 4111 } 4112 4113 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4114 SDLoc sdl = getCurSDLoc(); 4115 4116 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4117 unsigned& Alignment) { 4118 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4119 Ptr = I.getArgOperand(0); 4120 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4121 Mask = I.getArgOperand(2); 4122 Src0 = I.getArgOperand(3); 4123 }; 4124 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4125 unsigned& Alignment) { 4126 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4127 Ptr = I.getArgOperand(0); 4128 Alignment = 0; 4129 Mask = I.getArgOperand(1); 4130 Src0 = I.getArgOperand(2); 4131 }; 4132 4133 Value *PtrOperand, *MaskOperand, *Src0Operand; 4134 unsigned Alignment; 4135 if (IsExpanding) 4136 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4137 else 4138 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4139 4140 SDValue Ptr = getValue(PtrOperand); 4141 SDValue Src0 = getValue(Src0Operand); 4142 SDValue Mask = getValue(MaskOperand); 4143 4144 EVT VT = Src0.getValueType(); 4145 if (!Alignment) 4146 Alignment = DAG.getEVTAlignment(VT); 4147 4148 AAMDNodes AAInfo; 4149 I.getAAMetadata(AAInfo); 4150 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4151 4152 // Do not serialize masked loads of constant memory with anything. 4153 bool AddToChain = 4154 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4155 PtrOperand, 4156 LocationSize::precise( 4157 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4158 AAInfo)); 4159 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4160 4161 MachineMemOperand *MMO = 4162 DAG.getMachineFunction(). 4163 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4164 MachineMemOperand::MOLoad, VT.getStoreSize(), 4165 Alignment, AAInfo, Ranges); 4166 4167 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4168 ISD::NON_EXTLOAD, IsExpanding); 4169 if (AddToChain) 4170 PendingLoads.push_back(Load.getValue(1)); 4171 setValue(&I, Load); 4172 } 4173 4174 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4175 SDLoc sdl = getCurSDLoc(); 4176 4177 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4178 const Value *Ptr = I.getArgOperand(0); 4179 SDValue Src0 = getValue(I.getArgOperand(3)); 4180 SDValue Mask = getValue(I.getArgOperand(2)); 4181 4182 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4183 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4184 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4185 if (!Alignment) 4186 Alignment = DAG.getEVTAlignment(VT); 4187 4188 AAMDNodes AAInfo; 4189 I.getAAMetadata(AAInfo); 4190 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4191 4192 SDValue Root = DAG.getRoot(); 4193 SDValue Base; 4194 SDValue Index; 4195 SDValue Scale; 4196 const Value *BasePtr = Ptr; 4197 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4198 bool ConstantMemory = false; 4199 if (UniformBase && AA && 4200 AA->pointsToConstantMemory( 4201 MemoryLocation(BasePtr, 4202 LocationSize::precise( 4203 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4204 AAInfo))) { 4205 // Do not serialize (non-volatile) loads of constant memory with anything. 4206 Root = DAG.getEntryNode(); 4207 ConstantMemory = true; 4208 } 4209 4210 MachineMemOperand *MMO = 4211 DAG.getMachineFunction(). 4212 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4213 MachineMemOperand::MOLoad, VT.getStoreSize(), 4214 Alignment, AAInfo, Ranges); 4215 4216 if (!UniformBase) { 4217 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4218 Index = getValue(Ptr); 4219 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4220 } 4221 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4222 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4223 Ops, MMO); 4224 4225 SDValue OutChain = Gather.getValue(1); 4226 if (!ConstantMemory) 4227 PendingLoads.push_back(OutChain); 4228 setValue(&I, Gather); 4229 } 4230 4231 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4232 SDLoc dl = getCurSDLoc(); 4233 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4234 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4235 SyncScope::ID SSID = I.getSyncScopeID(); 4236 4237 SDValue InChain = getRoot(); 4238 4239 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4240 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4241 SDValue L = DAG.getAtomicCmpSwap( 4242 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4243 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4244 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4245 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4246 4247 SDValue OutChain = L.getValue(2); 4248 4249 setValue(&I, L); 4250 DAG.setRoot(OutChain); 4251 } 4252 4253 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4254 SDLoc dl = getCurSDLoc(); 4255 ISD::NodeType NT; 4256 switch (I.getOperation()) { 4257 default: llvm_unreachable("Unknown atomicrmw operation"); 4258 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4259 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4260 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4261 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4262 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4263 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4264 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4265 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4266 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4267 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4268 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4269 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4270 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4271 } 4272 AtomicOrdering Order = I.getOrdering(); 4273 SyncScope::ID SSID = I.getSyncScopeID(); 4274 4275 SDValue InChain = getRoot(); 4276 4277 SDValue L = 4278 DAG.getAtomic(NT, dl, 4279 getValue(I.getValOperand()).getSimpleValueType(), 4280 InChain, 4281 getValue(I.getPointerOperand()), 4282 getValue(I.getValOperand()), 4283 I.getPointerOperand(), 4284 /* Alignment=*/ 0, Order, SSID); 4285 4286 SDValue OutChain = L.getValue(1); 4287 4288 setValue(&I, L); 4289 DAG.setRoot(OutChain); 4290 } 4291 4292 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4293 SDLoc dl = getCurSDLoc(); 4294 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4295 SDValue Ops[3]; 4296 Ops[0] = getRoot(); 4297 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4298 TLI.getFenceOperandTy(DAG.getDataLayout())); 4299 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4300 TLI.getFenceOperandTy(DAG.getDataLayout())); 4301 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4302 } 4303 4304 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4305 SDLoc dl = getCurSDLoc(); 4306 AtomicOrdering Order = I.getOrdering(); 4307 SyncScope::ID SSID = I.getSyncScopeID(); 4308 4309 SDValue InChain = getRoot(); 4310 4311 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4312 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4313 4314 if (!TLI.supportsUnalignedAtomics() && 4315 I.getAlignment() < VT.getStoreSize()) 4316 report_fatal_error("Cannot generate unaligned atomic load"); 4317 4318 MachineMemOperand *MMO = 4319 DAG.getMachineFunction(). 4320 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4321 MachineMemOperand::MOVolatile | 4322 MachineMemOperand::MOLoad, 4323 VT.getStoreSize(), 4324 I.getAlignment() ? I.getAlignment() : 4325 DAG.getEVTAlignment(VT), 4326 AAMDNodes(), nullptr, SSID, Order); 4327 4328 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4329 SDValue L = 4330 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4331 getValue(I.getPointerOperand()), MMO); 4332 4333 SDValue OutChain = L.getValue(1); 4334 4335 setValue(&I, L); 4336 DAG.setRoot(OutChain); 4337 } 4338 4339 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4340 SDLoc dl = getCurSDLoc(); 4341 4342 AtomicOrdering Order = I.getOrdering(); 4343 SyncScope::ID SSID = I.getSyncScopeID(); 4344 4345 SDValue InChain = getRoot(); 4346 4347 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4348 EVT VT = 4349 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4350 4351 if (I.getAlignment() < VT.getStoreSize()) 4352 report_fatal_error("Cannot generate unaligned atomic store"); 4353 4354 SDValue OutChain = 4355 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4356 InChain, 4357 getValue(I.getPointerOperand()), 4358 getValue(I.getValueOperand()), 4359 I.getPointerOperand(), I.getAlignment(), 4360 Order, SSID); 4361 4362 DAG.setRoot(OutChain); 4363 } 4364 4365 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4366 /// node. 4367 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4368 unsigned Intrinsic) { 4369 // Ignore the callsite's attributes. A specific call site may be marked with 4370 // readnone, but the lowering code will expect the chain based on the 4371 // definition. 4372 const Function *F = I.getCalledFunction(); 4373 bool HasChain = !F->doesNotAccessMemory(); 4374 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4375 4376 // Build the operand list. 4377 SmallVector<SDValue, 8> Ops; 4378 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4379 if (OnlyLoad) { 4380 // We don't need to serialize loads against other loads. 4381 Ops.push_back(DAG.getRoot()); 4382 } else { 4383 Ops.push_back(getRoot()); 4384 } 4385 } 4386 4387 // Info is set by getTgtMemInstrinsic 4388 TargetLowering::IntrinsicInfo Info; 4389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4390 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4391 DAG.getMachineFunction(), 4392 Intrinsic); 4393 4394 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4395 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4396 Info.opc == ISD::INTRINSIC_W_CHAIN) 4397 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4398 TLI.getPointerTy(DAG.getDataLayout()))); 4399 4400 // Add all operands of the call to the operand list. 4401 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4402 SDValue Op = getValue(I.getArgOperand(i)); 4403 Ops.push_back(Op); 4404 } 4405 4406 SmallVector<EVT, 4> ValueVTs; 4407 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4408 4409 if (HasChain) 4410 ValueVTs.push_back(MVT::Other); 4411 4412 SDVTList VTs = DAG.getVTList(ValueVTs); 4413 4414 // Create the node. 4415 SDValue Result; 4416 if (IsTgtIntrinsic) { 4417 // This is target intrinsic that touches memory 4418 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4419 Ops, Info.memVT, 4420 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4421 Info.flags, Info.size); 4422 } else if (!HasChain) { 4423 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4424 } else if (!I.getType()->isVoidTy()) { 4425 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4426 } else { 4427 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4428 } 4429 4430 if (HasChain) { 4431 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4432 if (OnlyLoad) 4433 PendingLoads.push_back(Chain); 4434 else 4435 DAG.setRoot(Chain); 4436 } 4437 4438 if (!I.getType()->isVoidTy()) { 4439 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4440 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4441 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4442 } else 4443 Result = lowerRangeToAssertZExt(DAG, I, Result); 4444 4445 setValue(&I, Result); 4446 } 4447 } 4448 4449 /// GetSignificand - Get the significand and build it into a floating-point 4450 /// number with exponent of 1: 4451 /// 4452 /// Op = (Op & 0x007fffff) | 0x3f800000; 4453 /// 4454 /// where Op is the hexadecimal representation of floating point value. 4455 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4456 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4457 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4458 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4459 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4460 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4461 } 4462 4463 /// GetExponent - Get the exponent: 4464 /// 4465 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4466 /// 4467 /// where Op is the hexadecimal representation of floating point value. 4468 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4469 const TargetLowering &TLI, const SDLoc &dl) { 4470 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4471 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4472 SDValue t1 = DAG.getNode( 4473 ISD::SRL, dl, MVT::i32, t0, 4474 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4475 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4476 DAG.getConstant(127, dl, MVT::i32)); 4477 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4478 } 4479 4480 /// getF32Constant - Get 32-bit floating point constant. 4481 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4482 const SDLoc &dl) { 4483 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4484 MVT::f32); 4485 } 4486 4487 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4488 SelectionDAG &DAG) { 4489 // TODO: What fast-math-flags should be set on the floating-point nodes? 4490 4491 // IntegerPartOfX = ((int32_t)(t0); 4492 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4493 4494 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4495 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4496 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4497 4498 // IntegerPartOfX <<= 23; 4499 IntegerPartOfX = DAG.getNode( 4500 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4501 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4502 DAG.getDataLayout()))); 4503 4504 SDValue TwoToFractionalPartOfX; 4505 if (LimitFloatPrecision <= 6) { 4506 // For floating-point precision of 6: 4507 // 4508 // TwoToFractionalPartOfX = 4509 // 0.997535578f + 4510 // (0.735607626f + 0.252464424f * x) * x; 4511 // 4512 // error 0.0144103317, which is 6 bits 4513 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4514 getF32Constant(DAG, 0x3e814304, dl)); 4515 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4516 getF32Constant(DAG, 0x3f3c50c8, dl)); 4517 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4518 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4519 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4520 } else if (LimitFloatPrecision <= 12) { 4521 // For floating-point precision of 12: 4522 // 4523 // TwoToFractionalPartOfX = 4524 // 0.999892986f + 4525 // (0.696457318f + 4526 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4527 // 4528 // error 0.000107046256, which is 13 to 14 bits 4529 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4530 getF32Constant(DAG, 0x3da235e3, dl)); 4531 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4532 getF32Constant(DAG, 0x3e65b8f3, dl)); 4533 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4534 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4535 getF32Constant(DAG, 0x3f324b07, dl)); 4536 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4537 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4538 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4539 } else { // LimitFloatPrecision <= 18 4540 // For floating-point precision of 18: 4541 // 4542 // TwoToFractionalPartOfX = 4543 // 0.999999982f + 4544 // (0.693148872f + 4545 // (0.240227044f + 4546 // (0.554906021e-1f + 4547 // (0.961591928e-2f + 4548 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4549 // error 2.47208000*10^(-7), which is better than 18 bits 4550 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4551 getF32Constant(DAG, 0x3924b03e, dl)); 4552 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4553 getF32Constant(DAG, 0x3ab24b87, dl)); 4554 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4555 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4556 getF32Constant(DAG, 0x3c1d8c17, dl)); 4557 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4558 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4559 getF32Constant(DAG, 0x3d634a1d, dl)); 4560 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4561 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4562 getF32Constant(DAG, 0x3e75fe14, dl)); 4563 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4564 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4565 getF32Constant(DAG, 0x3f317234, dl)); 4566 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4567 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4568 getF32Constant(DAG, 0x3f800000, dl)); 4569 } 4570 4571 // Add the exponent into the result in integer domain. 4572 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4573 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4574 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4575 } 4576 4577 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4578 /// limited-precision mode. 4579 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4580 const TargetLowering &TLI) { 4581 if (Op.getValueType() == MVT::f32 && 4582 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4583 4584 // Put the exponent in the right bit position for later addition to the 4585 // final result: 4586 // 4587 // #define LOG2OFe 1.4426950f 4588 // t0 = Op * LOG2OFe 4589 4590 // TODO: What fast-math-flags should be set here? 4591 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4592 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4593 return getLimitedPrecisionExp2(t0, dl, DAG); 4594 } 4595 4596 // No special expansion. 4597 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4598 } 4599 4600 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4601 /// limited-precision mode. 4602 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4603 const TargetLowering &TLI) { 4604 // TODO: What fast-math-flags should be set on the floating-point nodes? 4605 4606 if (Op.getValueType() == MVT::f32 && 4607 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4608 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4609 4610 // Scale the exponent by log(2) [0.69314718f]. 4611 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4612 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4613 getF32Constant(DAG, 0x3f317218, dl)); 4614 4615 // Get the significand and build it into a floating-point number with 4616 // exponent of 1. 4617 SDValue X = GetSignificand(DAG, Op1, dl); 4618 4619 SDValue LogOfMantissa; 4620 if (LimitFloatPrecision <= 6) { 4621 // For floating-point precision of 6: 4622 // 4623 // LogofMantissa = 4624 // -1.1609546f + 4625 // (1.4034025f - 0.23903021f * x) * x; 4626 // 4627 // error 0.0034276066, which is better than 8 bits 4628 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4629 getF32Constant(DAG, 0xbe74c456, dl)); 4630 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4631 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4632 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4633 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4634 getF32Constant(DAG, 0x3f949a29, dl)); 4635 } else if (LimitFloatPrecision <= 12) { 4636 // For floating-point precision of 12: 4637 // 4638 // LogOfMantissa = 4639 // -1.7417939f + 4640 // (2.8212026f + 4641 // (-1.4699568f + 4642 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4643 // 4644 // error 0.000061011436, which is 14 bits 4645 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4646 getF32Constant(DAG, 0xbd67b6d6, dl)); 4647 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4648 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4650 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4651 getF32Constant(DAG, 0x3fbc278b, dl)); 4652 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4653 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4654 getF32Constant(DAG, 0x40348e95, dl)); 4655 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4656 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4657 getF32Constant(DAG, 0x3fdef31a, dl)); 4658 } else { // LimitFloatPrecision <= 18 4659 // For floating-point precision of 18: 4660 // 4661 // LogOfMantissa = 4662 // -2.1072184f + 4663 // (4.2372794f + 4664 // (-3.7029485f + 4665 // (2.2781945f + 4666 // (-0.87823314f + 4667 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4668 // 4669 // error 0.0000023660568, which is better than 18 bits 4670 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4671 getF32Constant(DAG, 0xbc91e5ac, dl)); 4672 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4673 getF32Constant(DAG, 0x3e4350aa, dl)); 4674 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4675 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4676 getF32Constant(DAG, 0x3f60d3e3, dl)); 4677 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4678 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4679 getF32Constant(DAG, 0x4011cdf0, dl)); 4680 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4681 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4682 getF32Constant(DAG, 0x406cfd1c, dl)); 4683 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4684 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4685 getF32Constant(DAG, 0x408797cb, dl)); 4686 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4687 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4688 getF32Constant(DAG, 0x4006dcab, dl)); 4689 } 4690 4691 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4692 } 4693 4694 // No special expansion. 4695 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4696 } 4697 4698 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4699 /// limited-precision mode. 4700 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4701 const TargetLowering &TLI) { 4702 // TODO: What fast-math-flags should be set on the floating-point nodes? 4703 4704 if (Op.getValueType() == MVT::f32 && 4705 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4706 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4707 4708 // Get the exponent. 4709 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4710 4711 // Get the significand and build it into a floating-point number with 4712 // exponent of 1. 4713 SDValue X = GetSignificand(DAG, Op1, dl); 4714 4715 // Different possible minimax approximations of significand in 4716 // floating-point for various degrees of accuracy over [1,2]. 4717 SDValue Log2ofMantissa; 4718 if (LimitFloatPrecision <= 6) { 4719 // For floating-point precision of 6: 4720 // 4721 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4722 // 4723 // error 0.0049451742, which is more than 7 bits 4724 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4725 getF32Constant(DAG, 0xbeb08fe0, dl)); 4726 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4727 getF32Constant(DAG, 0x40019463, dl)); 4728 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4729 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4730 getF32Constant(DAG, 0x3fd6633d, dl)); 4731 } else if (LimitFloatPrecision <= 12) { 4732 // For floating-point precision of 12: 4733 // 4734 // Log2ofMantissa = 4735 // -2.51285454f + 4736 // (4.07009056f + 4737 // (-2.12067489f + 4738 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4739 // 4740 // error 0.0000876136000, which is better than 13 bits 4741 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4742 getF32Constant(DAG, 0xbda7262e, dl)); 4743 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4744 getF32Constant(DAG, 0x3f25280b, dl)); 4745 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4746 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4747 getF32Constant(DAG, 0x4007b923, dl)); 4748 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4749 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4750 getF32Constant(DAG, 0x40823e2f, dl)); 4751 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4752 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4753 getF32Constant(DAG, 0x4020d29c, dl)); 4754 } else { // LimitFloatPrecision <= 18 4755 // For floating-point precision of 18: 4756 // 4757 // Log2ofMantissa = 4758 // -3.0400495f + 4759 // (6.1129976f + 4760 // (-5.3420409f + 4761 // (3.2865683f + 4762 // (-1.2669343f + 4763 // (0.27515199f - 4764 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4765 // 4766 // error 0.0000018516, which is better than 18 bits 4767 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4768 getF32Constant(DAG, 0xbcd2769e, dl)); 4769 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4770 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4771 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4772 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4773 getF32Constant(DAG, 0x3fa22ae7, dl)); 4774 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4775 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4776 getF32Constant(DAG, 0x40525723, dl)); 4777 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4778 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4779 getF32Constant(DAG, 0x40aaf200, dl)); 4780 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4781 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4782 getF32Constant(DAG, 0x40c39dad, dl)); 4783 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4784 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4785 getF32Constant(DAG, 0x4042902c, dl)); 4786 } 4787 4788 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4789 } 4790 4791 // No special expansion. 4792 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4793 } 4794 4795 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4796 /// limited-precision mode. 4797 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4798 const TargetLowering &TLI) { 4799 // TODO: What fast-math-flags should be set on the floating-point nodes? 4800 4801 if (Op.getValueType() == MVT::f32 && 4802 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4803 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4804 4805 // Scale the exponent by log10(2) [0.30102999f]. 4806 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4807 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4808 getF32Constant(DAG, 0x3e9a209a, dl)); 4809 4810 // Get the significand and build it into a floating-point number with 4811 // exponent of 1. 4812 SDValue X = GetSignificand(DAG, Op1, dl); 4813 4814 SDValue Log10ofMantissa; 4815 if (LimitFloatPrecision <= 6) { 4816 // For floating-point precision of 6: 4817 // 4818 // Log10ofMantissa = 4819 // -0.50419619f + 4820 // (0.60948995f - 0.10380950f * x) * x; 4821 // 4822 // error 0.0014886165, which is 6 bits 4823 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4824 getF32Constant(DAG, 0xbdd49a13, dl)); 4825 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4826 getF32Constant(DAG, 0x3f1c0789, dl)); 4827 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4828 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4829 getF32Constant(DAG, 0x3f011300, dl)); 4830 } else if (LimitFloatPrecision <= 12) { 4831 // For floating-point precision of 12: 4832 // 4833 // Log10ofMantissa = 4834 // -0.64831180f + 4835 // (0.91751397f + 4836 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4837 // 4838 // error 0.00019228036, which is better than 12 bits 4839 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4840 getF32Constant(DAG, 0x3d431f31, dl)); 4841 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4842 getF32Constant(DAG, 0x3ea21fb2, dl)); 4843 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4844 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4845 getF32Constant(DAG, 0x3f6ae232, dl)); 4846 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4847 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4848 getF32Constant(DAG, 0x3f25f7c3, dl)); 4849 } else { // LimitFloatPrecision <= 18 4850 // For floating-point precision of 18: 4851 // 4852 // Log10ofMantissa = 4853 // -0.84299375f + 4854 // (1.5327582f + 4855 // (-1.0688956f + 4856 // (0.49102474f + 4857 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4858 // 4859 // error 0.0000037995730, which is better than 18 bits 4860 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4861 getF32Constant(DAG, 0x3c5d51ce, dl)); 4862 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4863 getF32Constant(DAG, 0x3e00685a, dl)); 4864 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4865 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4866 getF32Constant(DAG, 0x3efb6798, dl)); 4867 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4868 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4869 getF32Constant(DAG, 0x3f88d192, dl)); 4870 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4871 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4872 getF32Constant(DAG, 0x3fc4316c, dl)); 4873 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4874 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4875 getF32Constant(DAG, 0x3f57ce70, dl)); 4876 } 4877 4878 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4879 } 4880 4881 // No special expansion. 4882 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4883 } 4884 4885 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4886 /// limited-precision mode. 4887 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4888 const TargetLowering &TLI) { 4889 if (Op.getValueType() == MVT::f32 && 4890 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4891 return getLimitedPrecisionExp2(Op, dl, DAG); 4892 4893 // No special expansion. 4894 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4895 } 4896 4897 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4898 /// limited-precision mode with x == 10.0f. 4899 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4900 SelectionDAG &DAG, const TargetLowering &TLI) { 4901 bool IsExp10 = false; 4902 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4903 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4904 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4905 APFloat Ten(10.0f); 4906 IsExp10 = LHSC->isExactlyValue(Ten); 4907 } 4908 } 4909 4910 // TODO: What fast-math-flags should be set on the FMUL node? 4911 if (IsExp10) { 4912 // Put the exponent in the right bit position for later addition to the 4913 // final result: 4914 // 4915 // #define LOG2OF10 3.3219281f 4916 // t0 = Op * LOG2OF10; 4917 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4918 getF32Constant(DAG, 0x40549a78, dl)); 4919 return getLimitedPrecisionExp2(t0, dl, DAG); 4920 } 4921 4922 // No special expansion. 4923 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4924 } 4925 4926 /// ExpandPowI - Expand a llvm.powi intrinsic. 4927 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4928 SelectionDAG &DAG) { 4929 // If RHS is a constant, we can expand this out to a multiplication tree, 4930 // otherwise we end up lowering to a call to __powidf2 (for example). When 4931 // optimizing for size, we only want to do this if the expansion would produce 4932 // a small number of multiplies, otherwise we do the full expansion. 4933 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4934 // Get the exponent as a positive value. 4935 unsigned Val = RHSC->getSExtValue(); 4936 if ((int)Val < 0) Val = -Val; 4937 4938 // powi(x, 0) -> 1.0 4939 if (Val == 0) 4940 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4941 4942 const Function &F = DAG.getMachineFunction().getFunction(); 4943 if (!F.optForSize() || 4944 // If optimizing for size, don't insert too many multiplies. 4945 // This inserts up to 5 multiplies. 4946 countPopulation(Val) + Log2_32(Val) < 7) { 4947 // We use the simple binary decomposition method to generate the multiply 4948 // sequence. There are more optimal ways to do this (for example, 4949 // powi(x,15) generates one more multiply than it should), but this has 4950 // the benefit of being both really simple and much better than a libcall. 4951 SDValue Res; // Logically starts equal to 1.0 4952 SDValue CurSquare = LHS; 4953 // TODO: Intrinsics should have fast-math-flags that propagate to these 4954 // nodes. 4955 while (Val) { 4956 if (Val & 1) { 4957 if (Res.getNode()) 4958 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4959 else 4960 Res = CurSquare; // 1.0*CurSquare. 4961 } 4962 4963 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4964 CurSquare, CurSquare); 4965 Val >>= 1; 4966 } 4967 4968 // If the original was negative, invert the result, producing 1/(x*x*x). 4969 if (RHSC->getSExtValue() < 0) 4970 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4971 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4972 return Res; 4973 } 4974 } 4975 4976 // Otherwise, expand to a libcall. 4977 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4978 } 4979 4980 // getUnderlyingArgReg - Find underlying register used for a truncated or 4981 // bitcasted argument. 4982 static unsigned getUnderlyingArgReg(const SDValue &N) { 4983 switch (N.getOpcode()) { 4984 case ISD::CopyFromReg: 4985 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4986 case ISD::BITCAST: 4987 case ISD::AssertZext: 4988 case ISD::AssertSext: 4989 case ISD::TRUNCATE: 4990 return getUnderlyingArgReg(N.getOperand(0)); 4991 default: 4992 return 0; 4993 } 4994 } 4995 4996 /// If the DbgValueInst is a dbg_value of a function argument, create the 4997 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4998 /// instruction selection, they will be inserted to the entry BB. 4999 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5000 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5001 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5002 const Argument *Arg = dyn_cast<Argument>(V); 5003 if (!Arg) 5004 return false; 5005 5006 MachineFunction &MF = DAG.getMachineFunction(); 5007 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5008 5009 bool IsIndirect = false; 5010 Optional<MachineOperand> Op; 5011 // Some arguments' frame index is recorded during argument lowering. 5012 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5013 if (FI != std::numeric_limits<int>::max()) 5014 Op = MachineOperand::CreateFI(FI); 5015 5016 if (!Op && N.getNode()) { 5017 unsigned Reg = getUnderlyingArgReg(N); 5018 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 5019 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5020 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 5021 if (PR) 5022 Reg = PR; 5023 } 5024 if (Reg) { 5025 Op = MachineOperand::CreateReg(Reg, false); 5026 IsIndirect = IsDbgDeclare; 5027 } 5028 } 5029 5030 if (!Op && N.getNode()) 5031 // Check if frame index is available. 5032 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 5033 if (FrameIndexSDNode *FINode = 5034 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5035 Op = MachineOperand::CreateFI(FINode->getIndex()); 5036 5037 if (!Op) { 5038 // Check if ValueMap has reg number. 5039 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5040 if (VMI != FuncInfo.ValueMap.end()) { 5041 const auto &TLI = DAG.getTargetLoweringInfo(); 5042 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5043 V->getType(), getABIRegCopyCC(V)); 5044 if (RFV.occupiesMultipleRegs()) { 5045 unsigned Offset = 0; 5046 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5047 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5048 auto FragmentExpr = DIExpression::createFragmentExpression( 5049 Expr, Offset, RegAndSize.second); 5050 if (!FragmentExpr) 5051 continue; 5052 FuncInfo.ArgDbgValues.push_back( 5053 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5054 Op->getReg(), Variable, *FragmentExpr)); 5055 Offset += RegAndSize.second; 5056 } 5057 return true; 5058 } 5059 Op = MachineOperand::CreateReg(VMI->second, false); 5060 IsIndirect = IsDbgDeclare; 5061 } 5062 } 5063 5064 if (!Op) 5065 return false; 5066 5067 assert(Variable->isValidLocationForIntrinsic(DL) && 5068 "Expected inlined-at fields to agree"); 5069 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5070 FuncInfo.ArgDbgValues.push_back( 5071 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5072 *Op, Variable, Expr)); 5073 5074 return true; 5075 } 5076 5077 /// Return the appropriate SDDbgValue based on N. 5078 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5079 DILocalVariable *Variable, 5080 DIExpression *Expr, 5081 const DebugLoc &dl, 5082 unsigned DbgSDNodeOrder) { 5083 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5084 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5085 // stack slot locations. 5086 // 5087 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5088 // debug values here after optimization: 5089 // 5090 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5091 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5092 // 5093 // Both describe the direct values of their associated variables. 5094 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5095 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5096 } 5097 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5098 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5099 } 5100 5101 // VisualStudio defines setjmp as _setjmp 5102 #if defined(_MSC_VER) && defined(setjmp) && \ 5103 !defined(setjmp_undefined_for_msvc) 5104 # pragma push_macro("setjmp") 5105 # undef setjmp 5106 # define setjmp_undefined_for_msvc 5107 #endif 5108 5109 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5110 switch (Intrinsic) { 5111 case Intrinsic::smul_fix: 5112 return ISD::SMULFIX; 5113 case Intrinsic::umul_fix: 5114 return ISD::UMULFIX; 5115 default: 5116 llvm_unreachable("Unhandled fixed point intrinsic"); 5117 } 5118 } 5119 5120 /// Lower the call to the specified intrinsic function. If we want to emit this 5121 /// as a call to a named external function, return the name. Otherwise, lower it 5122 /// and return null. 5123 const char * 5124 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5126 SDLoc sdl = getCurSDLoc(); 5127 DebugLoc dl = getCurDebugLoc(); 5128 SDValue Res; 5129 5130 switch (Intrinsic) { 5131 default: 5132 // By default, turn this into a target intrinsic node. 5133 visitTargetIntrinsic(I, Intrinsic); 5134 return nullptr; 5135 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5136 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5137 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5138 case Intrinsic::returnaddress: 5139 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5140 TLI.getPointerTy(DAG.getDataLayout()), 5141 getValue(I.getArgOperand(0)))); 5142 return nullptr; 5143 case Intrinsic::addressofreturnaddress: 5144 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5145 TLI.getPointerTy(DAG.getDataLayout()))); 5146 return nullptr; 5147 case Intrinsic::sponentry: 5148 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5149 TLI.getPointerTy(DAG.getDataLayout()))); 5150 return nullptr; 5151 case Intrinsic::frameaddress: 5152 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5153 TLI.getPointerTy(DAG.getDataLayout()), 5154 getValue(I.getArgOperand(0)))); 5155 return nullptr; 5156 case Intrinsic::read_register: { 5157 Value *Reg = I.getArgOperand(0); 5158 SDValue Chain = getRoot(); 5159 SDValue RegName = 5160 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5161 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5162 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5163 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5164 setValue(&I, Res); 5165 DAG.setRoot(Res.getValue(1)); 5166 return nullptr; 5167 } 5168 case Intrinsic::write_register: { 5169 Value *Reg = I.getArgOperand(0); 5170 Value *RegValue = I.getArgOperand(1); 5171 SDValue Chain = getRoot(); 5172 SDValue RegName = 5173 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5174 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5175 RegName, getValue(RegValue))); 5176 return nullptr; 5177 } 5178 case Intrinsic::setjmp: 5179 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5180 case Intrinsic::longjmp: 5181 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5182 case Intrinsic::memcpy: { 5183 const auto &MCI = cast<MemCpyInst>(I); 5184 SDValue Op1 = getValue(I.getArgOperand(0)); 5185 SDValue Op2 = getValue(I.getArgOperand(1)); 5186 SDValue Op3 = getValue(I.getArgOperand(2)); 5187 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5188 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5189 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5190 unsigned Align = MinAlign(DstAlign, SrcAlign); 5191 bool isVol = MCI.isVolatile(); 5192 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5193 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5194 // node. 5195 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5196 false, isTC, 5197 MachinePointerInfo(I.getArgOperand(0)), 5198 MachinePointerInfo(I.getArgOperand(1))); 5199 updateDAGForMaybeTailCall(MC); 5200 return nullptr; 5201 } 5202 case Intrinsic::memset: { 5203 const auto &MSI = cast<MemSetInst>(I); 5204 SDValue Op1 = getValue(I.getArgOperand(0)); 5205 SDValue Op2 = getValue(I.getArgOperand(1)); 5206 SDValue Op3 = getValue(I.getArgOperand(2)); 5207 // @llvm.memset defines 0 and 1 to both mean no alignment. 5208 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5209 bool isVol = MSI.isVolatile(); 5210 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5211 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5212 isTC, MachinePointerInfo(I.getArgOperand(0))); 5213 updateDAGForMaybeTailCall(MS); 5214 return nullptr; 5215 } 5216 case Intrinsic::memmove: { 5217 const auto &MMI = cast<MemMoveInst>(I); 5218 SDValue Op1 = getValue(I.getArgOperand(0)); 5219 SDValue Op2 = getValue(I.getArgOperand(1)); 5220 SDValue Op3 = getValue(I.getArgOperand(2)); 5221 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5222 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5223 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5224 unsigned Align = MinAlign(DstAlign, SrcAlign); 5225 bool isVol = MMI.isVolatile(); 5226 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5227 // FIXME: Support passing different dest/src alignments to the memmove DAG 5228 // node. 5229 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5230 isTC, MachinePointerInfo(I.getArgOperand(0)), 5231 MachinePointerInfo(I.getArgOperand(1))); 5232 updateDAGForMaybeTailCall(MM); 5233 return nullptr; 5234 } 5235 case Intrinsic::memcpy_element_unordered_atomic: { 5236 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5237 SDValue Dst = getValue(MI.getRawDest()); 5238 SDValue Src = getValue(MI.getRawSource()); 5239 SDValue Length = getValue(MI.getLength()); 5240 5241 unsigned DstAlign = MI.getDestAlignment(); 5242 unsigned SrcAlign = MI.getSourceAlignment(); 5243 Type *LengthTy = MI.getLength()->getType(); 5244 unsigned ElemSz = MI.getElementSizeInBytes(); 5245 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5246 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5247 SrcAlign, Length, LengthTy, ElemSz, isTC, 5248 MachinePointerInfo(MI.getRawDest()), 5249 MachinePointerInfo(MI.getRawSource())); 5250 updateDAGForMaybeTailCall(MC); 5251 return nullptr; 5252 } 5253 case Intrinsic::memmove_element_unordered_atomic: { 5254 auto &MI = cast<AtomicMemMoveInst>(I); 5255 SDValue Dst = getValue(MI.getRawDest()); 5256 SDValue Src = getValue(MI.getRawSource()); 5257 SDValue Length = getValue(MI.getLength()); 5258 5259 unsigned DstAlign = MI.getDestAlignment(); 5260 unsigned SrcAlign = MI.getSourceAlignment(); 5261 Type *LengthTy = MI.getLength()->getType(); 5262 unsigned ElemSz = MI.getElementSizeInBytes(); 5263 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5264 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5265 SrcAlign, Length, LengthTy, ElemSz, isTC, 5266 MachinePointerInfo(MI.getRawDest()), 5267 MachinePointerInfo(MI.getRawSource())); 5268 updateDAGForMaybeTailCall(MC); 5269 return nullptr; 5270 } 5271 case Intrinsic::memset_element_unordered_atomic: { 5272 auto &MI = cast<AtomicMemSetInst>(I); 5273 SDValue Dst = getValue(MI.getRawDest()); 5274 SDValue Val = getValue(MI.getValue()); 5275 SDValue Length = getValue(MI.getLength()); 5276 5277 unsigned DstAlign = MI.getDestAlignment(); 5278 Type *LengthTy = MI.getLength()->getType(); 5279 unsigned ElemSz = MI.getElementSizeInBytes(); 5280 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5281 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5282 LengthTy, ElemSz, isTC, 5283 MachinePointerInfo(MI.getRawDest())); 5284 updateDAGForMaybeTailCall(MC); 5285 return nullptr; 5286 } 5287 case Intrinsic::dbg_addr: 5288 case Intrinsic::dbg_declare: { 5289 const auto &DI = cast<DbgVariableIntrinsic>(I); 5290 DILocalVariable *Variable = DI.getVariable(); 5291 DIExpression *Expression = DI.getExpression(); 5292 dropDanglingDebugInfo(Variable, Expression); 5293 assert(Variable && "Missing variable"); 5294 5295 // Check if address has undef value. 5296 const Value *Address = DI.getVariableLocation(); 5297 if (!Address || isa<UndefValue>(Address) || 5298 (Address->use_empty() && !isa<Argument>(Address))) { 5299 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5300 return nullptr; 5301 } 5302 5303 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5304 5305 // Check if this variable can be described by a frame index, typically 5306 // either as a static alloca or a byval parameter. 5307 int FI = std::numeric_limits<int>::max(); 5308 if (const auto *AI = 5309 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5310 if (AI->isStaticAlloca()) { 5311 auto I = FuncInfo.StaticAllocaMap.find(AI); 5312 if (I != FuncInfo.StaticAllocaMap.end()) 5313 FI = I->second; 5314 } 5315 } else if (const auto *Arg = dyn_cast<Argument>( 5316 Address->stripInBoundsConstantOffsets())) { 5317 FI = FuncInfo.getArgumentFrameIndex(Arg); 5318 } 5319 5320 // llvm.dbg.addr is control dependent and always generates indirect 5321 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5322 // the MachineFunction variable table. 5323 if (FI != std::numeric_limits<int>::max()) { 5324 if (Intrinsic == Intrinsic::dbg_addr) { 5325 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5326 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5327 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5328 } 5329 return nullptr; 5330 } 5331 5332 SDValue &N = NodeMap[Address]; 5333 if (!N.getNode() && isa<Argument>(Address)) 5334 // Check unused arguments map. 5335 N = UnusedArgNodeMap[Address]; 5336 SDDbgValue *SDV; 5337 if (N.getNode()) { 5338 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5339 Address = BCI->getOperand(0); 5340 // Parameters are handled specially. 5341 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5342 if (isParameter && FINode) { 5343 // Byval parameter. We have a frame index at this point. 5344 SDV = 5345 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5346 /*IsIndirect*/ true, dl, SDNodeOrder); 5347 } else if (isa<Argument>(Address)) { 5348 // Address is an argument, so try to emit its dbg value using 5349 // virtual register info from the FuncInfo.ValueMap. 5350 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5351 return nullptr; 5352 } else { 5353 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5354 true, dl, SDNodeOrder); 5355 } 5356 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5357 } else { 5358 // If Address is an argument then try to emit its dbg value using 5359 // virtual register info from the FuncInfo.ValueMap. 5360 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5361 N)) { 5362 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5363 } 5364 } 5365 return nullptr; 5366 } 5367 case Intrinsic::dbg_label: { 5368 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5369 DILabel *Label = DI.getLabel(); 5370 assert(Label && "Missing label"); 5371 5372 SDDbgLabel *SDV; 5373 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5374 DAG.AddDbgLabel(SDV); 5375 return nullptr; 5376 } 5377 case Intrinsic::dbg_value: { 5378 const DbgValueInst &DI = cast<DbgValueInst>(I); 5379 assert(DI.getVariable() && "Missing variable"); 5380 5381 DILocalVariable *Variable = DI.getVariable(); 5382 DIExpression *Expression = DI.getExpression(); 5383 dropDanglingDebugInfo(Variable, Expression); 5384 const Value *V = DI.getValue(); 5385 if (!V) 5386 return nullptr; 5387 5388 SDDbgValue *SDV; 5389 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5390 isa<ConstantPointerNull>(V)) { 5391 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5392 DAG.AddDbgValue(SDV, nullptr, false); 5393 return nullptr; 5394 } 5395 5396 // If the Value is a frame index, we can create a FrameIndex debug value 5397 // without relying on the DAG at all. 5398 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 5399 auto SI = FuncInfo.StaticAllocaMap.find(AI); 5400 if (SI != FuncInfo.StaticAllocaMap.end()) { 5401 auto SDV = 5402 DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 5403 /*IsIndirect*/ false, dl, SDNodeOrder); 5404 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 5405 // is still available even if the SDNode gets optimized out. 5406 DAG.AddDbgValue(SDV, nullptr, false); 5407 return nullptr; 5408 } 5409 } 5410 5411 // Do not use getValue() in here; we don't want to generate code at 5412 // this point if it hasn't been done yet. 5413 SDValue N = NodeMap[V]; 5414 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5415 N = UnusedArgNodeMap[V]; 5416 if (N.getNode()) { 5417 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5418 return nullptr; 5419 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5420 DAG.AddDbgValue(SDV, N.getNode(), false); 5421 return nullptr; 5422 } 5423 5424 // The value is not used in this block yet (or it would have an SDNode). 5425 // We still want the value to appear for the user if possible -- if it has 5426 // an associated VReg, we can refer to that instead. 5427 if (!isa<Argument>(V)) { 5428 auto VMI = FuncInfo.ValueMap.find(V); 5429 if (VMI != FuncInfo.ValueMap.end()) { 5430 unsigned Reg = VMI->second; 5431 // If this is a PHI node, it may be split up into several MI PHI nodes 5432 // (in FunctionLoweringInfo::set). 5433 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5434 V->getType(), None); 5435 if (RFV.occupiesMultipleRegs()) { 5436 unsigned Offset = 0; 5437 unsigned BitsToDescribe = 0; 5438 if (auto VarSize = Variable->getSizeInBits()) 5439 BitsToDescribe = *VarSize; 5440 if (auto Fragment = Expression->getFragmentInfo()) 5441 BitsToDescribe = Fragment->SizeInBits; 5442 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5443 unsigned RegisterSize = RegAndSize.second; 5444 // Bail out if all bits are described already. 5445 if (Offset >= BitsToDescribe) 5446 break; 5447 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5448 ? BitsToDescribe - Offset 5449 : RegisterSize; 5450 auto FragmentExpr = DIExpression::createFragmentExpression( 5451 Expression, Offset, FragmentSize); 5452 if (!FragmentExpr) 5453 continue; 5454 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5455 false, dl, SDNodeOrder); 5456 DAG.AddDbgValue(SDV, nullptr, false); 5457 Offset += RegisterSize; 5458 } 5459 } else { 5460 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5461 SDNodeOrder); 5462 DAG.AddDbgValue(SDV, nullptr, false); 5463 } 5464 return nullptr; 5465 } 5466 } 5467 5468 // TODO: When we get here we will either drop the dbg.value completely, or 5469 // we try to move it forward by letting it dangle for awhile. So we should 5470 // probably add an extra DbgValue to the DAG here, with a reference to 5471 // "noreg", to indicate that we have lost the debug location for the 5472 // variable. 5473 5474 if (!V->use_empty() ) { 5475 // Do not call getValue(V) yet, as we don't want to generate code. 5476 // Remember it for later. 5477 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5478 return nullptr; 5479 } 5480 5481 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5482 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5483 return nullptr; 5484 } 5485 5486 case Intrinsic::eh_typeid_for: { 5487 // Find the type id for the given typeinfo. 5488 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5489 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5490 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5491 setValue(&I, Res); 5492 return nullptr; 5493 } 5494 5495 case Intrinsic::eh_return_i32: 5496 case Intrinsic::eh_return_i64: 5497 DAG.getMachineFunction().setCallsEHReturn(true); 5498 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5499 MVT::Other, 5500 getControlRoot(), 5501 getValue(I.getArgOperand(0)), 5502 getValue(I.getArgOperand(1)))); 5503 return nullptr; 5504 case Intrinsic::eh_unwind_init: 5505 DAG.getMachineFunction().setCallsUnwindInit(true); 5506 return nullptr; 5507 case Intrinsic::eh_dwarf_cfa: 5508 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5509 TLI.getPointerTy(DAG.getDataLayout()), 5510 getValue(I.getArgOperand(0)))); 5511 return nullptr; 5512 case Intrinsic::eh_sjlj_callsite: { 5513 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5514 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5515 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5516 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5517 5518 MMI.setCurrentCallSite(CI->getZExtValue()); 5519 return nullptr; 5520 } 5521 case Intrinsic::eh_sjlj_functioncontext: { 5522 // Get and store the index of the function context. 5523 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5524 AllocaInst *FnCtx = 5525 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5526 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5527 MFI.setFunctionContextIndex(FI); 5528 return nullptr; 5529 } 5530 case Intrinsic::eh_sjlj_setjmp: { 5531 SDValue Ops[2]; 5532 Ops[0] = getRoot(); 5533 Ops[1] = getValue(I.getArgOperand(0)); 5534 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5535 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5536 setValue(&I, Op.getValue(0)); 5537 DAG.setRoot(Op.getValue(1)); 5538 return nullptr; 5539 } 5540 case Intrinsic::eh_sjlj_longjmp: 5541 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5542 getRoot(), getValue(I.getArgOperand(0)))); 5543 return nullptr; 5544 case Intrinsic::eh_sjlj_setup_dispatch: 5545 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5546 getRoot())); 5547 return nullptr; 5548 case Intrinsic::masked_gather: 5549 visitMaskedGather(I); 5550 return nullptr; 5551 case Intrinsic::masked_load: 5552 visitMaskedLoad(I); 5553 return nullptr; 5554 case Intrinsic::masked_scatter: 5555 visitMaskedScatter(I); 5556 return nullptr; 5557 case Intrinsic::masked_store: 5558 visitMaskedStore(I); 5559 return nullptr; 5560 case Intrinsic::masked_expandload: 5561 visitMaskedLoad(I, true /* IsExpanding */); 5562 return nullptr; 5563 case Intrinsic::masked_compressstore: 5564 visitMaskedStore(I, true /* IsCompressing */); 5565 return nullptr; 5566 case Intrinsic::x86_mmx_pslli_w: 5567 case Intrinsic::x86_mmx_pslli_d: 5568 case Intrinsic::x86_mmx_pslli_q: 5569 case Intrinsic::x86_mmx_psrli_w: 5570 case Intrinsic::x86_mmx_psrli_d: 5571 case Intrinsic::x86_mmx_psrli_q: 5572 case Intrinsic::x86_mmx_psrai_w: 5573 case Intrinsic::x86_mmx_psrai_d: { 5574 SDValue ShAmt = getValue(I.getArgOperand(1)); 5575 if (isa<ConstantSDNode>(ShAmt)) { 5576 visitTargetIntrinsic(I, Intrinsic); 5577 return nullptr; 5578 } 5579 unsigned NewIntrinsic = 0; 5580 EVT ShAmtVT = MVT::v2i32; 5581 switch (Intrinsic) { 5582 case Intrinsic::x86_mmx_pslli_w: 5583 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5584 break; 5585 case Intrinsic::x86_mmx_pslli_d: 5586 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5587 break; 5588 case Intrinsic::x86_mmx_pslli_q: 5589 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5590 break; 5591 case Intrinsic::x86_mmx_psrli_w: 5592 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5593 break; 5594 case Intrinsic::x86_mmx_psrli_d: 5595 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5596 break; 5597 case Intrinsic::x86_mmx_psrli_q: 5598 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5599 break; 5600 case Intrinsic::x86_mmx_psrai_w: 5601 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5602 break; 5603 case Intrinsic::x86_mmx_psrai_d: 5604 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5605 break; 5606 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5607 } 5608 5609 // The vector shift intrinsics with scalars uses 32b shift amounts but 5610 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5611 // to be zero. 5612 // We must do this early because v2i32 is not a legal type. 5613 SDValue ShOps[2]; 5614 ShOps[0] = ShAmt; 5615 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5616 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5617 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5618 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5619 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5620 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5621 getValue(I.getArgOperand(0)), ShAmt); 5622 setValue(&I, Res); 5623 return nullptr; 5624 } 5625 case Intrinsic::powi: 5626 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5627 getValue(I.getArgOperand(1)), DAG)); 5628 return nullptr; 5629 case Intrinsic::log: 5630 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5631 return nullptr; 5632 case Intrinsic::log2: 5633 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5634 return nullptr; 5635 case Intrinsic::log10: 5636 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5637 return nullptr; 5638 case Intrinsic::exp: 5639 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5640 return nullptr; 5641 case Intrinsic::exp2: 5642 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5643 return nullptr; 5644 case Intrinsic::pow: 5645 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5646 getValue(I.getArgOperand(1)), DAG, TLI)); 5647 return nullptr; 5648 case Intrinsic::sqrt: 5649 case Intrinsic::fabs: 5650 case Intrinsic::sin: 5651 case Intrinsic::cos: 5652 case Intrinsic::floor: 5653 case Intrinsic::ceil: 5654 case Intrinsic::trunc: 5655 case Intrinsic::rint: 5656 case Intrinsic::nearbyint: 5657 case Intrinsic::round: 5658 case Intrinsic::canonicalize: { 5659 unsigned Opcode; 5660 switch (Intrinsic) { 5661 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5662 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5663 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5664 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5665 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5666 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5667 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5668 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5669 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5670 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5671 case Intrinsic::round: Opcode = ISD::FROUND; break; 5672 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5673 } 5674 5675 setValue(&I, DAG.getNode(Opcode, sdl, 5676 getValue(I.getArgOperand(0)).getValueType(), 5677 getValue(I.getArgOperand(0)))); 5678 return nullptr; 5679 } 5680 case Intrinsic::minnum: { 5681 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5682 unsigned Opc = 5683 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5684 ? ISD::FMINIMUM 5685 : ISD::FMINNUM; 5686 setValue(&I, DAG.getNode(Opc, sdl, VT, 5687 getValue(I.getArgOperand(0)), 5688 getValue(I.getArgOperand(1)))); 5689 return nullptr; 5690 } 5691 case Intrinsic::maxnum: { 5692 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5693 unsigned Opc = 5694 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5695 ? ISD::FMAXIMUM 5696 : ISD::FMAXNUM; 5697 setValue(&I, DAG.getNode(Opc, sdl, VT, 5698 getValue(I.getArgOperand(0)), 5699 getValue(I.getArgOperand(1)))); 5700 return nullptr; 5701 } 5702 case Intrinsic::minimum: 5703 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5704 getValue(I.getArgOperand(0)).getValueType(), 5705 getValue(I.getArgOperand(0)), 5706 getValue(I.getArgOperand(1)))); 5707 return nullptr; 5708 case Intrinsic::maximum: 5709 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5710 getValue(I.getArgOperand(0)).getValueType(), 5711 getValue(I.getArgOperand(0)), 5712 getValue(I.getArgOperand(1)))); 5713 return nullptr; 5714 case Intrinsic::copysign: 5715 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5716 getValue(I.getArgOperand(0)).getValueType(), 5717 getValue(I.getArgOperand(0)), 5718 getValue(I.getArgOperand(1)))); 5719 return nullptr; 5720 case Intrinsic::fma: 5721 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5722 getValue(I.getArgOperand(0)).getValueType(), 5723 getValue(I.getArgOperand(0)), 5724 getValue(I.getArgOperand(1)), 5725 getValue(I.getArgOperand(2)))); 5726 return nullptr; 5727 case Intrinsic::experimental_constrained_fadd: 5728 case Intrinsic::experimental_constrained_fsub: 5729 case Intrinsic::experimental_constrained_fmul: 5730 case Intrinsic::experimental_constrained_fdiv: 5731 case Intrinsic::experimental_constrained_frem: 5732 case Intrinsic::experimental_constrained_fma: 5733 case Intrinsic::experimental_constrained_sqrt: 5734 case Intrinsic::experimental_constrained_pow: 5735 case Intrinsic::experimental_constrained_powi: 5736 case Intrinsic::experimental_constrained_sin: 5737 case Intrinsic::experimental_constrained_cos: 5738 case Intrinsic::experimental_constrained_exp: 5739 case Intrinsic::experimental_constrained_exp2: 5740 case Intrinsic::experimental_constrained_log: 5741 case Intrinsic::experimental_constrained_log10: 5742 case Intrinsic::experimental_constrained_log2: 5743 case Intrinsic::experimental_constrained_rint: 5744 case Intrinsic::experimental_constrained_nearbyint: 5745 case Intrinsic::experimental_constrained_maxnum: 5746 case Intrinsic::experimental_constrained_minnum: 5747 case Intrinsic::experimental_constrained_ceil: 5748 case Intrinsic::experimental_constrained_floor: 5749 case Intrinsic::experimental_constrained_round: 5750 case Intrinsic::experimental_constrained_trunc: 5751 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5752 return nullptr; 5753 case Intrinsic::fmuladd: { 5754 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5755 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5756 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5757 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5758 getValue(I.getArgOperand(0)).getValueType(), 5759 getValue(I.getArgOperand(0)), 5760 getValue(I.getArgOperand(1)), 5761 getValue(I.getArgOperand(2)))); 5762 } else { 5763 // TODO: Intrinsic calls should have fast-math-flags. 5764 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5765 getValue(I.getArgOperand(0)).getValueType(), 5766 getValue(I.getArgOperand(0)), 5767 getValue(I.getArgOperand(1))); 5768 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5769 getValue(I.getArgOperand(0)).getValueType(), 5770 Mul, 5771 getValue(I.getArgOperand(2))); 5772 setValue(&I, Add); 5773 } 5774 return nullptr; 5775 } 5776 case Intrinsic::convert_to_fp16: 5777 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5778 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5779 getValue(I.getArgOperand(0)), 5780 DAG.getTargetConstant(0, sdl, 5781 MVT::i32)))); 5782 return nullptr; 5783 case Intrinsic::convert_from_fp16: 5784 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5785 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5786 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5787 getValue(I.getArgOperand(0))))); 5788 return nullptr; 5789 case Intrinsic::pcmarker: { 5790 SDValue Tmp = getValue(I.getArgOperand(0)); 5791 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5792 return nullptr; 5793 } 5794 case Intrinsic::readcyclecounter: { 5795 SDValue Op = getRoot(); 5796 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5797 DAG.getVTList(MVT::i64, MVT::Other), Op); 5798 setValue(&I, Res); 5799 DAG.setRoot(Res.getValue(1)); 5800 return nullptr; 5801 } 5802 case Intrinsic::bitreverse: 5803 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5804 getValue(I.getArgOperand(0)).getValueType(), 5805 getValue(I.getArgOperand(0)))); 5806 return nullptr; 5807 case Intrinsic::bswap: 5808 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5809 getValue(I.getArgOperand(0)).getValueType(), 5810 getValue(I.getArgOperand(0)))); 5811 return nullptr; 5812 case Intrinsic::cttz: { 5813 SDValue Arg = getValue(I.getArgOperand(0)); 5814 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5815 EVT Ty = Arg.getValueType(); 5816 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5817 sdl, Ty, Arg)); 5818 return nullptr; 5819 } 5820 case Intrinsic::ctlz: { 5821 SDValue Arg = getValue(I.getArgOperand(0)); 5822 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5823 EVT Ty = Arg.getValueType(); 5824 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5825 sdl, Ty, Arg)); 5826 return nullptr; 5827 } 5828 case Intrinsic::ctpop: { 5829 SDValue Arg = getValue(I.getArgOperand(0)); 5830 EVT Ty = Arg.getValueType(); 5831 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5832 return nullptr; 5833 } 5834 case Intrinsic::fshl: 5835 case Intrinsic::fshr: { 5836 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5837 SDValue X = getValue(I.getArgOperand(0)); 5838 SDValue Y = getValue(I.getArgOperand(1)); 5839 SDValue Z = getValue(I.getArgOperand(2)); 5840 EVT VT = X.getValueType(); 5841 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5842 SDValue Zero = DAG.getConstant(0, sdl, VT); 5843 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5844 5845 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5846 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5847 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5848 return nullptr; 5849 } 5850 5851 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5852 // avoid the select that is necessary in the general case to filter out 5853 // the 0-shift possibility that leads to UB. 5854 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5855 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5856 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5857 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5858 return nullptr; 5859 } 5860 5861 // Some targets only rotate one way. Try the opposite direction. 5862 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5863 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5864 // Negate the shift amount because it is safe to ignore the high bits. 5865 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5866 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5867 return nullptr; 5868 } 5869 5870 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5871 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5872 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5873 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5874 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5875 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5876 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5877 return nullptr; 5878 } 5879 5880 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5881 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5882 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5883 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5884 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5885 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5886 5887 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5888 // and that is undefined. We must compare and select to avoid UB. 5889 EVT CCVT = MVT::i1; 5890 if (VT.isVector()) 5891 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5892 5893 // For fshl, 0-shift returns the 1st arg (X). 5894 // For fshr, 0-shift returns the 2nd arg (Y). 5895 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5896 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5897 return nullptr; 5898 } 5899 case Intrinsic::sadd_sat: { 5900 SDValue Op1 = getValue(I.getArgOperand(0)); 5901 SDValue Op2 = getValue(I.getArgOperand(1)); 5902 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5903 return nullptr; 5904 } 5905 case Intrinsic::uadd_sat: { 5906 SDValue Op1 = getValue(I.getArgOperand(0)); 5907 SDValue Op2 = getValue(I.getArgOperand(1)); 5908 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5909 return nullptr; 5910 } 5911 case Intrinsic::ssub_sat: { 5912 SDValue Op1 = getValue(I.getArgOperand(0)); 5913 SDValue Op2 = getValue(I.getArgOperand(1)); 5914 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5915 return nullptr; 5916 } 5917 case Intrinsic::usub_sat: { 5918 SDValue Op1 = getValue(I.getArgOperand(0)); 5919 SDValue Op2 = getValue(I.getArgOperand(1)); 5920 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5921 return nullptr; 5922 } 5923 case Intrinsic::smul_fix: 5924 case Intrinsic::umul_fix: { 5925 SDValue Op1 = getValue(I.getArgOperand(0)); 5926 SDValue Op2 = getValue(I.getArgOperand(1)); 5927 SDValue Op3 = getValue(I.getArgOperand(2)); 5928 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 5929 Op1.getValueType(), Op1, Op2, Op3)); 5930 return nullptr; 5931 } 5932 case Intrinsic::stacksave: { 5933 SDValue Op = getRoot(); 5934 Res = DAG.getNode( 5935 ISD::STACKSAVE, sdl, 5936 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5937 setValue(&I, Res); 5938 DAG.setRoot(Res.getValue(1)); 5939 return nullptr; 5940 } 5941 case Intrinsic::stackrestore: 5942 Res = getValue(I.getArgOperand(0)); 5943 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5944 return nullptr; 5945 case Intrinsic::get_dynamic_area_offset: { 5946 SDValue Op = getRoot(); 5947 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5948 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5949 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5950 // target. 5951 if (PtrTy != ResTy) 5952 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5953 " intrinsic!"); 5954 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5955 Op); 5956 DAG.setRoot(Op); 5957 setValue(&I, Res); 5958 return nullptr; 5959 } 5960 case Intrinsic::stackguard: { 5961 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5962 MachineFunction &MF = DAG.getMachineFunction(); 5963 const Module &M = *MF.getFunction().getParent(); 5964 SDValue Chain = getRoot(); 5965 if (TLI.useLoadStackGuardNode()) { 5966 Res = getLoadStackGuard(DAG, sdl, Chain); 5967 } else { 5968 const Value *Global = TLI.getSDagStackGuard(M); 5969 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5970 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5971 MachinePointerInfo(Global, 0), Align, 5972 MachineMemOperand::MOVolatile); 5973 } 5974 if (TLI.useStackGuardXorFP()) 5975 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5976 DAG.setRoot(Chain); 5977 setValue(&I, Res); 5978 return nullptr; 5979 } 5980 case Intrinsic::stackprotector: { 5981 // Emit code into the DAG to store the stack guard onto the stack. 5982 MachineFunction &MF = DAG.getMachineFunction(); 5983 MachineFrameInfo &MFI = MF.getFrameInfo(); 5984 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5985 SDValue Src, Chain = getRoot(); 5986 5987 if (TLI.useLoadStackGuardNode()) 5988 Src = getLoadStackGuard(DAG, sdl, Chain); 5989 else 5990 Src = getValue(I.getArgOperand(0)); // The guard's value. 5991 5992 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5993 5994 int FI = FuncInfo.StaticAllocaMap[Slot]; 5995 MFI.setStackProtectorIndex(FI); 5996 5997 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5998 5999 // Store the stack protector onto the stack. 6000 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6001 DAG.getMachineFunction(), FI), 6002 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6003 setValue(&I, Res); 6004 DAG.setRoot(Res); 6005 return nullptr; 6006 } 6007 case Intrinsic::objectsize: { 6008 // If we don't know by now, we're never going to know. 6009 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6010 6011 assert(CI && "Non-constant type in __builtin_object_size?"); 6012 6013 SDValue Arg = getValue(I.getCalledValue()); 6014 EVT Ty = Arg.getValueType(); 6015 6016 if (CI->isZero()) 6017 Res = DAG.getConstant(-1ULL, sdl, Ty); 6018 else 6019 Res = DAG.getConstant(0, sdl, Ty); 6020 6021 setValue(&I, Res); 6022 return nullptr; 6023 } 6024 6025 case Intrinsic::is_constant: 6026 // If this wasn't constant-folded away by now, then it's not a 6027 // constant. 6028 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6029 return nullptr; 6030 6031 case Intrinsic::annotation: 6032 case Intrinsic::ptr_annotation: 6033 case Intrinsic::launder_invariant_group: 6034 case Intrinsic::strip_invariant_group: 6035 // Drop the intrinsic, but forward the value 6036 setValue(&I, getValue(I.getOperand(0))); 6037 return nullptr; 6038 case Intrinsic::assume: 6039 case Intrinsic::var_annotation: 6040 case Intrinsic::sideeffect: 6041 // Discard annotate attributes, assumptions, and artificial side-effects. 6042 return nullptr; 6043 6044 case Intrinsic::codeview_annotation: { 6045 // Emit a label associated with this metadata. 6046 MachineFunction &MF = DAG.getMachineFunction(); 6047 MCSymbol *Label = 6048 MF.getMMI().getContext().createTempSymbol("annotation", true); 6049 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6050 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6051 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6052 DAG.setRoot(Res); 6053 return nullptr; 6054 } 6055 6056 case Intrinsic::init_trampoline: { 6057 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6058 6059 SDValue Ops[6]; 6060 Ops[0] = getRoot(); 6061 Ops[1] = getValue(I.getArgOperand(0)); 6062 Ops[2] = getValue(I.getArgOperand(1)); 6063 Ops[3] = getValue(I.getArgOperand(2)); 6064 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6065 Ops[5] = DAG.getSrcValue(F); 6066 6067 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6068 6069 DAG.setRoot(Res); 6070 return nullptr; 6071 } 6072 case Intrinsic::adjust_trampoline: 6073 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6074 TLI.getPointerTy(DAG.getDataLayout()), 6075 getValue(I.getArgOperand(0)))); 6076 return nullptr; 6077 case Intrinsic::gcroot: { 6078 assert(DAG.getMachineFunction().getFunction().hasGC() && 6079 "only valid in functions with gc specified, enforced by Verifier"); 6080 assert(GFI && "implied by previous"); 6081 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6082 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6083 6084 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6085 GFI->addStackRoot(FI->getIndex(), TypeMap); 6086 return nullptr; 6087 } 6088 case Intrinsic::gcread: 6089 case Intrinsic::gcwrite: 6090 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6091 case Intrinsic::flt_rounds: 6092 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6093 return nullptr; 6094 6095 case Intrinsic::expect: 6096 // Just replace __builtin_expect(exp, c) with EXP. 6097 setValue(&I, getValue(I.getArgOperand(0))); 6098 return nullptr; 6099 6100 case Intrinsic::debugtrap: 6101 case Intrinsic::trap: { 6102 StringRef TrapFuncName = 6103 I.getAttributes() 6104 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6105 .getValueAsString(); 6106 if (TrapFuncName.empty()) { 6107 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6108 ISD::TRAP : ISD::DEBUGTRAP; 6109 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6110 return nullptr; 6111 } 6112 TargetLowering::ArgListTy Args; 6113 6114 TargetLowering::CallLoweringInfo CLI(DAG); 6115 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6116 CallingConv::C, I.getType(), 6117 DAG.getExternalSymbol(TrapFuncName.data(), 6118 TLI.getPointerTy(DAG.getDataLayout())), 6119 std::move(Args)); 6120 6121 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6122 DAG.setRoot(Result.second); 6123 return nullptr; 6124 } 6125 6126 case Intrinsic::uadd_with_overflow: 6127 case Intrinsic::sadd_with_overflow: 6128 case Intrinsic::usub_with_overflow: 6129 case Intrinsic::ssub_with_overflow: 6130 case Intrinsic::umul_with_overflow: 6131 case Intrinsic::smul_with_overflow: { 6132 ISD::NodeType Op; 6133 switch (Intrinsic) { 6134 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6135 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6136 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6137 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6138 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6139 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6140 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6141 } 6142 SDValue Op1 = getValue(I.getArgOperand(0)); 6143 SDValue Op2 = getValue(I.getArgOperand(1)); 6144 6145 EVT ResultVT = Op1.getValueType(); 6146 EVT OverflowVT = MVT::i1; 6147 if (ResultVT.isVector()) 6148 OverflowVT = EVT::getVectorVT( 6149 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6150 6151 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6152 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6153 return nullptr; 6154 } 6155 case Intrinsic::prefetch: { 6156 SDValue Ops[5]; 6157 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6158 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6159 Ops[0] = DAG.getRoot(); 6160 Ops[1] = getValue(I.getArgOperand(0)); 6161 Ops[2] = getValue(I.getArgOperand(1)); 6162 Ops[3] = getValue(I.getArgOperand(2)); 6163 Ops[4] = getValue(I.getArgOperand(3)); 6164 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6165 DAG.getVTList(MVT::Other), Ops, 6166 EVT::getIntegerVT(*Context, 8), 6167 MachinePointerInfo(I.getArgOperand(0)), 6168 0, /* align */ 6169 Flags); 6170 6171 // Chain the prefetch in parallell with any pending loads, to stay out of 6172 // the way of later optimizations. 6173 PendingLoads.push_back(Result); 6174 Result = getRoot(); 6175 DAG.setRoot(Result); 6176 return nullptr; 6177 } 6178 case Intrinsic::lifetime_start: 6179 case Intrinsic::lifetime_end: { 6180 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6181 // Stack coloring is not enabled in O0, discard region information. 6182 if (TM.getOptLevel() == CodeGenOpt::None) 6183 return nullptr; 6184 6185 SmallVector<Value *, 4> Allocas; 6186 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6187 6188 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6189 E = Allocas.end(); Object != E; ++Object) { 6190 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6191 6192 // Could not find an Alloca. 6193 if (!LifetimeObject) 6194 continue; 6195 6196 // First check that the Alloca is static, otherwise it won't have a 6197 // valid frame index. 6198 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6199 if (SI == FuncInfo.StaticAllocaMap.end()) 6200 return nullptr; 6201 6202 int FI = SI->second; 6203 6204 SDValue Ops[2]; 6205 Ops[0] = getRoot(); 6206 Ops[1] = 6207 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6208 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6209 6210 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6211 DAG.setRoot(Res); 6212 } 6213 return nullptr; 6214 } 6215 case Intrinsic::invariant_start: 6216 // Discard region information. 6217 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6218 return nullptr; 6219 case Intrinsic::invariant_end: 6220 // Discard region information. 6221 return nullptr; 6222 case Intrinsic::clear_cache: 6223 return TLI.getClearCacheBuiltinName(); 6224 case Intrinsic::donothing: 6225 // ignore 6226 return nullptr; 6227 case Intrinsic::experimental_stackmap: 6228 visitStackmap(I); 6229 return nullptr; 6230 case Intrinsic::experimental_patchpoint_void: 6231 case Intrinsic::experimental_patchpoint_i64: 6232 visitPatchpoint(&I); 6233 return nullptr; 6234 case Intrinsic::experimental_gc_statepoint: 6235 LowerStatepoint(ImmutableStatepoint(&I)); 6236 return nullptr; 6237 case Intrinsic::experimental_gc_result: 6238 visitGCResult(cast<GCResultInst>(I)); 6239 return nullptr; 6240 case Intrinsic::experimental_gc_relocate: 6241 visitGCRelocate(cast<GCRelocateInst>(I)); 6242 return nullptr; 6243 case Intrinsic::instrprof_increment: 6244 llvm_unreachable("instrprof failed to lower an increment"); 6245 case Intrinsic::instrprof_value_profile: 6246 llvm_unreachable("instrprof failed to lower a value profiling call"); 6247 case Intrinsic::localescape: { 6248 MachineFunction &MF = DAG.getMachineFunction(); 6249 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6250 6251 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6252 // is the same on all targets. 6253 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6254 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6255 if (isa<ConstantPointerNull>(Arg)) 6256 continue; // Skip null pointers. They represent a hole in index space. 6257 AllocaInst *Slot = cast<AllocaInst>(Arg); 6258 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6259 "can only escape static allocas"); 6260 int FI = FuncInfo.StaticAllocaMap[Slot]; 6261 MCSymbol *FrameAllocSym = 6262 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6263 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6264 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6265 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6266 .addSym(FrameAllocSym) 6267 .addFrameIndex(FI); 6268 } 6269 6270 return nullptr; 6271 } 6272 6273 case Intrinsic::localrecover: { 6274 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6275 MachineFunction &MF = DAG.getMachineFunction(); 6276 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6277 6278 // Get the symbol that defines the frame offset. 6279 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6280 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6281 unsigned IdxVal = 6282 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6283 MCSymbol *FrameAllocSym = 6284 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6285 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6286 6287 // Create a MCSymbol for the label to avoid any target lowering 6288 // that would make this PC relative. 6289 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6290 SDValue OffsetVal = 6291 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6292 6293 // Add the offset to the FP. 6294 Value *FP = I.getArgOperand(1); 6295 SDValue FPVal = getValue(FP); 6296 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6297 setValue(&I, Add); 6298 6299 return nullptr; 6300 } 6301 6302 case Intrinsic::eh_exceptionpointer: 6303 case Intrinsic::eh_exceptioncode: { 6304 // Get the exception pointer vreg, copy from it, and resize it to fit. 6305 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6306 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6307 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6308 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6309 SDValue N = 6310 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6311 if (Intrinsic == Intrinsic::eh_exceptioncode) 6312 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6313 setValue(&I, N); 6314 return nullptr; 6315 } 6316 case Intrinsic::xray_customevent: { 6317 // Here we want to make sure that the intrinsic behaves as if it has a 6318 // specific calling convention, and only for x86_64. 6319 // FIXME: Support other platforms later. 6320 const auto &Triple = DAG.getTarget().getTargetTriple(); 6321 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6322 return nullptr; 6323 6324 SDLoc DL = getCurSDLoc(); 6325 SmallVector<SDValue, 8> Ops; 6326 6327 // We want to say that we always want the arguments in registers. 6328 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6329 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6331 SDValue Chain = getRoot(); 6332 Ops.push_back(LogEntryVal); 6333 Ops.push_back(StrSizeVal); 6334 Ops.push_back(Chain); 6335 6336 // We need to enforce the calling convention for the callsite, so that 6337 // argument ordering is enforced correctly, and that register allocation can 6338 // see that some registers may be assumed clobbered and have to preserve 6339 // them across calls to the intrinsic. 6340 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6341 DL, NodeTys, Ops); 6342 SDValue patchableNode = SDValue(MN, 0); 6343 DAG.setRoot(patchableNode); 6344 setValue(&I, patchableNode); 6345 return nullptr; 6346 } 6347 case Intrinsic::xray_typedevent: { 6348 // Here we want to make sure that the intrinsic behaves as if it has a 6349 // specific calling convention, and only for x86_64. 6350 // FIXME: Support other platforms later. 6351 const auto &Triple = DAG.getTarget().getTargetTriple(); 6352 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6353 return nullptr; 6354 6355 SDLoc DL = getCurSDLoc(); 6356 SmallVector<SDValue, 8> Ops; 6357 6358 // We want to say that we always want the arguments in registers. 6359 // It's unclear to me how manipulating the selection DAG here forces callers 6360 // to provide arguments in registers instead of on the stack. 6361 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6362 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6363 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6364 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6365 SDValue Chain = getRoot(); 6366 Ops.push_back(LogTypeId); 6367 Ops.push_back(LogEntryVal); 6368 Ops.push_back(StrSizeVal); 6369 Ops.push_back(Chain); 6370 6371 // We need to enforce the calling convention for the callsite, so that 6372 // argument ordering is enforced correctly, and that register allocation can 6373 // see that some registers may be assumed clobbered and have to preserve 6374 // them across calls to the intrinsic. 6375 MachineSDNode *MN = DAG.getMachineNode( 6376 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6377 SDValue patchableNode = SDValue(MN, 0); 6378 DAG.setRoot(patchableNode); 6379 setValue(&I, patchableNode); 6380 return nullptr; 6381 } 6382 case Intrinsic::experimental_deoptimize: 6383 LowerDeoptimizeCall(&I); 6384 return nullptr; 6385 6386 case Intrinsic::experimental_vector_reduce_fadd: 6387 case Intrinsic::experimental_vector_reduce_fmul: 6388 case Intrinsic::experimental_vector_reduce_add: 6389 case Intrinsic::experimental_vector_reduce_mul: 6390 case Intrinsic::experimental_vector_reduce_and: 6391 case Intrinsic::experimental_vector_reduce_or: 6392 case Intrinsic::experimental_vector_reduce_xor: 6393 case Intrinsic::experimental_vector_reduce_smax: 6394 case Intrinsic::experimental_vector_reduce_smin: 6395 case Intrinsic::experimental_vector_reduce_umax: 6396 case Intrinsic::experimental_vector_reduce_umin: 6397 case Intrinsic::experimental_vector_reduce_fmax: 6398 case Intrinsic::experimental_vector_reduce_fmin: 6399 visitVectorReduce(I, Intrinsic); 6400 return nullptr; 6401 6402 case Intrinsic::icall_branch_funnel: { 6403 SmallVector<SDValue, 16> Ops; 6404 Ops.push_back(DAG.getRoot()); 6405 Ops.push_back(getValue(I.getArgOperand(0))); 6406 6407 int64_t Offset; 6408 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6409 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6410 if (!Base) 6411 report_fatal_error( 6412 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6413 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6414 6415 struct BranchFunnelTarget { 6416 int64_t Offset; 6417 SDValue Target; 6418 }; 6419 SmallVector<BranchFunnelTarget, 8> Targets; 6420 6421 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6422 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6423 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6424 if (ElemBase != Base) 6425 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6426 "to the same GlobalValue"); 6427 6428 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6429 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6430 if (!GA) 6431 report_fatal_error( 6432 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6433 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6434 GA->getGlobal(), getCurSDLoc(), 6435 Val.getValueType(), GA->getOffset())}); 6436 } 6437 llvm::sort(Targets, 6438 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6439 return T1.Offset < T2.Offset; 6440 }); 6441 6442 for (auto &T : Targets) { 6443 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6444 Ops.push_back(T.Target); 6445 } 6446 6447 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6448 getCurSDLoc(), MVT::Other, Ops), 6449 0); 6450 DAG.setRoot(N); 6451 setValue(&I, N); 6452 HasTailCall = true; 6453 return nullptr; 6454 } 6455 6456 case Intrinsic::wasm_landingpad_index: 6457 // Information this intrinsic contained has been transferred to 6458 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6459 // delete it now. 6460 return nullptr; 6461 } 6462 } 6463 6464 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6465 const ConstrainedFPIntrinsic &FPI) { 6466 SDLoc sdl = getCurSDLoc(); 6467 unsigned Opcode; 6468 switch (FPI.getIntrinsicID()) { 6469 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6470 case Intrinsic::experimental_constrained_fadd: 6471 Opcode = ISD::STRICT_FADD; 6472 break; 6473 case Intrinsic::experimental_constrained_fsub: 6474 Opcode = ISD::STRICT_FSUB; 6475 break; 6476 case Intrinsic::experimental_constrained_fmul: 6477 Opcode = ISD::STRICT_FMUL; 6478 break; 6479 case Intrinsic::experimental_constrained_fdiv: 6480 Opcode = ISD::STRICT_FDIV; 6481 break; 6482 case Intrinsic::experimental_constrained_frem: 6483 Opcode = ISD::STRICT_FREM; 6484 break; 6485 case Intrinsic::experimental_constrained_fma: 6486 Opcode = ISD::STRICT_FMA; 6487 break; 6488 case Intrinsic::experimental_constrained_sqrt: 6489 Opcode = ISD::STRICT_FSQRT; 6490 break; 6491 case Intrinsic::experimental_constrained_pow: 6492 Opcode = ISD::STRICT_FPOW; 6493 break; 6494 case Intrinsic::experimental_constrained_powi: 6495 Opcode = ISD::STRICT_FPOWI; 6496 break; 6497 case Intrinsic::experimental_constrained_sin: 6498 Opcode = ISD::STRICT_FSIN; 6499 break; 6500 case Intrinsic::experimental_constrained_cos: 6501 Opcode = ISD::STRICT_FCOS; 6502 break; 6503 case Intrinsic::experimental_constrained_exp: 6504 Opcode = ISD::STRICT_FEXP; 6505 break; 6506 case Intrinsic::experimental_constrained_exp2: 6507 Opcode = ISD::STRICT_FEXP2; 6508 break; 6509 case Intrinsic::experimental_constrained_log: 6510 Opcode = ISD::STRICT_FLOG; 6511 break; 6512 case Intrinsic::experimental_constrained_log10: 6513 Opcode = ISD::STRICT_FLOG10; 6514 break; 6515 case Intrinsic::experimental_constrained_log2: 6516 Opcode = ISD::STRICT_FLOG2; 6517 break; 6518 case Intrinsic::experimental_constrained_rint: 6519 Opcode = ISD::STRICT_FRINT; 6520 break; 6521 case Intrinsic::experimental_constrained_nearbyint: 6522 Opcode = ISD::STRICT_FNEARBYINT; 6523 break; 6524 case Intrinsic::experimental_constrained_maxnum: 6525 Opcode = ISD::STRICT_FMAXNUM; 6526 break; 6527 case Intrinsic::experimental_constrained_minnum: 6528 Opcode = ISD::STRICT_FMINNUM; 6529 break; 6530 case Intrinsic::experimental_constrained_ceil: 6531 Opcode = ISD::STRICT_FCEIL; 6532 break; 6533 case Intrinsic::experimental_constrained_floor: 6534 Opcode = ISD::STRICT_FFLOOR; 6535 break; 6536 case Intrinsic::experimental_constrained_round: 6537 Opcode = ISD::STRICT_FROUND; 6538 break; 6539 case Intrinsic::experimental_constrained_trunc: 6540 Opcode = ISD::STRICT_FTRUNC; 6541 break; 6542 } 6543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6544 SDValue Chain = getRoot(); 6545 SmallVector<EVT, 4> ValueVTs; 6546 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6547 ValueVTs.push_back(MVT::Other); // Out chain 6548 6549 SDVTList VTs = DAG.getVTList(ValueVTs); 6550 SDValue Result; 6551 if (FPI.isUnaryOp()) 6552 Result = DAG.getNode(Opcode, sdl, VTs, 6553 { Chain, getValue(FPI.getArgOperand(0)) }); 6554 else if (FPI.isTernaryOp()) 6555 Result = DAG.getNode(Opcode, sdl, VTs, 6556 { Chain, getValue(FPI.getArgOperand(0)), 6557 getValue(FPI.getArgOperand(1)), 6558 getValue(FPI.getArgOperand(2)) }); 6559 else 6560 Result = DAG.getNode(Opcode, sdl, VTs, 6561 { Chain, getValue(FPI.getArgOperand(0)), 6562 getValue(FPI.getArgOperand(1)) }); 6563 6564 assert(Result.getNode()->getNumValues() == 2); 6565 SDValue OutChain = Result.getValue(1); 6566 DAG.setRoot(OutChain); 6567 SDValue FPResult = Result.getValue(0); 6568 setValue(&FPI, FPResult); 6569 } 6570 6571 std::pair<SDValue, SDValue> 6572 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6573 const BasicBlock *EHPadBB) { 6574 MachineFunction &MF = DAG.getMachineFunction(); 6575 MachineModuleInfo &MMI = MF.getMMI(); 6576 MCSymbol *BeginLabel = nullptr; 6577 6578 if (EHPadBB) { 6579 // Insert a label before the invoke call to mark the try range. This can be 6580 // used to detect deletion of the invoke via the MachineModuleInfo. 6581 BeginLabel = MMI.getContext().createTempSymbol(); 6582 6583 // For SjLj, keep track of which landing pads go with which invokes 6584 // so as to maintain the ordering of pads in the LSDA. 6585 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6586 if (CallSiteIndex) { 6587 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6588 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6589 6590 // Now that the call site is handled, stop tracking it. 6591 MMI.setCurrentCallSite(0); 6592 } 6593 6594 // Both PendingLoads and PendingExports must be flushed here; 6595 // this call might not return. 6596 (void)getRoot(); 6597 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6598 6599 CLI.setChain(getRoot()); 6600 } 6601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6602 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6603 6604 assert((CLI.IsTailCall || Result.second.getNode()) && 6605 "Non-null chain expected with non-tail call!"); 6606 assert((Result.second.getNode() || !Result.first.getNode()) && 6607 "Null value expected with tail call!"); 6608 6609 if (!Result.second.getNode()) { 6610 // As a special case, a null chain means that a tail call has been emitted 6611 // and the DAG root is already updated. 6612 HasTailCall = true; 6613 6614 // Since there's no actual continuation from this block, nothing can be 6615 // relying on us setting vregs for them. 6616 PendingExports.clear(); 6617 } else { 6618 DAG.setRoot(Result.second); 6619 } 6620 6621 if (EHPadBB) { 6622 // Insert a label at the end of the invoke call to mark the try range. This 6623 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6624 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6625 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6626 6627 // Inform MachineModuleInfo of range. 6628 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6629 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6630 // actually use outlined funclets and their LSDA info style. 6631 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6632 assert(CLI.CS); 6633 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6634 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6635 BeginLabel, EndLabel); 6636 } else if (!isScopedEHPersonality(Pers)) { 6637 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6638 } 6639 } 6640 6641 return Result; 6642 } 6643 6644 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6645 bool isTailCall, 6646 const BasicBlock *EHPadBB) { 6647 auto &DL = DAG.getDataLayout(); 6648 FunctionType *FTy = CS.getFunctionType(); 6649 Type *RetTy = CS.getType(); 6650 6651 TargetLowering::ArgListTy Args; 6652 Args.reserve(CS.arg_size()); 6653 6654 const Value *SwiftErrorVal = nullptr; 6655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6656 6657 // We can't tail call inside a function with a swifterror argument. Lowering 6658 // does not support this yet. It would have to move into the swifterror 6659 // register before the call. 6660 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6661 if (TLI.supportSwiftError() && 6662 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6663 isTailCall = false; 6664 6665 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6666 i != e; ++i) { 6667 TargetLowering::ArgListEntry Entry; 6668 const Value *V = *i; 6669 6670 // Skip empty types 6671 if (V->getType()->isEmptyTy()) 6672 continue; 6673 6674 SDValue ArgNode = getValue(V); 6675 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6676 6677 Entry.setAttributes(&CS, i - CS.arg_begin()); 6678 6679 // Use swifterror virtual register as input to the call. 6680 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6681 SwiftErrorVal = V; 6682 // We find the virtual register for the actual swifterror argument. 6683 // Instead of using the Value, we use the virtual register instead. 6684 Entry.Node = DAG.getRegister(FuncInfo 6685 .getOrCreateSwiftErrorVRegUseAt( 6686 CS.getInstruction(), FuncInfo.MBB, V) 6687 .first, 6688 EVT(TLI.getPointerTy(DL))); 6689 } 6690 6691 Args.push_back(Entry); 6692 6693 // If we have an explicit sret argument that is an Instruction, (i.e., it 6694 // might point to function-local memory), we can't meaningfully tail-call. 6695 if (Entry.IsSRet && isa<Instruction>(V)) 6696 isTailCall = false; 6697 } 6698 6699 // Check if target-independent constraints permit a tail call here. 6700 // Target-dependent constraints are checked within TLI->LowerCallTo. 6701 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6702 isTailCall = false; 6703 6704 // Disable tail calls if there is an swifterror argument. Targets have not 6705 // been updated to support tail calls. 6706 if (TLI.supportSwiftError() && SwiftErrorVal) 6707 isTailCall = false; 6708 6709 TargetLowering::CallLoweringInfo CLI(DAG); 6710 CLI.setDebugLoc(getCurSDLoc()) 6711 .setChain(getRoot()) 6712 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6713 .setTailCall(isTailCall) 6714 .setConvergent(CS.isConvergent()); 6715 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6716 6717 if (Result.first.getNode()) { 6718 const Instruction *Inst = CS.getInstruction(); 6719 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6720 setValue(Inst, Result.first); 6721 } 6722 6723 // The last element of CLI.InVals has the SDValue for swifterror return. 6724 // Here we copy it to a virtual register and update SwiftErrorMap for 6725 // book-keeping. 6726 if (SwiftErrorVal && TLI.supportSwiftError()) { 6727 // Get the last element of InVals. 6728 SDValue Src = CLI.InVals.back(); 6729 unsigned VReg; bool CreatedVReg; 6730 std::tie(VReg, CreatedVReg) = 6731 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6732 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6733 // We update the virtual register for the actual swifterror argument. 6734 if (CreatedVReg) 6735 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6736 DAG.setRoot(CopyNode); 6737 } 6738 } 6739 6740 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6741 SelectionDAGBuilder &Builder) { 6742 // Check to see if this load can be trivially constant folded, e.g. if the 6743 // input is from a string literal. 6744 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6745 // Cast pointer to the type we really want to load. 6746 Type *LoadTy = 6747 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6748 if (LoadVT.isVector()) 6749 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6750 6751 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6752 PointerType::getUnqual(LoadTy)); 6753 6754 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6755 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6756 return Builder.getValue(LoadCst); 6757 } 6758 6759 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6760 // still constant memory, the input chain can be the entry node. 6761 SDValue Root; 6762 bool ConstantMemory = false; 6763 6764 // Do not serialize (non-volatile) loads of constant memory with anything. 6765 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6766 Root = Builder.DAG.getEntryNode(); 6767 ConstantMemory = true; 6768 } else { 6769 // Do not serialize non-volatile loads against each other. 6770 Root = Builder.DAG.getRoot(); 6771 } 6772 6773 SDValue Ptr = Builder.getValue(PtrVal); 6774 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6775 Ptr, MachinePointerInfo(PtrVal), 6776 /* Alignment = */ 1); 6777 6778 if (!ConstantMemory) 6779 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6780 return LoadVal; 6781 } 6782 6783 /// Record the value for an instruction that produces an integer result, 6784 /// converting the type where necessary. 6785 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6786 SDValue Value, 6787 bool IsSigned) { 6788 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6789 I.getType(), true); 6790 if (IsSigned) 6791 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6792 else 6793 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6794 setValue(&I, Value); 6795 } 6796 6797 /// See if we can lower a memcmp call into an optimized form. If so, return 6798 /// true and lower it. Otherwise return false, and it will be lowered like a 6799 /// normal call. 6800 /// The caller already checked that \p I calls the appropriate LibFunc with a 6801 /// correct prototype. 6802 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6803 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6804 const Value *Size = I.getArgOperand(2); 6805 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6806 if (CSize && CSize->getZExtValue() == 0) { 6807 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6808 I.getType(), true); 6809 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6810 return true; 6811 } 6812 6813 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6814 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6815 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6816 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6817 if (Res.first.getNode()) { 6818 processIntegerCallValue(I, Res.first, true); 6819 PendingLoads.push_back(Res.second); 6820 return true; 6821 } 6822 6823 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6824 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6825 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6826 return false; 6827 6828 // If the target has a fast compare for the given size, it will return a 6829 // preferred load type for that size. Require that the load VT is legal and 6830 // that the target supports unaligned loads of that type. Otherwise, return 6831 // INVALID. 6832 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6833 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6834 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6835 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6836 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6837 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6838 // TODO: Check alignment of src and dest ptrs. 6839 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6840 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6841 if (!TLI.isTypeLegal(LVT) || 6842 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6843 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6844 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6845 } 6846 6847 return LVT; 6848 }; 6849 6850 // This turns into unaligned loads. We only do this if the target natively 6851 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6852 // we'll only produce a small number of byte loads. 6853 MVT LoadVT; 6854 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6855 switch (NumBitsToCompare) { 6856 default: 6857 return false; 6858 case 16: 6859 LoadVT = MVT::i16; 6860 break; 6861 case 32: 6862 LoadVT = MVT::i32; 6863 break; 6864 case 64: 6865 case 128: 6866 case 256: 6867 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6868 break; 6869 } 6870 6871 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6872 return false; 6873 6874 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6875 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6876 6877 // Bitcast to a wide integer type if the loads are vectors. 6878 if (LoadVT.isVector()) { 6879 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6880 LoadL = DAG.getBitcast(CmpVT, LoadL); 6881 LoadR = DAG.getBitcast(CmpVT, LoadR); 6882 } 6883 6884 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6885 processIntegerCallValue(I, Cmp, false); 6886 return true; 6887 } 6888 6889 /// See if we can lower a memchr call into an optimized form. If so, return 6890 /// true and lower it. Otherwise return false, and it will be lowered like a 6891 /// normal call. 6892 /// The caller already checked that \p I calls the appropriate LibFunc with a 6893 /// correct prototype. 6894 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6895 const Value *Src = I.getArgOperand(0); 6896 const Value *Char = I.getArgOperand(1); 6897 const Value *Length = I.getArgOperand(2); 6898 6899 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6900 std::pair<SDValue, SDValue> Res = 6901 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6902 getValue(Src), getValue(Char), getValue(Length), 6903 MachinePointerInfo(Src)); 6904 if (Res.first.getNode()) { 6905 setValue(&I, Res.first); 6906 PendingLoads.push_back(Res.second); 6907 return true; 6908 } 6909 6910 return false; 6911 } 6912 6913 /// See if we can lower a mempcpy call into an optimized form. If so, return 6914 /// true and lower it. Otherwise return false, and it will be lowered like a 6915 /// normal call. 6916 /// The caller already checked that \p I calls the appropriate LibFunc with a 6917 /// correct prototype. 6918 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6919 SDValue Dst = getValue(I.getArgOperand(0)); 6920 SDValue Src = getValue(I.getArgOperand(1)); 6921 SDValue Size = getValue(I.getArgOperand(2)); 6922 6923 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6924 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6925 unsigned Align = std::min(DstAlign, SrcAlign); 6926 if (Align == 0) // Alignment of one or both could not be inferred. 6927 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6928 6929 bool isVol = false; 6930 SDLoc sdl = getCurSDLoc(); 6931 6932 // In the mempcpy context we need to pass in a false value for isTailCall 6933 // because the return pointer needs to be adjusted by the size of 6934 // the copied memory. 6935 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6936 false, /*isTailCall=*/false, 6937 MachinePointerInfo(I.getArgOperand(0)), 6938 MachinePointerInfo(I.getArgOperand(1))); 6939 assert(MC.getNode() != nullptr && 6940 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6941 DAG.setRoot(MC); 6942 6943 // Check if Size needs to be truncated or extended. 6944 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6945 6946 // Adjust return pointer to point just past the last dst byte. 6947 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6948 Dst, Size); 6949 setValue(&I, DstPlusSize); 6950 return true; 6951 } 6952 6953 /// See if we can lower a strcpy call into an optimized form. If so, return 6954 /// true and lower it, otherwise return false and it will be lowered like a 6955 /// normal call. 6956 /// The caller already checked that \p I calls the appropriate LibFunc with a 6957 /// correct prototype. 6958 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6959 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6960 6961 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6962 std::pair<SDValue, SDValue> Res = 6963 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6964 getValue(Arg0), getValue(Arg1), 6965 MachinePointerInfo(Arg0), 6966 MachinePointerInfo(Arg1), isStpcpy); 6967 if (Res.first.getNode()) { 6968 setValue(&I, Res.first); 6969 DAG.setRoot(Res.second); 6970 return true; 6971 } 6972 6973 return false; 6974 } 6975 6976 /// See if we can lower a strcmp call into an optimized form. If so, return 6977 /// true and lower it, otherwise return false and it will be lowered like a 6978 /// normal call. 6979 /// The caller already checked that \p I calls the appropriate LibFunc with a 6980 /// correct prototype. 6981 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6982 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6983 6984 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6985 std::pair<SDValue, SDValue> Res = 6986 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6987 getValue(Arg0), getValue(Arg1), 6988 MachinePointerInfo(Arg0), 6989 MachinePointerInfo(Arg1)); 6990 if (Res.first.getNode()) { 6991 processIntegerCallValue(I, Res.first, true); 6992 PendingLoads.push_back(Res.second); 6993 return true; 6994 } 6995 6996 return false; 6997 } 6998 6999 /// See if we can lower a strlen call into an optimized form. If so, return 7000 /// true and lower it, otherwise return false and it will be lowered like a 7001 /// normal call. 7002 /// The caller already checked that \p I calls the appropriate LibFunc with a 7003 /// correct prototype. 7004 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7005 const Value *Arg0 = I.getArgOperand(0); 7006 7007 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7008 std::pair<SDValue, SDValue> Res = 7009 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7010 getValue(Arg0), MachinePointerInfo(Arg0)); 7011 if (Res.first.getNode()) { 7012 processIntegerCallValue(I, Res.first, false); 7013 PendingLoads.push_back(Res.second); 7014 return true; 7015 } 7016 7017 return false; 7018 } 7019 7020 /// See if we can lower a strnlen call into an optimized form. If so, return 7021 /// true and lower it, otherwise return false and it will be lowered like a 7022 /// normal call. 7023 /// The caller already checked that \p I calls the appropriate LibFunc with a 7024 /// correct prototype. 7025 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7026 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7027 7028 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7029 std::pair<SDValue, SDValue> Res = 7030 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7031 getValue(Arg0), getValue(Arg1), 7032 MachinePointerInfo(Arg0)); 7033 if (Res.first.getNode()) { 7034 processIntegerCallValue(I, Res.first, false); 7035 PendingLoads.push_back(Res.second); 7036 return true; 7037 } 7038 7039 return false; 7040 } 7041 7042 /// See if we can lower a unary floating-point operation into an SDNode with 7043 /// the specified Opcode. If so, return true and lower it, otherwise return 7044 /// false and it will be lowered like a normal call. 7045 /// The caller already checked that \p I calls the appropriate LibFunc with a 7046 /// correct prototype. 7047 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7048 unsigned Opcode) { 7049 // We already checked this call's prototype; verify it doesn't modify errno. 7050 if (!I.onlyReadsMemory()) 7051 return false; 7052 7053 SDValue Tmp = getValue(I.getArgOperand(0)); 7054 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7055 return true; 7056 } 7057 7058 /// See if we can lower a binary floating-point operation into an SDNode with 7059 /// the specified Opcode. If so, return true and lower it. Otherwise return 7060 /// false, and it will be lowered like a normal call. 7061 /// The caller already checked that \p I calls the appropriate LibFunc with a 7062 /// correct prototype. 7063 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7064 unsigned Opcode) { 7065 // We already checked this call's prototype; verify it doesn't modify errno. 7066 if (!I.onlyReadsMemory()) 7067 return false; 7068 7069 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7070 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7071 EVT VT = Tmp0.getValueType(); 7072 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7073 return true; 7074 } 7075 7076 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7077 // Handle inline assembly differently. 7078 if (isa<InlineAsm>(I.getCalledValue())) { 7079 visitInlineAsm(&I); 7080 return; 7081 } 7082 7083 const char *RenameFn = nullptr; 7084 if (Function *F = I.getCalledFunction()) { 7085 if (F->isDeclaration()) { 7086 // Is this an LLVM intrinsic or a target-specific intrinsic? 7087 unsigned IID = F->getIntrinsicID(); 7088 if (!IID) 7089 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7090 IID = II->getIntrinsicID(F); 7091 7092 if (IID) { 7093 RenameFn = visitIntrinsicCall(I, IID); 7094 if (!RenameFn) 7095 return; 7096 } 7097 } 7098 7099 // Check for well-known libc/libm calls. If the function is internal, it 7100 // can't be a library call. Don't do the check if marked as nobuiltin for 7101 // some reason or the call site requires strict floating point semantics. 7102 LibFunc Func; 7103 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7104 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7105 LibInfo->hasOptimizedCodeGen(Func)) { 7106 switch (Func) { 7107 default: break; 7108 case LibFunc_copysign: 7109 case LibFunc_copysignf: 7110 case LibFunc_copysignl: 7111 // We already checked this call's prototype; verify it doesn't modify 7112 // errno. 7113 if (I.onlyReadsMemory()) { 7114 SDValue LHS = getValue(I.getArgOperand(0)); 7115 SDValue RHS = getValue(I.getArgOperand(1)); 7116 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7117 LHS.getValueType(), LHS, RHS)); 7118 return; 7119 } 7120 break; 7121 case LibFunc_fabs: 7122 case LibFunc_fabsf: 7123 case LibFunc_fabsl: 7124 if (visitUnaryFloatCall(I, ISD::FABS)) 7125 return; 7126 break; 7127 case LibFunc_fmin: 7128 case LibFunc_fminf: 7129 case LibFunc_fminl: 7130 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7131 return; 7132 break; 7133 case LibFunc_fmax: 7134 case LibFunc_fmaxf: 7135 case LibFunc_fmaxl: 7136 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7137 return; 7138 break; 7139 case LibFunc_sin: 7140 case LibFunc_sinf: 7141 case LibFunc_sinl: 7142 if (visitUnaryFloatCall(I, ISD::FSIN)) 7143 return; 7144 break; 7145 case LibFunc_cos: 7146 case LibFunc_cosf: 7147 case LibFunc_cosl: 7148 if (visitUnaryFloatCall(I, ISD::FCOS)) 7149 return; 7150 break; 7151 case LibFunc_sqrt: 7152 case LibFunc_sqrtf: 7153 case LibFunc_sqrtl: 7154 case LibFunc_sqrt_finite: 7155 case LibFunc_sqrtf_finite: 7156 case LibFunc_sqrtl_finite: 7157 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7158 return; 7159 break; 7160 case LibFunc_floor: 7161 case LibFunc_floorf: 7162 case LibFunc_floorl: 7163 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7164 return; 7165 break; 7166 case LibFunc_nearbyint: 7167 case LibFunc_nearbyintf: 7168 case LibFunc_nearbyintl: 7169 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7170 return; 7171 break; 7172 case LibFunc_ceil: 7173 case LibFunc_ceilf: 7174 case LibFunc_ceill: 7175 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7176 return; 7177 break; 7178 case LibFunc_rint: 7179 case LibFunc_rintf: 7180 case LibFunc_rintl: 7181 if (visitUnaryFloatCall(I, ISD::FRINT)) 7182 return; 7183 break; 7184 case LibFunc_round: 7185 case LibFunc_roundf: 7186 case LibFunc_roundl: 7187 if (visitUnaryFloatCall(I, ISD::FROUND)) 7188 return; 7189 break; 7190 case LibFunc_trunc: 7191 case LibFunc_truncf: 7192 case LibFunc_truncl: 7193 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7194 return; 7195 break; 7196 case LibFunc_log2: 7197 case LibFunc_log2f: 7198 case LibFunc_log2l: 7199 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7200 return; 7201 break; 7202 case LibFunc_exp2: 7203 case LibFunc_exp2f: 7204 case LibFunc_exp2l: 7205 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7206 return; 7207 break; 7208 case LibFunc_memcmp: 7209 if (visitMemCmpCall(I)) 7210 return; 7211 break; 7212 case LibFunc_mempcpy: 7213 if (visitMemPCpyCall(I)) 7214 return; 7215 break; 7216 case LibFunc_memchr: 7217 if (visitMemChrCall(I)) 7218 return; 7219 break; 7220 case LibFunc_strcpy: 7221 if (visitStrCpyCall(I, false)) 7222 return; 7223 break; 7224 case LibFunc_stpcpy: 7225 if (visitStrCpyCall(I, true)) 7226 return; 7227 break; 7228 case LibFunc_strcmp: 7229 if (visitStrCmpCall(I)) 7230 return; 7231 break; 7232 case LibFunc_strlen: 7233 if (visitStrLenCall(I)) 7234 return; 7235 break; 7236 case LibFunc_strnlen: 7237 if (visitStrNLenCall(I)) 7238 return; 7239 break; 7240 } 7241 } 7242 } 7243 7244 SDValue Callee; 7245 if (!RenameFn) 7246 Callee = getValue(I.getCalledValue()); 7247 else 7248 Callee = DAG.getExternalSymbol( 7249 RenameFn, 7250 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7251 7252 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7253 // have to do anything here to lower funclet bundles. 7254 assert(!I.hasOperandBundlesOtherThan( 7255 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7256 "Cannot lower calls with arbitrary operand bundles!"); 7257 7258 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7259 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7260 else 7261 // Check if we can potentially perform a tail call. More detailed checking 7262 // is be done within LowerCallTo, after more information about the call is 7263 // known. 7264 LowerCallTo(&I, Callee, I.isTailCall()); 7265 } 7266 7267 namespace { 7268 7269 /// AsmOperandInfo - This contains information for each constraint that we are 7270 /// lowering. 7271 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7272 public: 7273 /// CallOperand - If this is the result output operand or a clobber 7274 /// this is null, otherwise it is the incoming operand to the CallInst. 7275 /// This gets modified as the asm is processed. 7276 SDValue CallOperand; 7277 7278 /// AssignedRegs - If this is a register or register class operand, this 7279 /// contains the set of register corresponding to the operand. 7280 RegsForValue AssignedRegs; 7281 7282 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7283 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7284 } 7285 7286 /// Whether or not this operand accesses memory 7287 bool hasMemory(const TargetLowering &TLI) const { 7288 // Indirect operand accesses access memory. 7289 if (isIndirect) 7290 return true; 7291 7292 for (const auto &Code : Codes) 7293 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7294 return true; 7295 7296 return false; 7297 } 7298 7299 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7300 /// corresponds to. If there is no Value* for this operand, it returns 7301 /// MVT::Other. 7302 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7303 const DataLayout &DL) const { 7304 if (!CallOperandVal) return MVT::Other; 7305 7306 if (isa<BasicBlock>(CallOperandVal)) 7307 return TLI.getPointerTy(DL); 7308 7309 llvm::Type *OpTy = CallOperandVal->getType(); 7310 7311 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7312 // If this is an indirect operand, the operand is a pointer to the 7313 // accessed type. 7314 if (isIndirect) { 7315 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7316 if (!PtrTy) 7317 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7318 OpTy = PtrTy->getElementType(); 7319 } 7320 7321 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7322 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7323 if (STy->getNumElements() == 1) 7324 OpTy = STy->getElementType(0); 7325 7326 // If OpTy is not a single value, it may be a struct/union that we 7327 // can tile with integers. 7328 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7329 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7330 switch (BitSize) { 7331 default: break; 7332 case 1: 7333 case 8: 7334 case 16: 7335 case 32: 7336 case 64: 7337 case 128: 7338 OpTy = IntegerType::get(Context, BitSize); 7339 break; 7340 } 7341 } 7342 7343 return TLI.getValueType(DL, OpTy, true); 7344 } 7345 }; 7346 7347 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7348 7349 } // end anonymous namespace 7350 7351 /// Make sure that the output operand \p OpInfo and its corresponding input 7352 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7353 /// out). 7354 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7355 SDISelAsmOperandInfo &MatchingOpInfo, 7356 SelectionDAG &DAG) { 7357 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7358 return; 7359 7360 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7361 const auto &TLI = DAG.getTargetLoweringInfo(); 7362 7363 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7364 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7365 OpInfo.ConstraintVT); 7366 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7367 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7368 MatchingOpInfo.ConstraintVT); 7369 if ((OpInfo.ConstraintVT.isInteger() != 7370 MatchingOpInfo.ConstraintVT.isInteger()) || 7371 (MatchRC.second != InputRC.second)) { 7372 // FIXME: error out in a more elegant fashion 7373 report_fatal_error("Unsupported asm: input constraint" 7374 " with a matching output constraint of" 7375 " incompatible type!"); 7376 } 7377 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7378 } 7379 7380 /// Get a direct memory input to behave well as an indirect operand. 7381 /// This may introduce stores, hence the need for a \p Chain. 7382 /// \return The (possibly updated) chain. 7383 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7384 SDISelAsmOperandInfo &OpInfo, 7385 SelectionDAG &DAG) { 7386 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7387 7388 // If we don't have an indirect input, put it in the constpool if we can, 7389 // otherwise spill it to a stack slot. 7390 // TODO: This isn't quite right. We need to handle these according to 7391 // the addressing mode that the constraint wants. Also, this may take 7392 // an additional register for the computation and we don't want that 7393 // either. 7394 7395 // If the operand is a float, integer, or vector constant, spill to a 7396 // constant pool entry to get its address. 7397 const Value *OpVal = OpInfo.CallOperandVal; 7398 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7399 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7400 OpInfo.CallOperand = DAG.getConstantPool( 7401 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7402 return Chain; 7403 } 7404 7405 // Otherwise, create a stack slot and emit a store to it before the asm. 7406 Type *Ty = OpVal->getType(); 7407 auto &DL = DAG.getDataLayout(); 7408 uint64_t TySize = DL.getTypeAllocSize(Ty); 7409 unsigned Align = DL.getPrefTypeAlignment(Ty); 7410 MachineFunction &MF = DAG.getMachineFunction(); 7411 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7412 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7413 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7414 MachinePointerInfo::getFixedStack(MF, SSFI)); 7415 OpInfo.CallOperand = StackSlot; 7416 7417 return Chain; 7418 } 7419 7420 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7421 /// specified operand. We prefer to assign virtual registers, to allow the 7422 /// register allocator to handle the assignment process. However, if the asm 7423 /// uses features that we can't model on machineinstrs, we have SDISel do the 7424 /// allocation. This produces generally horrible, but correct, code. 7425 /// 7426 /// OpInfo describes the operand 7427 /// RefOpInfo describes the matching operand if any, the operand otherwise 7428 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7429 SDISelAsmOperandInfo &OpInfo, 7430 SDISelAsmOperandInfo &RefOpInfo) { 7431 LLVMContext &Context = *DAG.getContext(); 7432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7433 7434 MachineFunction &MF = DAG.getMachineFunction(); 7435 SmallVector<unsigned, 4> Regs; 7436 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7437 7438 // No work to do for memory operations. 7439 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7440 return; 7441 7442 // If this is a constraint for a single physreg, or a constraint for a 7443 // register class, find it. 7444 unsigned AssignedReg; 7445 const TargetRegisterClass *RC; 7446 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7447 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7448 // RC is unset only on failure. Return immediately. 7449 if (!RC) 7450 return; 7451 7452 // Get the actual register value type. This is important, because the user 7453 // may have asked for (e.g.) the AX register in i32 type. We need to 7454 // remember that AX is actually i16 to get the right extension. 7455 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7456 7457 if (OpInfo.ConstraintVT != MVT::Other) { 7458 // If this is an FP operand in an integer register (or visa versa), or more 7459 // generally if the operand value disagrees with the register class we plan 7460 // to stick it in, fix the operand type. 7461 // 7462 // If this is an input value, the bitcast to the new type is done now. 7463 // Bitcast for output value is done at the end of visitInlineAsm(). 7464 if ((OpInfo.Type == InlineAsm::isOutput || 7465 OpInfo.Type == InlineAsm::isInput) && 7466 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7467 // Try to convert to the first EVT that the reg class contains. If the 7468 // types are identical size, use a bitcast to convert (e.g. two differing 7469 // vector types). Note: output bitcast is done at the end of 7470 // visitInlineAsm(). 7471 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7472 // Exclude indirect inputs while they are unsupported because the code 7473 // to perform the load is missing and thus OpInfo.CallOperand still 7474 // refers to the input address rather than the pointed-to value. 7475 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7476 OpInfo.CallOperand = 7477 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7478 OpInfo.ConstraintVT = RegVT; 7479 // If the operand is an FP value and we want it in integer registers, 7480 // use the corresponding integer type. This turns an f64 value into 7481 // i64, which can be passed with two i32 values on a 32-bit machine. 7482 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7483 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7484 if (OpInfo.Type == InlineAsm::isInput) 7485 OpInfo.CallOperand = 7486 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7487 OpInfo.ConstraintVT = VT; 7488 } 7489 } 7490 } 7491 7492 // No need to allocate a matching input constraint since the constraint it's 7493 // matching to has already been allocated. 7494 if (OpInfo.isMatchingInputConstraint()) 7495 return; 7496 7497 EVT ValueVT = OpInfo.ConstraintVT; 7498 if (OpInfo.ConstraintVT == MVT::Other) 7499 ValueVT = RegVT; 7500 7501 // Initialize NumRegs. 7502 unsigned NumRegs = 1; 7503 if (OpInfo.ConstraintVT != MVT::Other) 7504 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7505 7506 // If this is a constraint for a specific physical register, like {r17}, 7507 // assign it now. 7508 7509 // If this associated to a specific register, initialize iterator to correct 7510 // place. If virtual, make sure we have enough registers 7511 7512 // Initialize iterator if necessary 7513 TargetRegisterClass::iterator I = RC->begin(); 7514 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7515 7516 // Do not check for single registers. 7517 if (AssignedReg) { 7518 for (; *I != AssignedReg; ++I) 7519 assert(I != RC->end() && "AssignedReg should be member of RC"); 7520 } 7521 7522 for (; NumRegs; --NumRegs, ++I) { 7523 assert(I != RC->end() && "Ran out of registers to allocate!"); 7524 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7525 Regs.push_back(R); 7526 } 7527 7528 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7529 } 7530 7531 static unsigned 7532 findMatchingInlineAsmOperand(unsigned OperandNo, 7533 const std::vector<SDValue> &AsmNodeOperands) { 7534 // Scan until we find the definition we already emitted of this operand. 7535 unsigned CurOp = InlineAsm::Op_FirstOperand; 7536 for (; OperandNo; --OperandNo) { 7537 // Advance to the next operand. 7538 unsigned OpFlag = 7539 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7540 assert((InlineAsm::isRegDefKind(OpFlag) || 7541 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7542 InlineAsm::isMemKind(OpFlag)) && 7543 "Skipped past definitions?"); 7544 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7545 } 7546 return CurOp; 7547 } 7548 7549 namespace { 7550 7551 class ExtraFlags { 7552 unsigned Flags = 0; 7553 7554 public: 7555 explicit ExtraFlags(ImmutableCallSite CS) { 7556 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7557 if (IA->hasSideEffects()) 7558 Flags |= InlineAsm::Extra_HasSideEffects; 7559 if (IA->isAlignStack()) 7560 Flags |= InlineAsm::Extra_IsAlignStack; 7561 if (CS.isConvergent()) 7562 Flags |= InlineAsm::Extra_IsConvergent; 7563 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7564 } 7565 7566 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7567 // Ideally, we would only check against memory constraints. However, the 7568 // meaning of an Other constraint can be target-specific and we can't easily 7569 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7570 // for Other constraints as well. 7571 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7572 OpInfo.ConstraintType == TargetLowering::C_Other) { 7573 if (OpInfo.Type == InlineAsm::isInput) 7574 Flags |= InlineAsm::Extra_MayLoad; 7575 else if (OpInfo.Type == InlineAsm::isOutput) 7576 Flags |= InlineAsm::Extra_MayStore; 7577 else if (OpInfo.Type == InlineAsm::isClobber) 7578 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7579 } 7580 } 7581 7582 unsigned get() const { return Flags; } 7583 }; 7584 7585 } // end anonymous namespace 7586 7587 /// visitInlineAsm - Handle a call to an InlineAsm object. 7588 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7589 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7590 7591 /// ConstraintOperands - Information about all of the constraints. 7592 SDISelAsmOperandInfoVector ConstraintOperands; 7593 7594 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7595 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7596 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7597 7598 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7599 // AsmDialect, MayLoad, MayStore). 7600 bool HasSideEffect = IA->hasSideEffects(); 7601 ExtraFlags ExtraInfo(CS); 7602 7603 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7604 unsigned ResNo = 0; // ResNo - The result number of the next output. 7605 for (auto &T : TargetConstraints) { 7606 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7607 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7608 7609 // Compute the value type for each operand. 7610 if (OpInfo.Type == InlineAsm::isInput || 7611 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7612 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7613 7614 // Process the call argument. BasicBlocks are labels, currently appearing 7615 // only in asm's. 7616 const Instruction *I = CS.getInstruction(); 7617 if (isa<CallBrInst>(I) && 7618 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7619 cast<CallBrInst>(I)->getNumIndirectDests())) { 7620 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7621 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7622 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7623 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7624 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7625 } else { 7626 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7627 } 7628 7629 OpInfo.ConstraintVT = 7630 OpInfo 7631 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7632 .getSimpleVT(); 7633 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7634 // The return value of the call is this value. As such, there is no 7635 // corresponding argument. 7636 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7637 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7638 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7639 DAG.getDataLayout(), STy->getElementType(ResNo)); 7640 } else { 7641 assert(ResNo == 0 && "Asm only has one result!"); 7642 OpInfo.ConstraintVT = 7643 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7644 } 7645 ++ResNo; 7646 } else { 7647 OpInfo.ConstraintVT = MVT::Other; 7648 } 7649 7650 if (!HasSideEffect) 7651 HasSideEffect = OpInfo.hasMemory(TLI); 7652 7653 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7654 // FIXME: Could we compute this on OpInfo rather than T? 7655 7656 // Compute the constraint code and ConstraintType to use. 7657 TLI.ComputeConstraintToUse(T, SDValue()); 7658 7659 ExtraInfo.update(T); 7660 } 7661 7662 // We won't need to flush pending loads if this asm doesn't touch 7663 // memory and is nonvolatile. 7664 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7665 7666 // Second pass over the constraints: compute which constraint option to use. 7667 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7668 // If this is an output operand with a matching input operand, look up the 7669 // matching input. If their types mismatch, e.g. one is an integer, the 7670 // other is floating point, or their sizes are different, flag it as an 7671 // error. 7672 if (OpInfo.hasMatchingInput()) { 7673 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7674 patchMatchingInput(OpInfo, Input, DAG); 7675 } 7676 7677 // Compute the constraint code and ConstraintType to use. 7678 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7679 7680 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7681 OpInfo.Type == InlineAsm::isClobber) 7682 continue; 7683 7684 // If this is a memory input, and if the operand is not indirect, do what we 7685 // need to provide an address for the memory input. 7686 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7687 !OpInfo.isIndirect) { 7688 assert((OpInfo.isMultipleAlternative || 7689 (OpInfo.Type == InlineAsm::isInput)) && 7690 "Can only indirectify direct input operands!"); 7691 7692 // Memory operands really want the address of the value. 7693 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7694 7695 // There is no longer a Value* corresponding to this operand. 7696 OpInfo.CallOperandVal = nullptr; 7697 7698 // It is now an indirect operand. 7699 OpInfo.isIndirect = true; 7700 } 7701 7702 } 7703 7704 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7705 std::vector<SDValue> AsmNodeOperands; 7706 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7707 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7708 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7709 7710 // If we have a !srcloc metadata node associated with it, we want to attach 7711 // this to the ultimately generated inline asm machineinstr. To do this, we 7712 // pass in the third operand as this (potentially null) inline asm MDNode. 7713 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7714 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7715 7716 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7717 // bits as operand 3. 7718 AsmNodeOperands.push_back(DAG.getTargetConstant( 7719 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7720 7721 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7722 // this, assign virtual and physical registers for inputs and otput. 7723 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7724 // Assign Registers. 7725 SDISelAsmOperandInfo &RefOpInfo = 7726 OpInfo.isMatchingInputConstraint() 7727 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7728 : OpInfo; 7729 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7730 7731 switch (OpInfo.Type) { 7732 case InlineAsm::isOutput: 7733 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7734 (OpInfo.ConstraintType == TargetLowering::C_Other && 7735 OpInfo.isIndirect)) { 7736 unsigned ConstraintID = 7737 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7738 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7739 "Failed to convert memory constraint code to constraint id."); 7740 7741 // Add information to the INLINEASM node to know about this output. 7742 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7743 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7744 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7745 MVT::i32)); 7746 AsmNodeOperands.push_back(OpInfo.CallOperand); 7747 break; 7748 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 7749 !OpInfo.isIndirect) || 7750 OpInfo.ConstraintType == TargetLowering::C_Register || 7751 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7752 // Otherwise, this outputs to a register (directly for C_Register / 7753 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 7754 // register that we can use. 7755 if (OpInfo.AssignedRegs.Regs.empty()) { 7756 emitInlineAsmError( 7757 CS, "couldn't allocate output register for constraint '" + 7758 Twine(OpInfo.ConstraintCode) + "'"); 7759 return; 7760 } 7761 7762 // Add information to the INLINEASM node to know that this register is 7763 // set. 7764 OpInfo.AssignedRegs.AddInlineAsmOperands( 7765 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7766 : InlineAsm::Kind_RegDef, 7767 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7768 } 7769 break; 7770 7771 case InlineAsm::isInput: { 7772 SDValue InOperandVal = OpInfo.CallOperand; 7773 7774 if (OpInfo.isMatchingInputConstraint()) { 7775 // If this is required to match an output register we have already set, 7776 // just use its register. 7777 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7778 AsmNodeOperands); 7779 unsigned OpFlag = 7780 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7781 if (InlineAsm::isRegDefKind(OpFlag) || 7782 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7783 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7784 if (OpInfo.isIndirect) { 7785 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7786 emitInlineAsmError(CS, "inline asm not supported yet:" 7787 " don't know how to handle tied " 7788 "indirect register inputs"); 7789 return; 7790 } 7791 7792 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7793 SmallVector<unsigned, 4> Regs; 7794 7795 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7796 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7797 MachineRegisterInfo &RegInfo = 7798 DAG.getMachineFunction().getRegInfo(); 7799 for (unsigned i = 0; i != NumRegs; ++i) 7800 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7801 } else { 7802 emitInlineAsmError(CS, "inline asm error: This value type register " 7803 "class is not natively supported!"); 7804 return; 7805 } 7806 7807 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7808 7809 SDLoc dl = getCurSDLoc(); 7810 // Use the produced MatchedRegs object to 7811 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7812 CS.getInstruction()); 7813 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7814 true, OpInfo.getMatchedOperand(), dl, 7815 DAG, AsmNodeOperands); 7816 break; 7817 } 7818 7819 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7820 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7821 "Unexpected number of operands"); 7822 // Add information to the INLINEASM node to know about this input. 7823 // See InlineAsm.h isUseOperandTiedToDef. 7824 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7825 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7826 OpInfo.getMatchedOperand()); 7827 AsmNodeOperands.push_back(DAG.getTargetConstant( 7828 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7829 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7830 break; 7831 } 7832 7833 // Treat indirect 'X' constraint as memory. 7834 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7835 OpInfo.isIndirect) 7836 OpInfo.ConstraintType = TargetLowering::C_Memory; 7837 7838 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7839 std::vector<SDValue> Ops; 7840 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7841 Ops, DAG); 7842 if (Ops.empty()) { 7843 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7844 Twine(OpInfo.ConstraintCode) + "'"); 7845 return; 7846 } 7847 7848 // Add information to the INLINEASM node to know about this input. 7849 unsigned ResOpType = 7850 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7851 AsmNodeOperands.push_back(DAG.getTargetConstant( 7852 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7853 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7854 break; 7855 } 7856 7857 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7858 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7859 assert(InOperandVal.getValueType() == 7860 TLI.getPointerTy(DAG.getDataLayout()) && 7861 "Memory operands expect pointer values"); 7862 7863 unsigned ConstraintID = 7864 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7865 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7866 "Failed to convert memory constraint code to constraint id."); 7867 7868 // Add information to the INLINEASM node to know about this input. 7869 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7870 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7871 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7872 getCurSDLoc(), 7873 MVT::i32)); 7874 AsmNodeOperands.push_back(InOperandVal); 7875 break; 7876 } 7877 7878 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7879 OpInfo.ConstraintType == TargetLowering::C_Register) && 7880 "Unknown constraint type!"); 7881 7882 // TODO: Support this. 7883 if (OpInfo.isIndirect) { 7884 emitInlineAsmError( 7885 CS, "Don't know how to handle indirect register inputs yet " 7886 "for constraint '" + 7887 Twine(OpInfo.ConstraintCode) + "'"); 7888 return; 7889 } 7890 7891 // Copy the input into the appropriate registers. 7892 if (OpInfo.AssignedRegs.Regs.empty()) { 7893 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7894 Twine(OpInfo.ConstraintCode) + "'"); 7895 return; 7896 } 7897 7898 SDLoc dl = getCurSDLoc(); 7899 7900 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7901 Chain, &Flag, CS.getInstruction()); 7902 7903 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7904 dl, DAG, AsmNodeOperands); 7905 break; 7906 } 7907 case InlineAsm::isClobber: 7908 // Add the clobbered value to the operand list, so that the register 7909 // allocator is aware that the physreg got clobbered. 7910 if (!OpInfo.AssignedRegs.Regs.empty()) 7911 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7912 false, 0, getCurSDLoc(), DAG, 7913 AsmNodeOperands); 7914 break; 7915 } 7916 } 7917 7918 // Finish up input operands. Set the input chain and add the flag last. 7919 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7920 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7921 7922 unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR : ISD::INLINEASM; 7923 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 7924 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7925 Flag = Chain.getValue(1); 7926 7927 // Do additional work to generate outputs. 7928 7929 SmallVector<EVT, 1> ResultVTs; 7930 SmallVector<SDValue, 1> ResultValues; 7931 SmallVector<SDValue, 8> OutChains; 7932 7933 llvm::Type *CSResultType = CS.getType(); 7934 ArrayRef<Type *> ResultTypes; 7935 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 7936 ResultTypes = StructResult->elements(); 7937 else if (!CSResultType->isVoidTy()) 7938 ResultTypes = makeArrayRef(CSResultType); 7939 7940 auto CurResultType = ResultTypes.begin(); 7941 auto handleRegAssign = [&](SDValue V) { 7942 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7943 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7944 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7945 ++CurResultType; 7946 // If the type of the inline asm call site return value is different but has 7947 // same size as the type of the asm output bitcast it. One example of this 7948 // is for vectors with different width / number of elements. This can 7949 // happen for register classes that can contain multiple different value 7950 // types. The preg or vreg allocated may not have the same VT as was 7951 // expected. 7952 // 7953 // This can also happen for a return value that disagrees with the register 7954 // class it is put in, eg. a double in a general-purpose register on a 7955 // 32-bit machine. 7956 if (ResultVT != V.getValueType() && 7957 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7958 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7959 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7960 V.getValueType().isInteger()) { 7961 // If a result value was tied to an input value, the computed result 7962 // may have a wider width than the expected result. Extract the 7963 // relevant portion. 7964 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7965 } 7966 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7967 ResultVTs.push_back(ResultVT); 7968 ResultValues.push_back(V); 7969 }; 7970 7971 // Deal with output operands. 7972 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7973 if (OpInfo.Type == InlineAsm::isOutput) { 7974 SDValue Val; 7975 // Skip trivial output operands. 7976 if (OpInfo.AssignedRegs.Regs.empty()) 7977 continue; 7978 7979 switch (OpInfo.ConstraintType) { 7980 case TargetLowering::C_Register: 7981 case TargetLowering::C_RegisterClass: 7982 Val = OpInfo.AssignedRegs.getCopyFromRegs( 7983 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7984 break; 7985 case TargetLowering::C_Other: 7986 Val = TLI.LowerAsmOutputForConstraint(Chain, &Flag, getCurSDLoc(), 7987 OpInfo, DAG); 7988 break; 7989 case TargetLowering::C_Memory: 7990 break; // Already handled. 7991 case TargetLowering::C_Unknown: 7992 assert(false && "Unexpected unknown constraint"); 7993 } 7994 7995 // Indirect output manifest as stores. Record output chains. 7996 if (OpInfo.isIndirect) { 7997 7998 const Value *Ptr = OpInfo.CallOperandVal; 7999 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8000 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8001 MachinePointerInfo(Ptr)); 8002 OutChains.push_back(Store); 8003 } else { 8004 // generate CopyFromRegs to associated registers. 8005 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8006 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8007 for (const SDValue &V : Val->op_values()) 8008 handleRegAssign(V); 8009 } else 8010 handleRegAssign(Val); 8011 } 8012 } 8013 } 8014 8015 // Set results. 8016 if (!ResultValues.empty()) { 8017 assert(CurResultType == ResultTypes.end() && 8018 "Mismatch in number of ResultTypes"); 8019 assert(ResultValues.size() == ResultTypes.size() && 8020 "Mismatch in number of output operands in asm result"); 8021 8022 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8023 DAG.getVTList(ResultVTs), ResultValues); 8024 setValue(CS.getInstruction(), V); 8025 } 8026 8027 // Collect store chains. 8028 if (!OutChains.empty()) 8029 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8030 8031 // Only Update Root if inline assembly has a memory effect. 8032 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 8033 DAG.setRoot(Chain); 8034 } 8035 8036 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8037 const Twine &Message) { 8038 LLVMContext &Ctx = *DAG.getContext(); 8039 Ctx.emitError(CS.getInstruction(), Message); 8040 8041 // Make sure we leave the DAG in a valid state 8042 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8043 SmallVector<EVT, 1> ValueVTs; 8044 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8045 8046 if (ValueVTs.empty()) 8047 return; 8048 8049 SmallVector<SDValue, 1> Ops; 8050 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8051 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8052 8053 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8054 } 8055 8056 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8057 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8058 MVT::Other, getRoot(), 8059 getValue(I.getArgOperand(0)), 8060 DAG.getSrcValue(I.getArgOperand(0)))); 8061 } 8062 8063 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8064 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8065 const DataLayout &DL = DAG.getDataLayout(); 8066 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 8067 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 8068 DAG.getSrcValue(I.getOperand(0)), 8069 DL.getABITypeAlignment(I.getType())); 8070 setValue(&I, V); 8071 DAG.setRoot(V.getValue(1)); 8072 } 8073 8074 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8075 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8076 MVT::Other, getRoot(), 8077 getValue(I.getArgOperand(0)), 8078 DAG.getSrcValue(I.getArgOperand(0)))); 8079 } 8080 8081 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8082 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8083 MVT::Other, getRoot(), 8084 getValue(I.getArgOperand(0)), 8085 getValue(I.getArgOperand(1)), 8086 DAG.getSrcValue(I.getArgOperand(0)), 8087 DAG.getSrcValue(I.getArgOperand(1)))); 8088 } 8089 8090 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8091 const Instruction &I, 8092 SDValue Op) { 8093 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8094 if (!Range) 8095 return Op; 8096 8097 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8098 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8099 return Op; 8100 8101 APInt Lo = CR.getUnsignedMin(); 8102 if (!Lo.isMinValue()) 8103 return Op; 8104 8105 APInt Hi = CR.getUnsignedMax(); 8106 unsigned Bits = std::max(Hi.getActiveBits(), 8107 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8108 8109 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8110 8111 SDLoc SL = getCurSDLoc(); 8112 8113 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8114 DAG.getValueType(SmallVT)); 8115 unsigned NumVals = Op.getNode()->getNumValues(); 8116 if (NumVals == 1) 8117 return ZExt; 8118 8119 SmallVector<SDValue, 4> Ops; 8120 8121 Ops.push_back(ZExt); 8122 for (unsigned I = 1; I != NumVals; ++I) 8123 Ops.push_back(Op.getValue(I)); 8124 8125 return DAG.getMergeValues(Ops, SL); 8126 } 8127 8128 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8129 /// the call being lowered. 8130 /// 8131 /// This is a helper for lowering intrinsics that follow a target calling 8132 /// convention or require stack pointer adjustment. Only a subset of the 8133 /// intrinsic's operands need to participate in the calling convention. 8134 void SelectionDAGBuilder::populateCallLoweringInfo( 8135 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8136 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8137 bool IsPatchPoint) { 8138 TargetLowering::ArgListTy Args; 8139 Args.reserve(NumArgs); 8140 8141 // Populate the argument list. 8142 // Attributes for args start at offset 1, after the return attribute. 8143 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8144 ArgI != ArgE; ++ArgI) { 8145 const Value *V = CS->getOperand(ArgI); 8146 8147 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8148 8149 TargetLowering::ArgListEntry Entry; 8150 Entry.Node = getValue(V); 8151 Entry.Ty = V->getType(); 8152 Entry.setAttributes(&CS, ArgI); 8153 Args.push_back(Entry); 8154 } 8155 8156 CLI.setDebugLoc(getCurSDLoc()) 8157 .setChain(getRoot()) 8158 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8159 .setDiscardResult(CS->use_empty()) 8160 .setIsPatchPoint(IsPatchPoint); 8161 } 8162 8163 /// Add a stack map intrinsic call's live variable operands to a stackmap 8164 /// or patchpoint target node's operand list. 8165 /// 8166 /// Constants are converted to TargetConstants purely as an optimization to 8167 /// avoid constant materialization and register allocation. 8168 /// 8169 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8170 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8171 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8172 /// address materialization and register allocation, but may also be required 8173 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8174 /// alloca in the entry block, then the runtime may assume that the alloca's 8175 /// StackMap location can be read immediately after compilation and that the 8176 /// location is valid at any point during execution (this is similar to the 8177 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8178 /// only available in a register, then the runtime would need to trap when 8179 /// execution reaches the StackMap in order to read the alloca's location. 8180 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8181 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8182 SelectionDAGBuilder &Builder) { 8183 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8184 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8185 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8186 Ops.push_back( 8187 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8188 Ops.push_back( 8189 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8190 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8191 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8192 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8193 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8194 } else 8195 Ops.push_back(OpVal); 8196 } 8197 } 8198 8199 /// Lower llvm.experimental.stackmap directly to its target opcode. 8200 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8201 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8202 // [live variables...]) 8203 8204 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8205 8206 SDValue Chain, InFlag, Callee, NullPtr; 8207 SmallVector<SDValue, 32> Ops; 8208 8209 SDLoc DL = getCurSDLoc(); 8210 Callee = getValue(CI.getCalledValue()); 8211 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8212 8213 // The stackmap intrinsic only records the live variables (the arguemnts 8214 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8215 // intrinsic, this won't be lowered to a function call. This means we don't 8216 // have to worry about calling conventions and target specific lowering code. 8217 // Instead we perform the call lowering right here. 8218 // 8219 // chain, flag = CALLSEQ_START(chain, 0, 0) 8220 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8221 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8222 // 8223 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8224 InFlag = Chain.getValue(1); 8225 8226 // Add the <id> and <numBytes> constants. 8227 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8228 Ops.push_back(DAG.getTargetConstant( 8229 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8230 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8231 Ops.push_back(DAG.getTargetConstant( 8232 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8233 MVT::i32)); 8234 8235 // Push live variables for the stack map. 8236 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8237 8238 // We are not pushing any register mask info here on the operands list, 8239 // because the stackmap doesn't clobber anything. 8240 8241 // Push the chain and the glue flag. 8242 Ops.push_back(Chain); 8243 Ops.push_back(InFlag); 8244 8245 // Create the STACKMAP node. 8246 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8247 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8248 Chain = SDValue(SM, 0); 8249 InFlag = Chain.getValue(1); 8250 8251 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8252 8253 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8254 8255 // Set the root to the target-lowered call chain. 8256 DAG.setRoot(Chain); 8257 8258 // Inform the Frame Information that we have a stackmap in this function. 8259 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8260 } 8261 8262 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8263 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8264 const BasicBlock *EHPadBB) { 8265 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8266 // i32 <numBytes>, 8267 // i8* <target>, 8268 // i32 <numArgs>, 8269 // [Args...], 8270 // [live variables...]) 8271 8272 CallingConv::ID CC = CS.getCallingConv(); 8273 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8274 bool HasDef = !CS->getType()->isVoidTy(); 8275 SDLoc dl = getCurSDLoc(); 8276 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8277 8278 // Handle immediate and symbolic callees. 8279 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8280 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8281 /*isTarget=*/true); 8282 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8283 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8284 SDLoc(SymbolicCallee), 8285 SymbolicCallee->getValueType(0)); 8286 8287 // Get the real number of arguments participating in the call <numArgs> 8288 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8289 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8290 8291 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8292 // Intrinsics include all meta-operands up to but not including CC. 8293 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8294 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8295 "Not enough arguments provided to the patchpoint intrinsic"); 8296 8297 // For AnyRegCC the arguments are lowered later on manually. 8298 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8299 Type *ReturnTy = 8300 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8301 8302 TargetLowering::CallLoweringInfo CLI(DAG); 8303 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8304 true); 8305 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8306 8307 SDNode *CallEnd = Result.second.getNode(); 8308 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8309 CallEnd = CallEnd->getOperand(0).getNode(); 8310 8311 /// Get a call instruction from the call sequence chain. 8312 /// Tail calls are not allowed. 8313 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8314 "Expected a callseq node."); 8315 SDNode *Call = CallEnd->getOperand(0).getNode(); 8316 bool HasGlue = Call->getGluedNode(); 8317 8318 // Replace the target specific call node with the patchable intrinsic. 8319 SmallVector<SDValue, 8> Ops; 8320 8321 // Add the <id> and <numBytes> constants. 8322 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8323 Ops.push_back(DAG.getTargetConstant( 8324 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8325 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8326 Ops.push_back(DAG.getTargetConstant( 8327 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8328 MVT::i32)); 8329 8330 // Add the callee. 8331 Ops.push_back(Callee); 8332 8333 // Adjust <numArgs> to account for any arguments that have been passed on the 8334 // stack instead. 8335 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8336 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8337 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8338 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8339 8340 // Add the calling convention 8341 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8342 8343 // Add the arguments we omitted previously. The register allocator should 8344 // place these in any free register. 8345 if (IsAnyRegCC) 8346 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8347 Ops.push_back(getValue(CS.getArgument(i))); 8348 8349 // Push the arguments from the call instruction up to the register mask. 8350 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8351 Ops.append(Call->op_begin() + 2, e); 8352 8353 // Push live variables for the stack map. 8354 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8355 8356 // Push the register mask info. 8357 if (HasGlue) 8358 Ops.push_back(*(Call->op_end()-2)); 8359 else 8360 Ops.push_back(*(Call->op_end()-1)); 8361 8362 // Push the chain (this is originally the first operand of the call, but 8363 // becomes now the last or second to last operand). 8364 Ops.push_back(*(Call->op_begin())); 8365 8366 // Push the glue flag (last operand). 8367 if (HasGlue) 8368 Ops.push_back(*(Call->op_end()-1)); 8369 8370 SDVTList NodeTys; 8371 if (IsAnyRegCC && HasDef) { 8372 // Create the return types based on the intrinsic definition 8373 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8374 SmallVector<EVT, 3> ValueVTs; 8375 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8376 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8377 8378 // There is always a chain and a glue type at the end 8379 ValueVTs.push_back(MVT::Other); 8380 ValueVTs.push_back(MVT::Glue); 8381 NodeTys = DAG.getVTList(ValueVTs); 8382 } else 8383 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8384 8385 // Replace the target specific call node with a PATCHPOINT node. 8386 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8387 dl, NodeTys, Ops); 8388 8389 // Update the NodeMap. 8390 if (HasDef) { 8391 if (IsAnyRegCC) 8392 setValue(CS.getInstruction(), SDValue(MN, 0)); 8393 else 8394 setValue(CS.getInstruction(), Result.first); 8395 } 8396 8397 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8398 // call sequence. Furthermore the location of the chain and glue can change 8399 // when the AnyReg calling convention is used and the intrinsic returns a 8400 // value. 8401 if (IsAnyRegCC && HasDef) { 8402 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8403 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8404 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8405 } else 8406 DAG.ReplaceAllUsesWith(Call, MN); 8407 DAG.DeleteNode(Call); 8408 8409 // Inform the Frame Information that we have a patchpoint in this function. 8410 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8411 } 8412 8413 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8414 unsigned Intrinsic) { 8415 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8416 SDValue Op1 = getValue(I.getArgOperand(0)); 8417 SDValue Op2; 8418 if (I.getNumArgOperands() > 1) 8419 Op2 = getValue(I.getArgOperand(1)); 8420 SDLoc dl = getCurSDLoc(); 8421 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8422 SDValue Res; 8423 FastMathFlags FMF; 8424 if (isa<FPMathOperator>(I)) 8425 FMF = I.getFastMathFlags(); 8426 8427 switch (Intrinsic) { 8428 case Intrinsic::experimental_vector_reduce_fadd: 8429 if (FMF.isFast()) 8430 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8431 else 8432 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8433 break; 8434 case Intrinsic::experimental_vector_reduce_fmul: 8435 if (FMF.isFast()) 8436 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8437 else 8438 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8439 break; 8440 case Intrinsic::experimental_vector_reduce_add: 8441 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8442 break; 8443 case Intrinsic::experimental_vector_reduce_mul: 8444 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8445 break; 8446 case Intrinsic::experimental_vector_reduce_and: 8447 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8448 break; 8449 case Intrinsic::experimental_vector_reduce_or: 8450 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8451 break; 8452 case Intrinsic::experimental_vector_reduce_xor: 8453 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8454 break; 8455 case Intrinsic::experimental_vector_reduce_smax: 8456 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8457 break; 8458 case Intrinsic::experimental_vector_reduce_smin: 8459 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8460 break; 8461 case Intrinsic::experimental_vector_reduce_umax: 8462 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8463 break; 8464 case Intrinsic::experimental_vector_reduce_umin: 8465 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8466 break; 8467 case Intrinsic::experimental_vector_reduce_fmax: 8468 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8469 break; 8470 case Intrinsic::experimental_vector_reduce_fmin: 8471 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8472 break; 8473 default: 8474 llvm_unreachable("Unhandled vector reduce intrinsic"); 8475 } 8476 setValue(&I, Res); 8477 } 8478 8479 /// Returns an AttributeList representing the attributes applied to the return 8480 /// value of the given call. 8481 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8482 SmallVector<Attribute::AttrKind, 2> Attrs; 8483 if (CLI.RetSExt) 8484 Attrs.push_back(Attribute::SExt); 8485 if (CLI.RetZExt) 8486 Attrs.push_back(Attribute::ZExt); 8487 if (CLI.IsInReg) 8488 Attrs.push_back(Attribute::InReg); 8489 8490 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8491 Attrs); 8492 } 8493 8494 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8495 /// implementation, which just calls LowerCall. 8496 /// FIXME: When all targets are 8497 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8498 std::pair<SDValue, SDValue> 8499 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8500 // Handle the incoming return values from the call. 8501 CLI.Ins.clear(); 8502 Type *OrigRetTy = CLI.RetTy; 8503 SmallVector<EVT, 4> RetTys; 8504 SmallVector<uint64_t, 4> Offsets; 8505 auto &DL = CLI.DAG.getDataLayout(); 8506 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8507 8508 if (CLI.IsPostTypeLegalization) { 8509 // If we are lowering a libcall after legalization, split the return type. 8510 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8511 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8512 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8513 EVT RetVT = OldRetTys[i]; 8514 uint64_t Offset = OldOffsets[i]; 8515 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8516 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8517 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8518 RetTys.append(NumRegs, RegisterVT); 8519 for (unsigned j = 0; j != NumRegs; ++j) 8520 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8521 } 8522 } 8523 8524 SmallVector<ISD::OutputArg, 4> Outs; 8525 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8526 8527 bool CanLowerReturn = 8528 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8529 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8530 8531 SDValue DemoteStackSlot; 8532 int DemoteStackIdx = -100; 8533 if (!CanLowerReturn) { 8534 // FIXME: equivalent assert? 8535 // assert(!CS.hasInAllocaArgument() && 8536 // "sret demotion is incompatible with inalloca"); 8537 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8538 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8539 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8540 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8541 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8542 DL.getAllocaAddrSpace()); 8543 8544 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8545 ArgListEntry Entry; 8546 Entry.Node = DemoteStackSlot; 8547 Entry.Ty = StackSlotPtrType; 8548 Entry.IsSExt = false; 8549 Entry.IsZExt = false; 8550 Entry.IsInReg = false; 8551 Entry.IsSRet = true; 8552 Entry.IsNest = false; 8553 Entry.IsByVal = false; 8554 Entry.IsReturned = false; 8555 Entry.IsSwiftSelf = false; 8556 Entry.IsSwiftError = false; 8557 Entry.Alignment = Align; 8558 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8559 CLI.NumFixedArgs += 1; 8560 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8561 8562 // sret demotion isn't compatible with tail-calls, since the sret argument 8563 // points into the callers stack frame. 8564 CLI.IsTailCall = false; 8565 } else { 8566 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8567 EVT VT = RetTys[I]; 8568 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8569 CLI.CallConv, VT); 8570 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8571 CLI.CallConv, VT); 8572 for (unsigned i = 0; i != NumRegs; ++i) { 8573 ISD::InputArg MyFlags; 8574 MyFlags.VT = RegisterVT; 8575 MyFlags.ArgVT = VT; 8576 MyFlags.Used = CLI.IsReturnValueUsed; 8577 if (CLI.RetSExt) 8578 MyFlags.Flags.setSExt(); 8579 if (CLI.RetZExt) 8580 MyFlags.Flags.setZExt(); 8581 if (CLI.IsInReg) 8582 MyFlags.Flags.setInReg(); 8583 CLI.Ins.push_back(MyFlags); 8584 } 8585 } 8586 } 8587 8588 // We push in swifterror return as the last element of CLI.Ins. 8589 ArgListTy &Args = CLI.getArgs(); 8590 if (supportSwiftError()) { 8591 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8592 if (Args[i].IsSwiftError) { 8593 ISD::InputArg MyFlags; 8594 MyFlags.VT = getPointerTy(DL); 8595 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8596 MyFlags.Flags.setSwiftError(); 8597 CLI.Ins.push_back(MyFlags); 8598 } 8599 } 8600 } 8601 8602 // Handle all of the outgoing arguments. 8603 CLI.Outs.clear(); 8604 CLI.OutVals.clear(); 8605 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8606 SmallVector<EVT, 4> ValueVTs; 8607 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8608 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8609 Type *FinalType = Args[i].Ty; 8610 if (Args[i].IsByVal) 8611 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8612 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8613 FinalType, CLI.CallConv, CLI.IsVarArg); 8614 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8615 ++Value) { 8616 EVT VT = ValueVTs[Value]; 8617 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8618 SDValue Op = SDValue(Args[i].Node.getNode(), 8619 Args[i].Node.getResNo() + Value); 8620 ISD::ArgFlagsTy Flags; 8621 8622 // Certain targets (such as MIPS), may have a different ABI alignment 8623 // for a type depending on the context. Give the target a chance to 8624 // specify the alignment it wants. 8625 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8626 8627 if (Args[i].IsZExt) 8628 Flags.setZExt(); 8629 if (Args[i].IsSExt) 8630 Flags.setSExt(); 8631 if (Args[i].IsInReg) { 8632 // If we are using vectorcall calling convention, a structure that is 8633 // passed InReg - is surely an HVA 8634 if (CLI.CallConv == CallingConv::X86_VectorCall && 8635 isa<StructType>(FinalType)) { 8636 // The first value of a structure is marked 8637 if (0 == Value) 8638 Flags.setHvaStart(); 8639 Flags.setHva(); 8640 } 8641 // Set InReg Flag 8642 Flags.setInReg(); 8643 } 8644 if (Args[i].IsSRet) 8645 Flags.setSRet(); 8646 if (Args[i].IsSwiftSelf) 8647 Flags.setSwiftSelf(); 8648 if (Args[i].IsSwiftError) 8649 Flags.setSwiftError(); 8650 if (Args[i].IsByVal) 8651 Flags.setByVal(); 8652 if (Args[i].IsInAlloca) { 8653 Flags.setInAlloca(); 8654 // Set the byval flag for CCAssignFn callbacks that don't know about 8655 // inalloca. This way we can know how many bytes we should've allocated 8656 // and how many bytes a callee cleanup function will pop. If we port 8657 // inalloca to more targets, we'll have to add custom inalloca handling 8658 // in the various CC lowering callbacks. 8659 Flags.setByVal(); 8660 } 8661 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8662 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8663 Type *ElementTy = Ty->getElementType(); 8664 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8665 // For ByVal, alignment should come from FE. BE will guess if this 8666 // info is not there but there are cases it cannot get right. 8667 unsigned FrameAlign; 8668 if (Args[i].Alignment) 8669 FrameAlign = Args[i].Alignment; 8670 else 8671 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8672 Flags.setByValAlign(FrameAlign); 8673 } 8674 if (Args[i].IsNest) 8675 Flags.setNest(); 8676 if (NeedsRegBlock) 8677 Flags.setInConsecutiveRegs(); 8678 Flags.setOrigAlign(OriginalAlignment); 8679 8680 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8681 CLI.CallConv, VT); 8682 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8683 CLI.CallConv, VT); 8684 SmallVector<SDValue, 4> Parts(NumParts); 8685 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8686 8687 if (Args[i].IsSExt) 8688 ExtendKind = ISD::SIGN_EXTEND; 8689 else if (Args[i].IsZExt) 8690 ExtendKind = ISD::ZERO_EXTEND; 8691 8692 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8693 // for now. 8694 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8695 CanLowerReturn) { 8696 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8697 "unexpected use of 'returned'"); 8698 // Before passing 'returned' to the target lowering code, ensure that 8699 // either the register MVT and the actual EVT are the same size or that 8700 // the return value and argument are extended in the same way; in these 8701 // cases it's safe to pass the argument register value unchanged as the 8702 // return register value (although it's at the target's option whether 8703 // to do so) 8704 // TODO: allow code generation to take advantage of partially preserved 8705 // registers rather than clobbering the entire register when the 8706 // parameter extension method is not compatible with the return 8707 // extension method 8708 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8709 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8710 CLI.RetZExt == Args[i].IsZExt)) 8711 Flags.setReturned(); 8712 } 8713 8714 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8715 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8716 8717 for (unsigned j = 0; j != NumParts; ++j) { 8718 // if it isn't first piece, alignment must be 1 8719 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8720 i < CLI.NumFixedArgs, 8721 i, j*Parts[j].getValueType().getStoreSize()); 8722 if (NumParts > 1 && j == 0) 8723 MyFlags.Flags.setSplit(); 8724 else if (j != 0) { 8725 MyFlags.Flags.setOrigAlign(1); 8726 if (j == NumParts - 1) 8727 MyFlags.Flags.setSplitEnd(); 8728 } 8729 8730 CLI.Outs.push_back(MyFlags); 8731 CLI.OutVals.push_back(Parts[j]); 8732 } 8733 8734 if (NeedsRegBlock && Value == NumValues - 1) 8735 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8736 } 8737 } 8738 8739 SmallVector<SDValue, 4> InVals; 8740 CLI.Chain = LowerCall(CLI, InVals); 8741 8742 // Update CLI.InVals to use outside of this function. 8743 CLI.InVals = InVals; 8744 8745 // Verify that the target's LowerCall behaved as expected. 8746 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8747 "LowerCall didn't return a valid chain!"); 8748 assert((!CLI.IsTailCall || InVals.empty()) && 8749 "LowerCall emitted a return value for a tail call!"); 8750 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8751 "LowerCall didn't emit the correct number of values!"); 8752 8753 // For a tail call, the return value is merely live-out and there aren't 8754 // any nodes in the DAG representing it. Return a special value to 8755 // indicate that a tail call has been emitted and no more Instructions 8756 // should be processed in the current block. 8757 if (CLI.IsTailCall) { 8758 CLI.DAG.setRoot(CLI.Chain); 8759 return std::make_pair(SDValue(), SDValue()); 8760 } 8761 8762 #ifndef NDEBUG 8763 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8764 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8765 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8766 "LowerCall emitted a value with the wrong type!"); 8767 } 8768 #endif 8769 8770 SmallVector<SDValue, 4> ReturnValues; 8771 if (!CanLowerReturn) { 8772 // The instruction result is the result of loading from the 8773 // hidden sret parameter. 8774 SmallVector<EVT, 1> PVTs; 8775 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8776 8777 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8778 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8779 EVT PtrVT = PVTs[0]; 8780 8781 unsigned NumValues = RetTys.size(); 8782 ReturnValues.resize(NumValues); 8783 SmallVector<SDValue, 4> Chains(NumValues); 8784 8785 // An aggregate return value cannot wrap around the address space, so 8786 // offsets to its parts don't wrap either. 8787 SDNodeFlags Flags; 8788 Flags.setNoUnsignedWrap(true); 8789 8790 for (unsigned i = 0; i < NumValues; ++i) { 8791 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8792 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8793 PtrVT), Flags); 8794 SDValue L = CLI.DAG.getLoad( 8795 RetTys[i], CLI.DL, CLI.Chain, Add, 8796 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8797 DemoteStackIdx, Offsets[i]), 8798 /* Alignment = */ 1); 8799 ReturnValues[i] = L; 8800 Chains[i] = L.getValue(1); 8801 } 8802 8803 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8804 } else { 8805 // Collect the legal value parts into potentially illegal values 8806 // that correspond to the original function's return values. 8807 Optional<ISD::NodeType> AssertOp; 8808 if (CLI.RetSExt) 8809 AssertOp = ISD::AssertSext; 8810 else if (CLI.RetZExt) 8811 AssertOp = ISD::AssertZext; 8812 unsigned CurReg = 0; 8813 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8814 EVT VT = RetTys[I]; 8815 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8816 CLI.CallConv, VT); 8817 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8818 CLI.CallConv, VT); 8819 8820 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8821 NumRegs, RegisterVT, VT, nullptr, 8822 CLI.CallConv, AssertOp)); 8823 CurReg += NumRegs; 8824 } 8825 8826 // For a function returning void, there is no return value. We can't create 8827 // such a node, so we just return a null return value in that case. In 8828 // that case, nothing will actually look at the value. 8829 if (ReturnValues.empty()) 8830 return std::make_pair(SDValue(), CLI.Chain); 8831 } 8832 8833 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8834 CLI.DAG.getVTList(RetTys), ReturnValues); 8835 return std::make_pair(Res, CLI.Chain); 8836 } 8837 8838 void TargetLowering::LowerOperationWrapper(SDNode *N, 8839 SmallVectorImpl<SDValue> &Results, 8840 SelectionDAG &DAG) const { 8841 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8842 Results.push_back(Res); 8843 } 8844 8845 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8846 llvm_unreachable("LowerOperation not implemented for this target!"); 8847 } 8848 8849 void 8850 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8851 SDValue Op = getNonRegisterValue(V); 8852 assert((Op.getOpcode() != ISD::CopyFromReg || 8853 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8854 "Copy from a reg to the same reg!"); 8855 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8856 8857 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8858 // If this is an InlineAsm we have to match the registers required, not the 8859 // notional registers required by the type. 8860 8861 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8862 None); // This is not an ABI copy. 8863 SDValue Chain = DAG.getEntryNode(); 8864 8865 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8866 FuncInfo.PreferredExtendType.end()) 8867 ? ISD::ANY_EXTEND 8868 : FuncInfo.PreferredExtendType[V]; 8869 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8870 PendingExports.push_back(Chain); 8871 } 8872 8873 #include "llvm/CodeGen/SelectionDAGISel.h" 8874 8875 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8876 /// entry block, return true. This includes arguments used by switches, since 8877 /// the switch may expand into multiple basic blocks. 8878 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8879 // With FastISel active, we may be splitting blocks, so force creation 8880 // of virtual registers for all non-dead arguments. 8881 if (FastISel) 8882 return A->use_empty(); 8883 8884 const BasicBlock &Entry = A->getParent()->front(); 8885 for (const User *U : A->users()) 8886 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8887 return false; // Use not in entry block. 8888 8889 return true; 8890 } 8891 8892 using ArgCopyElisionMapTy = 8893 DenseMap<const Argument *, 8894 std::pair<const AllocaInst *, const StoreInst *>>; 8895 8896 /// Scan the entry block of the function in FuncInfo for arguments that look 8897 /// like copies into a local alloca. Record any copied arguments in 8898 /// ArgCopyElisionCandidates. 8899 static void 8900 findArgumentCopyElisionCandidates(const DataLayout &DL, 8901 FunctionLoweringInfo *FuncInfo, 8902 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8903 // Record the state of every static alloca used in the entry block. Argument 8904 // allocas are all used in the entry block, so we need approximately as many 8905 // entries as we have arguments. 8906 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8907 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8908 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8909 StaticAllocas.reserve(NumArgs * 2); 8910 8911 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8912 if (!V) 8913 return nullptr; 8914 V = V->stripPointerCasts(); 8915 const auto *AI = dyn_cast<AllocaInst>(V); 8916 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8917 return nullptr; 8918 auto Iter = StaticAllocas.insert({AI, Unknown}); 8919 return &Iter.first->second; 8920 }; 8921 8922 // Look for stores of arguments to static allocas. Look through bitcasts and 8923 // GEPs to handle type coercions, as long as the alloca is fully initialized 8924 // by the store. Any non-store use of an alloca escapes it and any subsequent 8925 // unanalyzed store might write it. 8926 // FIXME: Handle structs initialized with multiple stores. 8927 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8928 // Look for stores, and handle non-store uses conservatively. 8929 const auto *SI = dyn_cast<StoreInst>(&I); 8930 if (!SI) { 8931 // We will look through cast uses, so ignore them completely. 8932 if (I.isCast()) 8933 continue; 8934 // Ignore debug info intrinsics, they don't escape or store to allocas. 8935 if (isa<DbgInfoIntrinsic>(I)) 8936 continue; 8937 // This is an unknown instruction. Assume it escapes or writes to all 8938 // static alloca operands. 8939 for (const Use &U : I.operands()) { 8940 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8941 *Info = StaticAllocaInfo::Clobbered; 8942 } 8943 continue; 8944 } 8945 8946 // If the stored value is a static alloca, mark it as escaped. 8947 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8948 *Info = StaticAllocaInfo::Clobbered; 8949 8950 // Check if the destination is a static alloca. 8951 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8952 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8953 if (!Info) 8954 continue; 8955 const AllocaInst *AI = cast<AllocaInst>(Dst); 8956 8957 // Skip allocas that have been initialized or clobbered. 8958 if (*Info != StaticAllocaInfo::Unknown) 8959 continue; 8960 8961 // Check if the stored value is an argument, and that this store fully 8962 // initializes the alloca. Don't elide copies from the same argument twice. 8963 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8964 const auto *Arg = dyn_cast<Argument>(Val); 8965 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8966 Arg->getType()->isEmptyTy() || 8967 DL.getTypeStoreSize(Arg->getType()) != 8968 DL.getTypeAllocSize(AI->getAllocatedType()) || 8969 ArgCopyElisionCandidates.count(Arg)) { 8970 *Info = StaticAllocaInfo::Clobbered; 8971 continue; 8972 } 8973 8974 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8975 << '\n'); 8976 8977 // Mark this alloca and store for argument copy elision. 8978 *Info = StaticAllocaInfo::Elidable; 8979 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8980 8981 // Stop scanning if we've seen all arguments. This will happen early in -O0 8982 // builds, which is useful, because -O0 builds have large entry blocks and 8983 // many allocas. 8984 if (ArgCopyElisionCandidates.size() == NumArgs) 8985 break; 8986 } 8987 } 8988 8989 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8990 /// ArgVal is a load from a suitable fixed stack object. 8991 static void tryToElideArgumentCopy( 8992 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8993 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8994 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8995 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8996 SDValue ArgVal, bool &ArgHasUses) { 8997 // Check if this is a load from a fixed stack object. 8998 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8999 if (!LNode) 9000 return; 9001 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9002 if (!FINode) 9003 return; 9004 9005 // Check that the fixed stack object is the right size and alignment. 9006 // Look at the alignment that the user wrote on the alloca instead of looking 9007 // at the stack object. 9008 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9009 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9010 const AllocaInst *AI = ArgCopyIter->second.first; 9011 int FixedIndex = FINode->getIndex(); 9012 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9013 int OldIndex = AllocaIndex; 9014 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9015 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9016 LLVM_DEBUG( 9017 dbgs() << " argument copy elision failed due to bad fixed stack " 9018 "object size\n"); 9019 return; 9020 } 9021 unsigned RequiredAlignment = AI->getAlignment(); 9022 if (!RequiredAlignment) { 9023 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9024 AI->getAllocatedType()); 9025 } 9026 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9027 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9028 "greater than stack argument alignment (" 9029 << RequiredAlignment << " vs " 9030 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9031 return; 9032 } 9033 9034 // Perform the elision. Delete the old stack object and replace its only use 9035 // in the variable info map. Mark the stack object as mutable. 9036 LLVM_DEBUG({ 9037 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9038 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9039 << '\n'; 9040 }); 9041 MFI.RemoveStackObject(OldIndex); 9042 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9043 AllocaIndex = FixedIndex; 9044 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9045 Chains.push_back(ArgVal.getValue(1)); 9046 9047 // Avoid emitting code for the store implementing the copy. 9048 const StoreInst *SI = ArgCopyIter->second.second; 9049 ElidedArgCopyInstrs.insert(SI); 9050 9051 // Check for uses of the argument again so that we can avoid exporting ArgVal 9052 // if it is't used by anything other than the store. 9053 for (const Value *U : Arg.users()) { 9054 if (U != SI) { 9055 ArgHasUses = true; 9056 break; 9057 } 9058 } 9059 } 9060 9061 void SelectionDAGISel::LowerArguments(const Function &F) { 9062 SelectionDAG &DAG = SDB->DAG; 9063 SDLoc dl = SDB->getCurSDLoc(); 9064 const DataLayout &DL = DAG.getDataLayout(); 9065 SmallVector<ISD::InputArg, 16> Ins; 9066 9067 if (!FuncInfo->CanLowerReturn) { 9068 // Put in an sret pointer parameter before all the other parameters. 9069 SmallVector<EVT, 1> ValueVTs; 9070 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9071 F.getReturnType()->getPointerTo( 9072 DAG.getDataLayout().getAllocaAddrSpace()), 9073 ValueVTs); 9074 9075 // NOTE: Assuming that a pointer will never break down to more than one VT 9076 // or one register. 9077 ISD::ArgFlagsTy Flags; 9078 Flags.setSRet(); 9079 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9080 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9081 ISD::InputArg::NoArgIndex, 0); 9082 Ins.push_back(RetArg); 9083 } 9084 9085 // Look for stores of arguments to static allocas. Mark such arguments with a 9086 // flag to ask the target to give us the memory location of that argument if 9087 // available. 9088 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9089 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9090 9091 // Set up the incoming argument description vector. 9092 for (const Argument &Arg : F.args()) { 9093 unsigned ArgNo = Arg.getArgNo(); 9094 SmallVector<EVT, 4> ValueVTs; 9095 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9096 bool isArgValueUsed = !Arg.use_empty(); 9097 unsigned PartBase = 0; 9098 Type *FinalType = Arg.getType(); 9099 if (Arg.hasAttribute(Attribute::ByVal)) 9100 FinalType = cast<PointerType>(FinalType)->getElementType(); 9101 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9102 FinalType, F.getCallingConv(), F.isVarArg()); 9103 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9104 Value != NumValues; ++Value) { 9105 EVT VT = ValueVTs[Value]; 9106 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9107 ISD::ArgFlagsTy Flags; 9108 9109 // Certain targets (such as MIPS), may have a different ABI alignment 9110 // for a type depending on the context. Give the target a chance to 9111 // specify the alignment it wants. 9112 unsigned OriginalAlignment = 9113 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9114 9115 if (Arg.hasAttribute(Attribute::ZExt)) 9116 Flags.setZExt(); 9117 if (Arg.hasAttribute(Attribute::SExt)) 9118 Flags.setSExt(); 9119 if (Arg.hasAttribute(Attribute::InReg)) { 9120 // If we are using vectorcall calling convention, a structure that is 9121 // passed InReg - is surely an HVA 9122 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9123 isa<StructType>(Arg.getType())) { 9124 // The first value of a structure is marked 9125 if (0 == Value) 9126 Flags.setHvaStart(); 9127 Flags.setHva(); 9128 } 9129 // Set InReg Flag 9130 Flags.setInReg(); 9131 } 9132 if (Arg.hasAttribute(Attribute::StructRet)) 9133 Flags.setSRet(); 9134 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9135 Flags.setSwiftSelf(); 9136 if (Arg.hasAttribute(Attribute::SwiftError)) 9137 Flags.setSwiftError(); 9138 if (Arg.hasAttribute(Attribute::ByVal)) 9139 Flags.setByVal(); 9140 if (Arg.hasAttribute(Attribute::InAlloca)) { 9141 Flags.setInAlloca(); 9142 // Set the byval flag for CCAssignFn callbacks that don't know about 9143 // inalloca. This way we can know how many bytes we should've allocated 9144 // and how many bytes a callee cleanup function will pop. If we port 9145 // inalloca to more targets, we'll have to add custom inalloca handling 9146 // in the various CC lowering callbacks. 9147 Flags.setByVal(); 9148 } 9149 if (F.getCallingConv() == CallingConv::X86_INTR) { 9150 // IA Interrupt passes frame (1st parameter) by value in the stack. 9151 if (ArgNo == 0) 9152 Flags.setByVal(); 9153 } 9154 if (Flags.isByVal() || Flags.isInAlloca()) { 9155 PointerType *Ty = cast<PointerType>(Arg.getType()); 9156 Type *ElementTy = Ty->getElementType(); 9157 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9158 // For ByVal, alignment should be passed from FE. BE will guess if 9159 // this info is not there but there are cases it cannot get right. 9160 unsigned FrameAlign; 9161 if (Arg.getParamAlignment()) 9162 FrameAlign = Arg.getParamAlignment(); 9163 else 9164 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9165 Flags.setByValAlign(FrameAlign); 9166 } 9167 if (Arg.hasAttribute(Attribute::Nest)) 9168 Flags.setNest(); 9169 if (NeedsRegBlock) 9170 Flags.setInConsecutiveRegs(); 9171 Flags.setOrigAlign(OriginalAlignment); 9172 if (ArgCopyElisionCandidates.count(&Arg)) 9173 Flags.setCopyElisionCandidate(); 9174 9175 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9176 *CurDAG->getContext(), F.getCallingConv(), VT); 9177 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9178 *CurDAG->getContext(), F.getCallingConv(), VT); 9179 for (unsigned i = 0; i != NumRegs; ++i) { 9180 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9181 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9182 if (NumRegs > 1 && i == 0) 9183 MyFlags.Flags.setSplit(); 9184 // if it isn't first piece, alignment must be 1 9185 else if (i > 0) { 9186 MyFlags.Flags.setOrigAlign(1); 9187 if (i == NumRegs - 1) 9188 MyFlags.Flags.setSplitEnd(); 9189 } 9190 Ins.push_back(MyFlags); 9191 } 9192 if (NeedsRegBlock && Value == NumValues - 1) 9193 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9194 PartBase += VT.getStoreSize(); 9195 } 9196 } 9197 9198 // Call the target to set up the argument values. 9199 SmallVector<SDValue, 8> InVals; 9200 SDValue NewRoot = TLI->LowerFormalArguments( 9201 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9202 9203 // Verify that the target's LowerFormalArguments behaved as expected. 9204 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9205 "LowerFormalArguments didn't return a valid chain!"); 9206 assert(InVals.size() == Ins.size() && 9207 "LowerFormalArguments didn't emit the correct number of values!"); 9208 LLVM_DEBUG({ 9209 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9210 assert(InVals[i].getNode() && 9211 "LowerFormalArguments emitted a null value!"); 9212 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9213 "LowerFormalArguments emitted a value with the wrong type!"); 9214 } 9215 }); 9216 9217 // Update the DAG with the new chain value resulting from argument lowering. 9218 DAG.setRoot(NewRoot); 9219 9220 // Set up the argument values. 9221 unsigned i = 0; 9222 if (!FuncInfo->CanLowerReturn) { 9223 // Create a virtual register for the sret pointer, and put in a copy 9224 // from the sret argument into it. 9225 SmallVector<EVT, 1> ValueVTs; 9226 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9227 F.getReturnType()->getPointerTo( 9228 DAG.getDataLayout().getAllocaAddrSpace()), 9229 ValueVTs); 9230 MVT VT = ValueVTs[0].getSimpleVT(); 9231 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9232 Optional<ISD::NodeType> AssertOp = None; 9233 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9234 nullptr, F.getCallingConv(), AssertOp); 9235 9236 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9237 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9238 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9239 FuncInfo->DemoteRegister = SRetReg; 9240 NewRoot = 9241 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9242 DAG.setRoot(NewRoot); 9243 9244 // i indexes lowered arguments. Bump it past the hidden sret argument. 9245 ++i; 9246 } 9247 9248 SmallVector<SDValue, 4> Chains; 9249 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9250 for (const Argument &Arg : F.args()) { 9251 SmallVector<SDValue, 4> ArgValues; 9252 SmallVector<EVT, 4> ValueVTs; 9253 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9254 unsigned NumValues = ValueVTs.size(); 9255 if (NumValues == 0) 9256 continue; 9257 9258 bool ArgHasUses = !Arg.use_empty(); 9259 9260 // Elide the copying store if the target loaded this argument from a 9261 // suitable fixed stack object. 9262 if (Ins[i].Flags.isCopyElisionCandidate()) { 9263 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9264 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9265 InVals[i], ArgHasUses); 9266 } 9267 9268 // If this argument is unused then remember its value. It is used to generate 9269 // debugging information. 9270 bool isSwiftErrorArg = 9271 TLI->supportSwiftError() && 9272 Arg.hasAttribute(Attribute::SwiftError); 9273 if (!ArgHasUses && !isSwiftErrorArg) { 9274 SDB->setUnusedArgValue(&Arg, InVals[i]); 9275 9276 // Also remember any frame index for use in FastISel. 9277 if (FrameIndexSDNode *FI = 9278 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9279 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9280 } 9281 9282 for (unsigned Val = 0; Val != NumValues; ++Val) { 9283 EVT VT = ValueVTs[Val]; 9284 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9285 F.getCallingConv(), VT); 9286 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9287 *CurDAG->getContext(), F.getCallingConv(), VT); 9288 9289 // Even an apparant 'unused' swifterror argument needs to be returned. So 9290 // we do generate a copy for it that can be used on return from the 9291 // function. 9292 if (ArgHasUses || isSwiftErrorArg) { 9293 Optional<ISD::NodeType> AssertOp; 9294 if (Arg.hasAttribute(Attribute::SExt)) 9295 AssertOp = ISD::AssertSext; 9296 else if (Arg.hasAttribute(Attribute::ZExt)) 9297 AssertOp = ISD::AssertZext; 9298 9299 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9300 PartVT, VT, nullptr, 9301 F.getCallingConv(), AssertOp)); 9302 } 9303 9304 i += NumParts; 9305 } 9306 9307 // We don't need to do anything else for unused arguments. 9308 if (ArgValues.empty()) 9309 continue; 9310 9311 // Note down frame index. 9312 if (FrameIndexSDNode *FI = 9313 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9314 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9315 9316 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9317 SDB->getCurSDLoc()); 9318 9319 SDB->setValue(&Arg, Res); 9320 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9321 // We want to associate the argument with the frame index, among 9322 // involved operands, that correspond to the lowest address. The 9323 // getCopyFromParts function, called earlier, is swapping the order of 9324 // the operands to BUILD_PAIR depending on endianness. The result of 9325 // that swapping is that the least significant bits of the argument will 9326 // be in the first operand of the BUILD_PAIR node, and the most 9327 // significant bits will be in the second operand. 9328 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9329 if (LoadSDNode *LNode = 9330 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9331 if (FrameIndexSDNode *FI = 9332 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9333 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9334 } 9335 9336 // Update the SwiftErrorVRegDefMap. 9337 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9338 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9339 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9340 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9341 FuncInfo->SwiftErrorArg, Reg); 9342 } 9343 9344 // If this argument is live outside of the entry block, insert a copy from 9345 // wherever we got it to the vreg that other BB's will reference it as. 9346 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9347 // If we can, though, try to skip creating an unnecessary vreg. 9348 // FIXME: This isn't very clean... it would be nice to make this more 9349 // general. It's also subtly incompatible with the hacks FastISel 9350 // uses with vregs. 9351 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9352 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9353 FuncInfo->ValueMap[&Arg] = Reg; 9354 continue; 9355 } 9356 } 9357 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9358 FuncInfo->InitializeRegForValue(&Arg); 9359 SDB->CopyToExportRegsIfNeeded(&Arg); 9360 } 9361 } 9362 9363 if (!Chains.empty()) { 9364 Chains.push_back(NewRoot); 9365 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9366 } 9367 9368 DAG.setRoot(NewRoot); 9369 9370 assert(i == InVals.size() && "Argument register count mismatch!"); 9371 9372 // If any argument copy elisions occurred and we have debug info, update the 9373 // stale frame indices used in the dbg.declare variable info table. 9374 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9375 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9376 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9377 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9378 if (I != ArgCopyElisionFrameIndexMap.end()) 9379 VI.Slot = I->second; 9380 } 9381 } 9382 9383 // Finally, if the target has anything special to do, allow it to do so. 9384 EmitFunctionEntryCode(); 9385 } 9386 9387 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9388 /// ensure constants are generated when needed. Remember the virtual registers 9389 /// that need to be added to the Machine PHI nodes as input. We cannot just 9390 /// directly add them, because expansion might result in multiple MBB's for one 9391 /// BB. As such, the start of the BB might correspond to a different MBB than 9392 /// the end. 9393 void 9394 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9395 const Instruction *TI = LLVMBB->getTerminator(); 9396 9397 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9398 9399 // Check PHI nodes in successors that expect a value to be available from this 9400 // block. 9401 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9402 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9403 if (!isa<PHINode>(SuccBB->begin())) continue; 9404 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9405 9406 // If this terminator has multiple identical successors (common for 9407 // switches), only handle each succ once. 9408 if (!SuccsHandled.insert(SuccMBB).second) 9409 continue; 9410 9411 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9412 9413 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9414 // nodes and Machine PHI nodes, but the incoming operands have not been 9415 // emitted yet. 9416 for (const PHINode &PN : SuccBB->phis()) { 9417 // Ignore dead phi's. 9418 if (PN.use_empty()) 9419 continue; 9420 9421 // Skip empty types 9422 if (PN.getType()->isEmptyTy()) 9423 continue; 9424 9425 unsigned Reg; 9426 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9427 9428 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9429 unsigned &RegOut = ConstantsOut[C]; 9430 if (RegOut == 0) { 9431 RegOut = FuncInfo.CreateRegs(C->getType()); 9432 CopyValueToVirtualRegister(C, RegOut); 9433 } 9434 Reg = RegOut; 9435 } else { 9436 DenseMap<const Value *, unsigned>::iterator I = 9437 FuncInfo.ValueMap.find(PHIOp); 9438 if (I != FuncInfo.ValueMap.end()) 9439 Reg = I->second; 9440 else { 9441 assert(isa<AllocaInst>(PHIOp) && 9442 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9443 "Didn't codegen value into a register!??"); 9444 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9445 CopyValueToVirtualRegister(PHIOp, Reg); 9446 } 9447 } 9448 9449 // Remember that this register needs to added to the machine PHI node as 9450 // the input for this MBB. 9451 SmallVector<EVT, 4> ValueVTs; 9452 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9453 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9454 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9455 EVT VT = ValueVTs[vti]; 9456 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9457 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9458 FuncInfo.PHINodesToUpdate.push_back( 9459 std::make_pair(&*MBBI++, Reg + i)); 9460 Reg += NumRegisters; 9461 } 9462 } 9463 } 9464 9465 ConstantsOut.clear(); 9466 } 9467 9468 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9469 /// is 0. 9470 MachineBasicBlock * 9471 SelectionDAGBuilder::StackProtectorDescriptor:: 9472 AddSuccessorMBB(const BasicBlock *BB, 9473 MachineBasicBlock *ParentMBB, 9474 bool IsLikely, 9475 MachineBasicBlock *SuccMBB) { 9476 // If SuccBB has not been created yet, create it. 9477 if (!SuccMBB) { 9478 MachineFunction *MF = ParentMBB->getParent(); 9479 MachineFunction::iterator BBI(ParentMBB); 9480 SuccMBB = MF->CreateMachineBasicBlock(BB); 9481 MF->insert(++BBI, SuccMBB); 9482 } 9483 // Add it as a successor of ParentMBB. 9484 ParentMBB->addSuccessor( 9485 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9486 return SuccMBB; 9487 } 9488 9489 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9490 MachineFunction::iterator I(MBB); 9491 if (++I == FuncInfo.MF->end()) 9492 return nullptr; 9493 return &*I; 9494 } 9495 9496 /// During lowering new call nodes can be created (such as memset, etc.). 9497 /// Those will become new roots of the current DAG, but complications arise 9498 /// when they are tail calls. In such cases, the call lowering will update 9499 /// the root, but the builder still needs to know that a tail call has been 9500 /// lowered in order to avoid generating an additional return. 9501 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9502 // If the node is null, we do have a tail call. 9503 if (MaybeTC.getNode() != nullptr) 9504 DAG.setRoot(MaybeTC); 9505 else 9506 HasTailCall = true; 9507 } 9508 9509 uint64_t 9510 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9511 unsigned First, unsigned Last) const { 9512 assert(Last >= First); 9513 const APInt &LowCase = Clusters[First].Low->getValue(); 9514 const APInt &HighCase = Clusters[Last].High->getValue(); 9515 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9516 9517 // FIXME: A range of consecutive cases has 100% density, but only requires one 9518 // comparison to lower. We should discriminate against such consecutive ranges 9519 // in jump tables. 9520 9521 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9522 } 9523 9524 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9525 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9526 unsigned Last) const { 9527 assert(Last >= First); 9528 assert(TotalCases[Last] >= TotalCases[First]); 9529 uint64_t NumCases = 9530 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9531 return NumCases; 9532 } 9533 9534 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9535 unsigned First, unsigned Last, 9536 const SwitchInst *SI, 9537 MachineBasicBlock *DefaultMBB, 9538 CaseCluster &JTCluster) { 9539 assert(First <= Last); 9540 9541 auto Prob = BranchProbability::getZero(); 9542 unsigned NumCmps = 0; 9543 std::vector<MachineBasicBlock*> Table; 9544 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9545 9546 // Initialize probabilities in JTProbs. 9547 for (unsigned I = First; I <= Last; ++I) 9548 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9549 9550 for (unsigned I = First; I <= Last; ++I) { 9551 assert(Clusters[I].Kind == CC_Range); 9552 Prob += Clusters[I].Prob; 9553 const APInt &Low = Clusters[I].Low->getValue(); 9554 const APInt &High = Clusters[I].High->getValue(); 9555 NumCmps += (Low == High) ? 1 : 2; 9556 if (I != First) { 9557 // Fill the gap between this and the previous cluster. 9558 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9559 assert(PreviousHigh.slt(Low)); 9560 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9561 for (uint64_t J = 0; J < Gap; J++) 9562 Table.push_back(DefaultMBB); 9563 } 9564 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9565 for (uint64_t J = 0; J < ClusterSize; ++J) 9566 Table.push_back(Clusters[I].MBB); 9567 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9568 } 9569 9570 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9571 unsigned NumDests = JTProbs.size(); 9572 if (TLI.isSuitableForBitTests( 9573 NumDests, NumCmps, Clusters[First].Low->getValue(), 9574 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9575 // Clusters[First..Last] should be lowered as bit tests instead. 9576 return false; 9577 } 9578 9579 // Create the MBB that will load from and jump through the table. 9580 // Note: We create it here, but it's not inserted into the function yet. 9581 MachineFunction *CurMF = FuncInfo.MF; 9582 MachineBasicBlock *JumpTableMBB = 9583 CurMF->CreateMachineBasicBlock(SI->getParent()); 9584 9585 // Add successors. Note: use table order for determinism. 9586 SmallPtrSet<MachineBasicBlock *, 8> Done; 9587 for (MachineBasicBlock *Succ : Table) { 9588 if (Done.count(Succ)) 9589 continue; 9590 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9591 Done.insert(Succ); 9592 } 9593 JumpTableMBB->normalizeSuccProbs(); 9594 9595 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9596 ->createJumpTableIndex(Table); 9597 9598 // Set up the jump table info. 9599 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9600 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9601 Clusters[Last].High->getValue(), SI->getCondition(), 9602 nullptr, false); 9603 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9604 9605 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9606 JTCases.size() - 1, Prob); 9607 return true; 9608 } 9609 9610 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9611 const SwitchInst *SI, 9612 MachineBasicBlock *DefaultMBB) { 9613 #ifndef NDEBUG 9614 // Clusters must be non-empty, sorted, and only contain Range clusters. 9615 assert(!Clusters.empty()); 9616 for (CaseCluster &C : Clusters) 9617 assert(C.Kind == CC_Range); 9618 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9619 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9620 #endif 9621 9622 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9623 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9624 return; 9625 9626 const int64_t N = Clusters.size(); 9627 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9628 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9629 9630 if (N < 2 || N < MinJumpTableEntries) 9631 return; 9632 9633 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9634 SmallVector<unsigned, 8> TotalCases(N); 9635 for (unsigned i = 0; i < N; ++i) { 9636 const APInt &Hi = Clusters[i].High->getValue(); 9637 const APInt &Lo = Clusters[i].Low->getValue(); 9638 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9639 if (i != 0) 9640 TotalCases[i] += TotalCases[i - 1]; 9641 } 9642 9643 // Cheap case: the whole range may be suitable for jump table. 9644 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9645 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9646 assert(NumCases < UINT64_MAX / 100); 9647 assert(Range >= NumCases); 9648 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9649 CaseCluster JTCluster; 9650 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9651 Clusters[0] = JTCluster; 9652 Clusters.resize(1); 9653 return; 9654 } 9655 } 9656 9657 // The algorithm below is not suitable for -O0. 9658 if (TM.getOptLevel() == CodeGenOpt::None) 9659 return; 9660 9661 // Split Clusters into minimum number of dense partitions. The algorithm uses 9662 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9663 // for the Case Statement'" (1994), but builds the MinPartitions array in 9664 // reverse order to make it easier to reconstruct the partitions in ascending 9665 // order. In the choice between two optimal partitionings, it picks the one 9666 // which yields more jump tables. 9667 9668 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9669 SmallVector<unsigned, 8> MinPartitions(N); 9670 // LastElement[i] is the last element of the partition starting at i. 9671 SmallVector<unsigned, 8> LastElement(N); 9672 // PartitionsScore[i] is used to break ties when choosing between two 9673 // partitionings resulting in the same number of partitions. 9674 SmallVector<unsigned, 8> PartitionsScore(N); 9675 // For PartitionsScore, a small number of comparisons is considered as good as 9676 // a jump table and a single comparison is considered better than a jump 9677 // table. 9678 enum PartitionScores : unsigned { 9679 NoTable = 0, 9680 Table = 1, 9681 FewCases = 1, 9682 SingleCase = 2 9683 }; 9684 9685 // Base case: There is only one way to partition Clusters[N-1]. 9686 MinPartitions[N - 1] = 1; 9687 LastElement[N - 1] = N - 1; 9688 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9689 9690 // Note: loop indexes are signed to avoid underflow. 9691 for (int64_t i = N - 2; i >= 0; i--) { 9692 // Find optimal partitioning of Clusters[i..N-1]. 9693 // Baseline: Put Clusters[i] into a partition on its own. 9694 MinPartitions[i] = MinPartitions[i + 1] + 1; 9695 LastElement[i] = i; 9696 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9697 9698 // Search for a solution that results in fewer partitions. 9699 for (int64_t j = N - 1; j > i; j--) { 9700 // Try building a partition from Clusters[i..j]. 9701 uint64_t Range = getJumpTableRange(Clusters, i, j); 9702 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9703 assert(NumCases < UINT64_MAX / 100); 9704 assert(Range >= NumCases); 9705 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9706 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9707 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9708 int64_t NumEntries = j - i + 1; 9709 9710 if (NumEntries == 1) 9711 Score += PartitionScores::SingleCase; 9712 else if (NumEntries <= SmallNumberOfEntries) 9713 Score += PartitionScores::FewCases; 9714 else if (NumEntries >= MinJumpTableEntries) 9715 Score += PartitionScores::Table; 9716 9717 // If this leads to fewer partitions, or to the same number of 9718 // partitions with better score, it is a better partitioning. 9719 if (NumPartitions < MinPartitions[i] || 9720 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9721 MinPartitions[i] = NumPartitions; 9722 LastElement[i] = j; 9723 PartitionsScore[i] = Score; 9724 } 9725 } 9726 } 9727 } 9728 9729 // Iterate over the partitions, replacing some with jump tables in-place. 9730 unsigned DstIndex = 0; 9731 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9732 Last = LastElement[First]; 9733 assert(Last >= First); 9734 assert(DstIndex <= First); 9735 unsigned NumClusters = Last - First + 1; 9736 9737 CaseCluster JTCluster; 9738 if (NumClusters >= MinJumpTableEntries && 9739 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9740 Clusters[DstIndex++] = JTCluster; 9741 } else { 9742 for (unsigned I = First; I <= Last; ++I) 9743 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9744 } 9745 } 9746 Clusters.resize(DstIndex); 9747 } 9748 9749 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9750 unsigned First, unsigned Last, 9751 const SwitchInst *SI, 9752 CaseCluster &BTCluster) { 9753 assert(First <= Last); 9754 if (First == Last) 9755 return false; 9756 9757 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9758 unsigned NumCmps = 0; 9759 for (int64_t I = First; I <= Last; ++I) { 9760 assert(Clusters[I].Kind == CC_Range); 9761 Dests.set(Clusters[I].MBB->getNumber()); 9762 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9763 } 9764 unsigned NumDests = Dests.count(); 9765 9766 APInt Low = Clusters[First].Low->getValue(); 9767 APInt High = Clusters[Last].High->getValue(); 9768 assert(Low.slt(High)); 9769 9770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9771 const DataLayout &DL = DAG.getDataLayout(); 9772 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9773 return false; 9774 9775 APInt LowBound; 9776 APInt CmpRange; 9777 9778 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9779 assert(TLI.rangeFitsInWord(Low, High, DL) && 9780 "Case range must fit in bit mask!"); 9781 9782 // Check if the clusters cover a contiguous range such that no value in the 9783 // range will jump to the default statement. 9784 bool ContiguousRange = true; 9785 for (int64_t I = First + 1; I <= Last; ++I) { 9786 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9787 ContiguousRange = false; 9788 break; 9789 } 9790 } 9791 9792 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9793 // Optimize the case where all the case values fit in a word without having 9794 // to subtract minValue. In this case, we can optimize away the subtraction. 9795 LowBound = APInt::getNullValue(Low.getBitWidth()); 9796 CmpRange = High; 9797 ContiguousRange = false; 9798 } else { 9799 LowBound = Low; 9800 CmpRange = High - Low; 9801 } 9802 9803 CaseBitsVector CBV; 9804 auto TotalProb = BranchProbability::getZero(); 9805 for (unsigned i = First; i <= Last; ++i) { 9806 // Find the CaseBits for this destination. 9807 unsigned j; 9808 for (j = 0; j < CBV.size(); ++j) 9809 if (CBV[j].BB == Clusters[i].MBB) 9810 break; 9811 if (j == CBV.size()) 9812 CBV.push_back( 9813 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9814 CaseBits *CB = &CBV[j]; 9815 9816 // Update Mask, Bits and ExtraProb. 9817 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9818 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9819 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9820 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9821 CB->Bits += Hi - Lo + 1; 9822 CB->ExtraProb += Clusters[i].Prob; 9823 TotalProb += Clusters[i].Prob; 9824 } 9825 9826 BitTestInfo BTI; 9827 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9828 // Sort by probability first, number of bits second, bit mask third. 9829 if (a.ExtraProb != b.ExtraProb) 9830 return a.ExtraProb > b.ExtraProb; 9831 if (a.Bits != b.Bits) 9832 return a.Bits > b.Bits; 9833 return a.Mask < b.Mask; 9834 }); 9835 9836 for (auto &CB : CBV) { 9837 MachineBasicBlock *BitTestBB = 9838 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9839 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9840 } 9841 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9842 SI->getCondition(), -1U, MVT::Other, false, 9843 ContiguousRange, nullptr, nullptr, std::move(BTI), 9844 TotalProb); 9845 9846 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9847 BitTestCases.size() - 1, TotalProb); 9848 return true; 9849 } 9850 9851 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9852 const SwitchInst *SI) { 9853 // Partition Clusters into as few subsets as possible, where each subset has a 9854 // range that fits in a machine word and has <= 3 unique destinations. 9855 9856 #ifndef NDEBUG 9857 // Clusters must be sorted and contain Range or JumpTable clusters. 9858 assert(!Clusters.empty()); 9859 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9860 for (const CaseCluster &C : Clusters) 9861 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9862 for (unsigned i = 1; i < Clusters.size(); ++i) 9863 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9864 #endif 9865 9866 // The algorithm below is not suitable for -O0. 9867 if (TM.getOptLevel() == CodeGenOpt::None) 9868 return; 9869 9870 // If target does not have legal shift left, do not emit bit tests at all. 9871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9872 const DataLayout &DL = DAG.getDataLayout(); 9873 9874 EVT PTy = TLI.getPointerTy(DL); 9875 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9876 return; 9877 9878 int BitWidth = PTy.getSizeInBits(); 9879 const int64_t N = Clusters.size(); 9880 9881 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9882 SmallVector<unsigned, 8> MinPartitions(N); 9883 // LastElement[i] is the last element of the partition starting at i. 9884 SmallVector<unsigned, 8> LastElement(N); 9885 9886 // FIXME: This might not be the best algorithm for finding bit test clusters. 9887 9888 // Base case: There is only one way to partition Clusters[N-1]. 9889 MinPartitions[N - 1] = 1; 9890 LastElement[N - 1] = N - 1; 9891 9892 // Note: loop indexes are signed to avoid underflow. 9893 for (int64_t i = N - 2; i >= 0; --i) { 9894 // Find optimal partitioning of Clusters[i..N-1]. 9895 // Baseline: Put Clusters[i] into a partition on its own. 9896 MinPartitions[i] = MinPartitions[i + 1] + 1; 9897 LastElement[i] = i; 9898 9899 // Search for a solution that results in fewer partitions. 9900 // Note: the search is limited by BitWidth, reducing time complexity. 9901 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9902 // Try building a partition from Clusters[i..j]. 9903 9904 // Check the range. 9905 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9906 Clusters[j].High->getValue(), DL)) 9907 continue; 9908 9909 // Check nbr of destinations and cluster types. 9910 // FIXME: This works, but doesn't seem very efficient. 9911 bool RangesOnly = true; 9912 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9913 for (int64_t k = i; k <= j; k++) { 9914 if (Clusters[k].Kind != CC_Range) { 9915 RangesOnly = false; 9916 break; 9917 } 9918 Dests.set(Clusters[k].MBB->getNumber()); 9919 } 9920 if (!RangesOnly || Dests.count() > 3) 9921 break; 9922 9923 // Check if it's a better partition. 9924 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9925 if (NumPartitions < MinPartitions[i]) { 9926 // Found a better partition. 9927 MinPartitions[i] = NumPartitions; 9928 LastElement[i] = j; 9929 } 9930 } 9931 } 9932 9933 // Iterate over the partitions, replacing with bit-test clusters in-place. 9934 unsigned DstIndex = 0; 9935 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9936 Last = LastElement[First]; 9937 assert(First <= Last); 9938 assert(DstIndex <= First); 9939 9940 CaseCluster BitTestCluster; 9941 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9942 Clusters[DstIndex++] = BitTestCluster; 9943 } else { 9944 size_t NumClusters = Last - First + 1; 9945 std::memmove(&Clusters[DstIndex], &Clusters[First], 9946 sizeof(Clusters[0]) * NumClusters); 9947 DstIndex += NumClusters; 9948 } 9949 } 9950 Clusters.resize(DstIndex); 9951 } 9952 9953 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9954 MachineBasicBlock *SwitchMBB, 9955 MachineBasicBlock *DefaultMBB) { 9956 MachineFunction *CurMF = FuncInfo.MF; 9957 MachineBasicBlock *NextMBB = nullptr; 9958 MachineFunction::iterator BBI(W.MBB); 9959 if (++BBI != FuncInfo.MF->end()) 9960 NextMBB = &*BBI; 9961 9962 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9963 9964 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9965 9966 if (Size == 2 && W.MBB == SwitchMBB) { 9967 // If any two of the cases has the same destination, and if one value 9968 // is the same as the other, but has one bit unset that the other has set, 9969 // use bit manipulation to do two compares at once. For example: 9970 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9971 // TODO: This could be extended to merge any 2 cases in switches with 3 9972 // cases. 9973 // TODO: Handle cases where W.CaseBB != SwitchBB. 9974 CaseCluster &Small = *W.FirstCluster; 9975 CaseCluster &Big = *W.LastCluster; 9976 9977 if (Small.Low == Small.High && Big.Low == Big.High && 9978 Small.MBB == Big.MBB) { 9979 const APInt &SmallValue = Small.Low->getValue(); 9980 const APInt &BigValue = Big.Low->getValue(); 9981 9982 // Check that there is only one bit different. 9983 APInt CommonBit = BigValue ^ SmallValue; 9984 if (CommonBit.isPowerOf2()) { 9985 SDValue CondLHS = getValue(Cond); 9986 EVT VT = CondLHS.getValueType(); 9987 SDLoc DL = getCurSDLoc(); 9988 9989 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9990 DAG.getConstant(CommonBit, DL, VT)); 9991 SDValue Cond = DAG.getSetCC( 9992 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9993 ISD::SETEQ); 9994 9995 // Update successor info. 9996 // Both Small and Big will jump to Small.BB, so we sum up the 9997 // probabilities. 9998 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9999 if (BPI) 10000 addSuccessorWithProb( 10001 SwitchMBB, DefaultMBB, 10002 // The default destination is the first successor in IR. 10003 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10004 else 10005 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10006 10007 // Insert the true branch. 10008 SDValue BrCond = 10009 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10010 DAG.getBasicBlock(Small.MBB)); 10011 // Insert the false branch. 10012 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10013 DAG.getBasicBlock(DefaultMBB)); 10014 10015 DAG.setRoot(BrCond); 10016 return; 10017 } 10018 } 10019 } 10020 10021 if (TM.getOptLevel() != CodeGenOpt::None) { 10022 // Here, we order cases by probability so the most likely case will be 10023 // checked first. However, two clusters can have the same probability in 10024 // which case their relative ordering is non-deterministic. So we use Low 10025 // as a tie-breaker as clusters are guaranteed to never overlap. 10026 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10027 [](const CaseCluster &a, const CaseCluster &b) { 10028 return a.Prob != b.Prob ? 10029 a.Prob > b.Prob : 10030 a.Low->getValue().slt(b.Low->getValue()); 10031 }); 10032 10033 // Rearrange the case blocks so that the last one falls through if possible 10034 // without changing the order of probabilities. 10035 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10036 --I; 10037 if (I->Prob > W.LastCluster->Prob) 10038 break; 10039 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10040 std::swap(*I, *W.LastCluster); 10041 break; 10042 } 10043 } 10044 } 10045 10046 // Compute total probability. 10047 BranchProbability DefaultProb = W.DefaultProb; 10048 BranchProbability UnhandledProbs = DefaultProb; 10049 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10050 UnhandledProbs += I->Prob; 10051 10052 MachineBasicBlock *CurMBB = W.MBB; 10053 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10054 MachineBasicBlock *Fallthrough; 10055 if (I == W.LastCluster) { 10056 // For the last cluster, fall through to the default destination. 10057 Fallthrough = DefaultMBB; 10058 } else { 10059 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10060 CurMF->insert(BBI, Fallthrough); 10061 // Put Cond in a virtual register to make it available from the new blocks. 10062 ExportFromCurrentBlock(Cond); 10063 } 10064 UnhandledProbs -= I->Prob; 10065 10066 switch (I->Kind) { 10067 case CC_JumpTable: { 10068 // FIXME: Optimize away range check based on pivot comparisons. 10069 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10070 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10071 10072 // The jump block hasn't been inserted yet; insert it here. 10073 MachineBasicBlock *JumpMBB = JT->MBB; 10074 CurMF->insert(BBI, JumpMBB); 10075 10076 auto JumpProb = I->Prob; 10077 auto FallthroughProb = UnhandledProbs; 10078 10079 // If the default statement is a target of the jump table, we evenly 10080 // distribute the default probability to successors of CurMBB. Also 10081 // update the probability on the edge from JumpMBB to Fallthrough. 10082 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10083 SE = JumpMBB->succ_end(); 10084 SI != SE; ++SI) { 10085 if (*SI == DefaultMBB) { 10086 JumpProb += DefaultProb / 2; 10087 FallthroughProb -= DefaultProb / 2; 10088 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10089 JumpMBB->normalizeSuccProbs(); 10090 break; 10091 } 10092 } 10093 10094 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10095 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10096 CurMBB->normalizeSuccProbs(); 10097 10098 // The jump table header will be inserted in our current block, do the 10099 // range check, and fall through to our fallthrough block. 10100 JTH->HeaderBB = CurMBB; 10101 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10102 10103 // If we're in the right place, emit the jump table header right now. 10104 if (CurMBB == SwitchMBB) { 10105 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10106 JTH->Emitted = true; 10107 } 10108 break; 10109 } 10110 case CC_BitTests: { 10111 // FIXME: Optimize away range check based on pivot comparisons. 10112 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10113 10114 // The bit test blocks haven't been inserted yet; insert them here. 10115 for (BitTestCase &BTC : BTB->Cases) 10116 CurMF->insert(BBI, BTC.ThisBB); 10117 10118 // Fill in fields of the BitTestBlock. 10119 BTB->Parent = CurMBB; 10120 BTB->Default = Fallthrough; 10121 10122 BTB->DefaultProb = UnhandledProbs; 10123 // If the cases in bit test don't form a contiguous range, we evenly 10124 // distribute the probability on the edge to Fallthrough to two 10125 // successors of CurMBB. 10126 if (!BTB->ContiguousRange) { 10127 BTB->Prob += DefaultProb / 2; 10128 BTB->DefaultProb -= DefaultProb / 2; 10129 } 10130 10131 // If we're in the right place, emit the bit test header right now. 10132 if (CurMBB == SwitchMBB) { 10133 visitBitTestHeader(*BTB, SwitchMBB); 10134 BTB->Emitted = true; 10135 } 10136 break; 10137 } 10138 case CC_Range: { 10139 const Value *RHS, *LHS, *MHS; 10140 ISD::CondCode CC; 10141 if (I->Low == I->High) { 10142 // Check Cond == I->Low. 10143 CC = ISD::SETEQ; 10144 LHS = Cond; 10145 RHS=I->Low; 10146 MHS = nullptr; 10147 } else { 10148 // Check I->Low <= Cond <= I->High. 10149 CC = ISD::SETLE; 10150 LHS = I->Low; 10151 MHS = Cond; 10152 RHS = I->High; 10153 } 10154 10155 // The false probability is the sum of all unhandled cases. 10156 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10157 getCurSDLoc(), I->Prob, UnhandledProbs); 10158 10159 if (CurMBB == SwitchMBB) 10160 visitSwitchCase(CB, SwitchMBB); 10161 else 10162 SwitchCases.push_back(CB); 10163 10164 break; 10165 } 10166 } 10167 CurMBB = Fallthrough; 10168 } 10169 } 10170 10171 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10172 CaseClusterIt First, 10173 CaseClusterIt Last) { 10174 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10175 if (X.Prob != CC.Prob) 10176 return X.Prob > CC.Prob; 10177 10178 // Ties are broken by comparing the case value. 10179 return X.Low->getValue().slt(CC.Low->getValue()); 10180 }); 10181 } 10182 10183 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10184 const SwitchWorkListItem &W, 10185 Value *Cond, 10186 MachineBasicBlock *SwitchMBB) { 10187 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10188 "Clusters not sorted?"); 10189 10190 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10191 10192 // Balance the tree based on branch probabilities to create a near-optimal (in 10193 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10194 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10195 CaseClusterIt LastLeft = W.FirstCluster; 10196 CaseClusterIt FirstRight = W.LastCluster; 10197 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10198 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10199 10200 // Move LastLeft and FirstRight towards each other from opposite directions to 10201 // find a partitioning of the clusters which balances the probability on both 10202 // sides. If LeftProb and RightProb are equal, alternate which side is 10203 // taken to ensure 0-probability nodes are distributed evenly. 10204 unsigned I = 0; 10205 while (LastLeft + 1 < FirstRight) { 10206 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10207 LeftProb += (++LastLeft)->Prob; 10208 else 10209 RightProb += (--FirstRight)->Prob; 10210 I++; 10211 } 10212 10213 while (true) { 10214 // Our binary search tree differs from a typical BST in that ours can have up 10215 // to three values in each leaf. The pivot selection above doesn't take that 10216 // into account, which means the tree might require more nodes and be less 10217 // efficient. We compensate for this here. 10218 10219 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10220 unsigned NumRight = W.LastCluster - FirstRight + 1; 10221 10222 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10223 // If one side has less than 3 clusters, and the other has more than 3, 10224 // consider taking a cluster from the other side. 10225 10226 if (NumLeft < NumRight) { 10227 // Consider moving the first cluster on the right to the left side. 10228 CaseCluster &CC = *FirstRight; 10229 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10230 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10231 if (LeftSideRank <= RightSideRank) { 10232 // Moving the cluster to the left does not demote it. 10233 ++LastLeft; 10234 ++FirstRight; 10235 continue; 10236 } 10237 } else { 10238 assert(NumRight < NumLeft); 10239 // Consider moving the last element on the left to the right side. 10240 CaseCluster &CC = *LastLeft; 10241 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10242 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10243 if (RightSideRank <= LeftSideRank) { 10244 // Moving the cluster to the right does not demot it. 10245 --LastLeft; 10246 --FirstRight; 10247 continue; 10248 } 10249 } 10250 } 10251 break; 10252 } 10253 10254 assert(LastLeft + 1 == FirstRight); 10255 assert(LastLeft >= W.FirstCluster); 10256 assert(FirstRight <= W.LastCluster); 10257 10258 // Use the first element on the right as pivot since we will make less-than 10259 // comparisons against it. 10260 CaseClusterIt PivotCluster = FirstRight; 10261 assert(PivotCluster > W.FirstCluster); 10262 assert(PivotCluster <= W.LastCluster); 10263 10264 CaseClusterIt FirstLeft = W.FirstCluster; 10265 CaseClusterIt LastRight = W.LastCluster; 10266 10267 const ConstantInt *Pivot = PivotCluster->Low; 10268 10269 // New blocks will be inserted immediately after the current one. 10270 MachineFunction::iterator BBI(W.MBB); 10271 ++BBI; 10272 10273 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10274 // we can branch to its destination directly if it's squeezed exactly in 10275 // between the known lower bound and Pivot - 1. 10276 MachineBasicBlock *LeftMBB; 10277 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10278 FirstLeft->Low == W.GE && 10279 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10280 LeftMBB = FirstLeft->MBB; 10281 } else { 10282 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10283 FuncInfo.MF->insert(BBI, LeftMBB); 10284 WorkList.push_back( 10285 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10286 // Put Cond in a virtual register to make it available from the new blocks. 10287 ExportFromCurrentBlock(Cond); 10288 } 10289 10290 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10291 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10292 // directly if RHS.High equals the current upper bound. 10293 MachineBasicBlock *RightMBB; 10294 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10295 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10296 RightMBB = FirstRight->MBB; 10297 } else { 10298 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10299 FuncInfo.MF->insert(BBI, RightMBB); 10300 WorkList.push_back( 10301 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10302 // Put Cond in a virtual register to make it available from the new blocks. 10303 ExportFromCurrentBlock(Cond); 10304 } 10305 10306 // Create the CaseBlock record that will be used to lower the branch. 10307 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10308 getCurSDLoc(), LeftProb, RightProb); 10309 10310 if (W.MBB == SwitchMBB) 10311 visitSwitchCase(CB, SwitchMBB); 10312 else 10313 SwitchCases.push_back(CB); 10314 } 10315 10316 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10317 // from the swith statement. 10318 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10319 BranchProbability PeeledCaseProb) { 10320 if (PeeledCaseProb == BranchProbability::getOne()) 10321 return BranchProbability::getZero(); 10322 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10323 10324 uint32_t Numerator = CaseProb.getNumerator(); 10325 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10326 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10327 } 10328 10329 // Try to peel the top probability case if it exceeds the threshold. 10330 // Return current MachineBasicBlock for the switch statement if the peeling 10331 // does not occur. 10332 // If the peeling is performed, return the newly created MachineBasicBlock 10333 // for the peeled switch statement. Also update Clusters to remove the peeled 10334 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10335 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10336 const SwitchInst &SI, CaseClusterVector &Clusters, 10337 BranchProbability &PeeledCaseProb) { 10338 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10339 // Don't perform if there is only one cluster or optimizing for size. 10340 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10341 TM.getOptLevel() == CodeGenOpt::None || 10342 SwitchMBB->getParent()->getFunction().optForMinSize()) 10343 return SwitchMBB; 10344 10345 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10346 unsigned PeeledCaseIndex = 0; 10347 bool SwitchPeeled = false; 10348 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10349 CaseCluster &CC = Clusters[Index]; 10350 if (CC.Prob < TopCaseProb) 10351 continue; 10352 TopCaseProb = CC.Prob; 10353 PeeledCaseIndex = Index; 10354 SwitchPeeled = true; 10355 } 10356 if (!SwitchPeeled) 10357 return SwitchMBB; 10358 10359 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10360 << TopCaseProb << "\n"); 10361 10362 // Record the MBB for the peeled switch statement. 10363 MachineFunction::iterator BBI(SwitchMBB); 10364 ++BBI; 10365 MachineBasicBlock *PeeledSwitchMBB = 10366 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10367 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10368 10369 ExportFromCurrentBlock(SI.getCondition()); 10370 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10371 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10372 nullptr, nullptr, TopCaseProb.getCompl()}; 10373 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10374 10375 Clusters.erase(PeeledCaseIt); 10376 for (CaseCluster &CC : Clusters) { 10377 LLVM_DEBUG( 10378 dbgs() << "Scale the probablity for one cluster, before scaling: " 10379 << CC.Prob << "\n"); 10380 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10381 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10382 } 10383 PeeledCaseProb = TopCaseProb; 10384 return PeeledSwitchMBB; 10385 } 10386 10387 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10388 // Extract cases from the switch. 10389 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10390 CaseClusterVector Clusters; 10391 Clusters.reserve(SI.getNumCases()); 10392 for (auto I : SI.cases()) { 10393 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10394 const ConstantInt *CaseVal = I.getCaseValue(); 10395 BranchProbability Prob = 10396 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10397 : BranchProbability(1, SI.getNumCases() + 1); 10398 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10399 } 10400 10401 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10402 10403 // Cluster adjacent cases with the same destination. We do this at all 10404 // optimization levels because it's cheap to do and will make codegen faster 10405 // if there are many clusters. 10406 sortAndRangeify(Clusters); 10407 10408 if (TM.getOptLevel() != CodeGenOpt::None) { 10409 // Replace an unreachable default with the most popular destination. 10410 // FIXME: Exploit unreachable default more aggressively. 10411 bool UnreachableDefault = 10412 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10413 if (UnreachableDefault && !Clusters.empty()) { 10414 DenseMap<const BasicBlock *, unsigned> Popularity; 10415 unsigned MaxPop = 0; 10416 const BasicBlock *MaxBB = nullptr; 10417 for (auto I : SI.cases()) { 10418 const BasicBlock *BB = I.getCaseSuccessor(); 10419 if (++Popularity[BB] > MaxPop) { 10420 MaxPop = Popularity[BB]; 10421 MaxBB = BB; 10422 } 10423 } 10424 // Set new default. 10425 assert(MaxPop > 0 && MaxBB); 10426 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10427 10428 // Remove cases that were pointing to the destination that is now the 10429 // default. 10430 CaseClusterVector New; 10431 New.reserve(Clusters.size()); 10432 for (CaseCluster &CC : Clusters) { 10433 if (CC.MBB != DefaultMBB) 10434 New.push_back(CC); 10435 } 10436 Clusters = std::move(New); 10437 } 10438 } 10439 10440 // The branch probablity of the peeled case. 10441 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10442 MachineBasicBlock *PeeledSwitchMBB = 10443 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10444 10445 // If there is only the default destination, jump there directly. 10446 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10447 if (Clusters.empty()) { 10448 assert(PeeledSwitchMBB == SwitchMBB); 10449 SwitchMBB->addSuccessor(DefaultMBB); 10450 if (DefaultMBB != NextBlock(SwitchMBB)) { 10451 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10452 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10453 } 10454 return; 10455 } 10456 10457 findJumpTables(Clusters, &SI, DefaultMBB); 10458 findBitTestClusters(Clusters, &SI); 10459 10460 LLVM_DEBUG({ 10461 dbgs() << "Case clusters: "; 10462 for (const CaseCluster &C : Clusters) { 10463 if (C.Kind == CC_JumpTable) 10464 dbgs() << "JT:"; 10465 if (C.Kind == CC_BitTests) 10466 dbgs() << "BT:"; 10467 10468 C.Low->getValue().print(dbgs(), true); 10469 if (C.Low != C.High) { 10470 dbgs() << '-'; 10471 C.High->getValue().print(dbgs(), true); 10472 } 10473 dbgs() << ' '; 10474 } 10475 dbgs() << '\n'; 10476 }); 10477 10478 assert(!Clusters.empty()); 10479 SwitchWorkList WorkList; 10480 CaseClusterIt First = Clusters.begin(); 10481 CaseClusterIt Last = Clusters.end() - 1; 10482 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10483 // Scale the branchprobability for DefaultMBB if the peel occurs and 10484 // DefaultMBB is not replaced. 10485 if (PeeledCaseProb != BranchProbability::getZero() && 10486 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10487 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10488 WorkList.push_back( 10489 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10490 10491 while (!WorkList.empty()) { 10492 SwitchWorkListItem W = WorkList.back(); 10493 WorkList.pop_back(); 10494 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10495 10496 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10497 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10498 // For optimized builds, lower large range as a balanced binary tree. 10499 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10500 continue; 10501 } 10502 10503 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10504 } 10505 } 10506