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 #define DEBUG_TYPE "isel" 15 #include "SDNodeDbgValue.h" 16 #include "SelectionDAGBuilder.h" 17 #include "FunctionLoweringInfo.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/ConstantFolding.h" 22 #include "llvm/Constants.h" 23 #include "llvm/CallingConv.h" 24 #include "llvm/DerivedTypes.h" 25 #include "llvm/Function.h" 26 #include "llvm/GlobalVariable.h" 27 #include "llvm/InlineAsm.h" 28 #include "llvm/Instructions.h" 29 #include "llvm/Intrinsics.h" 30 #include "llvm/IntrinsicInst.h" 31 #include "llvm/LLVMContext.h" 32 #include "llvm/Module.h" 33 #include "llvm/CodeGen/Analysis.h" 34 #include "llvm/CodeGen/FastISel.h" 35 #include "llvm/CodeGen/GCStrategy.h" 36 #include "llvm/CodeGen/GCMetadata.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineJumpTableInfo.h" 41 #include "llvm/CodeGen/MachineModuleInfo.h" 42 #include "llvm/CodeGen/MachineRegisterInfo.h" 43 #include "llvm/CodeGen/PseudoSourceValue.h" 44 #include "llvm/CodeGen/SelectionDAG.h" 45 #include "llvm/Analysis/DebugInfo.h" 46 #include "llvm/Target/TargetRegisterInfo.h" 47 #include "llvm/Target/TargetData.h" 48 #include "llvm/Target/TargetFrameInfo.h" 49 #include "llvm/Target/TargetInstrInfo.h" 50 #include "llvm/Target/TargetIntrinsicInfo.h" 51 #include "llvm/Target/TargetLowering.h" 52 #include "llvm/Target/TargetOptions.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/CommandLine.h" 55 #include "llvm/Support/Debug.h" 56 #include "llvm/Support/ErrorHandling.h" 57 #include "llvm/Support/MathExtras.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 using namespace llvm; 61 62 /// LimitFloatPrecision - Generate low-precision inline sequences for 63 /// some float libcalls (6, 8 or 12 bits). 64 static unsigned LimitFloatPrecision; 65 66 static cl::opt<unsigned, true> 67 LimitFPPrecision("limit-float-precision", 68 cl::desc("Generate low-precision inline sequences " 69 "for some float libcalls"), 70 cl::location(LimitFloatPrecision), 71 cl::init(0)); 72 73 namespace { 74 /// RegsForValue - This struct represents the registers (physical or virtual) 75 /// that a particular set of values is assigned, and the type information 76 /// about the value. The most common situation is to represent one value at a 77 /// time, but struct or array values are handled element-wise as multiple 78 /// values. The splitting of aggregates is performed recursively, so that we 79 /// never have aggregate-typed registers. The values at this point do not 80 /// necessarily have legal types, so each value may require one or more 81 /// registers of some legal type. 82 /// 83 struct RegsForValue { 84 /// ValueVTs - The value types of the values, which may not be legal, and 85 /// may need be promoted or synthesized from one or more registers. 86 /// 87 SmallVector<EVT, 4> ValueVTs; 88 89 /// RegVTs - The value types of the registers. This is the same size as 90 /// ValueVTs and it records, for each value, what the type of the assigned 91 /// register or registers are. (Individual values are never synthesized 92 /// from more than one type of register.) 93 /// 94 /// With virtual registers, the contents of RegVTs is redundant with TLI's 95 /// getRegisterType member function, however when with physical registers 96 /// it is necessary to have a separate record of the types. 97 /// 98 SmallVector<EVT, 4> RegVTs; 99 100 /// Regs - This list holds the registers assigned to the values. 101 /// Each legal or promoted value requires one register, and each 102 /// expanded value requires multiple registers. 103 /// 104 SmallVector<unsigned, 4> Regs; 105 106 RegsForValue() {} 107 108 RegsForValue(const SmallVector<unsigned, 4> ®s, 109 EVT regvt, EVT valuevt) 110 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 111 112 RegsForValue(const SmallVector<unsigned, 4> ®s, 113 const SmallVector<EVT, 4> ®vts, 114 const SmallVector<EVT, 4> &valuevts) 115 : ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {} 116 117 RegsForValue(LLVMContext &Context, const TargetLowering &tli, 118 unsigned Reg, const Type *Ty) { 119 ComputeValueVTs(tli, Ty, ValueVTs); 120 121 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 122 EVT ValueVT = ValueVTs[Value]; 123 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT); 124 EVT RegisterVT = tli.getRegisterType(Context, ValueVT); 125 for (unsigned i = 0; i != NumRegs; ++i) 126 Regs.push_back(Reg + i); 127 RegVTs.push_back(RegisterVT); 128 Reg += NumRegs; 129 } 130 } 131 132 /// areValueTypesLegal - Return true if types of all the values are legal. 133 bool areValueTypesLegal(const TargetLowering &TLI) { 134 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 135 EVT RegisterVT = RegVTs[Value]; 136 if (!TLI.isTypeLegal(RegisterVT)) 137 return false; 138 } 139 return true; 140 } 141 142 /// append - Add the specified values to this one. 143 void append(const RegsForValue &RHS) { 144 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 145 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 146 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 147 } 148 149 150 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 151 /// this value and returns the result as a ValueVTs value. This uses 152 /// Chain/Flag as the input and updates them for the output Chain/Flag. 153 /// If the Flag pointer is NULL, no flag is used. 154 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 155 DebugLoc dl, 156 SDValue &Chain, SDValue *Flag) const; 157 158 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 159 /// specified value into the registers specified by this object. This uses 160 /// Chain/Flag as the input and updates them for the output Chain/Flag. 161 /// If the Flag pointer is NULL, no flag is used. 162 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 163 SDValue &Chain, SDValue *Flag) const; 164 165 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 166 /// operand list. This adds the code marker, matching input operand index 167 /// (if applicable), and includes the number of values added into it. 168 void AddInlineAsmOperands(unsigned Kind, 169 bool HasMatching, unsigned MatchingIdx, 170 SelectionDAG &DAG, 171 std::vector<SDValue> &Ops) const; 172 }; 173 } 174 175 /// getCopyFromParts - Create a value that contains the specified legal parts 176 /// combined into the value they represent. If the parts combine to a type 177 /// larger then ValueVT then AssertOp can be used to specify whether the extra 178 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 179 /// (ISD::AssertSext). 180 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, 181 const SDValue *Parts, 182 unsigned NumParts, EVT PartVT, EVT ValueVT, 183 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 184 assert(NumParts > 0 && "No parts to assemble!"); 185 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 186 SDValue Val = Parts[0]; 187 188 if (NumParts > 1) { 189 // Assemble the value from multiple parts. 190 if (!ValueVT.isVector() && ValueVT.isInteger()) { 191 unsigned PartBits = PartVT.getSizeInBits(); 192 unsigned ValueBits = ValueVT.getSizeInBits(); 193 194 // Assemble the power of 2 part. 195 unsigned RoundParts = NumParts & (NumParts - 1) ? 196 1 << Log2_32(NumParts) : NumParts; 197 unsigned RoundBits = PartBits * RoundParts; 198 EVT RoundVT = RoundBits == ValueBits ? 199 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 200 SDValue Lo, Hi; 201 202 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 203 204 if (RoundParts > 2) { 205 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2, 206 PartVT, HalfVT); 207 Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2, 208 RoundParts / 2, PartVT, HalfVT); 209 } else { 210 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]); 211 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]); 212 } 213 214 if (TLI.isBigEndian()) 215 std::swap(Lo, Hi); 216 217 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi); 218 219 if (RoundParts < NumParts) { 220 // Assemble the trailing non-power-of-2 part. 221 unsigned OddParts = NumParts - RoundParts; 222 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 223 Hi = getCopyFromParts(DAG, dl, 224 Parts + RoundParts, OddParts, PartVT, OddVT); 225 226 // Combine the round and odd parts. 227 Lo = Val; 228 if (TLI.isBigEndian()) 229 std::swap(Lo, Hi); 230 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 231 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi); 232 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi, 233 DAG.getConstant(Lo.getValueType().getSizeInBits(), 234 TLI.getPointerTy())); 235 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo); 236 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi); 237 } 238 } else if (ValueVT.isVector()) { 239 // Handle a multi-element vector. 240 EVT IntermediateVT, RegisterVT; 241 unsigned NumIntermediates; 242 unsigned NumRegs = 243 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 244 NumIntermediates, RegisterVT); 245 assert(NumRegs == NumParts 246 && "Part count doesn't match vector breakdown!"); 247 NumParts = NumRegs; // Silence a compiler warning. 248 assert(RegisterVT == PartVT 249 && "Part type doesn't match vector breakdown!"); 250 assert(RegisterVT == Parts[0].getValueType() && 251 "Part type doesn't match part!"); 252 253 // Assemble the parts into intermediate operands. 254 SmallVector<SDValue, 8> Ops(NumIntermediates); 255 if (NumIntermediates == NumParts) { 256 // If the register was not expanded, truncate or copy the value, 257 // as appropriate. 258 for (unsigned i = 0; i != NumParts; ++i) 259 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1, 260 PartVT, IntermediateVT); 261 } else if (NumParts > 0) { 262 // If the intermediate type was expanded, build the intermediate 263 // operands from the parts. 264 assert(NumParts % NumIntermediates == 0 && 265 "Must expand into a divisible number of parts!"); 266 unsigned Factor = NumParts / NumIntermediates; 267 for (unsigned i = 0; i != NumIntermediates; ++i) 268 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor, 269 PartVT, IntermediateVT); 270 } 271 272 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 273 // intermediate operands. 274 Val = DAG.getNode(IntermediateVT.isVector() ? 275 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl, 276 ValueVT, &Ops[0], NumIntermediates); 277 } else if (PartVT.isFloatingPoint()) { 278 // FP split into multiple FP parts (for ppcf128) 279 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) && 280 "Unexpected split"); 281 SDValue Lo, Hi; 282 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]); 283 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]); 284 if (TLI.isBigEndian()) 285 std::swap(Lo, Hi); 286 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi); 287 } else { 288 // FP split into integer parts (soft fp) 289 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 290 !PartVT.isVector() && "Unexpected split"); 291 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 292 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT); 293 } 294 } 295 296 // There is now one part, held in Val. Correct it to match ValueVT. 297 PartVT = Val.getValueType(); 298 299 if (PartVT == ValueVT) 300 return Val; 301 302 if (PartVT.isVector()) { 303 assert(ValueVT.isVector() && "Unknown vector conversion!"); 304 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val); 305 } 306 307 if (ValueVT.isVector()) { 308 assert(ValueVT.getVectorElementType() == PartVT && 309 ValueVT.getVectorNumElements() == 1 && 310 "Only trivial scalar-to-vector conversions should get here!"); 311 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val); 312 } 313 314 if (PartVT.isInteger() && 315 ValueVT.isInteger()) { 316 if (ValueVT.bitsLT(PartVT)) { 317 // For a truncate, see if we have any information to 318 // indicate whether the truncated bits will always be 319 // zero or sign-extension. 320 if (AssertOp != ISD::DELETED_NODE) 321 Val = DAG.getNode(AssertOp, dl, PartVT, Val, 322 DAG.getValueType(ValueVT)); 323 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 324 } else { 325 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val); 326 } 327 } 328 329 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 330 if (ValueVT.bitsLT(Val.getValueType())) { 331 // FP_ROUND's are always exact here. 332 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val, 333 DAG.getIntPtrConstant(1)); 334 } 335 336 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val); 337 } 338 339 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) 340 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val); 341 342 llvm_unreachable("Unknown mismatch!"); 343 return SDValue(); 344 } 345 346 /// getCopyToParts - Create a series of nodes that contain the specified value 347 /// split into legal parts. If the parts contain more bits than Val, then, for 348 /// integers, ExtendKind can be used to specify how to generate the extra bits. 349 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, 350 SDValue Val, SDValue *Parts, unsigned NumParts, 351 EVT PartVT, 352 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 353 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 354 EVT PtrVT = TLI.getPointerTy(); 355 EVT ValueVT = Val.getValueType(); 356 unsigned PartBits = PartVT.getSizeInBits(); 357 unsigned OrigNumParts = NumParts; 358 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 359 360 if (!NumParts) 361 return; 362 363 if (!ValueVT.isVector()) { 364 if (PartVT == ValueVT) { 365 assert(NumParts == 1 && "No-op copy with multiple parts!"); 366 Parts[0] = Val; 367 return; 368 } 369 370 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 371 // If the parts cover more bits than the value has, promote the value. 372 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 373 assert(NumParts == 1 && "Do not know what to promote to!"); 374 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val); 375 } else if (PartVT.isInteger() && ValueVT.isInteger()) { 376 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 377 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val); 378 } else { 379 llvm_unreachable("Unknown mismatch!"); 380 } 381 } else if (PartBits == ValueVT.getSizeInBits()) { 382 // Different types of the same size. 383 assert(NumParts == 1 && PartVT != ValueVT); 384 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val); 385 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 386 // If the parts cover less bits than value has, truncate the value. 387 if (PartVT.isInteger() && ValueVT.isInteger()) { 388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 389 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 390 } else { 391 llvm_unreachable("Unknown mismatch!"); 392 } 393 } 394 395 // The value may have changed - recompute ValueVT. 396 ValueVT = Val.getValueType(); 397 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 398 "Failed to tile the value with PartVT!"); 399 400 if (NumParts == 1) { 401 assert(PartVT == ValueVT && "Type conversion failed!"); 402 Parts[0] = Val; 403 return; 404 } 405 406 // Expand the value into multiple parts. 407 if (NumParts & (NumParts - 1)) { 408 // The number of parts is not a power of 2. Split off and copy the tail. 409 assert(PartVT.isInteger() && ValueVT.isInteger() && 410 "Do not know what to expand to!"); 411 unsigned RoundParts = 1 << Log2_32(NumParts); 412 unsigned RoundBits = RoundParts * PartBits; 413 unsigned OddParts = NumParts - RoundParts; 414 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val, 415 DAG.getConstant(RoundBits, 416 TLI.getPointerTy())); 417 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, 418 OddParts, PartVT); 419 420 if (TLI.isBigEndian()) 421 // The odd parts were reversed by getCopyToParts - unreverse them. 422 std::reverse(Parts + RoundParts, Parts + NumParts); 423 424 NumParts = RoundParts; 425 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 426 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val); 427 } 428 429 // The number of parts is a power of 2. Repeatedly bisect the value using 430 // EXTRACT_ELEMENT. 431 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl, 432 EVT::getIntegerVT(*DAG.getContext(), 433 ValueVT.getSizeInBits()), 434 Val); 435 436 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 437 for (unsigned i = 0; i < NumParts; i += StepSize) { 438 unsigned ThisBits = StepSize * PartBits / 2; 439 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 440 SDValue &Part0 = Parts[i]; 441 SDValue &Part1 = Parts[i+StepSize/2]; 442 443 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 444 ThisVT, Part0, 445 DAG.getConstant(1, PtrVT)); 446 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 447 ThisVT, Part0, 448 DAG.getConstant(0, PtrVT)); 449 450 if (ThisBits == PartBits && ThisVT != PartVT) { 451 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl, 452 PartVT, Part0); 453 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl, 454 PartVT, Part1); 455 } 456 } 457 } 458 459 if (TLI.isBigEndian()) 460 std::reverse(Parts, Parts + OrigNumParts); 461 462 return; 463 } 464 465 // Vector ValueVT. 466 if (NumParts == 1) { 467 if (PartVT != ValueVT) { 468 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 469 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val); 470 } else { 471 assert(ValueVT.getVectorElementType() == PartVT && 472 ValueVT.getVectorNumElements() == 1 && 473 "Only trivial vector-to-scalar conversions should get here!"); 474 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 475 PartVT, Val, 476 DAG.getConstant(0, PtrVT)); 477 } 478 } 479 480 Parts[0] = Val; 481 return; 482 } 483 484 // Handle a multi-element vector. 485 EVT IntermediateVT, RegisterVT; 486 unsigned NumIntermediates; 487 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 488 IntermediateVT, NumIntermediates, RegisterVT); 489 unsigned NumElements = ValueVT.getVectorNumElements(); 490 491 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 492 NumParts = NumRegs; // Silence a compiler warning. 493 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 494 495 // Split the vector into intermediate operands. 496 SmallVector<SDValue, 8> Ops(NumIntermediates); 497 for (unsigned i = 0; i != NumIntermediates; ++i) { 498 if (IntermediateVT.isVector()) 499 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, 500 IntermediateVT, Val, 501 DAG.getConstant(i * (NumElements / NumIntermediates), 502 PtrVT)); 503 else 504 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 505 IntermediateVT, Val, 506 DAG.getConstant(i, PtrVT)); 507 } 508 509 // Split the intermediate operands into legal parts. 510 if (NumParts == NumIntermediates) { 511 // If the register was not expanded, promote or copy the value, 512 // as appropriate. 513 for (unsigned i = 0; i != NumParts; ++i) 514 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT); 515 } else if (NumParts > 0) { 516 // If the intermediate type was expanded, split each the value into 517 // legal parts. 518 assert(NumParts % NumIntermediates == 0 && 519 "Must expand into a divisible number of parts!"); 520 unsigned Factor = NumParts / NumIntermediates; 521 for (unsigned i = 0; i != NumIntermediates; ++i) 522 getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT); 523 } 524 } 525 526 527 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) { 528 AA = &aa; 529 GFI = gfi; 530 TD = DAG.getTarget().getTargetData(); 531 } 532 533 /// clear - Clear out the current SelectionDAG and the associated 534 /// state and prepare this SelectionDAGBuilder object to be used 535 /// for a new block. This doesn't clear out information about 536 /// additional blocks that are needed to complete switch lowering 537 /// or PHI node updating; that information is cleared out as it is 538 /// consumed. 539 void SelectionDAGBuilder::clear() { 540 NodeMap.clear(); 541 PendingLoads.clear(); 542 PendingExports.clear(); 543 CurDebugLoc = DebugLoc(); 544 HasTailCall = false; 545 } 546 547 /// getRoot - Return the current virtual root of the Selection DAG, 548 /// flushing any PendingLoad items. This must be done before emitting 549 /// a store or any other node that may need to be ordered after any 550 /// prior load instructions. 551 /// 552 SDValue SelectionDAGBuilder::getRoot() { 553 if (PendingLoads.empty()) 554 return DAG.getRoot(); 555 556 if (PendingLoads.size() == 1) { 557 SDValue Root = PendingLoads[0]; 558 DAG.setRoot(Root); 559 PendingLoads.clear(); 560 return Root; 561 } 562 563 // Otherwise, we have to make a token factor node. 564 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 565 &PendingLoads[0], PendingLoads.size()); 566 PendingLoads.clear(); 567 DAG.setRoot(Root); 568 return Root; 569 } 570 571 /// getControlRoot - Similar to getRoot, but instead of flushing all the 572 /// PendingLoad items, flush all the PendingExports items. It is necessary 573 /// to do this before emitting a terminator instruction. 574 /// 575 SDValue SelectionDAGBuilder::getControlRoot() { 576 SDValue Root = DAG.getRoot(); 577 578 if (PendingExports.empty()) 579 return Root; 580 581 // Turn all of the CopyToReg chains into one factored node. 582 if (Root.getOpcode() != ISD::EntryToken) { 583 unsigned i = 0, e = PendingExports.size(); 584 for (; i != e; ++i) { 585 assert(PendingExports[i].getNode()->getNumOperands() > 1); 586 if (PendingExports[i].getNode()->getOperand(0) == Root) 587 break; // Don't add the root if we already indirectly depend on it. 588 } 589 590 if (i == e) 591 PendingExports.push_back(Root); 592 } 593 594 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 595 &PendingExports[0], 596 PendingExports.size()); 597 PendingExports.clear(); 598 DAG.setRoot(Root); 599 return Root; 600 } 601 602 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) { 603 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering. 604 DAG.AssignOrdering(Node, SDNodeOrder); 605 606 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) 607 AssignOrderingToNode(Node->getOperand(I).getNode()); 608 } 609 610 void SelectionDAGBuilder::visit(const Instruction &I) { 611 // Set up outgoing PHI node register values before emitting the terminator. 612 if (isa<TerminatorInst>(&I)) 613 HandlePHINodesInSuccessorBlocks(I.getParent()); 614 615 CurDebugLoc = I.getDebugLoc(); 616 617 visit(I.getOpcode(), I); 618 619 if (!isa<TerminatorInst>(&I) && !HasTailCall) 620 CopyToExportRegsIfNeeded(&I); 621 622 CurDebugLoc = DebugLoc(); 623 } 624 625 void SelectionDAGBuilder::visitPHI(const PHINode &) { 626 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 627 } 628 629 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 630 // Note: this doesn't use InstVisitor, because it has to work with 631 // ConstantExpr's in addition to instructions. 632 switch (Opcode) { 633 default: llvm_unreachable("Unknown instruction type encountered!"); 634 // Build the switch statement using the Instruction.def file. 635 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 636 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break; 637 #include "llvm/Instruction.def" 638 } 639 640 // Assign the ordering to the freshly created DAG nodes. 641 if (NodeMap.count(&I)) { 642 ++SDNodeOrder; 643 AssignOrderingToNode(getValue(&I).getNode()); 644 } 645 } 646 647 SDValue SelectionDAGBuilder::getValue(const Value *V) { 648 SDValue &N = NodeMap[V]; 649 if (N.getNode()) return N; 650 651 if (const Constant *C = dyn_cast<Constant>(V)) { 652 EVT VT = TLI.getValueType(V->getType(), true); 653 654 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 655 return N = DAG.getConstant(*CI, VT); 656 657 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 658 return N = DAG.getGlobalAddress(GV, VT); 659 660 if (isa<ConstantPointerNull>(C)) 661 return N = DAG.getConstant(0, TLI.getPointerTy()); 662 663 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 664 return N = DAG.getConstantFP(*CFP, VT); 665 666 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 667 return N = DAG.getUNDEF(VT); 668 669 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 670 visit(CE->getOpcode(), *CE); 671 SDValue N1 = NodeMap[V]; 672 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 673 return N1; 674 } 675 676 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 677 SmallVector<SDValue, 4> Constants; 678 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 679 OI != OE; ++OI) { 680 SDNode *Val = getValue(*OI).getNode(); 681 // If the operand is an empty aggregate, there are no values. 682 if (!Val) continue; 683 // Add each leaf value from the operand to the Constants list 684 // to form a flattened list of all the values. 685 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 686 Constants.push_back(SDValue(Val, i)); 687 } 688 689 return DAG.getMergeValues(&Constants[0], Constants.size(), 690 getCurDebugLoc()); 691 } 692 693 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 694 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 695 "Unknown struct or array constant!"); 696 697 SmallVector<EVT, 4> ValueVTs; 698 ComputeValueVTs(TLI, C->getType(), ValueVTs); 699 unsigned NumElts = ValueVTs.size(); 700 if (NumElts == 0) 701 return SDValue(); // empty struct 702 SmallVector<SDValue, 4> Constants(NumElts); 703 for (unsigned i = 0; i != NumElts; ++i) { 704 EVT EltVT = ValueVTs[i]; 705 if (isa<UndefValue>(C)) 706 Constants[i] = DAG.getUNDEF(EltVT); 707 else if (EltVT.isFloatingPoint()) 708 Constants[i] = DAG.getConstantFP(0, EltVT); 709 else 710 Constants[i] = DAG.getConstant(0, EltVT); 711 } 712 713 return DAG.getMergeValues(&Constants[0], NumElts, 714 getCurDebugLoc()); 715 } 716 717 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 718 return DAG.getBlockAddress(BA, VT); 719 720 const VectorType *VecTy = cast<VectorType>(V->getType()); 721 unsigned NumElements = VecTy->getNumElements(); 722 723 // Now that we know the number and type of the elements, get that number of 724 // elements into the Ops array based on what kind of constant it is. 725 SmallVector<SDValue, 16> Ops; 726 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) { 727 for (unsigned i = 0; i != NumElements; ++i) 728 Ops.push_back(getValue(CP->getOperand(i))); 729 } else { 730 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 731 EVT EltVT = TLI.getValueType(VecTy->getElementType()); 732 733 SDValue Op; 734 if (EltVT.isFloatingPoint()) 735 Op = DAG.getConstantFP(0, EltVT); 736 else 737 Op = DAG.getConstant(0, EltVT); 738 Ops.assign(NumElements, Op); 739 } 740 741 // Create a BUILD_VECTOR node. 742 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 743 VT, &Ops[0], Ops.size()); 744 } 745 746 // If this is a static alloca, generate it as the frameindex instead of 747 // computation. 748 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 749 DenseMap<const AllocaInst*, int>::iterator SI = 750 FuncInfo.StaticAllocaMap.find(AI); 751 if (SI != FuncInfo.StaticAllocaMap.end()) 752 return DAG.getFrameIndex(SI->second, TLI.getPointerTy()); 753 } 754 755 unsigned InReg = FuncInfo.ValueMap[V]; 756 assert(InReg && "Value not in map!"); 757 758 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType()); 759 SDValue Chain = DAG.getEntryNode(); 760 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL); 761 } 762 763 /// Get the EVTs and ArgFlags collections that represent the legalized return 764 /// type of the given function. This does not require a DAG or a return value, 765 /// and is suitable for use before any DAGs for the function are constructed. 766 static void getReturnInfo(const Type* ReturnType, 767 Attributes attr, SmallVectorImpl<EVT> &OutVTs, 768 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags, 769 const TargetLowering &TLI, 770 SmallVectorImpl<uint64_t> *Offsets = 0) { 771 SmallVector<EVT, 4> ValueVTs; 772 ComputeValueVTs(TLI, ReturnType, ValueVTs); 773 unsigned NumValues = ValueVTs.size(); 774 if (NumValues == 0) return; 775 unsigned Offset = 0; 776 777 for (unsigned j = 0, f = NumValues; j != f; ++j) { 778 EVT VT = ValueVTs[j]; 779 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 780 781 if (attr & Attribute::SExt) 782 ExtendKind = ISD::SIGN_EXTEND; 783 else if (attr & Attribute::ZExt) 784 ExtendKind = ISD::ZERO_EXTEND; 785 786 // FIXME: C calling convention requires the return type to be promoted to 787 // at least 32-bit. But this is not necessary for non-C calling 788 // conventions. The frontend should mark functions whose return values 789 // require promoting with signext or zeroext attributes. 790 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 791 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32); 792 if (VT.bitsLT(MinVT)) 793 VT = MinVT; 794 } 795 796 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT); 797 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT); 798 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize( 799 PartVT.getTypeForEVT(ReturnType->getContext())); 800 801 // 'inreg' on function refers to return value 802 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 803 if (attr & Attribute::InReg) 804 Flags.setInReg(); 805 806 // Propagate extension type if any 807 if (attr & Attribute::SExt) 808 Flags.setSExt(); 809 else if (attr & Attribute::ZExt) 810 Flags.setZExt(); 811 812 for (unsigned i = 0; i < NumParts; ++i) { 813 OutVTs.push_back(PartVT); 814 OutFlags.push_back(Flags); 815 if (Offsets) 816 { 817 Offsets->push_back(Offset); 818 Offset += PartSize; 819 } 820 } 821 } 822 } 823 824 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 825 SDValue Chain = getControlRoot(); 826 SmallVector<ISD::OutputArg, 8> Outs; 827 828 if (!FuncInfo.CanLowerReturn) { 829 unsigned DemoteReg = FuncInfo.DemoteRegister; 830 const Function *F = I.getParent()->getParent(); 831 832 // Emit a store of the return value through the virtual register. 833 // Leave Outs empty so that LowerReturn won't try to load return 834 // registers the usual way. 835 SmallVector<EVT, 1> PtrValueVTs; 836 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()), 837 PtrValueVTs); 838 839 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 840 SDValue RetOp = getValue(I.getOperand(0)); 841 842 SmallVector<EVT, 4> ValueVTs; 843 SmallVector<uint64_t, 4> Offsets; 844 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); 845 unsigned NumValues = ValueVTs.size(); 846 847 SmallVector<SDValue, 4> Chains(NumValues); 848 EVT PtrVT = PtrValueVTs[0]; 849 for (unsigned i = 0; i != NumValues; ++i) { 850 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr, 851 DAG.getConstant(Offsets[i], PtrVT)); 852 Chains[i] = 853 DAG.getStore(Chain, getCurDebugLoc(), 854 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 855 Add, NULL, Offsets[i], false, false, 0); 856 } 857 858 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 859 MVT::Other, &Chains[0], NumValues); 860 } else if (I.getNumOperands() != 0) { 861 SmallVector<EVT, 4> ValueVTs; 862 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs); 863 unsigned NumValues = ValueVTs.size(); 864 if (NumValues) { 865 SDValue RetOp = getValue(I.getOperand(0)); 866 for (unsigned j = 0, f = NumValues; j != f; ++j) { 867 EVT VT = ValueVTs[j]; 868 869 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 870 871 const Function *F = I.getParent()->getParent(); 872 if (F->paramHasAttr(0, Attribute::SExt)) 873 ExtendKind = ISD::SIGN_EXTEND; 874 else if (F->paramHasAttr(0, Attribute::ZExt)) 875 ExtendKind = ISD::ZERO_EXTEND; 876 877 // FIXME: C calling convention requires the return type to be promoted 878 // to at least 32-bit. But this is not necessary for non-C calling 879 // conventions. The frontend should mark functions whose return values 880 // require promoting with signext or zeroext attributes. 881 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) { 882 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32); 883 if (VT.bitsLT(MinVT)) 884 VT = MinVT; 885 } 886 887 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT); 888 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT); 889 SmallVector<SDValue, 4> Parts(NumParts); 890 getCopyToParts(DAG, getCurDebugLoc(), 891 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 892 &Parts[0], NumParts, PartVT, ExtendKind); 893 894 // 'inreg' on function refers to return value 895 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 896 if (F->paramHasAttr(0, Attribute::InReg)) 897 Flags.setInReg(); 898 899 // Propagate extension type if any 900 if (F->paramHasAttr(0, Attribute::SExt)) 901 Flags.setSExt(); 902 else if (F->paramHasAttr(0, Attribute::ZExt)) 903 Flags.setZExt(); 904 905 for (unsigned i = 0; i < NumParts; ++i) 906 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true)); 907 } 908 } 909 } 910 911 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 912 CallingConv::ID CallConv = 913 DAG.getMachineFunction().getFunction()->getCallingConv(); 914 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg, 915 Outs, getCurDebugLoc(), DAG); 916 917 // Verify that the target's LowerReturn behaved as expected. 918 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 919 "LowerReturn didn't return a valid chain!"); 920 921 // Update the DAG with the new chain value resulting from return lowering. 922 DAG.setRoot(Chain); 923 } 924 925 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 926 /// created for it, emit nodes to copy the value into the virtual 927 /// registers. 928 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 929 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 930 if (VMI != FuncInfo.ValueMap.end()) { 931 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 932 CopyValueToVirtualRegister(V, VMI->second); 933 } 934 } 935 936 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 937 /// the current basic block, add it to ValueMap now so that we'll get a 938 /// CopyTo/FromReg. 939 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 940 // No need to export constants. 941 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 942 943 // Already exported? 944 if (FuncInfo.isExportedInst(V)) return; 945 946 unsigned Reg = FuncInfo.InitializeRegForValue(V); 947 CopyValueToVirtualRegister(V, Reg); 948 } 949 950 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 951 const BasicBlock *FromBB) { 952 // The operands of the setcc have to be in this block. We don't know 953 // how to export them from some other block. 954 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 955 // Can export from current BB. 956 if (VI->getParent() == FromBB) 957 return true; 958 959 // Is already exported, noop. 960 return FuncInfo.isExportedInst(V); 961 } 962 963 // If this is an argument, we can export it if the BB is the entry block or 964 // if it is already exported. 965 if (isa<Argument>(V)) { 966 if (FromBB == &FromBB->getParent()->getEntryBlock()) 967 return true; 968 969 // Otherwise, can only export this if it is already exported. 970 return FuncInfo.isExportedInst(V); 971 } 972 973 // Otherwise, constants can always be exported. 974 return true; 975 } 976 977 static bool InBlock(const Value *V, const BasicBlock *BB) { 978 if (const Instruction *I = dyn_cast<Instruction>(V)) 979 return I->getParent() == BB; 980 return true; 981 } 982 983 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 984 /// This function emits a branch and is used at the leaves of an OR or an 985 /// AND operator tree. 986 /// 987 void 988 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 989 MachineBasicBlock *TBB, 990 MachineBasicBlock *FBB, 991 MachineBasicBlock *CurBB, 992 MachineBasicBlock *SwitchBB) { 993 const BasicBlock *BB = CurBB->getBasicBlock(); 994 995 // If the leaf of the tree is a comparison, merge the condition into 996 // the caseblock. 997 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 998 // The operands of the cmp have to be in this block. We don't know 999 // how to export them from some other block. If this is the first block 1000 // of the sequence, no exporting is needed. 1001 if (CurBB == SwitchBB || 1002 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1003 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1004 ISD::CondCode Condition; 1005 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1006 Condition = getICmpCondCode(IC->getPredicate()); 1007 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1008 Condition = getFCmpCondCode(FC->getPredicate()); 1009 } else { 1010 Condition = ISD::SETEQ; // silence warning. 1011 llvm_unreachable("Unknown compare instruction"); 1012 } 1013 1014 CaseBlock CB(Condition, BOp->getOperand(0), 1015 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1016 SwitchCases.push_back(CB); 1017 return; 1018 } 1019 } 1020 1021 // Create a CaseBlock record representing this branch. 1022 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1023 NULL, TBB, FBB, CurBB); 1024 SwitchCases.push_back(CB); 1025 } 1026 1027 /// FindMergedConditions - If Cond is an expression like 1028 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1029 MachineBasicBlock *TBB, 1030 MachineBasicBlock *FBB, 1031 MachineBasicBlock *CurBB, 1032 MachineBasicBlock *SwitchBB, 1033 unsigned Opc) { 1034 // If this node is not part of the or/and tree, emit it as a branch. 1035 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1036 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1037 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1038 BOp->getParent() != CurBB->getBasicBlock() || 1039 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1040 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1041 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB); 1042 return; 1043 } 1044 1045 // Create TmpBB after CurBB. 1046 MachineFunction::iterator BBI = CurBB; 1047 MachineFunction &MF = DAG.getMachineFunction(); 1048 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1049 CurBB->getParent()->insert(++BBI, TmpBB); 1050 1051 if (Opc == Instruction::Or) { 1052 // Codegen X | Y as: 1053 // jmp_if_X TBB 1054 // jmp TmpBB 1055 // TmpBB: 1056 // jmp_if_Y TBB 1057 // jmp FBB 1058 // 1059 1060 // Emit the LHS condition. 1061 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc); 1062 1063 // Emit the RHS condition into TmpBB. 1064 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1065 } else { 1066 assert(Opc == Instruction::And && "Unknown merge op!"); 1067 // Codegen X & Y as: 1068 // jmp_if_X TmpBB 1069 // jmp FBB 1070 // TmpBB: 1071 // jmp_if_Y TBB 1072 // jmp FBB 1073 // 1074 // This requires creation of TmpBB after CurBB. 1075 1076 // Emit the LHS condition. 1077 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc); 1078 1079 // Emit the RHS condition into TmpBB. 1080 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1081 } 1082 } 1083 1084 /// If the set of cases should be emitted as a series of branches, return true. 1085 /// If we should emit this as a bunch of and/or'd together conditions, return 1086 /// false. 1087 bool 1088 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){ 1089 if (Cases.size() != 2) return true; 1090 1091 // If this is two comparisons of the same values or'd or and'd together, they 1092 // will get folded into a single comparison, so don't emit two blocks. 1093 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1094 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1095 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1096 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1097 return false; 1098 } 1099 1100 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1101 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1102 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1103 Cases[0].CC == Cases[1].CC && 1104 isa<Constant>(Cases[0].CmpRHS) && 1105 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1106 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1107 return false; 1108 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1109 return false; 1110 } 1111 1112 return true; 1113 } 1114 1115 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1116 MachineBasicBlock *BrMBB = FuncInfo.MBBMap[I.getParent()]; 1117 1118 // Update machine-CFG edges. 1119 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1120 1121 // Figure out which block is immediately after the current one. 1122 MachineBasicBlock *NextBlock = 0; 1123 MachineFunction::iterator BBI = BrMBB; 1124 if (++BBI != FuncInfo.MF->end()) 1125 NextBlock = BBI; 1126 1127 if (I.isUnconditional()) { 1128 // Update machine-CFG edges. 1129 BrMBB->addSuccessor(Succ0MBB); 1130 1131 // If this is not a fall-through branch, emit the branch. 1132 if (Succ0MBB != NextBlock) 1133 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1134 MVT::Other, getControlRoot(), 1135 DAG.getBasicBlock(Succ0MBB))); 1136 1137 return; 1138 } 1139 1140 // If this condition is one of the special cases we handle, do special stuff 1141 // now. 1142 const Value *CondVal = I.getCondition(); 1143 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1144 1145 // If this is a series of conditions that are or'd or and'd together, emit 1146 // this as a sequence of branches instead of setcc's with and/or operations. 1147 // For example, instead of something like: 1148 // cmp A, B 1149 // C = seteq 1150 // cmp D, E 1151 // F = setle 1152 // or C, F 1153 // jnz foo 1154 // Emit: 1155 // cmp A, B 1156 // je foo 1157 // cmp D, E 1158 // jle foo 1159 // 1160 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1161 if (BOp->hasOneUse() && 1162 (BOp->getOpcode() == Instruction::And || 1163 BOp->getOpcode() == Instruction::Or)) { 1164 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1165 BOp->getOpcode()); 1166 // If the compares in later blocks need to use values not currently 1167 // exported from this block, export them now. This block should always 1168 // be the first entry. 1169 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1170 1171 // Allow some cases to be rejected. 1172 if (ShouldEmitAsBranches(SwitchCases)) { 1173 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1174 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1175 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1176 } 1177 1178 // Emit the branch for this block. 1179 visitSwitchCase(SwitchCases[0], BrMBB); 1180 SwitchCases.erase(SwitchCases.begin()); 1181 return; 1182 } 1183 1184 // Okay, we decided not to do this, remove any inserted MBB's and clear 1185 // SwitchCases. 1186 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1187 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1188 1189 SwitchCases.clear(); 1190 } 1191 } 1192 1193 // Create a CaseBlock record representing this branch. 1194 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1195 NULL, Succ0MBB, Succ1MBB, BrMBB); 1196 1197 // Use visitSwitchCase to actually insert the fast branch sequence for this 1198 // cond branch. 1199 visitSwitchCase(CB, BrMBB); 1200 } 1201 1202 /// visitSwitchCase - Emits the necessary code to represent a single node in 1203 /// the binary search tree resulting from lowering a switch instruction. 1204 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1205 MachineBasicBlock *SwitchBB) { 1206 SDValue Cond; 1207 SDValue CondLHS = getValue(CB.CmpLHS); 1208 DebugLoc dl = getCurDebugLoc(); 1209 1210 // Build the setcc now. 1211 if (CB.CmpMHS == NULL) { 1212 // Fold "(X == true)" to X and "(X == false)" to !X to 1213 // handle common cases produced by branch lowering. 1214 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1215 CB.CC == ISD::SETEQ) 1216 Cond = CondLHS; 1217 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1218 CB.CC == ISD::SETEQ) { 1219 SDValue True = DAG.getConstant(1, CondLHS.getValueType()); 1220 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1221 } else 1222 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1223 } else { 1224 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1225 1226 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1227 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1228 1229 SDValue CmpOp = getValue(CB.CmpMHS); 1230 EVT VT = CmpOp.getValueType(); 1231 1232 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 1233 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), 1234 ISD::SETLE); 1235 } else { 1236 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1237 VT, CmpOp, DAG.getConstant(Low, VT)); 1238 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1239 DAG.getConstant(High-Low, VT), ISD::SETULE); 1240 } 1241 } 1242 1243 // Update successor info 1244 SwitchBB->addSuccessor(CB.TrueBB); 1245 SwitchBB->addSuccessor(CB.FalseBB); 1246 1247 // Set NextBlock to be the MBB immediately after the current one, if any. 1248 // This is used to avoid emitting unnecessary branches to the next block. 1249 MachineBasicBlock *NextBlock = 0; 1250 MachineFunction::iterator BBI = SwitchBB; 1251 if (++BBI != FuncInfo.MF->end()) 1252 NextBlock = BBI; 1253 1254 // If the lhs block is the next block, invert the condition so that we can 1255 // fall through to the lhs instead of the rhs block. 1256 if (CB.TrueBB == NextBlock) { 1257 std::swap(CB.TrueBB, CB.FalseBB); 1258 SDValue True = DAG.getConstant(1, Cond.getValueType()); 1259 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1260 } 1261 1262 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1263 MVT::Other, getControlRoot(), Cond, 1264 DAG.getBasicBlock(CB.TrueBB)); 1265 1266 // If the branch was constant folded, fix up the CFG. 1267 if (BrCond.getOpcode() == ISD::BR) { 1268 SwitchBB->removeSuccessor(CB.FalseBB); 1269 } else { 1270 // Otherwise, go ahead and insert the false branch. 1271 if (BrCond == getControlRoot()) 1272 SwitchBB->removeSuccessor(CB.TrueBB); 1273 1274 if (CB.FalseBB != NextBlock) 1275 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1276 DAG.getBasicBlock(CB.FalseBB)); 1277 } 1278 1279 DAG.setRoot(BrCond); 1280 } 1281 1282 /// visitJumpTable - Emit JumpTable node in the current MBB 1283 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1284 // Emit the code for the jump table 1285 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1286 EVT PTy = TLI.getPointerTy(); 1287 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), 1288 JT.Reg, PTy); 1289 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1290 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(), 1291 MVT::Other, Index.getValue(1), 1292 Table, Index); 1293 DAG.setRoot(BrJumpTable); 1294 } 1295 1296 /// visitJumpTableHeader - This function emits necessary code to produce index 1297 /// in the JumpTable from switch case. 1298 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1299 JumpTableHeader &JTH, 1300 MachineBasicBlock *SwitchBB) { 1301 // Subtract the lowest switch case value from the value being switched on and 1302 // conditional branch to default mbb if the result is greater than the 1303 // difference between smallest and largest cases. 1304 SDValue SwitchOp = getValue(JTH.SValue); 1305 EVT VT = SwitchOp.getValueType(); 1306 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1307 DAG.getConstant(JTH.First, VT)); 1308 1309 // The SDNode we just created, which holds the value being switched on minus 1310 // the smallest case value, needs to be copied to a virtual register so it 1311 // can be used as an index into the jump table in a subsequent basic block. 1312 // This value may be smaller or larger than the target's pointer type, and 1313 // therefore require extension or truncating. 1314 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy()); 1315 1316 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy()); 1317 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1318 JumpTableReg, SwitchOp); 1319 JT.Reg = JumpTableReg; 1320 1321 // Emit the range check for the jump table, and branch to the default block 1322 // for the switch statement if the value being switched on exceeds the largest 1323 // case in the switch. 1324 SDValue CMP = DAG.getSetCC(getCurDebugLoc(), 1325 TLI.getSetCCResultType(Sub.getValueType()), Sub, 1326 DAG.getConstant(JTH.Last-JTH.First,VT), 1327 ISD::SETUGT); 1328 1329 // Set NextBlock to be the MBB immediately after the current one, if any. 1330 // This is used to avoid emitting unnecessary branches to the next block. 1331 MachineBasicBlock *NextBlock = 0; 1332 MachineFunction::iterator BBI = SwitchBB; 1333 1334 if (++BBI != FuncInfo.MF->end()) 1335 NextBlock = BBI; 1336 1337 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1338 MVT::Other, CopyTo, CMP, 1339 DAG.getBasicBlock(JT.Default)); 1340 1341 if (JT.MBB != NextBlock) 1342 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond, 1343 DAG.getBasicBlock(JT.MBB)); 1344 1345 DAG.setRoot(BrCond); 1346 } 1347 1348 /// visitBitTestHeader - This function emits necessary code to produce value 1349 /// suitable for "bit tests" 1350 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1351 MachineBasicBlock *SwitchBB) { 1352 // Subtract the minimum value 1353 SDValue SwitchOp = getValue(B.SValue); 1354 EVT VT = SwitchOp.getValueType(); 1355 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp, 1356 DAG.getConstant(B.First, VT)); 1357 1358 // Check range 1359 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(), 1360 TLI.getSetCCResultType(Sub.getValueType()), 1361 Sub, DAG.getConstant(B.Range, VT), 1362 ISD::SETUGT); 1363 1364 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), 1365 TLI.getPointerTy()); 1366 1367 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy()); 1368 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(), 1369 B.Reg, ShiftOp); 1370 1371 // Set NextBlock to be the MBB immediately after the current one, if any. 1372 // This is used to avoid emitting unnecessary branches to the next block. 1373 MachineBasicBlock *NextBlock = 0; 1374 MachineFunction::iterator BBI = SwitchBB; 1375 if (++BBI != FuncInfo.MF->end()) 1376 NextBlock = BBI; 1377 1378 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1379 1380 SwitchBB->addSuccessor(B.Default); 1381 SwitchBB->addSuccessor(MBB); 1382 1383 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1384 MVT::Other, CopyTo, RangeCmp, 1385 DAG.getBasicBlock(B.Default)); 1386 1387 if (MBB != NextBlock) 1388 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo, 1389 DAG.getBasicBlock(MBB)); 1390 1391 DAG.setRoot(BrRange); 1392 } 1393 1394 /// visitBitTestCase - this function produces one "bit test" 1395 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB, 1396 unsigned Reg, 1397 BitTestCase &B, 1398 MachineBasicBlock *SwitchBB) { 1399 // Make desired shift 1400 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg, 1401 TLI.getPointerTy()); 1402 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), 1403 TLI.getPointerTy(), 1404 DAG.getConstant(1, TLI.getPointerTy()), 1405 ShiftOp); 1406 1407 // Emit bit tests and jumps 1408 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(), 1409 TLI.getPointerTy(), SwitchVal, 1410 DAG.getConstant(B.Mask, TLI.getPointerTy())); 1411 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(), 1412 TLI.getSetCCResultType(AndOp.getValueType()), 1413 AndOp, DAG.getConstant(0, TLI.getPointerTy()), 1414 ISD::SETNE); 1415 1416 SwitchBB->addSuccessor(B.TargetBB); 1417 SwitchBB->addSuccessor(NextMBB); 1418 1419 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(), 1420 MVT::Other, getControlRoot(), 1421 AndCmp, DAG.getBasicBlock(B.TargetBB)); 1422 1423 // Set NextBlock to be the MBB immediately after the current one, if any. 1424 // This is used to avoid emitting unnecessary branches to the next block. 1425 MachineBasicBlock *NextBlock = 0; 1426 MachineFunction::iterator BBI = SwitchBB; 1427 if (++BBI != FuncInfo.MF->end()) 1428 NextBlock = BBI; 1429 1430 if (NextMBB != NextBlock) 1431 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd, 1432 DAG.getBasicBlock(NextMBB)); 1433 1434 DAG.setRoot(BrAnd); 1435 } 1436 1437 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1438 MachineBasicBlock *InvokeMBB = FuncInfo.MBBMap[I.getParent()]; 1439 1440 // Retrieve successors. 1441 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1442 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1443 1444 const Value *Callee(I.getCalledValue()); 1445 if (isa<InlineAsm>(Callee)) 1446 visitInlineAsm(&I); 1447 else 1448 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1449 1450 // If the value of the invoke is used outside of its defining block, make it 1451 // available as a virtual register. 1452 CopyToExportRegsIfNeeded(&I); 1453 1454 // Update successor info 1455 InvokeMBB->addSuccessor(Return); 1456 InvokeMBB->addSuccessor(LandingPad); 1457 1458 // Drop into normal successor. 1459 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1460 MVT::Other, getControlRoot(), 1461 DAG.getBasicBlock(Return))); 1462 } 1463 1464 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) { 1465 } 1466 1467 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 1468 /// small case ranges). 1469 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, 1470 CaseRecVector& WorkList, 1471 const Value* SV, 1472 MachineBasicBlock *Default, 1473 MachineBasicBlock *SwitchBB) { 1474 Case& BackCase = *(CR.Range.second-1); 1475 1476 // Size is the number of Cases represented by this range. 1477 size_t Size = CR.Range.second - CR.Range.first; 1478 if (Size > 3) 1479 return false; 1480 1481 // Get the MachineFunction which holds the current MBB. This is used when 1482 // inserting any additional MBBs necessary to represent the switch. 1483 MachineFunction *CurMF = FuncInfo.MF; 1484 1485 // Figure out which block is immediately after the current one. 1486 MachineBasicBlock *NextBlock = 0; 1487 MachineFunction::iterator BBI = CR.CaseBB; 1488 1489 if (++BBI != FuncInfo.MF->end()) 1490 NextBlock = BBI; 1491 1492 // TODO: If any two of the cases has the same destination, and if one value 1493 // is the same as the other, but has one bit unset that the other has set, 1494 // use bit manipulation to do two compares at once. For example: 1495 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 1496 1497 // Rearrange the case blocks so that the last one falls through if possible. 1498 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 1499 // The last case block won't fall through into 'NextBlock' if we emit the 1500 // branches in this order. See if rearranging a case value would help. 1501 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) { 1502 if (I->BB == NextBlock) { 1503 std::swap(*I, BackCase); 1504 break; 1505 } 1506 } 1507 } 1508 1509 // Create a CaseBlock record representing a conditional branch to 1510 // the Case's target mbb if the value being switched on SV is equal 1511 // to C. 1512 MachineBasicBlock *CurBlock = CR.CaseBB; 1513 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 1514 MachineBasicBlock *FallThrough; 1515 if (I != E-1) { 1516 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); 1517 CurMF->insert(BBI, FallThrough); 1518 1519 // Put SV in a virtual register to make it available from the new blocks. 1520 ExportFromCurrentBlock(SV); 1521 } else { 1522 // If the last case doesn't match, go to the default block. 1523 FallThrough = Default; 1524 } 1525 1526 const Value *RHS, *LHS, *MHS; 1527 ISD::CondCode CC; 1528 if (I->High == I->Low) { 1529 // This is just small small case range :) containing exactly 1 case 1530 CC = ISD::SETEQ; 1531 LHS = SV; RHS = I->High; MHS = NULL; 1532 } else { 1533 CC = ISD::SETLE; 1534 LHS = I->Low; MHS = SV; RHS = I->High; 1535 } 1536 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock); 1537 1538 // If emitting the first comparison, just call visitSwitchCase to emit the 1539 // code into the current block. Otherwise, push the CaseBlock onto the 1540 // vector to be later processed by SDISel, and insert the node's MBB 1541 // before the next MBB. 1542 if (CurBlock == SwitchBB) 1543 visitSwitchCase(CB, SwitchBB); 1544 else 1545 SwitchCases.push_back(CB); 1546 1547 CurBlock = FallThrough; 1548 } 1549 1550 return true; 1551 } 1552 1553 static inline bool areJTsAllowed(const TargetLowering &TLI) { 1554 return !DisableJumpTables && 1555 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 1556 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); 1557 } 1558 1559 static APInt ComputeRange(const APInt &First, const APInt &Last) { 1560 APInt LastExt(Last), FirstExt(First); 1561 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; 1562 LastExt.sext(BitWidth); FirstExt.sext(BitWidth); 1563 return (LastExt - FirstExt + 1ULL); 1564 } 1565 1566 /// handleJTSwitchCase - Emit jumptable for current switch case range 1567 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR, 1568 CaseRecVector& WorkList, 1569 const Value* SV, 1570 MachineBasicBlock* Default, 1571 MachineBasicBlock *SwitchBB) { 1572 Case& FrontCase = *CR.Range.first; 1573 Case& BackCase = *(CR.Range.second-1); 1574 1575 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1576 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1577 1578 APInt TSize(First.getBitWidth(), 0); 1579 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1580 I!=E; ++I) 1581 TSize += I->size(); 1582 1583 if (!areJTsAllowed(TLI) || TSize.ult(4)) 1584 return false; 1585 1586 APInt Range = ComputeRange(First, Last); 1587 double Density = TSize.roundToDouble() / Range.roundToDouble(); 1588 if (Density < 0.4) 1589 return false; 1590 1591 DEBUG(dbgs() << "Lowering jump table\n" 1592 << "First entry: " << First << ". Last entry: " << Last << '\n' 1593 << "Range: " << Range 1594 << "Size: " << TSize << ". Density: " << Density << "\n\n"); 1595 1596 // Get the MachineFunction which holds the current MBB. This is used when 1597 // inserting any additional MBBs necessary to represent the switch. 1598 MachineFunction *CurMF = FuncInfo.MF; 1599 1600 // Figure out which block is immediately after the current one. 1601 MachineFunction::iterator BBI = CR.CaseBB; 1602 ++BBI; 1603 1604 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1605 1606 // Create a new basic block to hold the code for loading the address 1607 // of the jump table, and jumping to it. Update successor information; 1608 // we will either branch to the default case for the switch, or the jump 1609 // table. 1610 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1611 CurMF->insert(BBI, JumpTableBB); 1612 CR.CaseBB->addSuccessor(Default); 1613 CR.CaseBB->addSuccessor(JumpTableBB); 1614 1615 // Build a vector of destination BBs, corresponding to each target 1616 // of the jump table. If the value of the jump table slot corresponds to 1617 // a case statement, push the case's BB onto the vector, otherwise, push 1618 // the default BB. 1619 std::vector<MachineBasicBlock*> DestBBs; 1620 APInt TEI = First; 1621 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 1622 const APInt &Low = cast<ConstantInt>(I->Low)->getValue(); 1623 const APInt &High = cast<ConstantInt>(I->High)->getValue(); 1624 1625 if (Low.sle(TEI) && TEI.sle(High)) { 1626 DestBBs.push_back(I->BB); 1627 if (TEI==High) 1628 ++I; 1629 } else { 1630 DestBBs.push_back(Default); 1631 } 1632 } 1633 1634 // Update successor info. Add one edge to each unique successor. 1635 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 1636 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 1637 E = DestBBs.end(); I != E; ++I) { 1638 if (!SuccsHandled[(*I)->getNumber()]) { 1639 SuccsHandled[(*I)->getNumber()] = true; 1640 JumpTableBB->addSuccessor(*I); 1641 } 1642 } 1643 1644 // Create a jump table index for this jump table. 1645 unsigned JTEncoding = TLI.getJumpTableEncoding(); 1646 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) 1647 ->createJumpTableIndex(DestBBs); 1648 1649 // Set the jump table information so that we can codegen it as a second 1650 // MachineBasicBlock 1651 JumpTable JT(-1U, JTI, JumpTableBB, Default); 1652 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB)); 1653 if (CR.CaseBB == SwitchBB) 1654 visitJumpTableHeader(JT, JTH, SwitchBB); 1655 1656 JTCases.push_back(JumpTableBlock(JTH, JT)); 1657 1658 return true; 1659 } 1660 1661 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into 1662 /// 2 subtrees. 1663 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 1664 CaseRecVector& WorkList, 1665 const Value* SV, 1666 MachineBasicBlock *Default, 1667 MachineBasicBlock *SwitchBB) { 1668 // Get the MachineFunction which holds the current MBB. This is used when 1669 // inserting any additional MBBs necessary to represent the switch. 1670 MachineFunction *CurMF = FuncInfo.MF; 1671 1672 // Figure out which block is immediately after the current one. 1673 MachineFunction::iterator BBI = CR.CaseBB; 1674 ++BBI; 1675 1676 Case& FrontCase = *CR.Range.first; 1677 Case& BackCase = *(CR.Range.second-1); 1678 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1679 1680 // Size is the number of Cases represented by this range. 1681 unsigned Size = CR.Range.second - CR.Range.first; 1682 1683 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 1684 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 1685 double FMetric = 0; 1686 CaseItr Pivot = CR.Range.first + Size/2; 1687 1688 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 1689 // (heuristically) allow us to emit JumpTable's later. 1690 APInt TSize(First.getBitWidth(), 0); 1691 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1692 I!=E; ++I) 1693 TSize += I->size(); 1694 1695 APInt LSize = FrontCase.size(); 1696 APInt RSize = TSize-LSize; 1697 DEBUG(dbgs() << "Selecting best pivot: \n" 1698 << "First: " << First << ", Last: " << Last <<'\n' 1699 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 1700 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 1701 J!=E; ++I, ++J) { 1702 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 1703 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 1704 APInt Range = ComputeRange(LEnd, RBegin); 1705 assert((Range - 2ULL).isNonNegative() && 1706 "Invalid case distance"); 1707 double LDensity = (double)LSize.roundToDouble() / 1708 (LEnd - First + 1ULL).roundToDouble(); 1709 double RDensity = (double)RSize.roundToDouble() / 1710 (Last - RBegin + 1ULL).roundToDouble(); 1711 double Metric = Range.logBase2()*(LDensity+RDensity); 1712 // Should always split in some non-trivial place 1713 DEBUG(dbgs() <<"=>Step\n" 1714 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 1715 << "LDensity: " << LDensity 1716 << ", RDensity: " << RDensity << '\n' 1717 << "Metric: " << Metric << '\n'); 1718 if (FMetric < Metric) { 1719 Pivot = J; 1720 FMetric = Metric; 1721 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); 1722 } 1723 1724 LSize += J->size(); 1725 RSize -= J->size(); 1726 } 1727 if (areJTsAllowed(TLI)) { 1728 // If our case is dense we *really* should handle it earlier! 1729 assert((FMetric > 0) && "Should handle dense range earlier!"); 1730 } else { 1731 Pivot = CR.Range.first + Size/2; 1732 } 1733 1734 CaseRange LHSR(CR.Range.first, Pivot); 1735 CaseRange RHSR(Pivot, CR.Range.second); 1736 Constant *C = Pivot->Low; 1737 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 1738 1739 // We know that we branch to the LHS if the Value being switched on is 1740 // less than the Pivot value, C. We use this to optimize our binary 1741 // tree a bit, by recognizing that if SV is greater than or equal to the 1742 // LHS's Case Value, and that Case Value is exactly one less than the 1743 // Pivot's Value, then we can branch directly to the LHS's Target, 1744 // rather than creating a leaf node for it. 1745 if ((LHSR.second - LHSR.first) == 1 && 1746 LHSR.first->High == CR.GE && 1747 cast<ConstantInt>(C)->getValue() == 1748 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 1749 TrueBB = LHSR.first->BB; 1750 } else { 1751 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1752 CurMF->insert(BBI, TrueBB); 1753 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 1754 1755 // Put SV in a virtual register to make it available from the new blocks. 1756 ExportFromCurrentBlock(SV); 1757 } 1758 1759 // Similar to the optimization above, if the Value being switched on is 1760 // known to be less than the Constant CR.LT, and the current Case Value 1761 // is CR.LT - 1, then we can branch directly to the target block for 1762 // the current Case Value, rather than emitting a RHS leaf node for it. 1763 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 1764 cast<ConstantInt>(RHSR.first->Low)->getValue() == 1765 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 1766 FalseBB = RHSR.first->BB; 1767 } else { 1768 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1769 CurMF->insert(BBI, FalseBB); 1770 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 1771 1772 // Put SV in a virtual register to make it available from the new blocks. 1773 ExportFromCurrentBlock(SV); 1774 } 1775 1776 // Create a CaseBlock record representing a conditional branch to 1777 // the LHS node if the value being switched on SV is less than C. 1778 // Otherwise, branch to LHS. 1779 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 1780 1781 if (CR.CaseBB == SwitchBB) 1782 visitSwitchCase(CB, SwitchBB); 1783 else 1784 SwitchCases.push_back(CB); 1785 1786 return true; 1787 } 1788 1789 /// handleBitTestsSwitchCase - if current case range has few destination and 1790 /// range span less, than machine word bitwidth, encode case range into series 1791 /// of masks and emit bit tests with these masks. 1792 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 1793 CaseRecVector& WorkList, 1794 const Value* SV, 1795 MachineBasicBlock* Default, 1796 MachineBasicBlock *SwitchBB){ 1797 EVT PTy = TLI.getPointerTy(); 1798 unsigned IntPtrBits = PTy.getSizeInBits(); 1799 1800 Case& FrontCase = *CR.Range.first; 1801 Case& BackCase = *(CR.Range.second-1); 1802 1803 // Get the MachineFunction which holds the current MBB. This is used when 1804 // inserting any additional MBBs necessary to represent the switch. 1805 MachineFunction *CurMF = FuncInfo.MF; 1806 1807 // If target does not have legal shift left, do not emit bit tests at all. 1808 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy())) 1809 return false; 1810 1811 size_t numCmps = 0; 1812 for (CaseItr I = CR.Range.first, E = CR.Range.second; 1813 I!=E; ++I) { 1814 // Single case counts one, case range - two. 1815 numCmps += (I->Low == I->High ? 1 : 2); 1816 } 1817 1818 // Count unique destinations 1819 SmallSet<MachineBasicBlock*, 4> Dests; 1820 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1821 Dests.insert(I->BB); 1822 if (Dests.size() > 3) 1823 // Don't bother the code below, if there are too much unique destinations 1824 return false; 1825 } 1826 DEBUG(dbgs() << "Total number of unique destinations: " 1827 << Dests.size() << '\n' 1828 << "Total number of comparisons: " << numCmps << '\n'); 1829 1830 // Compute span of values. 1831 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 1832 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 1833 APInt cmpRange = maxValue - minValue; 1834 1835 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n' 1836 << "Low bound: " << minValue << '\n' 1837 << "High bound: " << maxValue << '\n'); 1838 1839 if (cmpRange.uge(IntPtrBits) || 1840 (!(Dests.size() == 1 && numCmps >= 3) && 1841 !(Dests.size() == 2 && numCmps >= 5) && 1842 !(Dests.size() >= 3 && numCmps >= 6))) 1843 return false; 1844 1845 DEBUG(dbgs() << "Emitting bit tests\n"); 1846 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 1847 1848 // Optimize the case where all the case values fit in a 1849 // word without having to subtract minValue. In this case, 1850 // we can optimize away the subtraction. 1851 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) { 1852 cmpRange = maxValue; 1853 } else { 1854 lowBound = minValue; 1855 } 1856 1857 CaseBitsVector CasesBits; 1858 unsigned i, count = 0; 1859 1860 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 1861 MachineBasicBlock* Dest = I->BB; 1862 for (i = 0; i < count; ++i) 1863 if (Dest == CasesBits[i].BB) 1864 break; 1865 1866 if (i == count) { 1867 assert((count < 3) && "Too much destinations to test!"); 1868 CasesBits.push_back(CaseBits(0, Dest, 0)); 1869 count++; 1870 } 1871 1872 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 1873 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 1874 1875 uint64_t lo = (lowValue - lowBound).getZExtValue(); 1876 uint64_t hi = (highValue - lowBound).getZExtValue(); 1877 1878 for (uint64_t j = lo; j <= hi; j++) { 1879 CasesBits[i].Mask |= 1ULL << j; 1880 CasesBits[i].Bits++; 1881 } 1882 1883 } 1884 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 1885 1886 BitTestInfo BTC; 1887 1888 // Figure out which block is immediately after the current one. 1889 MachineFunction::iterator BBI = CR.CaseBB; 1890 ++BBI; 1891 1892 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 1893 1894 DEBUG(dbgs() << "Cases:\n"); 1895 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 1896 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask 1897 << ", Bits: " << CasesBits[i].Bits 1898 << ", BB: " << CasesBits[i].BB << '\n'); 1899 1900 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 1901 CurMF->insert(BBI, CaseBB); 1902 BTC.push_back(BitTestCase(CasesBits[i].Mask, 1903 CaseBB, 1904 CasesBits[i].BB)); 1905 1906 // Put SV in a virtual register to make it available from the new blocks. 1907 ExportFromCurrentBlock(SV); 1908 } 1909 1910 BitTestBlock BTB(lowBound, cmpRange, SV, 1911 -1U, (CR.CaseBB == SwitchBB), 1912 CR.CaseBB, Default, BTC); 1913 1914 if (CR.CaseBB == SwitchBB) 1915 visitBitTestHeader(BTB, SwitchBB); 1916 1917 BitTestCases.push_back(BTB); 1918 1919 return true; 1920 } 1921 1922 /// Clusterify - Transform simple list of Cases into list of CaseRange's 1923 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 1924 const SwitchInst& SI) { 1925 size_t numCmps = 0; 1926 1927 // Start with "simple" cases 1928 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) { 1929 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)]; 1930 Cases.push_back(Case(SI.getSuccessorValue(i), 1931 SI.getSuccessorValue(i), 1932 SMBB)); 1933 } 1934 std::sort(Cases.begin(), Cases.end(), CaseCmp()); 1935 1936 // Merge case into clusters 1937 if (Cases.size() >= 2) 1938 // Must recompute end() each iteration because it may be 1939 // invalidated by erase if we hold on to it 1940 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) { 1941 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue(); 1942 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue(); 1943 MachineBasicBlock* nextBB = J->BB; 1944 MachineBasicBlock* currentBB = I->BB; 1945 1946 // If the two neighboring cases go to the same destination, merge them 1947 // into a single case. 1948 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) { 1949 I->High = J->High; 1950 J = Cases.erase(J); 1951 } else { 1952 I = J++; 1953 } 1954 } 1955 1956 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) { 1957 if (I->Low != I->High) 1958 // A range counts double, since it requires two compares. 1959 ++numCmps; 1960 } 1961 1962 return numCmps; 1963 } 1964 1965 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 1966 MachineBasicBlock *SwitchMBB = FuncInfo.MBBMap[SI.getParent()]; 1967 1968 // Figure out which block is immediately after the current one. 1969 MachineBasicBlock *NextBlock = 0; 1970 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 1971 1972 // If there is only the default destination, branch to it if it is not the 1973 // next basic block. Otherwise, just fall through. 1974 if (SI.getNumOperands() == 2) { 1975 // Update machine-CFG edges. 1976 1977 // If this is not a fall-through branch, emit the branch. 1978 SwitchMBB->addSuccessor(Default); 1979 if (Default != NextBlock) 1980 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), 1981 MVT::Other, getControlRoot(), 1982 DAG.getBasicBlock(Default))); 1983 1984 return; 1985 } 1986 1987 // If there are any non-default case statements, create a vector of Cases 1988 // representing each one, and sort the vector so that we can efficiently 1989 // create a binary search tree from them. 1990 CaseVector Cases; 1991 size_t numCmps = Clusterify(Cases, SI); 1992 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 1993 << ". Total compares: " << numCmps << '\n'); 1994 numCmps = 0; 1995 1996 // Get the Value to be switched on and default basic blocks, which will be 1997 // inserted into CaseBlock records, representing basic blocks in the binary 1998 // search tree. 1999 const Value *SV = SI.getOperand(0); 2000 2001 // Push the initial CaseRec onto the worklist 2002 CaseRecVector WorkList; 2003 WorkList.push_back(CaseRec(SwitchMBB,0,0, 2004 CaseRange(Cases.begin(),Cases.end()))); 2005 2006 while (!WorkList.empty()) { 2007 // Grab a record representing a case range to process off the worklist 2008 CaseRec CR = WorkList.back(); 2009 WorkList.pop_back(); 2010 2011 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2012 continue; 2013 2014 // If the range has few cases (two or less) emit a series of specific 2015 // tests. 2016 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB)) 2017 continue; 2018 2019 // If the switch has more than 5 blocks, and at least 40% dense, and the 2020 // target supports indirect branches, then emit a jump table rather than 2021 // lowering the switch to a binary tree of conditional branches. 2022 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2023 continue; 2024 2025 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2026 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2027 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB); 2028 } 2029 } 2030 2031 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2032 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBBMap[I.getParent()]; 2033 2034 // Update machine-CFG edges with unique successors. 2035 SmallVector<BasicBlock*, 32> succs; 2036 succs.reserve(I.getNumSuccessors()); 2037 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) 2038 succs.push_back(I.getSuccessor(i)); 2039 array_pod_sort(succs.begin(), succs.end()); 2040 succs.erase(std::unique(succs.begin(), succs.end()), succs.end()); 2041 for (unsigned i = 0, e = succs.size(); i != e; ++i) 2042 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]); 2043 2044 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(), 2045 MVT::Other, getControlRoot(), 2046 getValue(I.getAddress()))); 2047 } 2048 2049 void SelectionDAGBuilder::visitFSub(const User &I) { 2050 // -0.0 - X --> fneg 2051 const Type *Ty = I.getType(); 2052 if (Ty->isVectorTy()) { 2053 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) { 2054 const VectorType *DestTy = cast<VectorType>(I.getType()); 2055 const Type *ElTy = DestTy->getElementType(); 2056 unsigned VL = DestTy->getNumElements(); 2057 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy)); 2058 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size()); 2059 if (CV == CNZ) { 2060 SDValue Op2 = getValue(I.getOperand(1)); 2061 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2062 Op2.getValueType(), Op2)); 2063 return; 2064 } 2065 } 2066 } 2067 2068 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) 2069 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) { 2070 SDValue Op2 = getValue(I.getOperand(1)); 2071 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(), 2072 Op2.getValueType(), Op2)); 2073 return; 2074 } 2075 2076 visitBinary(I, ISD::FSUB); 2077 } 2078 2079 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2080 SDValue Op1 = getValue(I.getOperand(0)); 2081 SDValue Op2 = getValue(I.getOperand(1)); 2082 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(), 2083 Op1.getValueType(), Op1, Op2)); 2084 } 2085 2086 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2087 SDValue Op1 = getValue(I.getOperand(0)); 2088 SDValue Op2 = getValue(I.getOperand(1)); 2089 if (!I.getType()->isVectorTy() && 2090 Op2.getValueType() != TLI.getShiftAmountTy()) { 2091 // If the operand is smaller than the shift count type, promote it. 2092 EVT PTy = TLI.getPointerTy(); 2093 EVT STy = TLI.getShiftAmountTy(); 2094 if (STy.bitsGT(Op2.getValueType())) 2095 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2096 TLI.getShiftAmountTy(), Op2); 2097 // If the operand is larger than the shift count type but the shift 2098 // count type has enough bits to represent any shift value, truncate 2099 // it now. This is a common case and it exposes the truncate to 2100 // optimization early. 2101 else if (STy.getSizeInBits() >= 2102 Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2103 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2104 TLI.getShiftAmountTy(), Op2); 2105 // Otherwise we'll need to temporarily settle for some other 2106 // convenient type; type legalization will make adjustments as 2107 // needed. 2108 else if (PTy.bitsLT(Op2.getValueType())) 2109 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2110 TLI.getPointerTy(), Op2); 2111 else if (PTy.bitsGT(Op2.getValueType())) 2112 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(), 2113 TLI.getPointerTy(), Op2); 2114 } 2115 2116 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), 2117 Op1.getValueType(), Op1, Op2)); 2118 } 2119 2120 void SelectionDAGBuilder::visitICmp(const User &I) { 2121 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2122 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2123 predicate = IC->getPredicate(); 2124 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2125 predicate = ICmpInst::Predicate(IC->getPredicate()); 2126 SDValue Op1 = getValue(I.getOperand(0)); 2127 SDValue Op2 = getValue(I.getOperand(1)); 2128 ISD::CondCode Opcode = getICmpCondCode(predicate); 2129 2130 EVT DestVT = TLI.getValueType(I.getType()); 2131 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode)); 2132 } 2133 2134 void SelectionDAGBuilder::visitFCmp(const User &I) { 2135 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2136 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2137 predicate = FC->getPredicate(); 2138 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2139 predicate = FCmpInst::Predicate(FC->getPredicate()); 2140 SDValue Op1 = getValue(I.getOperand(0)); 2141 SDValue Op2 = getValue(I.getOperand(1)); 2142 ISD::CondCode Condition = getFCmpCondCode(predicate); 2143 EVT DestVT = TLI.getValueType(I.getType()); 2144 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition)); 2145 } 2146 2147 void SelectionDAGBuilder::visitSelect(const User &I) { 2148 SmallVector<EVT, 4> ValueVTs; 2149 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2150 unsigned NumValues = ValueVTs.size(); 2151 if (NumValues == 0) return; 2152 2153 SmallVector<SDValue, 4> Values(NumValues); 2154 SDValue Cond = getValue(I.getOperand(0)); 2155 SDValue TrueVal = getValue(I.getOperand(1)); 2156 SDValue FalseVal = getValue(I.getOperand(2)); 2157 2158 for (unsigned i = 0; i != NumValues; ++i) 2159 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(), 2160 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i), 2161 Cond, 2162 SDValue(TrueVal.getNode(), 2163 TrueVal.getResNo() + i), 2164 SDValue(FalseVal.getNode(), 2165 FalseVal.getResNo() + i)); 2166 2167 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2168 DAG.getVTList(&ValueVTs[0], NumValues), 2169 &Values[0], NumValues)); 2170 } 2171 2172 void SelectionDAGBuilder::visitTrunc(const User &I) { 2173 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2174 SDValue N = getValue(I.getOperand(0)); 2175 EVT DestVT = TLI.getValueType(I.getType()); 2176 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N)); 2177 } 2178 2179 void SelectionDAGBuilder::visitZExt(const User &I) { 2180 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2181 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2182 SDValue N = getValue(I.getOperand(0)); 2183 EVT DestVT = TLI.getValueType(I.getType()); 2184 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N)); 2185 } 2186 2187 void SelectionDAGBuilder::visitSExt(const User &I) { 2188 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2189 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2190 SDValue N = getValue(I.getOperand(0)); 2191 EVT DestVT = TLI.getValueType(I.getType()); 2192 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N)); 2193 } 2194 2195 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2196 // FPTrunc is never a no-op cast, no need to check 2197 SDValue N = getValue(I.getOperand(0)); 2198 EVT DestVT = TLI.getValueType(I.getType()); 2199 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(), 2200 DestVT, N, DAG.getIntPtrConstant(0))); 2201 } 2202 2203 void SelectionDAGBuilder::visitFPExt(const User &I){ 2204 // FPTrunc is never a no-op cast, no need to check 2205 SDValue N = getValue(I.getOperand(0)); 2206 EVT DestVT = TLI.getValueType(I.getType()); 2207 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N)); 2208 } 2209 2210 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2211 // FPToUI is never a no-op cast, no need to check 2212 SDValue N = getValue(I.getOperand(0)); 2213 EVT DestVT = TLI.getValueType(I.getType()); 2214 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N)); 2215 } 2216 2217 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2218 // FPToSI is never a no-op cast, no need to check 2219 SDValue N = getValue(I.getOperand(0)); 2220 EVT DestVT = TLI.getValueType(I.getType()); 2221 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N)); 2222 } 2223 2224 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2225 // UIToFP is never a no-op cast, no need to check 2226 SDValue N = getValue(I.getOperand(0)); 2227 EVT DestVT = TLI.getValueType(I.getType()); 2228 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2229 } 2230 2231 void SelectionDAGBuilder::visitSIToFP(const User &I){ 2232 // SIToFP is never a no-op cast, no need to check 2233 SDValue N = getValue(I.getOperand(0)); 2234 EVT DestVT = TLI.getValueType(I.getType()); 2235 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N)); 2236 } 2237 2238 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2239 // What to do depends on the size of the integer and the size of the pointer. 2240 // We can either truncate, zero extend, or no-op, accordingly. 2241 SDValue N = getValue(I.getOperand(0)); 2242 EVT SrcVT = N.getValueType(); 2243 EVT DestVT = TLI.getValueType(I.getType()); 2244 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2245 } 2246 2247 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2248 // What to do depends on the size of the integer and the size of the pointer. 2249 // We can either truncate, zero extend, or no-op, accordingly. 2250 SDValue N = getValue(I.getOperand(0)); 2251 EVT SrcVT = N.getValueType(); 2252 EVT DestVT = TLI.getValueType(I.getType()); 2253 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT)); 2254 } 2255 2256 void SelectionDAGBuilder::visitBitCast(const User &I) { 2257 SDValue N = getValue(I.getOperand(0)); 2258 EVT DestVT = TLI.getValueType(I.getType()); 2259 2260 // BitCast assures us that source and destination are the same size so this is 2261 // either a BIT_CONVERT or a no-op. 2262 if (DestVT != N.getValueType()) 2263 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 2264 DestVT, N)); // convert types. 2265 else 2266 setValue(&I, N); // noop cast. 2267 } 2268 2269 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2270 SDValue InVec = getValue(I.getOperand(0)); 2271 SDValue InVal = getValue(I.getOperand(1)); 2272 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2273 TLI.getPointerTy(), 2274 getValue(I.getOperand(2))); 2275 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(), 2276 TLI.getValueType(I.getType()), 2277 InVec, InVal, InIdx)); 2278 } 2279 2280 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2281 SDValue InVec = getValue(I.getOperand(0)); 2282 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), 2283 TLI.getPointerTy(), 2284 getValue(I.getOperand(1))); 2285 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2286 TLI.getValueType(I.getType()), InVec, InIdx)); 2287 } 2288 2289 // Utility for visitShuffleVector - Returns true if the mask is mask starting 2290 // from SIndx and increasing to the element length (undefs are allowed). 2291 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) { 2292 unsigned MaskNumElts = Mask.size(); 2293 for (unsigned i = 0; i != MaskNumElts; ++i) 2294 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx))) 2295 return false; 2296 return true; 2297 } 2298 2299 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2300 SmallVector<int, 8> Mask; 2301 SDValue Src1 = getValue(I.getOperand(0)); 2302 SDValue Src2 = getValue(I.getOperand(1)); 2303 2304 // Convert the ConstantVector mask operand into an array of ints, with -1 2305 // representing undef values. 2306 SmallVector<Constant*, 8> MaskElts; 2307 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts); 2308 unsigned MaskNumElts = MaskElts.size(); 2309 for (unsigned i = 0; i != MaskNumElts; ++i) { 2310 if (isa<UndefValue>(MaskElts[i])) 2311 Mask.push_back(-1); 2312 else 2313 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue()); 2314 } 2315 2316 EVT VT = TLI.getValueType(I.getType()); 2317 EVT SrcVT = Src1.getValueType(); 2318 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2319 2320 if (SrcNumElts == MaskNumElts) { 2321 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2322 &Mask[0])); 2323 return; 2324 } 2325 2326 // Normalize the shuffle vector since mask and vector length don't match. 2327 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2328 // Mask is longer than the source vectors and is a multiple of the source 2329 // vectors. We can use concatenate vector to make the mask and vectors 2330 // lengths match. 2331 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) { 2332 // The shuffle is concatenating two vectors together. 2333 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(), 2334 VT, Src1, Src2)); 2335 return; 2336 } 2337 2338 // Pad both vectors with undefs to make them the same length as the mask. 2339 unsigned NumConcat = MaskNumElts / SrcNumElts; 2340 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 2341 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 2342 SDValue UndefVal = DAG.getUNDEF(SrcVT); 2343 2344 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 2345 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 2346 MOps1[0] = Src1; 2347 MOps2[0] = Src2; 2348 2349 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2350 getCurDebugLoc(), VT, 2351 &MOps1[0], NumConcat); 2352 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 2353 getCurDebugLoc(), VT, 2354 &MOps2[0], NumConcat); 2355 2356 // Readjust mask for new input vector length. 2357 SmallVector<int, 8> MappedOps; 2358 for (unsigned i = 0; i != MaskNumElts; ++i) { 2359 int Idx = Mask[i]; 2360 if (Idx < (int)SrcNumElts) 2361 MappedOps.push_back(Idx); 2362 else 2363 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts); 2364 } 2365 2366 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2367 &MappedOps[0])); 2368 return; 2369 } 2370 2371 if (SrcNumElts > MaskNumElts) { 2372 // Analyze the access pattern of the vector to see if we can extract 2373 // two subvectors and do the shuffle. The analysis is done by calculating 2374 // the range of elements the mask access on both vectors. 2375 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1}; 2376 int MaxRange[2] = {-1, -1}; 2377 2378 for (unsigned i = 0; i != MaskNumElts; ++i) { 2379 int Idx = Mask[i]; 2380 int Input = 0; 2381 if (Idx < 0) 2382 continue; 2383 2384 if (Idx >= (int)SrcNumElts) { 2385 Input = 1; 2386 Idx -= SrcNumElts; 2387 } 2388 if (Idx > MaxRange[Input]) 2389 MaxRange[Input] = Idx; 2390 if (Idx < MinRange[Input]) 2391 MinRange[Input] = Idx; 2392 } 2393 2394 // Check if the access is smaller than the vector size and can we find 2395 // a reasonable extract index. 2396 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not 2397 // Extract. 2398 int StartIdx[2]; // StartIdx to extract from 2399 for (int Input=0; Input < 2; ++Input) { 2400 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) { 2401 RangeUse[Input] = 0; // Unused 2402 StartIdx[Input] = 0; 2403 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) { 2404 // Fits within range but we should see if we can find a good 2405 // start index that is a multiple of the mask length. 2406 if (MaxRange[Input] < (int)MaskNumElts) { 2407 RangeUse[Input] = 1; // Extract from beginning of the vector 2408 StartIdx[Input] = 0; 2409 } else { 2410 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 2411 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 2412 StartIdx[Input] + MaskNumElts < SrcNumElts) 2413 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 2414 } 2415 } 2416 } 2417 2418 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 2419 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 2420 return; 2421 } 2422 else if (RangeUse[0] < 2 && RangeUse[1] < 2) { 2423 // Extract appropriate subvector and generate a vector shuffle 2424 for (int Input=0; Input < 2; ++Input) { 2425 SDValue &Src = Input == 0 ? Src1 : Src2; 2426 if (RangeUse[Input] == 0) 2427 Src = DAG.getUNDEF(VT); 2428 else 2429 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT, 2430 Src, DAG.getIntPtrConstant(StartIdx[Input])); 2431 } 2432 2433 // Calculate new mask. 2434 SmallVector<int, 8> MappedOps; 2435 for (unsigned i = 0; i != MaskNumElts; ++i) { 2436 int Idx = Mask[i]; 2437 if (Idx < 0) 2438 MappedOps.push_back(Idx); 2439 else if (Idx < (int)SrcNumElts) 2440 MappedOps.push_back(Idx - StartIdx[0]); 2441 else 2442 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts); 2443 } 2444 2445 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2, 2446 &MappedOps[0])); 2447 return; 2448 } 2449 } 2450 2451 // We can't use either concat vectors or extract subvectors so fall back to 2452 // replacing the shuffle with extract and build vector. 2453 // to insert and build vector. 2454 EVT EltVT = VT.getVectorElementType(); 2455 EVT PtrVT = TLI.getPointerTy(); 2456 SmallVector<SDValue,8> Ops; 2457 for (unsigned i = 0; i != MaskNumElts; ++i) { 2458 if (Mask[i] < 0) { 2459 Ops.push_back(DAG.getUNDEF(EltVT)); 2460 } else { 2461 int Idx = Mask[i]; 2462 SDValue Res; 2463 2464 if (Idx < (int)SrcNumElts) 2465 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2466 EltVT, Src1, DAG.getConstant(Idx, PtrVT)); 2467 else 2468 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(), 2469 EltVT, Src2, 2470 DAG.getConstant(Idx - SrcNumElts, PtrVT)); 2471 2472 Ops.push_back(Res); 2473 } 2474 } 2475 2476 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(), 2477 VT, &Ops[0], Ops.size())); 2478 } 2479 2480 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 2481 const Value *Op0 = I.getOperand(0); 2482 const Value *Op1 = I.getOperand(1); 2483 const Type *AggTy = I.getType(); 2484 const Type *ValTy = Op1->getType(); 2485 bool IntoUndef = isa<UndefValue>(Op0); 2486 bool FromUndef = isa<UndefValue>(Op1); 2487 2488 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2489 I.idx_begin(), I.idx_end()); 2490 2491 SmallVector<EVT, 4> AggValueVTs; 2492 ComputeValueVTs(TLI, AggTy, AggValueVTs); 2493 SmallVector<EVT, 4> ValValueVTs; 2494 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2495 2496 unsigned NumAggValues = AggValueVTs.size(); 2497 unsigned NumValValues = ValValueVTs.size(); 2498 SmallVector<SDValue, 4> Values(NumAggValues); 2499 2500 SDValue Agg = getValue(Op0); 2501 SDValue Val = getValue(Op1); 2502 unsigned i = 0; 2503 // Copy the beginning value(s) from the original aggregate. 2504 for (; i != LinearIndex; ++i) 2505 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2506 SDValue(Agg.getNode(), Agg.getResNo() + i); 2507 // Copy values from the inserted value(s). 2508 for (; i != LinearIndex + NumValValues; ++i) 2509 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2510 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 2511 // Copy remaining value(s) from the original aggregate. 2512 for (; i != NumAggValues; ++i) 2513 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 2514 SDValue(Agg.getNode(), Agg.getResNo() + i); 2515 2516 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2517 DAG.getVTList(&AggValueVTs[0], NumAggValues), 2518 &Values[0], NumAggValues)); 2519 } 2520 2521 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 2522 const Value *Op0 = I.getOperand(0); 2523 const Type *AggTy = Op0->getType(); 2524 const Type *ValTy = I.getType(); 2525 bool OutOfUndef = isa<UndefValue>(Op0); 2526 2527 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy, 2528 I.idx_begin(), I.idx_end()); 2529 2530 SmallVector<EVT, 4> ValValueVTs; 2531 ComputeValueVTs(TLI, ValTy, ValValueVTs); 2532 2533 unsigned NumValValues = ValValueVTs.size(); 2534 SmallVector<SDValue, 4> Values(NumValValues); 2535 2536 SDValue Agg = getValue(Op0); 2537 // Copy out the selected value(s). 2538 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 2539 Values[i - LinearIndex] = 2540 OutOfUndef ? 2541 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 2542 SDValue(Agg.getNode(), Agg.getResNo() + i); 2543 2544 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2545 DAG.getVTList(&ValValueVTs[0], NumValValues), 2546 &Values[0], NumValValues)); 2547 } 2548 2549 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 2550 SDValue N = getValue(I.getOperand(0)); 2551 const Type *Ty = I.getOperand(0)->getType(); 2552 2553 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 2554 OI != E; ++OI) { 2555 const Value *Idx = *OI; 2556 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 2557 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2558 if (Field) { 2559 // N = N + Offset 2560 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 2561 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2562 DAG.getIntPtrConstant(Offset)); 2563 } 2564 2565 Ty = StTy->getElementType(Field); 2566 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) { 2567 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 2568 2569 // Offset canonically 0 for unions, but type changes 2570 Ty = UnTy->getElementType(Field); 2571 } else { 2572 Ty = cast<SequentialType>(Ty)->getElementType(); 2573 2574 // If this is a constant subscript, handle it quickly. 2575 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 2576 if (CI->getZExtValue() == 0) continue; 2577 uint64_t Offs = 2578 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 2579 SDValue OffsVal; 2580 EVT PTy = TLI.getPointerTy(); 2581 unsigned PtrBits = PTy.getSizeInBits(); 2582 if (PtrBits < 64) 2583 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), 2584 TLI.getPointerTy(), 2585 DAG.getConstant(Offs, MVT::i64)); 2586 else 2587 OffsVal = DAG.getIntPtrConstant(Offs); 2588 2589 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N, 2590 OffsVal); 2591 continue; 2592 } 2593 2594 // N = N + Idx * ElementSize; 2595 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(), 2596 TD->getTypeAllocSize(Ty)); 2597 SDValue IdxN = getValue(Idx); 2598 2599 // If the index is smaller or larger than intptr_t, truncate or extend 2600 // it. 2601 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType()); 2602 2603 // If this is a multiply by a power of two, turn it into a shl 2604 // immediately. This is a very common case. 2605 if (ElementSize != 1) { 2606 if (ElementSize.isPowerOf2()) { 2607 unsigned Amt = ElementSize.logBase2(); 2608 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(), 2609 N.getValueType(), IdxN, 2610 DAG.getConstant(Amt, TLI.getPointerTy())); 2611 } else { 2612 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy()); 2613 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(), 2614 N.getValueType(), IdxN, Scale); 2615 } 2616 } 2617 2618 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2619 N.getValueType(), N, IdxN); 2620 } 2621 } 2622 2623 setValue(&I, N); 2624 } 2625 2626 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 2627 // If this is a fixed sized alloca in the entry block of the function, 2628 // allocate it statically on the stack. 2629 if (FuncInfo.StaticAllocaMap.count(&I)) 2630 return; // getValue will auto-populate this. 2631 2632 const Type *Ty = I.getAllocatedType(); 2633 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 2634 unsigned Align = 2635 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), 2636 I.getAlignment()); 2637 2638 SDValue AllocSize = getValue(I.getArraySize()); 2639 2640 EVT IntPtr = TLI.getPointerTy(); 2641 if (AllocSize.getValueType() != IntPtr) 2642 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr); 2643 2644 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr, 2645 AllocSize, 2646 DAG.getConstant(TySize, IntPtr)); 2647 2648 // Handle alignment. If the requested alignment is less than or equal to 2649 // the stack alignment, ignore it. If the size is greater than or equal to 2650 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 2651 unsigned StackAlign = TM.getFrameInfo()->getStackAlignment(); 2652 if (Align <= StackAlign) 2653 Align = 0; 2654 2655 // Round the size of the allocation up to the stack alignment size 2656 // by add SA-1 to the size. 2657 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2658 AllocSize.getValueType(), AllocSize, 2659 DAG.getIntPtrConstant(StackAlign-1)); 2660 2661 // Mask out the low bits for alignment purposes. 2662 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(), 2663 AllocSize.getValueType(), AllocSize, 2664 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 2665 2666 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 2667 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 2668 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(), 2669 VTs, Ops, 3); 2670 setValue(&I, DSA); 2671 DAG.setRoot(DSA.getValue(1)); 2672 2673 // Inform the Frame Information that we have just allocated a variable-sized 2674 // object. 2675 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(); 2676 } 2677 2678 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 2679 const Value *SV = I.getOperand(0); 2680 SDValue Ptr = getValue(SV); 2681 2682 const Type *Ty = I.getType(); 2683 2684 bool isVolatile = I.isVolatile(); 2685 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 2686 unsigned Alignment = I.getAlignment(); 2687 2688 SmallVector<EVT, 4> ValueVTs; 2689 SmallVector<uint64_t, 4> Offsets; 2690 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets); 2691 unsigned NumValues = ValueVTs.size(); 2692 if (NumValues == 0) 2693 return; 2694 2695 SDValue Root; 2696 bool ConstantMemory = false; 2697 if (I.isVolatile()) 2698 // Serialize volatile loads with other side effects. 2699 Root = getRoot(); 2700 else if (AA->pointsToConstantMemory(SV)) { 2701 // Do not serialize (non-volatile) loads of constant memory with anything. 2702 Root = DAG.getEntryNode(); 2703 ConstantMemory = true; 2704 } else { 2705 // Do not serialize non-volatile loads against each other. 2706 Root = DAG.getRoot(); 2707 } 2708 2709 SmallVector<SDValue, 4> Values(NumValues); 2710 SmallVector<SDValue, 4> Chains(NumValues); 2711 EVT PtrVT = Ptr.getValueType(); 2712 for (unsigned i = 0; i != NumValues; ++i) { 2713 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(), 2714 PtrVT, Ptr, 2715 DAG.getConstant(Offsets[i], PtrVT)); 2716 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root, 2717 A, SV, Offsets[i], isVolatile, 2718 isNonTemporal, Alignment); 2719 2720 Values[i] = L; 2721 Chains[i] = L.getValue(1); 2722 } 2723 2724 if (!ConstantMemory) { 2725 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2726 MVT::Other, &Chains[0], NumValues); 2727 if (isVolatile) 2728 DAG.setRoot(Chain); 2729 else 2730 PendingLoads.push_back(Chain); 2731 } 2732 2733 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 2734 DAG.getVTList(&ValueVTs[0], NumValues), 2735 &Values[0], NumValues)); 2736 } 2737 2738 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 2739 const Value *SrcV = I.getOperand(0); 2740 const Value *PtrV = I.getOperand(1); 2741 2742 SmallVector<EVT, 4> ValueVTs; 2743 SmallVector<uint64_t, 4> Offsets; 2744 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets); 2745 unsigned NumValues = ValueVTs.size(); 2746 if (NumValues == 0) 2747 return; 2748 2749 // Get the lowered operands. Note that we do this after 2750 // checking if NumResults is zero, because with zero results 2751 // the operands won't have values in the map. 2752 SDValue Src = getValue(SrcV); 2753 SDValue Ptr = getValue(PtrV); 2754 2755 SDValue Root = getRoot(); 2756 SmallVector<SDValue, 4> Chains(NumValues); 2757 EVT PtrVT = Ptr.getValueType(); 2758 bool isVolatile = I.isVolatile(); 2759 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 2760 unsigned Alignment = I.getAlignment(); 2761 2762 for (unsigned i = 0; i != NumValues; ++i) { 2763 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr, 2764 DAG.getConstant(Offsets[i], PtrVT)); 2765 Chains[i] = DAG.getStore(Root, getCurDebugLoc(), 2766 SDValue(Src.getNode(), Src.getResNo() + i), 2767 Add, PtrV, Offsets[i], isVolatile, 2768 isNonTemporal, Alignment); 2769 } 2770 2771 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 2772 MVT::Other, &Chains[0], NumValues)); 2773 } 2774 2775 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 2776 /// node. 2777 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 2778 unsigned Intrinsic) { 2779 bool HasChain = !I.doesNotAccessMemory(); 2780 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 2781 2782 // Build the operand list. 2783 SmallVector<SDValue, 8> Ops; 2784 if (HasChain) { // If this intrinsic has side-effects, chainify it. 2785 if (OnlyLoad) { 2786 // We don't need to serialize loads against other loads. 2787 Ops.push_back(DAG.getRoot()); 2788 } else { 2789 Ops.push_back(getRoot()); 2790 } 2791 } 2792 2793 // Info is set by getTgtMemInstrinsic 2794 TargetLowering::IntrinsicInfo Info; 2795 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 2796 2797 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 2798 if (!IsTgtIntrinsic) 2799 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy())); 2800 2801 // Add all operands of the call to the operand list. 2802 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) { 2803 SDValue Op = getValue(I.getOperand(i)); 2804 assert(TLI.isTypeLegal(Op.getValueType()) && 2805 "Intrinsic uses a non-legal type?"); 2806 Ops.push_back(Op); 2807 } 2808 2809 SmallVector<EVT, 4> ValueVTs; 2810 ComputeValueVTs(TLI, I.getType(), ValueVTs); 2811 #ifndef NDEBUG 2812 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) { 2813 assert(TLI.isTypeLegal(ValueVTs[Val]) && 2814 "Intrinsic uses a non-legal type?"); 2815 } 2816 #endif // NDEBUG 2817 2818 if (HasChain) 2819 ValueVTs.push_back(MVT::Other); 2820 2821 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 2822 2823 // Create the node. 2824 SDValue Result; 2825 if (IsTgtIntrinsic) { 2826 // This is target intrinsic that touches memory 2827 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(), 2828 VTs, &Ops[0], Ops.size(), 2829 Info.memVT, Info.ptrVal, Info.offset, 2830 Info.align, Info.vol, 2831 Info.readMem, Info.writeMem); 2832 } else if (!HasChain) { 2833 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(), 2834 VTs, &Ops[0], Ops.size()); 2835 } else if (!I.getType()->isVoidTy()) { 2836 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(), 2837 VTs, &Ops[0], Ops.size()); 2838 } else { 2839 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(), 2840 VTs, &Ops[0], Ops.size()); 2841 } 2842 2843 if (HasChain) { 2844 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 2845 if (OnlyLoad) 2846 PendingLoads.push_back(Chain); 2847 else 2848 DAG.setRoot(Chain); 2849 } 2850 2851 if (!I.getType()->isVoidTy()) { 2852 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 2853 EVT VT = TLI.getValueType(PTy); 2854 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result); 2855 } 2856 2857 setValue(&I, Result); 2858 } 2859 } 2860 2861 /// GetSignificand - Get the significand and build it into a floating-point 2862 /// number with exponent of 1: 2863 /// 2864 /// Op = (Op & 0x007fffff) | 0x3f800000; 2865 /// 2866 /// where Op is the hexidecimal representation of floating point value. 2867 static SDValue 2868 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) { 2869 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 2870 DAG.getConstant(0x007fffff, MVT::i32)); 2871 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 2872 DAG.getConstant(0x3f800000, MVT::i32)); 2873 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2); 2874 } 2875 2876 /// GetExponent - Get the exponent: 2877 /// 2878 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 2879 /// 2880 /// where Op is the hexidecimal representation of floating point value. 2881 static SDValue 2882 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 2883 DebugLoc dl) { 2884 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 2885 DAG.getConstant(0x7f800000, MVT::i32)); 2886 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 2887 DAG.getConstant(23, TLI.getPointerTy())); 2888 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 2889 DAG.getConstant(127, MVT::i32)); 2890 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 2891 } 2892 2893 /// getF32Constant - Get 32-bit floating point constant. 2894 static SDValue 2895 getF32Constant(SelectionDAG &DAG, unsigned Flt) { 2896 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32); 2897 } 2898 2899 /// Inlined utility function to implement binary input atomic intrinsics for 2900 /// visitIntrinsicCall: I is a call instruction 2901 /// Op is the associated NodeType for I 2902 const char * 2903 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I, 2904 ISD::NodeType Op) { 2905 SDValue Root = getRoot(); 2906 SDValue L = 2907 DAG.getAtomic(Op, getCurDebugLoc(), 2908 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 2909 Root, 2910 getValue(I.getOperand(1)), 2911 getValue(I.getOperand(2)), 2912 I.getOperand(1)); 2913 setValue(&I, L); 2914 DAG.setRoot(L.getValue(1)); 2915 return 0; 2916 } 2917 2918 // implVisitAluOverflow - Lower arithmetic overflow instrinsics. 2919 const char * 2920 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) { 2921 SDValue Op1 = getValue(I.getOperand(1)); 2922 SDValue Op2 = getValue(I.getOperand(2)); 2923 2924 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 2925 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2)); 2926 return 0; 2927 } 2928 2929 /// visitExp - Lower an exp intrinsic. Handles the special sequences for 2930 /// limited-precision mode. 2931 void 2932 SelectionDAGBuilder::visitExp(const CallInst &I) { 2933 SDValue result; 2934 DebugLoc dl = getCurDebugLoc(); 2935 2936 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 2937 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 2938 SDValue Op = getValue(I.getOperand(1)); 2939 2940 // Put the exponent in the right bit position for later addition to the 2941 // final result: 2942 // 2943 // #define LOG2OFe 1.4426950f 2944 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 2945 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 2946 getF32Constant(DAG, 0x3fb8aa3b)); 2947 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 2948 2949 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 2950 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 2951 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 2952 2953 // IntegerPartOfX <<= 23; 2954 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 2955 DAG.getConstant(23, TLI.getPointerTy())); 2956 2957 if (LimitFloatPrecision <= 6) { 2958 // For floating-point precision of 6: 2959 // 2960 // TwoToFractionalPartOfX = 2961 // 0.997535578f + 2962 // (0.735607626f + 0.252464424f * x) * x; 2963 // 2964 // error 0.0144103317, which is 6 bits 2965 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 2966 getF32Constant(DAG, 0x3e814304)); 2967 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 2968 getF32Constant(DAG, 0x3f3c50c8)); 2969 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 2970 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 2971 getF32Constant(DAG, 0x3f7f5e7e)); 2972 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5); 2973 2974 // Add the exponent into the result in integer domain. 2975 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2976 TwoToFracPartOfX, IntegerPartOfX); 2977 2978 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6); 2979 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 2980 // For floating-point precision of 12: 2981 // 2982 // TwoToFractionalPartOfX = 2983 // 0.999892986f + 2984 // (0.696457318f + 2985 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 2986 // 2987 // 0.000107046256 error, which is 13 to 14 bits 2988 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 2989 getF32Constant(DAG, 0x3da235e3)); 2990 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 2991 getF32Constant(DAG, 0x3e65b8f3)); 2992 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 2993 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 2994 getF32Constant(DAG, 0x3f324b07)); 2995 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 2996 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 2997 getF32Constant(DAG, 0x3f7ff8fd)); 2998 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7); 2999 3000 // Add the exponent into the result in integer domain. 3001 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3002 TwoToFracPartOfX, IntegerPartOfX); 3003 3004 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8); 3005 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3006 // For floating-point precision of 18: 3007 // 3008 // TwoToFractionalPartOfX = 3009 // 0.999999982f + 3010 // (0.693148872f + 3011 // (0.240227044f + 3012 // (0.554906021e-1f + 3013 // (0.961591928e-2f + 3014 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3015 // 3016 // error 2.47208000*10^(-7), which is better than 18 bits 3017 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3018 getF32Constant(DAG, 0x3924b03e)); 3019 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3020 getF32Constant(DAG, 0x3ab24b87)); 3021 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3022 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3023 getF32Constant(DAG, 0x3c1d8c17)); 3024 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3025 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3026 getF32Constant(DAG, 0x3d634a1d)); 3027 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3028 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3029 getF32Constant(DAG, 0x3e75fe14)); 3030 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3031 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3032 getF32Constant(DAG, 0x3f317234)); 3033 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3034 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3035 getF32Constant(DAG, 0x3f800000)); 3036 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl, 3037 MVT::i32, t13); 3038 3039 // Add the exponent into the result in integer domain. 3040 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3041 TwoToFracPartOfX, IntegerPartOfX); 3042 3043 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14); 3044 } 3045 } else { 3046 // No special expansion. 3047 result = DAG.getNode(ISD::FEXP, dl, 3048 getValue(I.getOperand(1)).getValueType(), 3049 getValue(I.getOperand(1))); 3050 } 3051 3052 setValue(&I, result); 3053 } 3054 3055 /// visitLog - Lower a log intrinsic. Handles the special sequences for 3056 /// limited-precision mode. 3057 void 3058 SelectionDAGBuilder::visitLog(const CallInst &I) { 3059 SDValue result; 3060 DebugLoc dl = getCurDebugLoc(); 3061 3062 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3063 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3064 SDValue Op = getValue(I.getOperand(1)); 3065 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3066 3067 // Scale the exponent by log(2) [0.69314718f]. 3068 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3069 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3070 getF32Constant(DAG, 0x3f317218)); 3071 3072 // Get the significand and build it into a floating-point number with 3073 // exponent of 1. 3074 SDValue X = GetSignificand(DAG, Op1, dl); 3075 3076 if (LimitFloatPrecision <= 6) { 3077 // For floating-point precision of 6: 3078 // 3079 // LogofMantissa = 3080 // -1.1609546f + 3081 // (1.4034025f - 0.23903021f * x) * x; 3082 // 3083 // error 0.0034276066, which is better than 8 bits 3084 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3085 getF32Constant(DAG, 0xbe74c456)); 3086 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3087 getF32Constant(DAG, 0x3fb3a2b1)); 3088 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3089 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3090 getF32Constant(DAG, 0x3f949a29)); 3091 3092 result = DAG.getNode(ISD::FADD, dl, 3093 MVT::f32, LogOfExponent, LogOfMantissa); 3094 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3095 // For floating-point precision of 12: 3096 // 3097 // LogOfMantissa = 3098 // -1.7417939f + 3099 // (2.8212026f + 3100 // (-1.4699568f + 3101 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3102 // 3103 // error 0.000061011436, which is 14 bits 3104 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3105 getF32Constant(DAG, 0xbd67b6d6)); 3106 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3107 getF32Constant(DAG, 0x3ee4f4b8)); 3108 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3109 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3110 getF32Constant(DAG, 0x3fbc278b)); 3111 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3112 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3113 getF32Constant(DAG, 0x40348e95)); 3114 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3115 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3116 getF32Constant(DAG, 0x3fdef31a)); 3117 3118 result = DAG.getNode(ISD::FADD, dl, 3119 MVT::f32, LogOfExponent, LogOfMantissa); 3120 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3121 // For floating-point precision of 18: 3122 // 3123 // LogOfMantissa = 3124 // -2.1072184f + 3125 // (4.2372794f + 3126 // (-3.7029485f + 3127 // (2.2781945f + 3128 // (-0.87823314f + 3129 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3130 // 3131 // error 0.0000023660568, which is better than 18 bits 3132 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3133 getF32Constant(DAG, 0xbc91e5ac)); 3134 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3135 getF32Constant(DAG, 0x3e4350aa)); 3136 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3137 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3138 getF32Constant(DAG, 0x3f60d3e3)); 3139 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3140 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3141 getF32Constant(DAG, 0x4011cdf0)); 3142 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3143 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3144 getF32Constant(DAG, 0x406cfd1c)); 3145 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3146 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3147 getF32Constant(DAG, 0x408797cb)); 3148 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3149 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3150 getF32Constant(DAG, 0x4006dcab)); 3151 3152 result = DAG.getNode(ISD::FADD, dl, 3153 MVT::f32, LogOfExponent, LogOfMantissa); 3154 } 3155 } else { 3156 // No special expansion. 3157 result = DAG.getNode(ISD::FLOG, dl, 3158 getValue(I.getOperand(1)).getValueType(), 3159 getValue(I.getOperand(1))); 3160 } 3161 3162 setValue(&I, result); 3163 } 3164 3165 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for 3166 /// limited-precision mode. 3167 void 3168 SelectionDAGBuilder::visitLog2(const CallInst &I) { 3169 SDValue result; 3170 DebugLoc dl = getCurDebugLoc(); 3171 3172 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3173 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3174 SDValue Op = getValue(I.getOperand(1)); 3175 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3176 3177 // Get the exponent. 3178 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3179 3180 // Get the significand and build it into a floating-point number with 3181 // exponent of 1. 3182 SDValue X = GetSignificand(DAG, Op1, dl); 3183 3184 // Different possible minimax approximations of significand in 3185 // floating-point for various degrees of accuracy over [1,2]. 3186 if (LimitFloatPrecision <= 6) { 3187 // For floating-point precision of 6: 3188 // 3189 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 3190 // 3191 // error 0.0049451742, which is more than 7 bits 3192 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3193 getF32Constant(DAG, 0xbeb08fe0)); 3194 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3195 getF32Constant(DAG, 0x40019463)); 3196 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3197 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3198 getF32Constant(DAG, 0x3fd6633d)); 3199 3200 result = DAG.getNode(ISD::FADD, dl, 3201 MVT::f32, LogOfExponent, Log2ofMantissa); 3202 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3203 // For floating-point precision of 12: 3204 // 3205 // Log2ofMantissa = 3206 // -2.51285454f + 3207 // (4.07009056f + 3208 // (-2.12067489f + 3209 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 3210 // 3211 // error 0.0000876136000, which is better than 13 bits 3212 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3213 getF32Constant(DAG, 0xbda7262e)); 3214 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3215 getF32Constant(DAG, 0x3f25280b)); 3216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3217 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3218 getF32Constant(DAG, 0x4007b923)); 3219 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3220 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3221 getF32Constant(DAG, 0x40823e2f)); 3222 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3223 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3224 getF32Constant(DAG, 0x4020d29c)); 3225 3226 result = DAG.getNode(ISD::FADD, dl, 3227 MVT::f32, LogOfExponent, Log2ofMantissa); 3228 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3229 // For floating-point precision of 18: 3230 // 3231 // Log2ofMantissa = 3232 // -3.0400495f + 3233 // (6.1129976f + 3234 // (-5.3420409f + 3235 // (3.2865683f + 3236 // (-1.2669343f + 3237 // (0.27515199f - 3238 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 3239 // 3240 // error 0.0000018516, which is better than 18 bits 3241 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3242 getF32Constant(DAG, 0xbcd2769e)); 3243 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3244 getF32Constant(DAG, 0x3e8ce0b9)); 3245 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3246 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3247 getF32Constant(DAG, 0x3fa22ae7)); 3248 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3249 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3250 getF32Constant(DAG, 0x40525723)); 3251 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3252 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3253 getF32Constant(DAG, 0x40aaf200)); 3254 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3255 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3256 getF32Constant(DAG, 0x40c39dad)); 3257 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3258 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3259 getF32Constant(DAG, 0x4042902c)); 3260 3261 result = DAG.getNode(ISD::FADD, dl, 3262 MVT::f32, LogOfExponent, Log2ofMantissa); 3263 } 3264 } else { 3265 // No special expansion. 3266 result = DAG.getNode(ISD::FLOG2, dl, 3267 getValue(I.getOperand(1)).getValueType(), 3268 getValue(I.getOperand(1))); 3269 } 3270 3271 setValue(&I, result); 3272 } 3273 3274 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for 3275 /// limited-precision mode. 3276 void 3277 SelectionDAGBuilder::visitLog10(const CallInst &I) { 3278 SDValue result; 3279 DebugLoc dl = getCurDebugLoc(); 3280 3281 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3282 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3283 SDValue Op = getValue(I.getOperand(1)); 3284 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op); 3285 3286 // Scale the exponent by log10(2) [0.30102999f]. 3287 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3288 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3289 getF32Constant(DAG, 0x3e9a209a)); 3290 3291 // Get the significand and build it into a floating-point number with 3292 // exponent of 1. 3293 SDValue X = GetSignificand(DAG, Op1, dl); 3294 3295 if (LimitFloatPrecision <= 6) { 3296 // For floating-point precision of 6: 3297 // 3298 // Log10ofMantissa = 3299 // -0.50419619f + 3300 // (0.60948995f - 0.10380950f * x) * x; 3301 // 3302 // error 0.0014886165, which is 6 bits 3303 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3304 getF32Constant(DAG, 0xbdd49a13)); 3305 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3306 getF32Constant(DAG, 0x3f1c0789)); 3307 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3308 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3309 getF32Constant(DAG, 0x3f011300)); 3310 3311 result = DAG.getNode(ISD::FADD, dl, 3312 MVT::f32, LogOfExponent, Log10ofMantissa); 3313 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3314 // For floating-point precision of 12: 3315 // 3316 // Log10ofMantissa = 3317 // -0.64831180f + 3318 // (0.91751397f + 3319 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 3320 // 3321 // error 0.00019228036, which is better than 12 bits 3322 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3323 getF32Constant(DAG, 0x3d431f31)); 3324 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3325 getF32Constant(DAG, 0x3ea21fb2)); 3326 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3327 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3328 getF32Constant(DAG, 0x3f6ae232)); 3329 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3330 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3331 getF32Constant(DAG, 0x3f25f7c3)); 3332 3333 result = DAG.getNode(ISD::FADD, dl, 3334 MVT::f32, LogOfExponent, Log10ofMantissa); 3335 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3336 // For floating-point precision of 18: 3337 // 3338 // Log10ofMantissa = 3339 // -0.84299375f + 3340 // (1.5327582f + 3341 // (-1.0688956f + 3342 // (0.49102474f + 3343 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 3344 // 3345 // error 0.0000037995730, which is better than 18 bits 3346 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3347 getF32Constant(DAG, 0x3c5d51ce)); 3348 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 3349 getF32Constant(DAG, 0x3e00685a)); 3350 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3351 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3352 getF32Constant(DAG, 0x3efb6798)); 3353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3354 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 3355 getF32Constant(DAG, 0x3f88d192)); 3356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3357 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3358 getF32Constant(DAG, 0x3fc4316c)); 3359 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3360 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 3361 getF32Constant(DAG, 0x3f57ce70)); 3362 3363 result = DAG.getNode(ISD::FADD, dl, 3364 MVT::f32, LogOfExponent, Log10ofMantissa); 3365 } 3366 } else { 3367 // No special expansion. 3368 result = DAG.getNode(ISD::FLOG10, dl, 3369 getValue(I.getOperand(1)).getValueType(), 3370 getValue(I.getOperand(1))); 3371 } 3372 3373 setValue(&I, result); 3374 } 3375 3376 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for 3377 /// limited-precision mode. 3378 void 3379 SelectionDAGBuilder::visitExp2(const CallInst &I) { 3380 SDValue result; 3381 DebugLoc dl = getCurDebugLoc(); 3382 3383 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 && 3384 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3385 SDValue Op = getValue(I.getOperand(1)); 3386 3387 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 3388 3389 // FractionalPartOfX = x - (float)IntegerPartOfX; 3390 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3391 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 3392 3393 // IntegerPartOfX <<= 23; 3394 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3395 DAG.getConstant(23, TLI.getPointerTy())); 3396 3397 if (LimitFloatPrecision <= 6) { 3398 // For floating-point precision of 6: 3399 // 3400 // TwoToFractionalPartOfX = 3401 // 0.997535578f + 3402 // (0.735607626f + 0.252464424f * x) * x; 3403 // 3404 // error 0.0144103317, which is 6 bits 3405 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3406 getF32Constant(DAG, 0x3e814304)); 3407 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3408 getF32Constant(DAG, 0x3f3c50c8)); 3409 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3410 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3411 getF32Constant(DAG, 0x3f7f5e7e)); 3412 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3413 SDValue TwoToFractionalPartOfX = 3414 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3415 3416 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3417 MVT::f32, TwoToFractionalPartOfX); 3418 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3419 // For floating-point precision of 12: 3420 // 3421 // TwoToFractionalPartOfX = 3422 // 0.999892986f + 3423 // (0.696457318f + 3424 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3425 // 3426 // error 0.000107046256, which is 13 to 14 bits 3427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3428 getF32Constant(DAG, 0x3da235e3)); 3429 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3430 getF32Constant(DAG, 0x3e65b8f3)); 3431 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3432 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3433 getF32Constant(DAG, 0x3f324b07)); 3434 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3435 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3436 getF32Constant(DAG, 0x3f7ff8fd)); 3437 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3438 SDValue TwoToFractionalPartOfX = 3439 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3440 3441 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3442 MVT::f32, TwoToFractionalPartOfX); 3443 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3444 // For floating-point precision of 18: 3445 // 3446 // TwoToFractionalPartOfX = 3447 // 0.999999982f + 3448 // (0.693148872f + 3449 // (0.240227044f + 3450 // (0.554906021e-1f + 3451 // (0.961591928e-2f + 3452 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3453 // error 2.47208000*10^(-7), which is better than 18 bits 3454 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3455 getF32Constant(DAG, 0x3924b03e)); 3456 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3457 getF32Constant(DAG, 0x3ab24b87)); 3458 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3459 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3460 getF32Constant(DAG, 0x3c1d8c17)); 3461 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3462 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3463 getF32Constant(DAG, 0x3d634a1d)); 3464 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3465 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3466 getF32Constant(DAG, 0x3e75fe14)); 3467 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3468 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3469 getF32Constant(DAG, 0x3f317234)); 3470 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3471 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3472 getF32Constant(DAG, 0x3f800000)); 3473 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 3474 SDValue TwoToFractionalPartOfX = 3475 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3476 3477 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3478 MVT::f32, TwoToFractionalPartOfX); 3479 } 3480 } else { 3481 // No special expansion. 3482 result = DAG.getNode(ISD::FEXP2, dl, 3483 getValue(I.getOperand(1)).getValueType(), 3484 getValue(I.getOperand(1))); 3485 } 3486 3487 setValue(&I, result); 3488 } 3489 3490 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 3491 /// limited-precision mode with x == 10.0f. 3492 void 3493 SelectionDAGBuilder::visitPow(const CallInst &I) { 3494 SDValue result; 3495 const Value *Val = I.getOperand(1); 3496 DebugLoc dl = getCurDebugLoc(); 3497 bool IsExp10 = false; 3498 3499 if (getValue(Val).getValueType() == MVT::f32 && 3500 getValue(I.getOperand(2)).getValueType() == MVT::f32 && 3501 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3502 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) { 3503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 3504 APFloat Ten(10.0f); 3505 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten); 3506 } 3507 } 3508 } 3509 3510 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3511 SDValue Op = getValue(I.getOperand(2)); 3512 3513 // Put the exponent in the right bit position for later addition to the 3514 // final result: 3515 // 3516 // #define LOG2OF10 3.3219281f 3517 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 3518 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3519 getF32Constant(DAG, 0x40549a78)); 3520 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3521 3522 // FractionalPartOfX = x - (float)IntegerPartOfX; 3523 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3524 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3525 3526 // IntegerPartOfX <<= 23; 3527 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3528 DAG.getConstant(23, TLI.getPointerTy())); 3529 3530 if (LimitFloatPrecision <= 6) { 3531 // For floating-point precision of 6: 3532 // 3533 // twoToFractionalPartOfX = 3534 // 0.997535578f + 3535 // (0.735607626f + 0.252464424f * x) * x; 3536 // 3537 // error 0.0144103317, which is 6 bits 3538 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3539 getF32Constant(DAG, 0x3e814304)); 3540 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3541 getF32Constant(DAG, 0x3f3c50c8)); 3542 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3543 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3544 getF32Constant(DAG, 0x3f7f5e7e)); 3545 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5); 3546 SDValue TwoToFractionalPartOfX = 3547 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX); 3548 3549 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3550 MVT::f32, TwoToFractionalPartOfX); 3551 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) { 3552 // For floating-point precision of 12: 3553 // 3554 // TwoToFractionalPartOfX = 3555 // 0.999892986f + 3556 // (0.696457318f + 3557 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3558 // 3559 // error 0.000107046256, which is 13 to 14 bits 3560 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3561 getF32Constant(DAG, 0x3da235e3)); 3562 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3563 getF32Constant(DAG, 0x3e65b8f3)); 3564 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3565 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3566 getF32Constant(DAG, 0x3f324b07)); 3567 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3568 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3569 getF32Constant(DAG, 0x3f7ff8fd)); 3570 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7); 3571 SDValue TwoToFractionalPartOfX = 3572 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX); 3573 3574 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3575 MVT::f32, TwoToFractionalPartOfX); 3576 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18 3577 // For floating-point precision of 18: 3578 // 3579 // TwoToFractionalPartOfX = 3580 // 0.999999982f + 3581 // (0.693148872f + 3582 // (0.240227044f + 3583 // (0.554906021e-1f + 3584 // (0.961591928e-2f + 3585 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3586 // error 2.47208000*10^(-7), which is better than 18 bits 3587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3588 getF32Constant(DAG, 0x3924b03e)); 3589 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3590 getF32Constant(DAG, 0x3ab24b87)); 3591 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3592 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3593 getF32Constant(DAG, 0x3c1d8c17)); 3594 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3595 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3596 getF32Constant(DAG, 0x3d634a1d)); 3597 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3598 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3599 getF32Constant(DAG, 0x3e75fe14)); 3600 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3601 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3602 getF32Constant(DAG, 0x3f317234)); 3603 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3604 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3605 getF32Constant(DAG, 0x3f800000)); 3606 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13); 3607 SDValue TwoToFractionalPartOfX = 3608 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX); 3609 3610 result = DAG.getNode(ISD::BIT_CONVERT, dl, 3611 MVT::f32, TwoToFractionalPartOfX); 3612 } 3613 } else { 3614 // No special expansion. 3615 result = DAG.getNode(ISD::FPOW, dl, 3616 getValue(I.getOperand(1)).getValueType(), 3617 getValue(I.getOperand(1)), 3618 getValue(I.getOperand(2))); 3619 } 3620 3621 setValue(&I, result); 3622 } 3623 3624 3625 /// ExpandPowI - Expand a llvm.powi intrinsic. 3626 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS, 3627 SelectionDAG &DAG) { 3628 // If RHS is a constant, we can expand this out to a multiplication tree, 3629 // otherwise we end up lowering to a call to __powidf2 (for example). When 3630 // optimizing for size, we only want to do this if the expansion would produce 3631 // a small number of multiplies, otherwise we do the full expansion. 3632 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3633 // Get the exponent as a positive value. 3634 unsigned Val = RHSC->getSExtValue(); 3635 if ((int)Val < 0) Val = -Val; 3636 3637 // powi(x, 0) -> 1.0 3638 if (Val == 0) 3639 return DAG.getConstantFP(1.0, LHS.getValueType()); 3640 3641 const Function *F = DAG.getMachineFunction().getFunction(); 3642 if (!F->hasFnAttr(Attribute::OptimizeForSize) || 3643 // If optimizing for size, don't insert too many multiplies. This 3644 // inserts up to 5 multiplies. 3645 CountPopulation_32(Val)+Log2_32(Val) < 7) { 3646 // We use the simple binary decomposition method to generate the multiply 3647 // sequence. There are more optimal ways to do this (for example, 3648 // powi(x,15) generates one more multiply than it should), but this has 3649 // the benefit of being both really simple and much better than a libcall. 3650 SDValue Res; // Logically starts equal to 1.0 3651 SDValue CurSquare = LHS; 3652 while (Val) { 3653 if (Val & 1) { 3654 if (Res.getNode()) 3655 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 3656 else 3657 Res = CurSquare; // 1.0*CurSquare. 3658 } 3659 3660 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 3661 CurSquare, CurSquare); 3662 Val >>= 1; 3663 } 3664 3665 // If the original was negative, invert the result, producing 1/(x*x*x). 3666 if (RHSC->getSExtValue() < 0) 3667 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 3668 DAG.getConstantFP(1.0, LHS.getValueType()), Res); 3669 return Res; 3670 } 3671 } 3672 3673 // Otherwise, expand to a libcall. 3674 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 3675 } 3676 3677 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 3678 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 3679 /// At the end of instruction selection, they will be inserted to the entry BB. 3680 bool 3681 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const DbgValueInst &DI, 3682 const Value *V, MDNode *Variable, 3683 uint64_t Offset, 3684 const SDValue &N) { 3685 if (!isa<Argument>(V)) 3686 return false; 3687 3688 MachineFunction &MF = DAG.getMachineFunction(); 3689 // Ignore inlined function arguments here. 3690 DIVariable DV(Variable); 3691 if (DV.isInlinedFnArgument(MF.getFunction())) 3692 return false; 3693 3694 MachineBasicBlock *MBB = FuncInfo.MBBMap[DI.getParent()]; 3695 if (MBB != &MF.front()) 3696 return false; 3697 3698 unsigned Reg = 0; 3699 if (N.getOpcode() == ISD::CopyFromReg) { 3700 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 3701 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 3702 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 3703 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 3704 if (PR) 3705 Reg = PR; 3706 } 3707 } 3708 3709 if (!Reg) { 3710 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 3711 if (VMI == FuncInfo.ValueMap.end()) 3712 return false; 3713 Reg = VMI->second; 3714 } 3715 3716 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo(); 3717 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(), 3718 TII->get(TargetOpcode::DBG_VALUE)) 3719 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable); 3720 FuncInfo.ArgDbgValues.push_back(&*MIB); 3721 return true; 3722 } 3723 3724 // VisualStudio defines setjmp as _setjmp 3725 #if defined(_MSC_VER) && defined(setjmp) 3726 #define setjmp_undefined_for_visual_studio 3727 #undef setjmp 3728 #endif 3729 3730 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 3731 /// we want to emit this as a call to a named external function, return the name 3732 /// otherwise lower it and return null. 3733 const char * 3734 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 3735 DebugLoc dl = getCurDebugLoc(); 3736 SDValue Res; 3737 3738 switch (Intrinsic) { 3739 default: 3740 // By default, turn this into a target intrinsic node. 3741 visitTargetIntrinsic(I, Intrinsic); 3742 return 0; 3743 case Intrinsic::vastart: visitVAStart(I); return 0; 3744 case Intrinsic::vaend: visitVAEnd(I); return 0; 3745 case Intrinsic::vacopy: visitVACopy(I); return 0; 3746 case Intrinsic::returnaddress: 3747 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(), 3748 getValue(I.getOperand(1)))); 3749 return 0; 3750 case Intrinsic::frameaddress: 3751 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(), 3752 getValue(I.getOperand(1)))); 3753 return 0; 3754 case Intrinsic::setjmp: 3755 return "_setjmp"+!TLI.usesUnderscoreSetJmp(); 3756 case Intrinsic::longjmp: 3757 return "_longjmp"+!TLI.usesUnderscoreLongJmp(); 3758 case Intrinsic::memcpy: { 3759 // Assert for address < 256 since we support only user defined address 3760 // spaces. 3761 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace() 3762 < 256 && 3763 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace() 3764 < 256 && 3765 "Unknown address space"); 3766 SDValue Op1 = getValue(I.getOperand(1)); 3767 SDValue Op2 = getValue(I.getOperand(2)); 3768 SDValue Op3 = getValue(I.getOperand(3)); 3769 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3770 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue(); 3771 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false, 3772 I.getOperand(1), 0, I.getOperand(2), 0)); 3773 return 0; 3774 } 3775 case Intrinsic::memset: { 3776 // Assert for address < 256 since we support only user defined address 3777 // spaces. 3778 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace() 3779 < 256 && 3780 "Unknown address space"); 3781 SDValue Op1 = getValue(I.getOperand(1)); 3782 SDValue Op2 = getValue(I.getOperand(2)); 3783 SDValue Op3 = getValue(I.getOperand(3)); 3784 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3785 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue(); 3786 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 3787 I.getOperand(1), 0)); 3788 return 0; 3789 } 3790 case Intrinsic::memmove: { 3791 // Assert for address < 256 since we support only user defined address 3792 // spaces. 3793 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace() 3794 < 256 && 3795 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace() 3796 < 256 && 3797 "Unknown address space"); 3798 SDValue Op1 = getValue(I.getOperand(1)); 3799 SDValue Op2 = getValue(I.getOperand(2)); 3800 SDValue Op3 = getValue(I.getOperand(3)); 3801 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue(); 3802 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue(); 3803 3804 // If the source and destination are known to not be aliases, we can 3805 // lower memmove as memcpy. 3806 uint64_t Size = -1ULL; 3807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3)) 3808 Size = C->getZExtValue(); 3809 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) == 3810 AliasAnalysis::NoAlias) { 3811 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 3812 false, I.getOperand(1), 0, I.getOperand(2), 0)); 3813 return 0; 3814 } 3815 3816 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol, 3817 I.getOperand(1), 0, I.getOperand(2), 0)); 3818 return 0; 3819 } 3820 case Intrinsic::dbg_declare: { 3821 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 3822 if (!DIVariable(DI.getVariable()).Verify()) 3823 return 0; 3824 3825 MDNode *Variable = DI.getVariable(); 3826 // Parameters are handled specially. 3827 bool isParameter = 3828 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable; 3829 const Value *Address = DI.getAddress(); 3830 if (!Address) 3831 return 0; 3832 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 3833 Address = BCI->getOperand(0); 3834 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 3835 if (AI) { 3836 // Don't handle byval arguments or VLAs, for example. 3837 // Non-byval arguments are handled here (they refer to the stack temporary 3838 // alloca at this point). 3839 DenseMap<const AllocaInst*, int>::iterator SI = 3840 FuncInfo.StaticAllocaMap.find(AI); 3841 if (SI == FuncInfo.StaticAllocaMap.end()) 3842 return 0; // VLAs. 3843 int FI = SI->second; 3844 3845 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 3846 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo()) 3847 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc()); 3848 } 3849 3850 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 3851 // but do not always have a corresponding SDNode built. The SDNodeOrder 3852 // absolute, but not relative, values are different depending on whether 3853 // debug info exists. 3854 ++SDNodeOrder; 3855 SDValue &N = NodeMap[Address]; 3856 SDDbgValue *SDV; 3857 if (N.getNode()) { 3858 if (isParameter && !AI) { 3859 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 3860 if (FINode) 3861 // Byval parameter. We have a frame index at this point. 3862 SDV = DAG.getDbgValue(Variable, FINode->getIndex(), 3863 0, dl, SDNodeOrder); 3864 else 3865 // Can't do anything with other non-AI cases yet. This might be a 3866 // parameter of a callee function that got inlined, for example. 3867 return 0; 3868 } else if (AI) 3869 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(), 3870 0, dl, SDNodeOrder); 3871 else 3872 // Can't do anything with other non-AI cases yet. 3873 return 0; 3874 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 3875 } else { 3876 // This isn't useful, but it shows what we're missing. 3877 SDV = DAG.getDbgValue(Variable, UndefValue::get(Address->getType()), 3878 0, dl, SDNodeOrder); 3879 DAG.AddDbgValue(SDV, 0, isParameter); 3880 } 3881 return 0; 3882 } 3883 case Intrinsic::dbg_value: { 3884 const DbgValueInst &DI = cast<DbgValueInst>(I); 3885 if (!DIVariable(DI.getVariable()).Verify()) 3886 return 0; 3887 3888 MDNode *Variable = DI.getVariable(); 3889 uint64_t Offset = DI.getOffset(); 3890 const Value *V = DI.getValue(); 3891 if (!V) 3892 return 0; 3893 3894 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder 3895 // but do not always have a corresponding SDNode built. The SDNodeOrder 3896 // absolute, but not relative, values are different depending on whether 3897 // debug info exists. 3898 ++SDNodeOrder; 3899 SDDbgValue *SDV; 3900 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) { 3901 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder); 3902 DAG.AddDbgValue(SDV, 0, false); 3903 } else { 3904 bool createUndef = false; 3905 // FIXME : Why not use getValue() directly ? 3906 SDValue &N = NodeMap[V]; 3907 if (N.getNode()) { 3908 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) { 3909 SDV = DAG.getDbgValue(Variable, N.getNode(), 3910 N.getResNo(), Offset, dl, SDNodeOrder); 3911 DAG.AddDbgValue(SDV, N.getNode(), false); 3912 } 3913 } else if (isa<PHINode>(V) && !V->use_empty()) { 3914 SDValue N = getValue(V); 3915 if (N.getNode()) { 3916 if (!EmitFuncArgumentDbgValue(DI, V, Variable, Offset, N)) { 3917 SDV = DAG.getDbgValue(Variable, N.getNode(), 3918 N.getResNo(), Offset, dl, SDNodeOrder); 3919 DAG.AddDbgValue(SDV, N.getNode(), false); 3920 } 3921 } else 3922 createUndef = true; 3923 } else 3924 createUndef = true; 3925 if (createUndef) { 3926 // We may expand this to cover more cases. One case where we have no 3927 // data available is an unreferenced parameter; we need this fallback. 3928 SDV = DAG.getDbgValue(Variable, UndefValue::get(V->getType()), 3929 Offset, dl, SDNodeOrder); 3930 DAG.AddDbgValue(SDV, 0, false); 3931 } 3932 } 3933 3934 // Build a debug info table entry. 3935 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 3936 V = BCI->getOperand(0); 3937 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 3938 // Don't handle byval struct arguments or VLAs, for example. 3939 if (!AI) 3940 return 0; 3941 DenseMap<const AllocaInst*, int>::iterator SI = 3942 FuncInfo.StaticAllocaMap.find(AI); 3943 if (SI == FuncInfo.StaticAllocaMap.end()) 3944 return 0; // VLAs. 3945 int FI = SI->second; 3946 3947 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 3948 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo()) 3949 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc()); 3950 return 0; 3951 } 3952 case Intrinsic::eh_exception: { 3953 // Insert the EXCEPTIONADDR instruction. 3954 assert(FuncInfo.MBBMap[I.getParent()]->isLandingPad() && 3955 "Call to eh.exception not in landing pad!"); 3956 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 3957 SDValue Ops[1]; 3958 Ops[0] = DAG.getRoot(); 3959 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1); 3960 setValue(&I, Op); 3961 DAG.setRoot(Op.getValue(1)); 3962 return 0; 3963 } 3964 3965 case Intrinsic::eh_selector: { 3966 MachineBasicBlock *CallMBB = FuncInfo.MBBMap[I.getParent()]; 3967 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 3968 if (CallMBB->isLandingPad()) 3969 AddCatchInfo(I, &MMI, CallMBB); 3970 else { 3971 #ifndef NDEBUG 3972 FuncInfo.CatchInfoLost.insert(&I); 3973 #endif 3974 // FIXME: Mark exception selector register as live in. Hack for PR1508. 3975 unsigned Reg = TLI.getExceptionSelectorRegister(); 3976 if (Reg) FuncInfo.MBBMap[I.getParent()]->addLiveIn(Reg); 3977 } 3978 3979 // Insert the EHSELECTION instruction. 3980 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other); 3981 SDValue Ops[2]; 3982 Ops[0] = getValue(I.getOperand(1)); 3983 Ops[1] = getRoot(); 3984 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2); 3985 DAG.setRoot(Op.getValue(1)); 3986 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32)); 3987 return 0; 3988 } 3989 3990 case Intrinsic::eh_typeid_for: { 3991 // Find the type id for the given typeinfo. 3992 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1)); 3993 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 3994 Res = DAG.getConstant(TypeID, MVT::i32); 3995 setValue(&I, Res); 3996 return 0; 3997 } 3998 3999 case Intrinsic::eh_return_i32: 4000 case Intrinsic::eh_return_i64: 4001 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4002 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl, 4003 MVT::Other, 4004 getControlRoot(), 4005 getValue(I.getOperand(1)), 4006 getValue(I.getOperand(2)))); 4007 return 0; 4008 case Intrinsic::eh_unwind_init: 4009 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4010 return 0; 4011 case Intrinsic::eh_dwarf_cfa: { 4012 EVT VT = getValue(I.getOperand(1)).getValueType(); 4013 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl, 4014 TLI.getPointerTy()); 4015 SDValue Offset = DAG.getNode(ISD::ADD, dl, 4016 TLI.getPointerTy(), 4017 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl, 4018 TLI.getPointerTy()), 4019 CfaArg); 4020 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl, 4021 TLI.getPointerTy(), 4022 DAG.getConstant(0, TLI.getPointerTy())); 4023 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 4024 FA, Offset)); 4025 return 0; 4026 } 4027 case Intrinsic::eh_sjlj_callsite: { 4028 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4029 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); 4030 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4031 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4032 4033 MMI.setCurrentCallSite(CI->getZExtValue()); 4034 return 0; 4035 } 4036 case Intrinsic::eh_sjlj_setjmp: { 4037 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(), 4038 getValue(I.getOperand(1)))); 4039 return 0; 4040 } 4041 case Intrinsic::eh_sjlj_longjmp: { 4042 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other, 4043 getRoot(), 4044 getValue(I.getOperand(1)))); 4045 return 0; 4046 } 4047 4048 case Intrinsic::convertff: 4049 case Intrinsic::convertfsi: 4050 case Intrinsic::convertfui: 4051 case Intrinsic::convertsif: 4052 case Intrinsic::convertuif: 4053 case Intrinsic::convertss: 4054 case Intrinsic::convertsu: 4055 case Intrinsic::convertus: 4056 case Intrinsic::convertuu: { 4057 ISD::CvtCode Code = ISD::CVT_INVALID; 4058 switch (Intrinsic) { 4059 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4060 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4061 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4062 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4063 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4064 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4065 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4066 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4067 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4068 } 4069 EVT DestVT = TLI.getValueType(I.getType()); 4070 const Value *Op1 = I.getOperand(1); 4071 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1), 4072 DAG.getValueType(DestVT), 4073 DAG.getValueType(getValue(Op1).getValueType()), 4074 getValue(I.getOperand(2)), 4075 getValue(I.getOperand(3)), 4076 Code); 4077 setValue(&I, Res); 4078 return 0; 4079 } 4080 case Intrinsic::sqrt: 4081 setValue(&I, DAG.getNode(ISD::FSQRT, dl, 4082 getValue(I.getOperand(1)).getValueType(), 4083 getValue(I.getOperand(1)))); 4084 return 0; 4085 case Intrinsic::powi: 4086 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)), 4087 getValue(I.getOperand(2)), DAG)); 4088 return 0; 4089 case Intrinsic::sin: 4090 setValue(&I, DAG.getNode(ISD::FSIN, dl, 4091 getValue(I.getOperand(1)).getValueType(), 4092 getValue(I.getOperand(1)))); 4093 return 0; 4094 case Intrinsic::cos: 4095 setValue(&I, DAG.getNode(ISD::FCOS, dl, 4096 getValue(I.getOperand(1)).getValueType(), 4097 getValue(I.getOperand(1)))); 4098 return 0; 4099 case Intrinsic::log: 4100 visitLog(I); 4101 return 0; 4102 case Intrinsic::log2: 4103 visitLog2(I); 4104 return 0; 4105 case Intrinsic::log10: 4106 visitLog10(I); 4107 return 0; 4108 case Intrinsic::exp: 4109 visitExp(I); 4110 return 0; 4111 case Intrinsic::exp2: 4112 visitExp2(I); 4113 return 0; 4114 case Intrinsic::pow: 4115 visitPow(I); 4116 return 0; 4117 case Intrinsic::convert_to_fp16: 4118 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl, 4119 MVT::i16, getValue(I.getOperand(1)))); 4120 return 0; 4121 case Intrinsic::convert_from_fp16: 4122 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl, 4123 MVT::f32, getValue(I.getOperand(1)))); 4124 return 0; 4125 case Intrinsic::pcmarker: { 4126 SDValue Tmp = getValue(I.getOperand(1)); 4127 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp)); 4128 return 0; 4129 } 4130 case Intrinsic::readcyclecounter: { 4131 SDValue Op = getRoot(); 4132 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl, 4133 DAG.getVTList(MVT::i64, MVT::Other), 4134 &Op, 1); 4135 setValue(&I, Res); 4136 DAG.setRoot(Res.getValue(1)); 4137 return 0; 4138 } 4139 case Intrinsic::bswap: 4140 setValue(&I, DAG.getNode(ISD::BSWAP, dl, 4141 getValue(I.getOperand(1)).getValueType(), 4142 getValue(I.getOperand(1)))); 4143 return 0; 4144 case Intrinsic::cttz: { 4145 SDValue Arg = getValue(I.getOperand(1)); 4146 EVT Ty = Arg.getValueType(); 4147 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg)); 4148 return 0; 4149 } 4150 case Intrinsic::ctlz: { 4151 SDValue Arg = getValue(I.getOperand(1)); 4152 EVT Ty = Arg.getValueType(); 4153 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg)); 4154 return 0; 4155 } 4156 case Intrinsic::ctpop: { 4157 SDValue Arg = getValue(I.getOperand(1)); 4158 EVT Ty = Arg.getValueType(); 4159 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg)); 4160 return 0; 4161 } 4162 case Intrinsic::stacksave: { 4163 SDValue Op = getRoot(); 4164 Res = DAG.getNode(ISD::STACKSAVE, dl, 4165 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1); 4166 setValue(&I, Res); 4167 DAG.setRoot(Res.getValue(1)); 4168 return 0; 4169 } 4170 case Intrinsic::stackrestore: { 4171 Res = getValue(I.getOperand(1)); 4172 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res)); 4173 return 0; 4174 } 4175 case Intrinsic::stackprotector: { 4176 // Emit code into the DAG to store the stack guard onto the stack. 4177 MachineFunction &MF = DAG.getMachineFunction(); 4178 MachineFrameInfo *MFI = MF.getFrameInfo(); 4179 EVT PtrTy = TLI.getPointerTy(); 4180 4181 SDValue Src = getValue(I.getOperand(1)); // The guard's value. 4182 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2)); 4183 4184 int FI = FuncInfo.StaticAllocaMap[Slot]; 4185 MFI->setStackProtectorIndex(FI); 4186 4187 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 4188 4189 // Store the stack protector onto the stack. 4190 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN, 4191 PseudoSourceValue::getFixedStack(FI), 4192 0, true, false, 0); 4193 setValue(&I, Res); 4194 DAG.setRoot(Res); 4195 return 0; 4196 } 4197 case Intrinsic::objectsize: { 4198 // If we don't know by now, we're never going to know. 4199 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2)); 4200 4201 assert(CI && "Non-constant type in __builtin_object_size?"); 4202 4203 SDValue Arg = getValue(I.getOperand(0)); 4204 EVT Ty = Arg.getValueType(); 4205 4206 if (CI->getZExtValue() == 0) 4207 Res = DAG.getConstant(-1ULL, Ty); 4208 else 4209 Res = DAG.getConstant(0, Ty); 4210 4211 setValue(&I, Res); 4212 return 0; 4213 } 4214 case Intrinsic::var_annotation: 4215 // Discard annotate attributes 4216 return 0; 4217 4218 case Intrinsic::init_trampoline: { 4219 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts()); 4220 4221 SDValue Ops[6]; 4222 Ops[0] = getRoot(); 4223 Ops[1] = getValue(I.getOperand(1)); 4224 Ops[2] = getValue(I.getOperand(2)); 4225 Ops[3] = getValue(I.getOperand(3)); 4226 Ops[4] = DAG.getSrcValue(I.getOperand(1)); 4227 Ops[5] = DAG.getSrcValue(F); 4228 4229 Res = DAG.getNode(ISD::TRAMPOLINE, dl, 4230 DAG.getVTList(TLI.getPointerTy(), MVT::Other), 4231 Ops, 6); 4232 4233 setValue(&I, Res); 4234 DAG.setRoot(Res.getValue(1)); 4235 return 0; 4236 } 4237 case Intrinsic::gcroot: 4238 if (GFI) { 4239 const Value *Alloca = I.getOperand(1); 4240 const Constant *TypeMap = cast<Constant>(I.getOperand(2)); 4241 4242 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 4243 GFI->addStackRoot(FI->getIndex(), TypeMap); 4244 } 4245 return 0; 4246 case Intrinsic::gcread: 4247 case Intrinsic::gcwrite: 4248 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 4249 return 0; 4250 case Intrinsic::flt_rounds: 4251 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32)); 4252 return 0; 4253 case Intrinsic::trap: 4254 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot())); 4255 return 0; 4256 case Intrinsic::uadd_with_overflow: 4257 return implVisitAluOverflow(I, ISD::UADDO); 4258 case Intrinsic::sadd_with_overflow: 4259 return implVisitAluOverflow(I, ISD::SADDO); 4260 case Intrinsic::usub_with_overflow: 4261 return implVisitAluOverflow(I, ISD::USUBO); 4262 case Intrinsic::ssub_with_overflow: 4263 return implVisitAluOverflow(I, ISD::SSUBO); 4264 case Intrinsic::umul_with_overflow: 4265 return implVisitAluOverflow(I, ISD::UMULO); 4266 case Intrinsic::smul_with_overflow: 4267 return implVisitAluOverflow(I, ISD::SMULO); 4268 4269 case Intrinsic::prefetch: { 4270 SDValue Ops[4]; 4271 Ops[0] = getRoot(); 4272 Ops[1] = getValue(I.getOperand(1)); 4273 Ops[2] = getValue(I.getOperand(2)); 4274 Ops[3] = getValue(I.getOperand(3)); 4275 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4)); 4276 return 0; 4277 } 4278 4279 case Intrinsic::memory_barrier: { 4280 SDValue Ops[6]; 4281 Ops[0] = getRoot(); 4282 for (int x = 1; x < 6; ++x) 4283 Ops[x] = getValue(I.getOperand(x)); 4284 4285 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6)); 4286 return 0; 4287 } 4288 case Intrinsic::atomic_cmp_swap: { 4289 SDValue Root = getRoot(); 4290 SDValue L = 4291 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(), 4292 getValue(I.getOperand(2)).getValueType().getSimpleVT(), 4293 Root, 4294 getValue(I.getOperand(1)), 4295 getValue(I.getOperand(2)), 4296 getValue(I.getOperand(3)), 4297 I.getOperand(1)); 4298 setValue(&I, L); 4299 DAG.setRoot(L.getValue(1)); 4300 return 0; 4301 } 4302 case Intrinsic::atomic_load_add: 4303 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD); 4304 case Intrinsic::atomic_load_sub: 4305 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB); 4306 case Intrinsic::atomic_load_or: 4307 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR); 4308 case Intrinsic::atomic_load_xor: 4309 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR); 4310 case Intrinsic::atomic_load_and: 4311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND); 4312 case Intrinsic::atomic_load_nand: 4313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND); 4314 case Intrinsic::atomic_load_max: 4315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX); 4316 case Intrinsic::atomic_load_min: 4317 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN); 4318 case Intrinsic::atomic_load_umin: 4319 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN); 4320 case Intrinsic::atomic_load_umax: 4321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX); 4322 case Intrinsic::atomic_swap: 4323 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP); 4324 4325 case Intrinsic::invariant_start: 4326 case Intrinsic::lifetime_start: 4327 // Discard region information. 4328 setValue(&I, DAG.getUNDEF(TLI.getPointerTy())); 4329 return 0; 4330 case Intrinsic::invariant_end: 4331 case Intrinsic::lifetime_end: 4332 // Discard region information. 4333 return 0; 4334 } 4335 } 4336 4337 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 4338 bool isTailCall, 4339 MachineBasicBlock *LandingPad) { 4340 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 4341 const FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 4342 const Type *RetTy = FTy->getReturnType(); 4343 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4344 MCSymbol *BeginLabel = 0; 4345 4346 TargetLowering::ArgListTy Args; 4347 TargetLowering::ArgListEntry Entry; 4348 Args.reserve(CS.arg_size()); 4349 4350 // Check whether the function can return without sret-demotion. 4351 SmallVector<EVT, 4> OutVTs; 4352 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 4353 SmallVector<uint64_t, 4> Offsets; 4354 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(), 4355 OutVTs, OutsFlags, TLI, &Offsets); 4356 4357 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 4358 FTy->isVarArg(), OutVTs, OutsFlags, DAG); 4359 4360 SDValue DemoteStackSlot; 4361 4362 if (!CanLowerReturn) { 4363 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize( 4364 FTy->getReturnType()); 4365 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment( 4366 FTy->getReturnType()); 4367 MachineFunction &MF = DAG.getMachineFunction(); 4368 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 4369 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 4370 4371 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 4372 Entry.Node = DemoteStackSlot; 4373 Entry.Ty = StackSlotPtrType; 4374 Entry.isSExt = false; 4375 Entry.isZExt = false; 4376 Entry.isInReg = false; 4377 Entry.isSRet = true; 4378 Entry.isNest = false; 4379 Entry.isByVal = false; 4380 Entry.Alignment = Align; 4381 Args.push_back(Entry); 4382 RetTy = Type::getVoidTy(FTy->getContext()); 4383 } 4384 4385 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 4386 i != e; ++i) { 4387 SDValue ArgNode = getValue(*i); 4388 Entry.Node = ArgNode; Entry.Ty = (*i)->getType(); 4389 4390 unsigned attrInd = i - CS.arg_begin() + 1; 4391 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 4392 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 4393 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 4394 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 4395 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 4396 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 4397 Entry.Alignment = CS.getParamAlignment(attrInd); 4398 Args.push_back(Entry); 4399 } 4400 4401 if (LandingPad) { 4402 // Insert a label before the invoke call to mark the try range. This can be 4403 // used to detect deletion of the invoke via the MachineModuleInfo. 4404 BeginLabel = MMI.getContext().CreateTempSymbol(); 4405 4406 // For SjLj, keep track of which landing pads go with which invokes 4407 // so as to maintain the ordering of pads in the LSDA. 4408 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 4409 if (CallSiteIndex) { 4410 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 4411 // Now that the call site is handled, stop tracking it. 4412 MMI.setCurrentCallSite(0); 4413 } 4414 4415 // Both PendingLoads and PendingExports must be flushed here; 4416 // this call might not return. 4417 (void)getRoot(); 4418 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel)); 4419 } 4420 4421 // Check if target-independent constraints permit a tail call here. 4422 // Target-dependent constraints are checked within TLI.LowerCallTo. 4423 if (isTailCall && 4424 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI)) 4425 isTailCall = false; 4426 4427 std::pair<SDValue,SDValue> Result = 4428 TLI.LowerCallTo(getRoot(), RetTy, 4429 CS.paramHasAttr(0, Attribute::SExt), 4430 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(), 4431 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(), 4432 CS.getCallingConv(), 4433 isTailCall, 4434 !CS.getInstruction()->use_empty(), 4435 Callee, Args, DAG, getCurDebugLoc()); 4436 assert((isTailCall || Result.second.getNode()) && 4437 "Non-null chain expected with non-tail call!"); 4438 assert((Result.second.getNode() || !Result.first.getNode()) && 4439 "Null value expected with tail call!"); 4440 if (Result.first.getNode()) { 4441 setValue(CS.getInstruction(), Result.first); 4442 } else if (!CanLowerReturn && Result.second.getNode()) { 4443 // The instruction result is the result of loading from the 4444 // hidden sret parameter. 4445 SmallVector<EVT, 1> PVTs; 4446 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 4447 4448 ComputeValueVTs(TLI, PtrRetTy, PVTs); 4449 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 4450 EVT PtrVT = PVTs[0]; 4451 unsigned NumValues = OutVTs.size(); 4452 SmallVector<SDValue, 4> Values(NumValues); 4453 SmallVector<SDValue, 4> Chains(NumValues); 4454 4455 for (unsigned i = 0; i < NumValues; ++i) { 4456 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, 4457 DemoteStackSlot, 4458 DAG.getConstant(Offsets[i], PtrVT)); 4459 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second, 4460 Add, NULL, Offsets[i], false, false, 1); 4461 Values[i] = L; 4462 Chains[i] = L.getValue(1); 4463 } 4464 4465 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), 4466 MVT::Other, &Chains[0], NumValues); 4467 PendingLoads.push_back(Chain); 4468 4469 // Collect the legal value parts into potentially illegal values 4470 // that correspond to the original function's return values. 4471 SmallVector<EVT, 4> RetTys; 4472 RetTy = FTy->getReturnType(); 4473 ComputeValueVTs(TLI, RetTy, RetTys); 4474 ISD::NodeType AssertOp = ISD::DELETED_NODE; 4475 SmallVector<SDValue, 4> ReturnValues; 4476 unsigned CurReg = 0; 4477 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 4478 EVT VT = RetTys[I]; 4479 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT); 4480 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT); 4481 4482 SDValue ReturnValue = 4483 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs, 4484 RegisterVT, VT, AssertOp); 4485 ReturnValues.push_back(ReturnValue); 4486 CurReg += NumRegs; 4487 } 4488 4489 setValue(CS.getInstruction(), 4490 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(), 4491 DAG.getVTList(&RetTys[0], RetTys.size()), 4492 &ReturnValues[0], ReturnValues.size())); 4493 4494 } 4495 4496 // As a special case, a null chain means that a tail call has been emitted and 4497 // the DAG root is already updated. 4498 if (Result.second.getNode()) 4499 DAG.setRoot(Result.second); 4500 else 4501 HasTailCall = true; 4502 4503 if (LandingPad) { 4504 // Insert a label at the end of the invoke call to mark the try range. This 4505 // can be used to detect deletion of the invoke via the MachineModuleInfo. 4506 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol(); 4507 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel)); 4508 4509 // Inform MachineModuleInfo of range. 4510 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 4511 } 4512 } 4513 4514 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 4515 /// value is equal or not-equal to zero. 4516 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 4517 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 4518 UI != E; ++UI) { 4519 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 4520 if (IC->isEquality()) 4521 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 4522 if (C->isNullValue()) 4523 continue; 4524 // Unknown instruction. 4525 return false; 4526 } 4527 return true; 4528 } 4529 4530 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 4531 const Type *LoadTy, 4532 SelectionDAGBuilder &Builder) { 4533 4534 // Check to see if this load can be trivially constant folded, e.g. if the 4535 // input is from a string literal. 4536 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 4537 // Cast pointer to the type we really want to load. 4538 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 4539 PointerType::getUnqual(LoadTy)); 4540 4541 if (const Constant *LoadCst = 4542 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 4543 Builder.TD)) 4544 return Builder.getValue(LoadCst); 4545 } 4546 4547 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 4548 // still constant memory, the input chain can be the entry node. 4549 SDValue Root; 4550 bool ConstantMemory = false; 4551 4552 // Do not serialize (non-volatile) loads of constant memory with anything. 4553 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 4554 Root = Builder.DAG.getEntryNode(); 4555 ConstantMemory = true; 4556 } else { 4557 // Do not serialize non-volatile loads against each other. 4558 Root = Builder.DAG.getRoot(); 4559 } 4560 4561 SDValue Ptr = Builder.getValue(PtrVal); 4562 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root, 4563 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/, 4564 false /*volatile*/, 4565 false /*nontemporal*/, 1 /* align=1 */); 4566 4567 if (!ConstantMemory) 4568 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 4569 return LoadVal; 4570 } 4571 4572 4573 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 4574 /// If so, return true and lower it, otherwise return false and it will be 4575 /// lowered like a normal call. 4576 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 4577 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 4578 if (I.getNumOperands() != 4) 4579 return false; 4580 4581 const Value *LHS = I.getOperand(1), *RHS = I.getOperand(2); 4582 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 4583 !I.getOperand(3)->getType()->isIntegerTy() || 4584 !I.getType()->isIntegerTy()) 4585 return false; 4586 4587 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3)); 4588 4589 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 4590 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 4591 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) { 4592 bool ActuallyDoIt = true; 4593 MVT LoadVT; 4594 const Type *LoadTy; 4595 switch (Size->getZExtValue()) { 4596 default: 4597 LoadVT = MVT::Other; 4598 LoadTy = 0; 4599 ActuallyDoIt = false; 4600 break; 4601 case 2: 4602 LoadVT = MVT::i16; 4603 LoadTy = Type::getInt16Ty(Size->getContext()); 4604 break; 4605 case 4: 4606 LoadVT = MVT::i32; 4607 LoadTy = Type::getInt32Ty(Size->getContext()); 4608 break; 4609 case 8: 4610 LoadVT = MVT::i64; 4611 LoadTy = Type::getInt64Ty(Size->getContext()); 4612 break; 4613 /* 4614 case 16: 4615 LoadVT = MVT::v4i32; 4616 LoadTy = Type::getInt32Ty(Size->getContext()); 4617 LoadTy = VectorType::get(LoadTy, 4); 4618 break; 4619 */ 4620 } 4621 4622 // This turns into unaligned loads. We only do this if the target natively 4623 // supports the MVT we'll be loading or if it is small enough (<= 4) that 4624 // we'll only produce a small number of byte loads. 4625 4626 // Require that we can find a legal MVT, and only do this if the target 4627 // supports unaligned loads of that type. Expanding into byte loads would 4628 // bloat the code. 4629 if (ActuallyDoIt && Size->getZExtValue() > 4) { 4630 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 4631 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 4632 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT)) 4633 ActuallyDoIt = false; 4634 } 4635 4636 if (ActuallyDoIt) { 4637 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 4638 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 4639 4640 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal, 4641 ISD::SETNE); 4642 EVT CallVT = TLI.getValueType(I.getType(), true); 4643 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT)); 4644 return true; 4645 } 4646 } 4647 4648 4649 return false; 4650 } 4651 4652 4653 void SelectionDAGBuilder::visitCall(const CallInst &I) { 4654 const char *RenameFn = 0; 4655 if (Function *F = I.getCalledFunction()) { 4656 if (F->isDeclaration()) { 4657 const TargetIntrinsicInfo *II = TM.getIntrinsicInfo(); 4658 if (II) { 4659 if (unsigned IID = II->getIntrinsicID(F)) { 4660 RenameFn = visitIntrinsicCall(I, IID); 4661 if (!RenameFn) 4662 return; 4663 } 4664 } 4665 if (unsigned IID = F->getIntrinsicID()) { 4666 RenameFn = visitIntrinsicCall(I, IID); 4667 if (!RenameFn) 4668 return; 4669 } 4670 } 4671 4672 // Check for well-known libc/libm calls. If the function is internal, it 4673 // can't be a library call. 4674 if (!F->hasLocalLinkage() && F->hasName()) { 4675 StringRef Name = F->getName(); 4676 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") { 4677 if (I.getNumOperands() == 3 && // Basic sanity checks. 4678 I.getOperand(1)->getType()->isFloatingPointTy() && 4679 I.getType() == I.getOperand(1)->getType() && 4680 I.getType() == I.getOperand(2)->getType()) { 4681 SDValue LHS = getValue(I.getOperand(1)); 4682 SDValue RHS = getValue(I.getOperand(2)); 4683 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(), 4684 LHS.getValueType(), LHS, RHS)); 4685 return; 4686 } 4687 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") { 4688 if (I.getNumOperands() == 2 && // Basic sanity checks. 4689 I.getOperand(1)->getType()->isFloatingPointTy() && 4690 I.getType() == I.getOperand(1)->getType()) { 4691 SDValue Tmp = getValue(I.getOperand(1)); 4692 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(), 4693 Tmp.getValueType(), Tmp)); 4694 return; 4695 } 4696 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") { 4697 if (I.getNumOperands() == 2 && // Basic sanity checks. 4698 I.getOperand(1)->getType()->isFloatingPointTy() && 4699 I.getType() == I.getOperand(1)->getType() && 4700 I.onlyReadsMemory()) { 4701 SDValue Tmp = getValue(I.getOperand(1)); 4702 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(), 4703 Tmp.getValueType(), Tmp)); 4704 return; 4705 } 4706 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") { 4707 if (I.getNumOperands() == 2 && // Basic sanity checks. 4708 I.getOperand(1)->getType()->isFloatingPointTy() && 4709 I.getType() == I.getOperand(1)->getType() && 4710 I.onlyReadsMemory()) { 4711 SDValue Tmp = getValue(I.getOperand(1)); 4712 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(), 4713 Tmp.getValueType(), Tmp)); 4714 return; 4715 } 4716 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") { 4717 if (I.getNumOperands() == 2 && // Basic sanity checks. 4718 I.getOperand(1)->getType()->isFloatingPointTy() && 4719 I.getType() == I.getOperand(1)->getType() && 4720 I.onlyReadsMemory()) { 4721 SDValue Tmp = getValue(I.getOperand(1)); 4722 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(), 4723 Tmp.getValueType(), Tmp)); 4724 return; 4725 } 4726 } else if (Name == "memcmp") { 4727 if (visitMemCmpCall(I)) 4728 return; 4729 } 4730 } 4731 } else if (isa<InlineAsm>(I.getOperand(0))) { 4732 visitInlineAsm(&I); 4733 return; 4734 } 4735 4736 SDValue Callee; 4737 if (!RenameFn) 4738 Callee = getValue(I.getOperand(0)); 4739 else 4740 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy()); 4741 4742 // Check if we can potentially perform a tail call. More detailed checking is 4743 // be done within LowerCallTo, after more information about the call is known. 4744 LowerCallTo(&I, Callee, I.isTailCall()); 4745 } 4746 4747 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 4748 /// this value and returns the result as a ValueVT value. This uses 4749 /// Chain/Flag as the input and updates them for the output Chain/Flag. 4750 /// If the Flag pointer is NULL, no flag is used. 4751 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 4752 FunctionLoweringInfo &FuncInfo, 4753 DebugLoc dl, 4754 SDValue &Chain, SDValue *Flag) const { 4755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4756 4757 // Assemble the legal parts into the final values. 4758 SmallVector<SDValue, 4> Values(ValueVTs.size()); 4759 SmallVector<SDValue, 8> Parts; 4760 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 4761 // Copy the legal parts from the registers. 4762 EVT ValueVT = ValueVTs[Value]; 4763 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 4764 EVT RegisterVT = RegVTs[Value]; 4765 4766 Parts.resize(NumRegs); 4767 for (unsigned i = 0; i != NumRegs; ++i) { 4768 SDValue P; 4769 if (Flag == 0) { 4770 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 4771 } else { 4772 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 4773 *Flag = P.getValue(2); 4774 } 4775 4776 Chain = P.getValue(1); 4777 4778 // If the source register was virtual and if we know something about it, 4779 // add an assert node. 4780 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) && 4781 RegisterVT.isInteger() && !RegisterVT.isVector()) { 4782 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister; 4783 if (FuncInfo.LiveOutRegInfo.size() > SlotNo) { 4784 const FunctionLoweringInfo::LiveOutInfo &LOI = 4785 FuncInfo.LiveOutRegInfo[SlotNo]; 4786 4787 unsigned RegSize = RegisterVT.getSizeInBits(); 4788 unsigned NumSignBits = LOI.NumSignBits; 4789 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes(); 4790 4791 // FIXME: We capture more information than the dag can represent. For 4792 // now, just use the tightest assertzext/assertsext possible. 4793 bool isSExt = true; 4794 EVT FromVT(MVT::Other); 4795 if (NumSignBits == RegSize) 4796 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 4797 else if (NumZeroBits >= RegSize-1) 4798 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 4799 else if (NumSignBits > RegSize-8) 4800 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 4801 else if (NumZeroBits >= RegSize-8) 4802 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 4803 else if (NumSignBits > RegSize-16) 4804 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 4805 else if (NumZeroBits >= RegSize-16) 4806 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 4807 else if (NumSignBits > RegSize-32) 4808 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 4809 else if (NumZeroBits >= RegSize-32) 4810 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 4811 4812 if (FromVT != MVT::Other) 4813 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 4814 RegisterVT, P, DAG.getValueType(FromVT)); 4815 } 4816 } 4817 4818 Parts[i] = P; 4819 } 4820 4821 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 4822 NumRegs, RegisterVT, ValueVT); 4823 Part += NumRegs; 4824 Parts.clear(); 4825 } 4826 4827 return DAG.getNode(ISD::MERGE_VALUES, dl, 4828 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 4829 &Values[0], ValueVTs.size()); 4830 } 4831 4832 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 4833 /// specified value into the registers specified by this object. This uses 4834 /// Chain/Flag as the input and updates them for the output Chain/Flag. 4835 /// If the Flag pointer is NULL, no flag is used. 4836 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl, 4837 SDValue &Chain, SDValue *Flag) const { 4838 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4839 4840 // Get the list of the values's legal parts. 4841 unsigned NumRegs = Regs.size(); 4842 SmallVector<SDValue, 8> Parts(NumRegs); 4843 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 4844 EVT ValueVT = ValueVTs[Value]; 4845 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 4846 EVT RegisterVT = RegVTs[Value]; 4847 4848 getCopyToParts(DAG, dl, 4849 Val.getValue(Val.getResNo() + Value), 4850 &Parts[Part], NumParts, RegisterVT); 4851 Part += NumParts; 4852 } 4853 4854 // Copy the parts into the registers. 4855 SmallVector<SDValue, 8> Chains(NumRegs); 4856 for (unsigned i = 0; i != NumRegs; ++i) { 4857 SDValue Part; 4858 if (Flag == 0) { 4859 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 4860 } else { 4861 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 4862 *Flag = Part.getValue(1); 4863 } 4864 4865 Chains[i] = Part.getValue(0); 4866 } 4867 4868 if (NumRegs == 1 || Flag) 4869 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 4870 // flagged to it. That is the CopyToReg nodes and the user are considered 4871 // a single scheduling unit. If we create a TokenFactor and return it as 4872 // chain, then the TokenFactor is both a predecessor (operand) of the 4873 // user as well as a successor (the TF operands are flagged to the user). 4874 // c1, f1 = CopyToReg 4875 // c2, f2 = CopyToReg 4876 // c3 = TokenFactor c1, c2 4877 // ... 4878 // = op c3, ..., f2 4879 Chain = Chains[NumRegs-1]; 4880 else 4881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 4882 } 4883 4884 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 4885 /// operand list. This adds the code marker and includes the number of 4886 /// values added into it. 4887 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 4888 unsigned MatchingIdx, 4889 SelectionDAG &DAG, 4890 std::vector<SDValue> &Ops) const { 4891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4892 4893 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 4894 if (HasMatching) 4895 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 4896 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); 4897 Ops.push_back(Res); 4898 4899 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 4900 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 4901 EVT RegisterVT = RegVTs[Value]; 4902 for (unsigned i = 0; i != NumRegs; ++i) { 4903 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 4904 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); 4905 } 4906 } 4907 } 4908 4909 /// isAllocatableRegister - If the specified register is safe to allocate, 4910 /// i.e. it isn't a stack pointer or some other special register, return the 4911 /// register class for the register. Otherwise, return null. 4912 static const TargetRegisterClass * 4913 isAllocatableRegister(unsigned Reg, MachineFunction &MF, 4914 const TargetLowering &TLI, 4915 const TargetRegisterInfo *TRI) { 4916 EVT FoundVT = MVT::Other; 4917 const TargetRegisterClass *FoundRC = 0; 4918 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(), 4919 E = TRI->regclass_end(); RCI != E; ++RCI) { 4920 EVT ThisVT = MVT::Other; 4921 4922 const TargetRegisterClass *RC = *RCI; 4923 // If none of the value types for this register class are valid, we 4924 // can't use it. For example, 64-bit reg classes on 32-bit targets. 4925 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end(); 4926 I != E; ++I) { 4927 if (TLI.isTypeLegal(*I)) { 4928 // If we have already found this register in a different register class, 4929 // choose the one with the largest VT specified. For example, on 4930 // PowerPC, we favor f64 register classes over f32. 4931 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) { 4932 ThisVT = *I; 4933 break; 4934 } 4935 } 4936 } 4937 4938 if (ThisVT == MVT::Other) continue; 4939 4940 // NOTE: This isn't ideal. In particular, this might allocate the 4941 // frame pointer in functions that need it (due to them not being taken 4942 // out of allocation, because a variable sized allocation hasn't been seen 4943 // yet). This is a slight code pessimization, but should still work. 4944 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF), 4945 E = RC->allocation_order_end(MF); I != E; ++I) 4946 if (*I == Reg) { 4947 // We found a matching register class. Keep looking at others in case 4948 // we find one with larger registers that this physreg is also in. 4949 FoundRC = RC; 4950 FoundVT = ThisVT; 4951 break; 4952 } 4953 } 4954 return FoundRC; 4955 } 4956 4957 4958 namespace llvm { 4959 /// AsmOperandInfo - This contains information for each constraint that we are 4960 /// lowering. 4961 class LLVM_LIBRARY_VISIBILITY SDISelAsmOperandInfo : 4962 public TargetLowering::AsmOperandInfo { 4963 public: 4964 /// CallOperand - If this is the result output operand or a clobber 4965 /// this is null, otherwise it is the incoming operand to the CallInst. 4966 /// This gets modified as the asm is processed. 4967 SDValue CallOperand; 4968 4969 /// AssignedRegs - If this is a register or register class operand, this 4970 /// contains the set of register corresponding to the operand. 4971 RegsForValue AssignedRegs; 4972 4973 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info) 4974 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 4975 } 4976 4977 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers 4978 /// busy in OutputRegs/InputRegs. 4979 void MarkAllocatedRegs(bool isOutReg, bool isInReg, 4980 std::set<unsigned> &OutputRegs, 4981 std::set<unsigned> &InputRegs, 4982 const TargetRegisterInfo &TRI) const { 4983 if (isOutReg) { 4984 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 4985 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI); 4986 } 4987 if (isInReg) { 4988 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i) 4989 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI); 4990 } 4991 } 4992 4993 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 4994 /// corresponds to. If there is no Value* for this operand, it returns 4995 /// MVT::Other. 4996 EVT getCallOperandValEVT(LLVMContext &Context, 4997 const TargetLowering &TLI, 4998 const TargetData *TD) const { 4999 if (CallOperandVal == 0) return MVT::Other; 5000 5001 if (isa<BasicBlock>(CallOperandVal)) 5002 return TLI.getPointerTy(); 5003 5004 const llvm::Type *OpTy = CallOperandVal->getType(); 5005 5006 // If this is an indirect operand, the operand is a pointer to the 5007 // accessed type. 5008 if (isIndirect) { 5009 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 5010 if (!PtrTy) 5011 report_fatal_error("Indirect operand for inline asm not a pointer!"); 5012 OpTy = PtrTy->getElementType(); 5013 } 5014 5015 // If OpTy is not a single value, it may be a struct/union that we 5016 // can tile with integers. 5017 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 5018 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 5019 switch (BitSize) { 5020 default: break; 5021 case 1: 5022 case 8: 5023 case 16: 5024 case 32: 5025 case 64: 5026 case 128: 5027 OpTy = IntegerType::get(Context, BitSize); 5028 break; 5029 } 5030 } 5031 5032 return TLI.getValueType(OpTy, true); 5033 } 5034 5035 private: 5036 /// MarkRegAndAliases - Mark the specified register and all aliases in the 5037 /// specified set. 5038 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 5039 const TargetRegisterInfo &TRI) { 5040 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg"); 5041 Regs.insert(Reg); 5042 if (const unsigned *Aliases = TRI.getAliasSet(Reg)) 5043 for (; *Aliases; ++Aliases) 5044 Regs.insert(*Aliases); 5045 } 5046 }; 5047 } // end llvm namespace. 5048 5049 5050 /// GetRegistersForValue - Assign registers (virtual or physical) for the 5051 /// specified operand. We prefer to assign virtual registers, to allow the 5052 /// register allocator to handle the assignment process. However, if the asm 5053 /// uses features that we can't model on machineinstrs, we have SDISel do the 5054 /// allocation. This produces generally horrible, but correct, code. 5055 /// 5056 /// OpInfo describes the operand. 5057 /// Input and OutputRegs are the set of already allocated physical registers. 5058 /// 5059 void SelectionDAGBuilder:: 5060 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, 5061 std::set<unsigned> &OutputRegs, 5062 std::set<unsigned> &InputRegs) { 5063 LLVMContext &Context = FuncInfo.Fn->getContext(); 5064 5065 // Compute whether this value requires an input register, an output register, 5066 // or both. 5067 bool isOutReg = false; 5068 bool isInReg = false; 5069 switch (OpInfo.Type) { 5070 case InlineAsm::isOutput: 5071 isOutReg = true; 5072 5073 // If there is an input constraint that matches this, we need to reserve 5074 // the input register so no other inputs allocate to it. 5075 isInReg = OpInfo.hasMatchingInput(); 5076 break; 5077 case InlineAsm::isInput: 5078 isInReg = true; 5079 isOutReg = false; 5080 break; 5081 case InlineAsm::isClobber: 5082 isOutReg = true; 5083 isInReg = true; 5084 break; 5085 } 5086 5087 5088 MachineFunction &MF = DAG.getMachineFunction(); 5089 SmallVector<unsigned, 4> Regs; 5090 5091 // If this is a constraint for a single physreg, or a constraint for a 5092 // register class, find it. 5093 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 5094 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 5095 OpInfo.ConstraintVT); 5096 5097 unsigned NumRegs = 1; 5098 if (OpInfo.ConstraintVT != MVT::Other) { 5099 // If this is a FP input in an integer register (or visa versa) insert a bit 5100 // cast of the input value. More generally, handle any case where the input 5101 // value disagrees with the register class we plan to stick this in. 5102 if (OpInfo.Type == InlineAsm::isInput && 5103 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 5104 // Try to convert to the first EVT that the reg class contains. If the 5105 // types are identical size, use a bitcast to convert (e.g. two differing 5106 // vector types). 5107 EVT RegVT = *PhysReg.second->vt_begin(); 5108 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 5109 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5110 RegVT, OpInfo.CallOperand); 5111 OpInfo.ConstraintVT = RegVT; 5112 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 5113 // If the input is a FP value and we want it in FP registers, do a 5114 // bitcast to the corresponding integer type. This turns an f64 value 5115 // into i64, which can be passed with two i32 values on a 32-bit 5116 // machine. 5117 RegVT = EVT::getIntegerVT(Context, 5118 OpInfo.ConstraintVT.getSizeInBits()); 5119 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5120 RegVT, OpInfo.CallOperand); 5121 OpInfo.ConstraintVT = RegVT; 5122 } 5123 } 5124 5125 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 5126 } 5127 5128 EVT RegVT; 5129 EVT ValueVT = OpInfo.ConstraintVT; 5130 5131 // If this is a constraint for a specific physical register, like {r17}, 5132 // assign it now. 5133 if (unsigned AssignedReg = PhysReg.first) { 5134 const TargetRegisterClass *RC = PhysReg.second; 5135 if (OpInfo.ConstraintVT == MVT::Other) 5136 ValueVT = *RC->vt_begin(); 5137 5138 // Get the actual register value type. This is important, because the user 5139 // may have asked for (e.g.) the AX register in i32 type. We need to 5140 // remember that AX is actually i16 to get the right extension. 5141 RegVT = *RC->vt_begin(); 5142 5143 // This is a explicit reference to a physical register. 5144 Regs.push_back(AssignedReg); 5145 5146 // If this is an expanded reference, add the rest of the regs to Regs. 5147 if (NumRegs != 1) { 5148 TargetRegisterClass::iterator I = RC->begin(); 5149 for (; *I != AssignedReg; ++I) 5150 assert(I != RC->end() && "Didn't find reg!"); 5151 5152 // Already added the first reg. 5153 --NumRegs; ++I; 5154 for (; NumRegs; --NumRegs, ++I) { 5155 assert(I != RC->end() && "Ran out of registers to allocate!"); 5156 Regs.push_back(*I); 5157 } 5158 } 5159 5160 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5161 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5162 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5163 return; 5164 } 5165 5166 // Otherwise, if this was a reference to an LLVM register class, create vregs 5167 // for this reference. 5168 if (const TargetRegisterClass *RC = PhysReg.second) { 5169 RegVT = *RC->vt_begin(); 5170 if (OpInfo.ConstraintVT == MVT::Other) 5171 ValueVT = RegVT; 5172 5173 // Create the appropriate number of virtual registers. 5174 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5175 for (; NumRegs; --NumRegs) 5176 Regs.push_back(RegInfo.createVirtualRegister(RC)); 5177 5178 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 5179 return; 5180 } 5181 5182 // This is a reference to a register class that doesn't directly correspond 5183 // to an LLVM register class. Allocate NumRegs consecutive, available, 5184 // registers from the class. 5185 std::vector<unsigned> RegClassRegs 5186 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode, 5187 OpInfo.ConstraintVT); 5188 5189 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo(); 5190 unsigned NumAllocated = 0; 5191 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) { 5192 unsigned Reg = RegClassRegs[i]; 5193 // See if this register is available. 5194 if ((isOutReg && OutputRegs.count(Reg)) || // Already used. 5195 (isInReg && InputRegs.count(Reg))) { // Already used. 5196 // Make sure we find consecutive registers. 5197 NumAllocated = 0; 5198 continue; 5199 } 5200 5201 // Check to see if this register is allocatable (i.e. don't give out the 5202 // stack pointer). 5203 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI); 5204 if (!RC) { // Couldn't allocate this register. 5205 // Reset NumAllocated to make sure we return consecutive registers. 5206 NumAllocated = 0; 5207 continue; 5208 } 5209 5210 // Okay, this register is good, we can use it. 5211 ++NumAllocated; 5212 5213 // If we allocated enough consecutive registers, succeed. 5214 if (NumAllocated == NumRegs) { 5215 unsigned RegStart = (i-NumAllocated)+1; 5216 unsigned RegEnd = i+1; 5217 // Mark all of the allocated registers used. 5218 for (unsigned i = RegStart; i != RegEnd; ++i) 5219 Regs.push_back(RegClassRegs[i]); 5220 5221 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(), 5222 OpInfo.ConstraintVT); 5223 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI); 5224 return; 5225 } 5226 } 5227 5228 // Otherwise, we couldn't allocate enough registers for this. 5229 } 5230 5231 /// visitInlineAsm - Handle a call to an InlineAsm object. 5232 /// 5233 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 5234 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 5235 5236 /// ConstraintOperands - Information about all of the constraints. 5237 std::vector<SDISelAsmOperandInfo> ConstraintOperands; 5238 5239 std::set<unsigned> OutputRegs, InputRegs; 5240 5241 // Do a prepass over the constraints, canonicalizing them, and building up the 5242 // ConstraintOperands list. 5243 std::vector<InlineAsm::ConstraintInfo> 5244 ConstraintInfos = IA->ParseConstraints(); 5245 5246 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI); 5247 5248 SDValue Chain, Flag; 5249 5250 // We won't need to flush pending loads if this asm doesn't touch 5251 // memory and is nonvolatile. 5252 if (hasMemory || IA->hasSideEffects()) 5253 Chain = getRoot(); 5254 else 5255 Chain = DAG.getRoot(); 5256 5257 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 5258 unsigned ResNo = 0; // ResNo - The result number of the next output. 5259 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5260 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i])); 5261 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 5262 5263 EVT OpVT = MVT::Other; 5264 5265 // Compute the value type for each operand. 5266 switch (OpInfo.Type) { 5267 case InlineAsm::isOutput: 5268 // Indirect outputs just consume an argument. 5269 if (OpInfo.isIndirect) { 5270 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5271 break; 5272 } 5273 5274 // The return value of the call is this value. As such, there is no 5275 // corresponding argument. 5276 assert(!CS.getType()->isVoidTy() && 5277 "Bad inline asm!"); 5278 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) { 5279 OpVT = TLI.getValueType(STy->getElementType(ResNo)); 5280 } else { 5281 assert(ResNo == 0 && "Asm only has one result!"); 5282 OpVT = TLI.getValueType(CS.getType()); 5283 } 5284 ++ResNo; 5285 break; 5286 case InlineAsm::isInput: 5287 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 5288 break; 5289 case InlineAsm::isClobber: 5290 // Nothing to do. 5291 break; 5292 } 5293 5294 // If this is an input or an indirect output, process the call argument. 5295 // BasicBlocks are labels, currently appearing only in asm's. 5296 if (OpInfo.CallOperandVal) { 5297 // Strip bitcasts, if any. This mostly comes up for functions. 5298 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts(); 5299 5300 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 5301 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 5302 } else { 5303 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 5304 } 5305 5306 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD); 5307 } 5308 5309 OpInfo.ConstraintVT = OpVT; 5310 } 5311 5312 // Second pass over the constraints: compute which constraint option to use 5313 // and assign registers to constraints that want a specific physreg. 5314 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 5315 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5316 5317 // If this is an output operand with a matching input operand, look up the 5318 // matching input. If their types mismatch, e.g. one is an integer, the 5319 // other is floating point, or their sizes are different, flag it as an 5320 // error. 5321 if (OpInfo.hasMatchingInput()) { 5322 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 5323 5324 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 5325 if ((OpInfo.ConstraintVT.isInteger() != 5326 Input.ConstraintVT.isInteger()) || 5327 (OpInfo.ConstraintVT.getSizeInBits() != 5328 Input.ConstraintVT.getSizeInBits())) { 5329 report_fatal_error("Unsupported asm: input constraint" 5330 " with a matching output constraint of" 5331 " incompatible type!"); 5332 } 5333 Input.ConstraintVT = OpInfo.ConstraintVT; 5334 } 5335 } 5336 5337 // Compute the constraint code and ConstraintType to use. 5338 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG); 5339 5340 // If this is a memory input, and if the operand is not indirect, do what we 5341 // need to to provide an address for the memory input. 5342 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 5343 !OpInfo.isIndirect) { 5344 assert(OpInfo.Type == InlineAsm::isInput && 5345 "Can only indirectify direct input operands!"); 5346 5347 // Memory operands really want the address of the value. If we don't have 5348 // an indirect input, put it in the constpool if we can, otherwise spill 5349 // it to a stack slot. 5350 5351 // If the operand is a float, integer, or vector constant, spill to a 5352 // constant pool entry to get its address. 5353 const Value *OpVal = OpInfo.CallOperandVal; 5354 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 5355 isa<ConstantVector>(OpVal)) { 5356 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 5357 TLI.getPointerTy()); 5358 } else { 5359 // Otherwise, create a stack slot and emit a store to it before the 5360 // asm. 5361 const Type *Ty = OpVal->getType(); 5362 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty); 5363 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty); 5364 MachineFunction &MF = DAG.getMachineFunction(); 5365 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5366 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy()); 5367 Chain = DAG.getStore(Chain, getCurDebugLoc(), 5368 OpInfo.CallOperand, StackSlot, NULL, 0, 5369 false, false, 0); 5370 OpInfo.CallOperand = StackSlot; 5371 } 5372 5373 // There is no longer a Value* corresponding to this operand. 5374 OpInfo.CallOperandVal = 0; 5375 5376 // It is now an indirect operand. 5377 OpInfo.isIndirect = true; 5378 } 5379 5380 // If this constraint is for a specific register, allocate it before 5381 // anything else. 5382 if (OpInfo.ConstraintType == TargetLowering::C_Register) 5383 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5384 } 5385 5386 ConstraintInfos.clear(); 5387 5388 // Second pass - Loop over all of the operands, assigning virtual or physregs 5389 // to register class operands. 5390 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5391 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5392 5393 // C_Register operands have already been allocated, Other/Memory don't need 5394 // to be. 5395 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 5396 GetRegistersForValue(OpInfo, OutputRegs, InputRegs); 5397 } 5398 5399 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 5400 std::vector<SDValue> AsmNodeOperands; 5401 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 5402 AsmNodeOperands.push_back( 5403 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 5404 TLI.getPointerTy())); 5405 5406 // If we have a !srcloc metadata node associated with it, we want to attach 5407 // this to the ultimately generated inline asm machineinstr. To do this, we 5408 // pass in the third operand as this (potentially null) inline asm MDNode. 5409 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 5410 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 5411 5412 // Loop over all of the inputs, copying the operand values into the 5413 // appropriate registers and processing the output regs. 5414 RegsForValue RetValRegs; 5415 5416 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 5417 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 5418 5419 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 5420 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 5421 5422 switch (OpInfo.Type) { 5423 case InlineAsm::isOutput: { 5424 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 5425 OpInfo.ConstraintType != TargetLowering::C_Register) { 5426 // Memory output, or 'other' output (e.g. 'X' constraint). 5427 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 5428 5429 // Add information to the INLINEASM node to know about this output. 5430 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 5431 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, 5432 TLI.getPointerTy())); 5433 AsmNodeOperands.push_back(OpInfo.CallOperand); 5434 break; 5435 } 5436 5437 // Otherwise, this is a register or register class output. 5438 5439 // Copy the output from the appropriate register. Find a register that 5440 // we can use. 5441 if (OpInfo.AssignedRegs.Regs.empty()) 5442 report_fatal_error("Couldn't allocate output reg for constraint '" + 5443 Twine(OpInfo.ConstraintCode) + "'!"); 5444 5445 // If this is an indirect operand, store through the pointer after the 5446 // asm. 5447 if (OpInfo.isIndirect) { 5448 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 5449 OpInfo.CallOperandVal)); 5450 } else { 5451 // This is the result value of the call. 5452 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 5453 // Concatenate this output onto the outputs list. 5454 RetValRegs.append(OpInfo.AssignedRegs); 5455 } 5456 5457 // Add information to the INLINEASM node to know that this register is 5458 // set. 5459 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ? 5460 InlineAsm::Kind_RegDefEarlyClobber : 5461 InlineAsm::Kind_RegDef, 5462 false, 5463 0, 5464 DAG, 5465 AsmNodeOperands); 5466 break; 5467 } 5468 case InlineAsm::isInput: { 5469 SDValue InOperandVal = OpInfo.CallOperand; 5470 5471 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 5472 // If this is required to match an output register we have already set, 5473 // just use its register. 5474 unsigned OperandNo = OpInfo.getMatchedOperand(); 5475 5476 // Scan until we find the definition we already emitted of this operand. 5477 // When we find it, create a RegsForValue operand. 5478 unsigned CurOp = InlineAsm::Op_FirstOperand; 5479 for (; OperandNo; --OperandNo) { 5480 // Advance to the next operand. 5481 unsigned OpFlag = 5482 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5483 assert((InlineAsm::isRegDefKind(OpFlag) || 5484 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 5485 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 5486 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 5487 } 5488 5489 unsigned OpFlag = 5490 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 5491 if (InlineAsm::isRegDefKind(OpFlag) || 5492 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 5493 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 5494 if (OpInfo.isIndirect) { 5495 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 5496 LLVMContext &Ctx = *DAG.getContext(); 5497 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 5498 " don't know how to handle tied " 5499 "indirect register inputs"); 5500 } 5501 5502 RegsForValue MatchedRegs; 5503 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 5504 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType(); 5505 MatchedRegs.RegVTs.push_back(RegVT); 5506 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 5507 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 5508 i != e; ++i) 5509 MatchedRegs.Regs.push_back 5510 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT))); 5511 5512 // Use the produced MatchedRegs object to 5513 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5514 Chain, &Flag); 5515 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 5516 true, OpInfo.getMatchedOperand(), 5517 DAG, AsmNodeOperands); 5518 break; 5519 } 5520 5521 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 5522 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 5523 "Unexpected number of operands"); 5524 // Add information to the INLINEASM node to know about this input. 5525 // See InlineAsm.h isUseOperandTiedToDef. 5526 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 5527 OpInfo.getMatchedOperand()); 5528 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 5529 TLI.getPointerTy())); 5530 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 5531 break; 5532 } 5533 5534 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 5535 assert(!OpInfo.isIndirect && 5536 "Don't know how to handle indirect other inputs yet!"); 5537 5538 std::vector<SDValue> Ops; 5539 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0], 5540 hasMemory, Ops, DAG); 5541 if (Ops.empty()) 5542 report_fatal_error("Invalid operand for inline asm constraint '" + 5543 Twine(OpInfo.ConstraintCode) + "'!"); 5544 5545 // Add information to the INLINEASM node to know about this input. 5546 unsigned ResOpType = 5547 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 5548 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5549 TLI.getPointerTy())); 5550 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 5551 break; 5552 } 5553 5554 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 5555 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 5556 assert(InOperandVal.getValueType() == TLI.getPointerTy() && 5557 "Memory operands expect pointer values"); 5558 5559 // Add information to the INLINEASM node to know about this input. 5560 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 5561 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 5562 TLI.getPointerTy())); 5563 AsmNodeOperands.push_back(InOperandVal); 5564 break; 5565 } 5566 5567 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 5568 OpInfo.ConstraintType == TargetLowering::C_Register) && 5569 "Unknown constraint type!"); 5570 assert(!OpInfo.isIndirect && 5571 "Don't know how to handle indirect register inputs yet!"); 5572 5573 // Copy the input into the appropriate registers. 5574 if (OpInfo.AssignedRegs.Regs.empty() || 5575 !OpInfo.AssignedRegs.areValueTypesLegal(TLI)) 5576 report_fatal_error("Couldn't allocate input reg for constraint '" + 5577 Twine(OpInfo.ConstraintCode) + "'!"); 5578 5579 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(), 5580 Chain, &Flag); 5581 5582 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 5583 DAG, AsmNodeOperands); 5584 break; 5585 } 5586 case InlineAsm::isClobber: { 5587 // Add the clobbered value to the operand list, so that the register 5588 // allocator is aware that the physreg got clobbered. 5589 if (!OpInfo.AssignedRegs.Regs.empty()) 5590 OpInfo.AssignedRegs.AddInlineAsmOperands( 5591 InlineAsm::Kind_RegDefEarlyClobber, 5592 false, 0, DAG, 5593 AsmNodeOperands); 5594 break; 5595 } 5596 } 5597 } 5598 5599 // Finish up input operands. Set the input chain and add the flag last. 5600 AsmNodeOperands[0] = Chain; 5601 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 5602 5603 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(), 5604 DAG.getVTList(MVT::Other, MVT::Flag), 5605 &AsmNodeOperands[0], AsmNodeOperands.size()); 5606 Flag = Chain.getValue(1); 5607 5608 // If this asm returns a register value, copy the result from that register 5609 // and set it as the value of the call. 5610 if (!RetValRegs.Regs.empty()) { 5611 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 5612 Chain, &Flag); 5613 5614 // FIXME: Why don't we do this for inline asms with MRVs? 5615 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 5616 EVT ResultType = TLI.getValueType(CS.getType()); 5617 5618 // If any of the results of the inline asm is a vector, it may have the 5619 // wrong width/num elts. This can happen for register classes that can 5620 // contain multiple different value types. The preg or vreg allocated may 5621 // not have the same VT as was expected. Convert it to the right type 5622 // with bit_convert. 5623 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 5624 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), 5625 ResultType, Val); 5626 5627 } else if (ResultType != Val.getValueType() && 5628 ResultType.isInteger() && Val.getValueType().isInteger()) { 5629 // If a result value was tied to an input value, the computed result may 5630 // have a wider width than the expected result. Extract the relevant 5631 // portion. 5632 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val); 5633 } 5634 5635 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 5636 } 5637 5638 setValue(CS.getInstruction(), Val); 5639 // Don't need to use this as a chain in this case. 5640 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 5641 return; 5642 } 5643 5644 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 5645 5646 // Process indirect outputs, first output all of the flagged copies out of 5647 // physregs. 5648 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 5649 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 5650 const Value *Ptr = IndirectStoresToEmit[i].second; 5651 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), 5652 Chain, &Flag); 5653 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 5654 } 5655 5656 // Emit the non-flagged stores from the physregs. 5657 SmallVector<SDValue, 8> OutChains; 5658 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 5659 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(), 5660 StoresToEmit[i].first, 5661 getValue(StoresToEmit[i].second), 5662 StoresToEmit[i].second, 0, 5663 false, false, 0); 5664 OutChains.push_back(Val); 5665 } 5666 5667 if (!OutChains.empty()) 5668 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other, 5669 &OutChains[0], OutChains.size()); 5670 5671 DAG.setRoot(Chain); 5672 } 5673 5674 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 5675 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(), 5676 MVT::Other, getRoot(), 5677 getValue(I.getOperand(1)), 5678 DAG.getSrcValue(I.getOperand(1)))); 5679 } 5680 5681 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 5682 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(), 5683 getRoot(), getValue(I.getOperand(0)), 5684 DAG.getSrcValue(I.getOperand(0))); 5685 setValue(&I, V); 5686 DAG.setRoot(V.getValue(1)); 5687 } 5688 5689 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 5690 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(), 5691 MVT::Other, getRoot(), 5692 getValue(I.getOperand(1)), 5693 DAG.getSrcValue(I.getOperand(1)))); 5694 } 5695 5696 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 5697 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(), 5698 MVT::Other, getRoot(), 5699 getValue(I.getOperand(1)), 5700 getValue(I.getOperand(2)), 5701 DAG.getSrcValue(I.getOperand(1)), 5702 DAG.getSrcValue(I.getOperand(2)))); 5703 } 5704 5705 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 5706 /// implementation, which just calls LowerCall. 5707 /// FIXME: When all targets are 5708 /// migrated to using LowerCall, this hook should be integrated into SDISel. 5709 std::pair<SDValue, SDValue> 5710 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy, 5711 bool RetSExt, bool RetZExt, bool isVarArg, 5712 bool isInreg, unsigned NumFixedArgs, 5713 CallingConv::ID CallConv, bool isTailCall, 5714 bool isReturnValueUsed, 5715 SDValue Callee, 5716 ArgListTy &Args, SelectionDAG &DAG, 5717 DebugLoc dl) const { 5718 // Handle all of the outgoing arguments. 5719 SmallVector<ISD::OutputArg, 32> Outs; 5720 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5721 SmallVector<EVT, 4> ValueVTs; 5722 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 5723 for (unsigned Value = 0, NumValues = ValueVTs.size(); 5724 Value != NumValues; ++Value) { 5725 EVT VT = ValueVTs[Value]; 5726 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext()); 5727 SDValue Op = SDValue(Args[i].Node.getNode(), 5728 Args[i].Node.getResNo() + Value); 5729 ISD::ArgFlagsTy Flags; 5730 unsigned OriginalAlignment = 5731 getTargetData()->getABITypeAlignment(ArgTy); 5732 5733 if (Args[i].isZExt) 5734 Flags.setZExt(); 5735 if (Args[i].isSExt) 5736 Flags.setSExt(); 5737 if (Args[i].isInReg) 5738 Flags.setInReg(); 5739 if (Args[i].isSRet) 5740 Flags.setSRet(); 5741 if (Args[i].isByVal) { 5742 Flags.setByVal(); 5743 const PointerType *Ty = cast<PointerType>(Args[i].Ty); 5744 const Type *ElementTy = Ty->getElementType(); 5745 unsigned FrameAlign = getByValTypeAlignment(ElementTy); 5746 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy); 5747 // For ByVal, alignment should come from FE. BE will guess if this 5748 // info is not there but there are cases it cannot get right. 5749 if (Args[i].Alignment) 5750 FrameAlign = Args[i].Alignment; 5751 Flags.setByValAlign(FrameAlign); 5752 Flags.setByValSize(FrameSize); 5753 } 5754 if (Args[i].isNest) 5755 Flags.setNest(); 5756 Flags.setOrigAlign(OriginalAlignment); 5757 5758 EVT PartVT = getRegisterType(RetTy->getContext(), VT); 5759 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT); 5760 SmallVector<SDValue, 4> Parts(NumParts); 5761 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 5762 5763 if (Args[i].isSExt) 5764 ExtendKind = ISD::SIGN_EXTEND; 5765 else if (Args[i].isZExt) 5766 ExtendKind = ISD::ZERO_EXTEND; 5767 5768 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, 5769 PartVT, ExtendKind); 5770 5771 for (unsigned j = 0; j != NumParts; ++j) { 5772 // if it isn't first piece, alignment must be 1 5773 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs); 5774 if (NumParts > 1 && j == 0) 5775 MyFlags.Flags.setSplit(); 5776 else if (j != 0) 5777 MyFlags.Flags.setOrigAlign(1); 5778 5779 Outs.push_back(MyFlags); 5780 } 5781 } 5782 } 5783 5784 // Handle the incoming return values from the call. 5785 SmallVector<ISD::InputArg, 32> Ins; 5786 SmallVector<EVT, 4> RetTys; 5787 ComputeValueVTs(*this, RetTy, RetTys); 5788 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 5789 EVT VT = RetTys[I]; 5790 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 5791 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 5792 for (unsigned i = 0; i != NumRegs; ++i) { 5793 ISD::InputArg MyFlags; 5794 MyFlags.VT = RegisterVT; 5795 MyFlags.Used = isReturnValueUsed; 5796 if (RetSExt) 5797 MyFlags.Flags.setSExt(); 5798 if (RetZExt) 5799 MyFlags.Flags.setZExt(); 5800 if (isInreg) 5801 MyFlags.Flags.setInReg(); 5802 Ins.push_back(MyFlags); 5803 } 5804 } 5805 5806 SmallVector<SDValue, 4> InVals; 5807 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall, 5808 Outs, Ins, dl, DAG, InVals); 5809 5810 // Verify that the target's LowerCall behaved as expected. 5811 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 5812 "LowerCall didn't return a valid chain!"); 5813 assert((!isTailCall || InVals.empty()) && 5814 "LowerCall emitted a return value for a tail call!"); 5815 assert((isTailCall || InVals.size() == Ins.size()) && 5816 "LowerCall didn't emit the correct number of values!"); 5817 5818 // For a tail call, the return value is merely live-out and there aren't 5819 // any nodes in the DAG representing it. Return a special value to 5820 // indicate that a tail call has been emitted and no more Instructions 5821 // should be processed in the current block. 5822 if (isTailCall) { 5823 DAG.setRoot(Chain); 5824 return std::make_pair(SDValue(), SDValue()); 5825 } 5826 5827 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 5828 assert(InVals[i].getNode() && 5829 "LowerCall emitted a null value!"); 5830 assert(Ins[i].VT == InVals[i].getValueType() && 5831 "LowerCall emitted a value with the wrong type!"); 5832 }); 5833 5834 // Collect the legal value parts into potentially illegal values 5835 // that correspond to the original function's return values. 5836 ISD::NodeType AssertOp = ISD::DELETED_NODE; 5837 if (RetSExt) 5838 AssertOp = ISD::AssertSext; 5839 else if (RetZExt) 5840 AssertOp = ISD::AssertZext; 5841 SmallVector<SDValue, 4> ReturnValues; 5842 unsigned CurReg = 0; 5843 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 5844 EVT VT = RetTys[I]; 5845 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT); 5846 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT); 5847 5848 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg], 5849 NumRegs, RegisterVT, VT, 5850 AssertOp)); 5851 CurReg += NumRegs; 5852 } 5853 5854 // For a function returning void, there is no return value. We can't create 5855 // such a node, so we just return a null return value in that case. In 5856 // that case, nothing will actualy look at the value. 5857 if (ReturnValues.empty()) 5858 return std::make_pair(SDValue(), Chain); 5859 5860 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 5861 DAG.getVTList(&RetTys[0], RetTys.size()), 5862 &ReturnValues[0], ReturnValues.size()); 5863 return std::make_pair(Res, Chain); 5864 } 5865 5866 void TargetLowering::LowerOperationWrapper(SDNode *N, 5867 SmallVectorImpl<SDValue> &Results, 5868 SelectionDAG &DAG) const { 5869 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 5870 if (Res.getNode()) 5871 Results.push_back(Res); 5872 } 5873 5874 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 5875 llvm_unreachable("LowerOperation not implemented for this target!"); 5876 return SDValue(); 5877 } 5878 5879 void 5880 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 5881 SDValue Op = getValue(V); 5882 assert((Op.getOpcode() != ISD::CopyFromReg || 5883 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 5884 "Copy from a reg to the same reg!"); 5885 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 5886 5887 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType()); 5888 SDValue Chain = DAG.getEntryNode(); 5889 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0); 5890 PendingExports.push_back(Chain); 5891 } 5892 5893 #include "llvm/CodeGen/SelectionDAGISel.h" 5894 5895 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) { 5896 // If this is the entry block, emit arguments. 5897 const Function &F = *LLVMBB->getParent(); 5898 SelectionDAG &DAG = SDB->DAG; 5899 SDValue OldRoot = DAG.getRoot(); 5900 DebugLoc dl = SDB->getCurDebugLoc(); 5901 const TargetData *TD = TLI.getTargetData(); 5902 SmallVector<ISD::InputArg, 16> Ins; 5903 5904 // Check whether the function can return without sret-demotion. 5905 SmallVector<EVT, 4> OutVTs; 5906 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags; 5907 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(), 5908 OutVTs, OutsFlags, TLI); 5909 5910 FuncInfo->CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), 5911 F.isVarArg(), 5912 OutVTs, OutsFlags, DAG); 5913 if (!FuncInfo->CanLowerReturn) { 5914 // Put in an sret pointer parameter before all the other parameters. 5915 SmallVector<EVT, 1> ValueVTs; 5916 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 5917 5918 // NOTE: Assuming that a pointer will never break down to more than one VT 5919 // or one register. 5920 ISD::ArgFlagsTy Flags; 5921 Flags.setSRet(); 5922 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]); 5923 ISD::InputArg RetArg(Flags, RegisterVT, true); 5924 Ins.push_back(RetArg); 5925 } 5926 5927 // Set up the incoming argument description vector. 5928 unsigned Idx = 1; 5929 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 5930 I != E; ++I, ++Idx) { 5931 SmallVector<EVT, 4> ValueVTs; 5932 ComputeValueVTs(TLI, I->getType(), ValueVTs); 5933 bool isArgValueUsed = !I->use_empty(); 5934 for (unsigned Value = 0, NumValues = ValueVTs.size(); 5935 Value != NumValues; ++Value) { 5936 EVT VT = ValueVTs[Value]; 5937 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5938 ISD::ArgFlagsTy Flags; 5939 unsigned OriginalAlignment = 5940 TD->getABITypeAlignment(ArgTy); 5941 5942 if (F.paramHasAttr(Idx, Attribute::ZExt)) 5943 Flags.setZExt(); 5944 if (F.paramHasAttr(Idx, Attribute::SExt)) 5945 Flags.setSExt(); 5946 if (F.paramHasAttr(Idx, Attribute::InReg)) 5947 Flags.setInReg(); 5948 if (F.paramHasAttr(Idx, Attribute::StructRet)) 5949 Flags.setSRet(); 5950 if (F.paramHasAttr(Idx, Attribute::ByVal)) { 5951 Flags.setByVal(); 5952 const PointerType *Ty = cast<PointerType>(I->getType()); 5953 const Type *ElementTy = Ty->getElementType(); 5954 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy); 5955 unsigned FrameSize = TD->getTypeAllocSize(ElementTy); 5956 // For ByVal, alignment should be passed from FE. BE will guess if 5957 // this info is not there but there are cases it cannot get right. 5958 if (F.getParamAlignment(Idx)) 5959 FrameAlign = F.getParamAlignment(Idx); 5960 Flags.setByValAlign(FrameAlign); 5961 Flags.setByValSize(FrameSize); 5962 } 5963 if (F.paramHasAttr(Idx, Attribute::Nest)) 5964 Flags.setNest(); 5965 Flags.setOrigAlign(OriginalAlignment); 5966 5967 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 5968 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT); 5969 for (unsigned i = 0; i != NumRegs; ++i) { 5970 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed); 5971 if (NumRegs > 1 && i == 0) 5972 MyFlags.Flags.setSplit(); 5973 // if it isn't first piece, alignment must be 1 5974 else if (i > 0) 5975 MyFlags.Flags.setOrigAlign(1); 5976 Ins.push_back(MyFlags); 5977 } 5978 } 5979 } 5980 5981 // Call the target to set up the argument values. 5982 SmallVector<SDValue, 8> InVals; 5983 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 5984 F.isVarArg(), Ins, 5985 dl, DAG, InVals); 5986 5987 // Verify that the target's LowerFormalArguments behaved as expected. 5988 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 5989 "LowerFormalArguments didn't return a valid chain!"); 5990 assert(InVals.size() == Ins.size() && 5991 "LowerFormalArguments didn't emit the correct number of values!"); 5992 DEBUG({ 5993 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 5994 assert(InVals[i].getNode() && 5995 "LowerFormalArguments emitted a null value!"); 5996 assert(Ins[i].VT == InVals[i].getValueType() && 5997 "LowerFormalArguments emitted a value with the wrong type!"); 5998 } 5999 }); 6000 6001 // Update the DAG with the new chain value resulting from argument lowering. 6002 DAG.setRoot(NewRoot); 6003 6004 // Set up the argument values. 6005 unsigned i = 0; 6006 Idx = 1; 6007 if (!FuncInfo->CanLowerReturn) { 6008 // Create a virtual register for the sret pointer, and put in a copy 6009 // from the sret argument into it. 6010 SmallVector<EVT, 1> ValueVTs; 6011 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 6012 EVT VT = ValueVTs[0]; 6013 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6014 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6015 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 6016 RegVT, VT, AssertOp); 6017 6018 MachineFunction& MF = SDB->DAG.getMachineFunction(); 6019 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 6020 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)); 6021 FuncInfo->DemoteRegister = SRetReg; 6022 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), 6023 SRetReg, ArgValue); 6024 DAG.setRoot(NewRoot); 6025 6026 // i indexes lowered arguments. Bump it past the hidden sret argument. 6027 // Idx indexes LLVM arguments. Don't touch it. 6028 ++i; 6029 } 6030 6031 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 6032 ++I, ++Idx) { 6033 SmallVector<SDValue, 4> ArgValues; 6034 SmallVector<EVT, 4> ValueVTs; 6035 ComputeValueVTs(TLI, I->getType(), ValueVTs); 6036 unsigned NumValues = ValueVTs.size(); 6037 for (unsigned Value = 0; Value != NumValues; ++Value) { 6038 EVT VT = ValueVTs[Value]; 6039 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT); 6040 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT); 6041 6042 if (!I->use_empty()) { 6043 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6044 if (F.paramHasAttr(Idx, Attribute::SExt)) 6045 AssertOp = ISD::AssertSext; 6046 else if (F.paramHasAttr(Idx, Attribute::ZExt)) 6047 AssertOp = ISD::AssertZext; 6048 6049 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 6050 NumParts, PartVT, VT, 6051 AssertOp)); 6052 } 6053 6054 i += NumParts; 6055 } 6056 6057 if (!I->use_empty()) { 6058 SDValue Res; 6059 if (!ArgValues.empty()) 6060 Res = DAG.getMergeValues(&ArgValues[0], NumValues, 6061 SDB->getCurDebugLoc()); 6062 SDB->setValue(I, Res); 6063 6064 // If this argument is live outside of the entry block, insert a copy from 6065 // whereever we got it to the vreg that other BB's will reference it as. 6066 SDB->CopyToExportRegsIfNeeded(I); 6067 } 6068 } 6069 6070 assert(i == InVals.size() && "Argument register count mismatch!"); 6071 6072 // Finally, if the target has anything special to do, allow it to do so. 6073 // FIXME: this should insert code into the DAG! 6074 EmitFunctionEntryCode(); 6075 } 6076 6077 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 6078 /// ensure constants are generated when needed. Remember the virtual registers 6079 /// that need to be added to the Machine PHI nodes as input. We cannot just 6080 /// directly add them, because expansion might result in multiple MBB's for one 6081 /// BB. As such, the start of the BB might correspond to a different MBB than 6082 /// the end. 6083 /// 6084 void 6085 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 6086 const TerminatorInst *TI = LLVMBB->getTerminator(); 6087 6088 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 6089 6090 // Check successor nodes' PHI nodes that expect a constant to be available 6091 // from this block. 6092 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 6093 const BasicBlock *SuccBB = TI->getSuccessor(succ); 6094 if (!isa<PHINode>(SuccBB->begin())) continue; 6095 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 6096 6097 // If this terminator has multiple identical successors (common for 6098 // switches), only handle each succ once. 6099 if (!SuccsHandled.insert(SuccMBB)) continue; 6100 6101 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 6102 6103 // At this point we know that there is a 1-1 correspondence between LLVM PHI 6104 // nodes and Machine PHI nodes, but the incoming operands have not been 6105 // emitted yet. 6106 for (BasicBlock::const_iterator I = SuccBB->begin(); 6107 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 6108 // Ignore dead phi's. 6109 if (PN->use_empty()) continue; 6110 6111 unsigned Reg; 6112 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 6113 6114 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 6115 unsigned &RegOut = ConstantsOut[C]; 6116 if (RegOut == 0) { 6117 RegOut = FuncInfo.CreateRegForValue(C); 6118 CopyValueToVirtualRegister(C, RegOut); 6119 } 6120 Reg = RegOut; 6121 } else { 6122 Reg = FuncInfo.ValueMap[PHIOp]; 6123 if (Reg == 0) { 6124 assert(isa<AllocaInst>(PHIOp) && 6125 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 6126 "Didn't codegen value into a register!??"); 6127 Reg = FuncInfo.CreateRegForValue(PHIOp); 6128 CopyValueToVirtualRegister(PHIOp, Reg); 6129 } 6130 } 6131 6132 // Remember that this register needs to added to the machine PHI node as 6133 // the input for this MBB. 6134 SmallVector<EVT, 4> ValueVTs; 6135 ComputeValueVTs(TLI, PN->getType(), ValueVTs); 6136 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 6137 EVT VT = ValueVTs[vti]; 6138 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 6139 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 6140 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 6141 Reg += NumRegisters; 6142 } 6143 } 6144 } 6145 ConstantsOut.clear(); 6146 } 6147