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