1 //===- FastISel.cpp - Implementation of the FastISel class ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the FastISel class. 10 // 11 // "Fast" instruction selection is designed to emit very poor code quickly. 12 // Also, it is not designed to be able to do much lowering, so most illegal 13 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is 14 // also not intended to be able to do much optimization, except in a few cases 15 // where doing optimizations reduces overall compile time. For example, folding 16 // constants into immediate fields is often done, because it's cheap and it 17 // reduces the number of instructions later phases have to examine. 18 // 19 // "Fast" instruction selection is able to fail gracefully and transfer 20 // control to the SelectionDAG selector for operations that it doesn't 21 // support. In many cases, this allows us to avoid duplicating a lot of 22 // the complicated lowering logic that SelectionDAG currently has. 23 // 24 // The intended use for "fast" instruction selection is "-O0" mode 25 // compilation, where the quality of the generated code is irrelevant when 26 // weighed against the speed at which the code can be generated. Also, 27 // at -O0, the LLVM optimizers are not running, and this makes the 28 // compile time of codegen a much higher portion of the overall compile 29 // time. Despite its limitations, "fast" instruction selection is able to 30 // handle enough code on its own to provide noticeable overall speedups 31 // in -O0 compiles. 32 // 33 // Basic operations are supported in a target-independent way, by reading 34 // the same instruction descriptions that the SelectionDAG selector reads, 35 // and identifying simple arithmetic operations that can be directly selected 36 // from simple operators. More complicated operations currently require 37 // target-specific code. 38 // 39 //===----------------------------------------------------------------------===// 40 41 #include "llvm/CodeGen/FastISel.h" 42 #include "llvm/ADT/APFloat.h" 43 #include "llvm/ADT/APSInt.h" 44 #include "llvm/ADT/DenseMap.h" 45 #include "llvm/ADT/Optional.h" 46 #include "llvm/ADT/SmallPtrSet.h" 47 #include "llvm/ADT/SmallString.h" 48 #include "llvm/ADT/SmallVector.h" 49 #include "llvm/ADT/Statistic.h" 50 #include "llvm/Analysis/BranchProbabilityInfo.h" 51 #include "llvm/Analysis/TargetLibraryInfo.h" 52 #include "llvm/CodeGen/Analysis.h" 53 #include "llvm/CodeGen/FunctionLoweringInfo.h" 54 #include "llvm/CodeGen/ISDOpcodes.h" 55 #include "llvm/CodeGen/MachineBasicBlock.h" 56 #include "llvm/CodeGen/MachineFrameInfo.h" 57 #include "llvm/CodeGen/MachineInstr.h" 58 #include "llvm/CodeGen/MachineInstrBuilder.h" 59 #include "llvm/CodeGen/MachineMemOperand.h" 60 #include "llvm/CodeGen/MachineModuleInfo.h" 61 #include "llvm/CodeGen/MachineOperand.h" 62 #include "llvm/CodeGen/MachineRegisterInfo.h" 63 #include "llvm/CodeGen/StackMaps.h" 64 #include "llvm/CodeGen/TargetInstrInfo.h" 65 #include "llvm/CodeGen/TargetLowering.h" 66 #include "llvm/CodeGen/TargetSubtargetInfo.h" 67 #include "llvm/CodeGen/ValueTypes.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfo.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/GlobalValue.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Mangler.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Type.h" 92 #include "llvm/IR/User.h" 93 #include "llvm/IR/Value.h" 94 #include "llvm/MC/MCContext.h" 95 #include "llvm/MC/MCInstrDesc.h" 96 #include "llvm/MC/MCRegisterInfo.h" 97 #include "llvm/Support/Casting.h" 98 #include "llvm/Support/Debug.h" 99 #include "llvm/Support/ErrorHandling.h" 100 #include "llvm/Support/MachineValueType.h" 101 #include "llvm/Support/MathExtras.h" 102 #include "llvm/Support/raw_ostream.h" 103 #include "llvm/Target/TargetMachine.h" 104 #include "llvm/Target/TargetOptions.h" 105 #include <algorithm> 106 #include <cassert> 107 #include <cstdint> 108 #include <iterator> 109 #include <utility> 110 111 using namespace llvm; 112 using namespace PatternMatch; 113 114 #define DEBUG_TYPE "isel" 115 116 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by " 117 "target-independent selector"); 118 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by " 119 "target-specific selector"); 120 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure"); 121 122 /// Set the current block to which generated machine instructions will be 123 /// appended. 124 void FastISel::startNewBlock() { 125 assert(LocalValueMap.empty() && 126 "local values should be cleared after finishing a BB"); 127 128 // Instructions are appended to FuncInfo.MBB. If the basic block already 129 // contains labels or copies, use the last instruction as the last local 130 // value. 131 EmitStartPt = nullptr; 132 if (!FuncInfo.MBB->empty()) 133 EmitStartPt = &FuncInfo.MBB->back(); 134 LastLocalValue = EmitStartPt; 135 } 136 137 void FastISel::finishBasicBlock() { flushLocalValueMap(); } 138 139 bool FastISel::lowerArguments() { 140 if (!FuncInfo.CanLowerReturn) 141 // Fallback to SDISel argument lowering code to deal with sret pointer 142 // parameter. 143 return false; 144 145 if (!fastLowerArguments()) 146 return false; 147 148 // Enter arguments into ValueMap for uses in non-entry BBs. 149 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(), 150 E = FuncInfo.Fn->arg_end(); 151 I != E; ++I) { 152 DenseMap<const Value *, Register>::iterator VI = LocalValueMap.find(&*I); 153 assert(VI != LocalValueMap.end() && "Missed an argument?"); 154 FuncInfo.ValueMap[&*I] = VI->second; 155 } 156 return true; 157 } 158 159 /// Return the defined register if this instruction defines exactly one 160 /// virtual register and uses no other virtual registers. Otherwise return 0. 161 static Register findLocalRegDef(MachineInstr &MI) { 162 Register RegDef; 163 for (const MachineOperand &MO : MI.operands()) { 164 if (!MO.isReg()) 165 continue; 166 if (MO.isDef()) { 167 if (RegDef) 168 return Register(); 169 RegDef = MO.getReg(); 170 } else if (MO.getReg().isVirtual()) { 171 // This is another use of a vreg. Don't delete it. 172 return Register(); 173 } 174 } 175 return RegDef; 176 } 177 178 static bool isRegUsedByPhiNodes(Register DefReg, 179 FunctionLoweringInfo &FuncInfo) { 180 for (auto &P : FuncInfo.PHINodesToUpdate) 181 if (P.second == DefReg) 182 return true; 183 return false; 184 } 185 186 void FastISel::flushLocalValueMap() { 187 // If FastISel bails out, it could leave local value instructions behind 188 // that aren't used for anything. Detect and erase those. 189 if (LastLocalValue != EmitStartPt) { 190 MachineBasicBlock::reverse_iterator RE = 191 EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt) 192 : FuncInfo.MBB->rend(); 193 MachineBasicBlock::reverse_iterator RI(LastLocalValue); 194 for (; RI != RE;) { 195 MachineInstr &LocalMI = *RI; 196 // Increment before erasing what it points to. 197 ++RI; 198 Register DefReg = findLocalRegDef(LocalMI); 199 if (!DefReg) 200 continue; 201 if (FuncInfo.RegsWithFixups.count(DefReg)) 202 continue; 203 bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo); 204 if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) { 205 if (EmitStartPt == &LocalMI) 206 EmitStartPt = EmitStartPt->getPrevNode(); 207 LLVM_DEBUG(dbgs() << "removing dead local value materialization" 208 << LocalMI); 209 LocalMI.eraseFromParent(); 210 } 211 } 212 } 213 214 LocalValueMap.clear(); 215 LastLocalValue = EmitStartPt; 216 recomputeInsertPt(); 217 SavedInsertPt = FuncInfo.InsertPt; 218 } 219 220 bool FastISel::hasTrivialKill(const Value *V) { 221 // Don't consider constants or arguments to have trivial kills. 222 const Instruction *I = dyn_cast<Instruction>(V); 223 if (!I) 224 return false; 225 226 // No-op casts are trivially coalesced by fast-isel. 227 if (const auto *Cast = dyn_cast<CastInst>(I)) 228 if (Cast->isNoopCast(DL) && !hasTrivialKill(Cast->getOperand(0))) 229 return false; 230 231 // Even the value might have only one use in the LLVM IR, it is possible that 232 // FastISel might fold the use into another instruction and now there is more 233 // than one use at the Machine Instruction level. 234 Register Reg = lookUpRegForValue(V); 235 if (Reg && !MRI.use_empty(Reg)) 236 return false; 237 238 // GEPs with all zero indices are trivially coalesced by fast-isel. 239 if (const auto *GEP = dyn_cast<GetElementPtrInst>(I)) 240 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0))) 241 return false; 242 243 // Only instructions with a single use in the same basic block are considered 244 // to have trivial kills. 245 return I->hasOneUse() && 246 !(I->getOpcode() == Instruction::BitCast || 247 I->getOpcode() == Instruction::PtrToInt || 248 I->getOpcode() == Instruction::IntToPtr) && 249 cast<Instruction>(*I->user_begin())->getParent() == I->getParent(); 250 } 251 252 Register FastISel::getRegForValue(const Value *V) { 253 EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true); 254 // Don't handle non-simple values in FastISel. 255 if (!RealVT.isSimple()) 256 return Register(); 257 258 // Ignore illegal types. We must do this before looking up the value 259 // in ValueMap because Arguments are given virtual registers regardless 260 // of whether FastISel can handle them. 261 MVT VT = RealVT.getSimpleVT(); 262 if (!TLI.isTypeLegal(VT)) { 263 // Handle integer promotions, though, because they're common and easy. 264 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16) 265 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 266 else 267 return Register(); 268 } 269 270 // Look up the value to see if we already have a register for it. 271 Register Reg = lookUpRegForValue(V); 272 if (Reg) 273 return Reg; 274 275 // In bottom-up mode, just create the virtual register which will be used 276 // to hold the value. It will be materialized later. 277 if (isa<Instruction>(V) && 278 (!isa<AllocaInst>(V) || 279 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V)))) 280 return FuncInfo.InitializeRegForValue(V); 281 282 SavePoint SaveInsertPt = enterLocalValueArea(); 283 284 // Materialize the value in a register. Emit any instructions in the 285 // local value area. 286 Reg = materializeRegForValue(V, VT); 287 288 leaveLocalValueArea(SaveInsertPt); 289 290 return Reg; 291 } 292 293 Register FastISel::materializeConstant(const Value *V, MVT VT) { 294 Register Reg; 295 if (const auto *CI = dyn_cast<ConstantInt>(V)) { 296 if (CI->getValue().getActiveBits() <= 64) 297 Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 298 } else if (isa<AllocaInst>(V)) 299 Reg = fastMaterializeAlloca(cast<AllocaInst>(V)); 300 else if (isa<ConstantPointerNull>(V)) 301 // Translate this as an integer zero so that it can be 302 // local-CSE'd with actual integer zeros. 303 Reg = 304 getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getType()))); 305 else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 306 if (CF->isNullValue()) 307 Reg = fastMaterializeFloatZero(CF); 308 else 309 // Try to emit the constant directly. 310 Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF); 311 312 if (!Reg) { 313 // Try to emit the constant by using an integer constant with a cast. 314 const APFloat &Flt = CF->getValueAPF(); 315 EVT IntVT = TLI.getPointerTy(DL); 316 uint32_t IntBitWidth = IntVT.getSizeInBits(); 317 APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false); 318 bool isExact; 319 (void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact); 320 if (isExact) { 321 Register IntegerReg = 322 getRegForValue(ConstantInt::get(V->getContext(), SIntVal)); 323 if (IntegerReg) 324 Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg, 325 /*Op0IsKill=*/false); 326 } 327 } 328 } else if (const auto *Op = dyn_cast<Operator>(V)) { 329 if (!selectOperator(Op, Op->getOpcode())) 330 if (!isa<Instruction>(Op) || 331 !fastSelectInstruction(cast<Instruction>(Op))) 332 return 0; 333 Reg = lookUpRegForValue(Op); 334 } else if (isa<UndefValue>(V)) { 335 Reg = createResultReg(TLI.getRegClassFor(VT)); 336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 337 TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 338 } 339 return Reg; 340 } 341 342 /// Helper for getRegForValue. This function is called when the value isn't 343 /// already available in a register and must be materialized with new 344 /// instructions. 345 Register FastISel::materializeRegForValue(const Value *V, MVT VT) { 346 Register Reg; 347 // Give the target-specific code a try first. 348 if (isa<Constant>(V)) 349 Reg = fastMaterializeConstant(cast<Constant>(V)); 350 351 // If target-specific code couldn't or didn't want to handle the value, then 352 // give target-independent code a try. 353 if (!Reg) 354 Reg = materializeConstant(V, VT); 355 356 // Don't cache constant materializations in the general ValueMap. 357 // To do so would require tracking what uses they dominate. 358 if (Reg) { 359 LocalValueMap[V] = Reg; 360 LastLocalValue = MRI.getVRegDef(Reg); 361 } 362 return Reg; 363 } 364 365 Register FastISel::lookUpRegForValue(const Value *V) { 366 // Look up the value to see if we already have a register for it. We 367 // cache values defined by Instructions across blocks, and other values 368 // only locally. This is because Instructions already have the SSA 369 // def-dominates-use requirement enforced. 370 DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(V); 371 if (I != FuncInfo.ValueMap.end()) 372 return I->second; 373 return LocalValueMap[V]; 374 } 375 376 void FastISel::updateValueMap(const Value *I, Register Reg, unsigned NumRegs) { 377 if (!isa<Instruction>(I)) { 378 LocalValueMap[I] = Reg; 379 return; 380 } 381 382 Register &AssignedReg = FuncInfo.ValueMap[I]; 383 if (!AssignedReg) 384 // Use the new register. 385 AssignedReg = Reg; 386 else if (Reg != AssignedReg) { 387 // Arrange for uses of AssignedReg to be replaced by uses of Reg. 388 for (unsigned i = 0; i < NumRegs; i++) { 389 FuncInfo.RegFixups[AssignedReg + i] = Reg + i; 390 FuncInfo.RegsWithFixups.insert(Reg + i); 391 } 392 393 AssignedReg = Reg; 394 } 395 } 396 397 std::pair<Register, bool> FastISel::getRegForGEPIndex(const Value *Idx) { 398 Register IdxN = getRegForValue(Idx); 399 if (!IdxN) 400 // Unhandled operand. Halt "fast" selection and bail. 401 return std::pair<Register, bool>(Register(), false); 402 403 bool IdxNIsKill = hasTrivialKill(Idx); 404 405 // If the index is smaller or larger than intptr_t, truncate or extend it. 406 MVT PtrVT = TLI.getPointerTy(DL); 407 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 408 if (IdxVT.bitsLT(PtrVT)) { 409 IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN, 410 IdxNIsKill); 411 IdxNIsKill = true; 412 } else if (IdxVT.bitsGT(PtrVT)) { 413 IdxN = 414 fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill); 415 IdxNIsKill = true; 416 } 417 return std::pair<Register, bool>(IdxN, IdxNIsKill); 418 } 419 420 void FastISel::recomputeInsertPt() { 421 if (getLastLocalValue()) { 422 FuncInfo.InsertPt = getLastLocalValue(); 423 FuncInfo.MBB = FuncInfo.InsertPt->getParent(); 424 ++FuncInfo.InsertPt; 425 } else 426 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI(); 427 428 // Now skip past any EH_LABELs, which must remain at the beginning. 429 while (FuncInfo.InsertPt != FuncInfo.MBB->end() && 430 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL) 431 ++FuncInfo.InsertPt; 432 } 433 434 void FastISel::removeDeadCode(MachineBasicBlock::iterator I, 435 MachineBasicBlock::iterator E) { 436 assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 && 437 "Invalid iterator!"); 438 while (I != E) { 439 if (SavedInsertPt == I) 440 SavedInsertPt = E; 441 if (EmitStartPt == I) 442 EmitStartPt = E.isValid() ? &*E : nullptr; 443 if (LastLocalValue == I) 444 LastLocalValue = E.isValid() ? &*E : nullptr; 445 446 MachineInstr *Dead = &*I; 447 ++I; 448 Dead->eraseFromParent(); 449 ++NumFastIselDead; 450 } 451 recomputeInsertPt(); 452 } 453 454 FastISel::SavePoint FastISel::enterLocalValueArea() { 455 SavePoint OldInsertPt = FuncInfo.InsertPt; 456 recomputeInsertPt(); 457 return OldInsertPt; 458 } 459 460 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) { 461 if (FuncInfo.InsertPt != FuncInfo.MBB->begin()) 462 LastLocalValue = &*std::prev(FuncInfo.InsertPt); 463 464 // Restore the previous insert position. 465 FuncInfo.InsertPt = OldInsertPt; 466 } 467 468 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) { 469 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 470 if (VT == MVT::Other || !VT.isSimple()) 471 // Unhandled type. Halt "fast" selection and bail. 472 return false; 473 474 // We only handle legal types. For example, on x86-32 the instruction 475 // selector contains all of the 64-bit instructions from x86-64, 476 // under the assumption that i64 won't be used if the target doesn't 477 // support it. 478 if (!TLI.isTypeLegal(VT)) { 479 // MVT::i1 is special. Allow AND, OR, or XOR because they 480 // don't require additional zeroing, which makes them easy. 481 if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR || 482 ISDOpcode == ISD::XOR)) 483 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 484 else 485 return false; 486 } 487 488 // Check if the first operand is a constant, and handle it as "ri". At -O0, 489 // we don't have anything that canonicalizes operand order. 490 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0))) 491 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) { 492 Register Op1 = getRegForValue(I->getOperand(1)); 493 if (!Op1) 494 return false; 495 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 496 497 Register ResultReg = 498 fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill, 499 CI->getZExtValue(), VT.getSimpleVT()); 500 if (!ResultReg) 501 return false; 502 503 // We successfully emitted code for the given LLVM Instruction. 504 updateValueMap(I, ResultReg); 505 return true; 506 } 507 508 Register Op0 = getRegForValue(I->getOperand(0)); 509 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 510 return false; 511 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 512 513 // Check if the second operand is a constant and handle it appropriately. 514 if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 515 uint64_t Imm = CI->getSExtValue(); 516 517 // Transform "sdiv exact X, 8" -> "sra X, 3". 518 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) && 519 cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) { 520 Imm = Log2_64(Imm); 521 ISDOpcode = ISD::SRA; 522 } 523 524 // Transform "urem x, pow2" -> "and x, pow2-1". 525 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) && 526 isPowerOf2_64(Imm)) { 527 --Imm; 528 ISDOpcode = ISD::AND; 529 } 530 531 Register ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, 532 Op0IsKill, Imm, VT.getSimpleVT()); 533 if (!ResultReg) 534 return false; 535 536 // We successfully emitted code for the given LLVM Instruction. 537 updateValueMap(I, ResultReg); 538 return true; 539 } 540 541 Register Op1 = getRegForValue(I->getOperand(1)); 542 if (!Op1) // Unhandled operand. Halt "fast" selection and bail. 543 return false; 544 bool Op1IsKill = hasTrivialKill(I->getOperand(1)); 545 546 // Now we have both operands in registers. Emit the instruction. 547 Register ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 548 ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill); 549 if (!ResultReg) 550 // Target-specific code wasn't able to find a machine opcode for 551 // the given ISD opcode and type. Halt "fast" selection and bail. 552 return false; 553 554 // We successfully emitted code for the given LLVM Instruction. 555 updateValueMap(I, ResultReg); 556 return true; 557 } 558 559 bool FastISel::selectGetElementPtr(const User *I) { 560 Register N = getRegForValue(I->getOperand(0)); 561 if (!N) // Unhandled operand. Halt "fast" selection and bail. 562 return false; 563 564 // FIXME: The code below does not handle vector GEPs. Halt "fast" selection 565 // and bail. 566 if (isa<VectorType>(I->getType())) 567 return false; 568 569 bool NIsKill = hasTrivialKill(I->getOperand(0)); 570 571 // Keep a running tab of the total offset to coalesce multiple N = N + Offset 572 // into a single N = N + TotalOffset. 573 uint64_t TotalOffs = 0; 574 // FIXME: What's a good SWAG number for MaxOffs? 575 uint64_t MaxOffs = 2048; 576 MVT VT = TLI.getPointerTy(DL); 577 for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I); 578 GTI != E; ++GTI) { 579 const Value *Idx = GTI.getOperand(); 580 if (StructType *StTy = GTI.getStructTypeOrNull()) { 581 uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue(); 582 if (Field) { 583 // N = N + Offset 584 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field); 585 if (TotalOffs >= MaxOffs) { 586 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 587 if (!N) // Unhandled operand. Halt "fast" selection and bail. 588 return false; 589 NIsKill = true; 590 TotalOffs = 0; 591 } 592 } 593 } else { 594 Type *Ty = GTI.getIndexedType(); 595 596 // If this is a constant subscript, handle it quickly. 597 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 598 if (CI->isZero()) 599 continue; 600 // N = N + Offset 601 uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue(); 602 TotalOffs += DL.getTypeAllocSize(Ty) * IdxN; 603 if (TotalOffs >= MaxOffs) { 604 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 605 if (!N) // Unhandled operand. Halt "fast" selection and bail. 606 return false; 607 NIsKill = true; 608 TotalOffs = 0; 609 } 610 continue; 611 } 612 if (TotalOffs) { 613 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 614 if (!N) // Unhandled operand. Halt "fast" selection and bail. 615 return false; 616 NIsKill = true; 617 TotalOffs = 0; 618 } 619 620 // N = N + Idx * ElementSize; 621 uint64_t ElementSize = DL.getTypeAllocSize(Ty); 622 std::pair<Register, bool> Pair = getRegForGEPIndex(Idx); 623 Register IdxN = Pair.first; 624 bool IdxNIsKill = Pair.second; 625 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 626 return false; 627 628 if (ElementSize != 1) { 629 IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT); 630 if (!IdxN) // Unhandled operand. Halt "fast" selection and bail. 631 return false; 632 IdxNIsKill = true; 633 } 634 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill); 635 if (!N) // Unhandled operand. Halt "fast" selection and bail. 636 return false; 637 } 638 } 639 if (TotalOffs) { 640 N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT); 641 if (!N) // Unhandled operand. Halt "fast" selection and bail. 642 return false; 643 } 644 645 // We successfully emitted code for the given LLVM Instruction. 646 updateValueMap(I, N); 647 return true; 648 } 649 650 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops, 651 const CallInst *CI, unsigned StartIdx) { 652 for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) { 653 Value *Val = CI->getArgOperand(i); 654 // Check for constants and encode them with a StackMaps::ConstantOp prefix. 655 if (const auto *C = dyn_cast<ConstantInt>(Val)) { 656 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 657 Ops.push_back(MachineOperand::CreateImm(C->getSExtValue())); 658 } else if (isa<ConstantPointerNull>(Val)) { 659 Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp)); 660 Ops.push_back(MachineOperand::CreateImm(0)); 661 } else if (auto *AI = dyn_cast<AllocaInst>(Val)) { 662 // Values coming from a stack location also require a special encoding, 663 // but that is added later on by the target specific frame index 664 // elimination implementation. 665 auto SI = FuncInfo.StaticAllocaMap.find(AI); 666 if (SI != FuncInfo.StaticAllocaMap.end()) 667 Ops.push_back(MachineOperand::CreateFI(SI->second)); 668 else 669 return false; 670 } else { 671 Register Reg = getRegForValue(Val); 672 if (!Reg) 673 return false; 674 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 675 } 676 } 677 return true; 678 } 679 680 bool FastISel::selectStackmap(const CallInst *I) { 681 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>, 682 // [live variables...]) 683 assert(I->getCalledFunction()->getReturnType()->isVoidTy() && 684 "Stackmap cannot return a value."); 685 686 // The stackmap intrinsic only records the live variables (the arguments 687 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 688 // intrinsic, this won't be lowered to a function call. This means we don't 689 // have to worry about calling conventions and target-specific lowering code. 690 // Instead we perform the call lowering right here. 691 // 692 // CALLSEQ_START(0, 0...) 693 // STACKMAP(id, nbytes, ...) 694 // CALLSEQ_END(0, 0) 695 // 696 SmallVector<MachineOperand, 32> Ops; 697 698 // Add the <id> and <numBytes> constants. 699 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 700 "Expected a constant integer."); 701 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 702 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 703 704 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 705 "Expected a constant integer."); 706 const auto *NumBytes = 707 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 708 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 709 710 // Push live variables for the stack map (skipping the first two arguments 711 // <id> and <numBytes>). 712 if (!addStackMapLiveVars(Ops, I, 2)) 713 return false; 714 715 // We are not adding any register mask info here, because the stackmap doesn't 716 // clobber anything. 717 718 // Add scratch registers as implicit def and early clobber. 719 CallingConv::ID CC = I->getCallingConv(); 720 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 721 for (unsigned i = 0; ScratchRegs[i]; ++i) 722 Ops.push_back(MachineOperand::CreateReg( 723 ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false, 724 /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true)); 725 726 // Issue CALLSEQ_START 727 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 728 auto Builder = 729 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)); 730 const MCInstrDesc &MCID = Builder.getInstr()->getDesc(); 731 for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I) 732 Builder.addImm(0); 733 734 // Issue STACKMAP. 735 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 736 TII.get(TargetOpcode::STACKMAP)); 737 for (auto const &MO : Ops) 738 MIB.add(MO); 739 740 // Issue CALLSEQ_END 741 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 743 .addImm(0) 744 .addImm(0); 745 746 // Inform the Frame Information that we have a stackmap in this function. 747 FuncInfo.MF->getFrameInfo().setHasStackMap(); 748 749 return true; 750 } 751 752 /// Lower an argument list according to the target calling convention. 753 /// 754 /// This is a helper for lowering intrinsics that follow a target calling 755 /// convention or require stack pointer adjustment. Only a subset of the 756 /// intrinsic's operands need to participate in the calling convention. 757 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx, 758 unsigned NumArgs, const Value *Callee, 759 bool ForceRetVoidTy, CallLoweringInfo &CLI) { 760 ArgListTy Args; 761 Args.reserve(NumArgs); 762 763 // Populate the argument list. 764 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) { 765 Value *V = CI->getOperand(ArgI); 766 767 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 768 769 ArgListEntry Entry; 770 Entry.Val = V; 771 Entry.Ty = V->getType(); 772 Entry.setAttributes(CI, ArgI); 773 Args.push_back(Entry); 774 } 775 776 Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext()) 777 : CI->getType(); 778 CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs); 779 780 return lowerCallTo(CLI); 781 } 782 783 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee( 784 const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy, 785 StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) { 786 SmallString<32> MangledName; 787 Mangler::getNameWithPrefix(MangledName, Target, DL); 788 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 789 return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs); 790 } 791 792 bool FastISel::selectPatchpoint(const CallInst *I) { 793 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 794 // i32 <numBytes>, 795 // i8* <target>, 796 // i32 <numArgs>, 797 // [Args...], 798 // [live variables...]) 799 CallingConv::ID CC = I->getCallingConv(); 800 bool IsAnyRegCC = CC == CallingConv::AnyReg; 801 bool HasDef = !I->getType()->isVoidTy(); 802 Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts(); 803 804 // Get the real number of arguments participating in the call <numArgs> 805 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) && 806 "Expected a constant integer."); 807 const auto *NumArgsVal = 808 cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)); 809 unsigned NumArgs = NumArgsVal->getZExtValue(); 810 811 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 812 // This includes all meta-operands up to but not including CC. 813 unsigned NumMetaOpers = PatchPointOpers::CCPos; 814 assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs && 815 "Not enough arguments provided to the patchpoint intrinsic"); 816 817 // For AnyRegCC the arguments are lowered later on manually. 818 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 819 CallLoweringInfo CLI; 820 CLI.setIsPatchPoint(); 821 if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI)) 822 return false; 823 824 assert(CLI.Call && "No call instruction specified."); 825 826 SmallVector<MachineOperand, 32> Ops; 827 828 // Add an explicit result reg if we use the anyreg calling convention. 829 if (IsAnyRegCC && HasDef) { 830 assert(CLI.NumResultRegs == 0 && "Unexpected result register."); 831 CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64)); 832 CLI.NumResultRegs = 1; 833 Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true)); 834 } 835 836 // Add the <id> and <numBytes> constants. 837 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) && 838 "Expected a constant integer."); 839 const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)); 840 Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue())); 841 842 assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) && 843 "Expected a constant integer."); 844 const auto *NumBytes = 845 cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)); 846 Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue())); 847 848 // Add the call target. 849 if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) { 850 uint64_t CalleeConstAddr = 851 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 852 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 853 } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) { 854 if (C->getOpcode() == Instruction::IntToPtr) { 855 uint64_t CalleeConstAddr = 856 cast<ConstantInt>(C->getOperand(0))->getZExtValue(); 857 Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr)); 858 } else 859 llvm_unreachable("Unsupported ConstantExpr."); 860 } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) { 861 Ops.push_back(MachineOperand::CreateGA(GV, 0)); 862 } else if (isa<ConstantPointerNull>(Callee)) 863 Ops.push_back(MachineOperand::CreateImm(0)); 864 else 865 llvm_unreachable("Unsupported callee address."); 866 867 // Adjust <numArgs> to account for any arguments that have been passed on 868 // the stack instead. 869 unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size(); 870 Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs)); 871 872 // Add the calling convention 873 Ops.push_back(MachineOperand::CreateImm((unsigned)CC)); 874 875 // Add the arguments we omitted previously. The register allocator should 876 // place these in any free register. 877 if (IsAnyRegCC) { 878 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) { 879 Register Reg = getRegForValue(I->getArgOperand(i)); 880 if (!Reg) 881 return false; 882 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 883 } 884 } 885 886 // Push the arguments from the call instruction. 887 for (auto Reg : CLI.OutRegs) 888 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false)); 889 890 // Push live variables for the stack map. 891 if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs)) 892 return false; 893 894 // Push the register mask info. 895 Ops.push_back(MachineOperand::CreateRegMask( 896 TRI.getCallPreservedMask(*FuncInfo.MF, CC))); 897 898 // Add scratch registers as implicit def and early clobber. 899 const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC); 900 for (unsigned i = 0; ScratchRegs[i]; ++i) 901 Ops.push_back(MachineOperand::CreateReg( 902 ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false, 903 /*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true)); 904 905 // Add implicit defs (return values). 906 for (auto Reg : CLI.InRegs) 907 Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true, 908 /*isImp=*/true)); 909 910 // Insert the patchpoint instruction before the call generated by the target. 911 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc, 912 TII.get(TargetOpcode::PATCHPOINT)); 913 914 for (auto &MO : Ops) 915 MIB.add(MO); 916 917 MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI); 918 919 // Delete the original call instruction. 920 CLI.Call->eraseFromParent(); 921 922 // Inform the Frame Information that we have a patchpoint in this function. 923 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 924 925 if (CLI.NumResultRegs) 926 updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs); 927 return true; 928 } 929 930 bool FastISel::selectXRayCustomEvent(const CallInst *I) { 931 const auto &Triple = TM.getTargetTriple(); 932 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 933 return true; // don't do anything to this instruction. 934 SmallVector<MachineOperand, 8> Ops; 935 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 936 /*isDef=*/false)); 937 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 938 /*isDef=*/false)); 939 MachineInstrBuilder MIB = 940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 941 TII.get(TargetOpcode::PATCHABLE_EVENT_CALL)); 942 for (auto &MO : Ops) 943 MIB.add(MO); 944 945 // Insert the Patchable Event Call instruction, that gets lowered properly. 946 return true; 947 } 948 949 bool FastISel::selectXRayTypedEvent(const CallInst *I) { 950 const auto &Triple = TM.getTargetTriple(); 951 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 952 return true; // don't do anything to this instruction. 953 SmallVector<MachineOperand, 8> Ops; 954 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)), 955 /*isDef=*/false)); 956 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)), 957 /*isDef=*/false)); 958 Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)), 959 /*isDef=*/false)); 960 MachineInstrBuilder MIB = 961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 962 TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL)); 963 for (auto &MO : Ops) 964 MIB.add(MO); 965 966 // Insert the Patchable Typed Event Call instruction, that gets lowered properly. 967 return true; 968 } 969 970 /// Returns an AttributeList representing the attributes applied to the return 971 /// value of the given call. 972 static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) { 973 SmallVector<Attribute::AttrKind, 2> Attrs; 974 if (CLI.RetSExt) 975 Attrs.push_back(Attribute::SExt); 976 if (CLI.RetZExt) 977 Attrs.push_back(Attribute::ZExt); 978 if (CLI.IsInReg) 979 Attrs.push_back(Attribute::InReg); 980 981 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 982 Attrs); 983 } 984 985 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName, 986 unsigned NumArgs) { 987 MCContext &Ctx = MF->getContext(); 988 SmallString<32> MangledName; 989 Mangler::getNameWithPrefix(MangledName, SymName, DL); 990 MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName); 991 return lowerCallTo(CI, Sym, NumArgs); 992 } 993 994 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol, 995 unsigned NumArgs) { 996 FunctionType *FTy = CI->getFunctionType(); 997 Type *RetTy = CI->getType(); 998 999 ArgListTy Args; 1000 Args.reserve(NumArgs); 1001 1002 // Populate the argument list. 1003 // Attributes for args start at offset 1, after the return attribute. 1004 for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) { 1005 Value *V = CI->getOperand(ArgI); 1006 1007 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 1008 1009 ArgListEntry Entry; 1010 Entry.Val = V; 1011 Entry.Ty = V->getType(); 1012 Entry.setAttributes(CI, ArgI); 1013 Args.push_back(Entry); 1014 } 1015 TLI.markLibCallAttributes(MF, CI->getCallingConv(), Args); 1016 1017 CallLoweringInfo CLI; 1018 CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), *CI, NumArgs); 1019 1020 return lowerCallTo(CLI); 1021 } 1022 1023 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) { 1024 // Handle the incoming return values from the call. 1025 CLI.clearIns(); 1026 SmallVector<EVT, 4> RetTys; 1027 ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys); 1028 1029 SmallVector<ISD::OutputArg, 4> Outs; 1030 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL); 1031 1032 bool CanLowerReturn = TLI.CanLowerReturn( 1033 CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 1034 1035 // FIXME: sret demotion isn't supported yet - bail out. 1036 if (!CanLowerReturn) 1037 return false; 1038 1039 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 1040 EVT VT = RetTys[I]; 1041 MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT); 1042 unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT); 1043 for (unsigned i = 0; i != NumRegs; ++i) { 1044 ISD::InputArg MyFlags; 1045 MyFlags.VT = RegisterVT; 1046 MyFlags.ArgVT = VT; 1047 MyFlags.Used = CLI.IsReturnValueUsed; 1048 if (CLI.RetSExt) 1049 MyFlags.Flags.setSExt(); 1050 if (CLI.RetZExt) 1051 MyFlags.Flags.setZExt(); 1052 if (CLI.IsInReg) 1053 MyFlags.Flags.setInReg(); 1054 CLI.Ins.push_back(MyFlags); 1055 } 1056 } 1057 1058 // Handle all of the outgoing arguments. 1059 CLI.clearOuts(); 1060 for (auto &Arg : CLI.getArgs()) { 1061 Type *FinalType = Arg.Ty; 1062 if (Arg.IsByVal) 1063 FinalType = cast<PointerType>(Arg.Ty)->getElementType(); 1064 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1065 FinalType, CLI.CallConv, CLI.IsVarArg); 1066 1067 ISD::ArgFlagsTy Flags; 1068 if (Arg.IsZExt) 1069 Flags.setZExt(); 1070 if (Arg.IsSExt) 1071 Flags.setSExt(); 1072 if (Arg.IsInReg) 1073 Flags.setInReg(); 1074 if (Arg.IsSRet) 1075 Flags.setSRet(); 1076 if (Arg.IsSwiftSelf) 1077 Flags.setSwiftSelf(); 1078 if (Arg.IsSwiftError) 1079 Flags.setSwiftError(); 1080 if (Arg.IsCFGuardTarget) 1081 Flags.setCFGuardTarget(); 1082 if (Arg.IsByVal) 1083 Flags.setByVal(); 1084 if (Arg.IsInAlloca) { 1085 Flags.setInAlloca(); 1086 // Set the byval flag for CCAssignFn callbacks that don't know about 1087 // inalloca. This way we can know how many bytes we should've allocated 1088 // and how many bytes a callee cleanup function will pop. If we port 1089 // inalloca to more targets, we'll have to add custom inalloca handling in 1090 // the various CC lowering callbacks. 1091 Flags.setByVal(); 1092 } 1093 if (Arg.IsPreallocated) { 1094 Flags.setPreallocated(); 1095 // Set the byval flag for CCAssignFn callbacks that don't know about 1096 // preallocated. This way we can know how many bytes we should've 1097 // allocated and how many bytes a callee cleanup function will pop. If we 1098 // port preallocated to more targets, we'll have to add custom 1099 // preallocated handling in the various CC lowering callbacks. 1100 Flags.setByVal(); 1101 } 1102 if (Arg.IsByVal || Arg.IsInAlloca || Arg.IsPreallocated) { 1103 PointerType *Ty = cast<PointerType>(Arg.Ty); 1104 Type *ElementTy = Ty->getElementType(); 1105 unsigned FrameSize = 1106 DL.getTypeAllocSize(Arg.ByValType ? Arg.ByValType : ElementTy); 1107 1108 // For ByVal, alignment should come from FE. BE will guess if this info 1109 // is not there, but there are cases it cannot get right. 1110 MaybeAlign FrameAlign = Arg.Alignment; 1111 if (!FrameAlign) 1112 FrameAlign = Align(TLI.getByValTypeAlignment(ElementTy, DL)); 1113 Flags.setByValSize(FrameSize); 1114 Flags.setByValAlign(*FrameAlign); 1115 } 1116 if (Arg.IsNest) 1117 Flags.setNest(); 1118 if (NeedsRegBlock) 1119 Flags.setInConsecutiveRegs(); 1120 Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty)); 1121 1122 CLI.OutVals.push_back(Arg.Val); 1123 CLI.OutFlags.push_back(Flags); 1124 } 1125 1126 if (!fastLowerCall(CLI)) 1127 return false; 1128 1129 // Set all unused physreg defs as dead. 1130 assert(CLI.Call && "No call instruction specified."); 1131 CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI); 1132 1133 if (CLI.NumResultRegs && CLI.CB) 1134 updateValueMap(CLI.CB, CLI.ResultReg, CLI.NumResultRegs); 1135 1136 // Set labels for heapallocsite call. 1137 if (CLI.CB) 1138 if (MDNode *MD = CLI.CB->getMetadata("heapallocsite")) 1139 CLI.Call->setHeapAllocMarker(*MF, MD); 1140 1141 return true; 1142 } 1143 1144 bool FastISel::lowerCall(const CallInst *CI) { 1145 FunctionType *FuncTy = CI->getFunctionType(); 1146 Type *RetTy = CI->getType(); 1147 1148 ArgListTy Args; 1149 ArgListEntry Entry; 1150 Args.reserve(CI->arg_size()); 1151 1152 for (auto i = CI->arg_begin(), e = CI->arg_end(); i != e; ++i) { 1153 Value *V = *i; 1154 1155 // Skip empty types 1156 if (V->getType()->isEmptyTy()) 1157 continue; 1158 1159 Entry.Val = V; 1160 Entry.Ty = V->getType(); 1161 1162 // Skip the first return-type Attribute to get to params. 1163 Entry.setAttributes(CI, i - CI->arg_begin()); 1164 Args.push_back(Entry); 1165 } 1166 1167 // Check if target-independent constraints permit a tail call here. 1168 // Target-dependent constraints are checked within fastLowerCall. 1169 bool IsTailCall = CI->isTailCall(); 1170 if (IsTailCall && !isInTailCallPosition(*CI, TM)) 1171 IsTailCall = false; 1172 if (IsTailCall && MF->getFunction() 1173 .getFnAttribute("disable-tail-calls") 1174 .getValueAsString() == "true") 1175 IsTailCall = false; 1176 1177 CallLoweringInfo CLI; 1178 CLI.setCallee(RetTy, FuncTy, CI->getCalledOperand(), std::move(Args), *CI) 1179 .setTailCall(IsTailCall); 1180 1181 return lowerCallTo(CLI); 1182 } 1183 1184 bool FastISel::selectCall(const User *I) { 1185 const CallInst *Call = cast<CallInst>(I); 1186 1187 // Handle simple inline asms. 1188 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledOperand())) { 1189 // Don't attempt to handle constraints. 1190 if (!IA->getConstraintString().empty()) 1191 return false; 1192 1193 unsigned ExtraInfo = 0; 1194 if (IA->hasSideEffects()) 1195 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 1196 if (IA->isAlignStack()) 1197 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 1198 if (Call->isConvergent()) 1199 ExtraInfo |= InlineAsm::Extra_IsConvergent; 1200 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 1201 1202 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1203 TII.get(TargetOpcode::INLINEASM)); 1204 MIB.addExternalSymbol(IA->getAsmString().c_str()); 1205 MIB.addImm(ExtraInfo); 1206 1207 const MDNode *SrcLoc = Call->getMetadata("srcloc"); 1208 if (SrcLoc) 1209 MIB.addMetadata(SrcLoc); 1210 1211 return true; 1212 } 1213 1214 // Handle intrinsic function calls. 1215 if (const auto *II = dyn_cast<IntrinsicInst>(Call)) 1216 return selectIntrinsicCall(II); 1217 1218 return lowerCall(Call); 1219 } 1220 1221 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) { 1222 switch (II->getIntrinsicID()) { 1223 default: 1224 break; 1225 // At -O0 we don't care about the lifetime intrinsics. 1226 case Intrinsic::lifetime_start: 1227 case Intrinsic::lifetime_end: 1228 // The donothing intrinsic does, well, nothing. 1229 case Intrinsic::donothing: 1230 // Neither does the sideeffect intrinsic. 1231 case Intrinsic::sideeffect: 1232 // Neither does the assume intrinsic; it's also OK not to codegen its operand. 1233 case Intrinsic::assume: 1234 return true; 1235 case Intrinsic::dbg_declare: { 1236 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 1237 assert(DI->getVariable() && "Missing variable"); 1238 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1239 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1240 << " (!hasDebugInfo)\n"); 1241 return true; 1242 } 1243 1244 const Value *Address = DI->getAddress(); 1245 if (!Address || isa<UndefValue>(Address)) { 1246 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1247 << " (bad/undef address)\n"); 1248 return true; 1249 } 1250 1251 // Byval arguments with frame indices were already handled after argument 1252 // lowering and before isel. 1253 const auto *Arg = 1254 dyn_cast<Argument>(Address->stripInBoundsConstantOffsets()); 1255 if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX) 1256 return true; 1257 1258 Optional<MachineOperand> Op; 1259 if (Register Reg = lookUpRegForValue(Address)) 1260 Op = MachineOperand::CreateReg(Reg, false); 1261 1262 // If we have a VLA that has a "use" in a metadata node that's then used 1263 // here but it has no other uses, then we have a problem. E.g., 1264 // 1265 // int foo (const int *x) { 1266 // char a[*x]; 1267 // return 0; 1268 // } 1269 // 1270 // If we assign 'a' a vreg and fast isel later on has to use the selection 1271 // DAG isel, it will want to copy the value to the vreg. However, there are 1272 // no uses, which goes counter to what selection DAG isel expects. 1273 if (!Op && !Address->use_empty() && isa<Instruction>(Address) && 1274 (!isa<AllocaInst>(Address) || 1275 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address)))) 1276 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address), 1277 false); 1278 1279 if (Op) { 1280 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1281 "Expected inlined-at fields to agree"); 1282 // A dbg.declare describes the address of a source variable, so lower it 1283 // into an indirect DBG_VALUE. 1284 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1285 TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true, 1286 *Op, DI->getVariable(), DI->getExpression()); 1287 } else { 1288 // We can't yet handle anything else here because it would require 1289 // generating code, thus altering codegen because of debug info. 1290 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI 1291 << " (no materialized reg for address)\n"); 1292 } 1293 return true; 1294 } 1295 case Intrinsic::dbg_value: { 1296 // This form of DBG_VALUE is target-independent. 1297 const DbgValueInst *DI = cast<DbgValueInst>(II); 1298 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1299 const Value *V = DI->getValue(); 1300 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 1301 "Expected inlined-at fields to agree"); 1302 if (!V || isa<UndefValue>(V)) { 1303 // Currently the optimizer can produce this; insert an undef to 1304 // help debugging. 1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U, 1306 DI->getVariable(), DI->getExpression()); 1307 } else if (const auto *CI = dyn_cast<ConstantInt>(V)) { 1308 if (CI->getBitWidth() > 64) 1309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1310 .addCImm(CI) 1311 .addImm(0U) 1312 .addMetadata(DI->getVariable()) 1313 .addMetadata(DI->getExpression()); 1314 else 1315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1316 .addImm(CI->getZExtValue()) 1317 .addImm(0U) 1318 .addMetadata(DI->getVariable()) 1319 .addMetadata(DI->getExpression()); 1320 } else if (const auto *CF = dyn_cast<ConstantFP>(V)) { 1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1322 .addFPImm(CF) 1323 .addImm(0U) 1324 .addMetadata(DI->getVariable()) 1325 .addMetadata(DI->getExpression()); 1326 } else if (Register Reg = lookUpRegForValue(V)) { 1327 // FIXME: This does not handle register-indirect values at offset 0. 1328 bool IsIndirect = false; 1329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg, 1330 DI->getVariable(), DI->getExpression()); 1331 } else { 1332 // We don't know how to handle other cases, so we drop. 1333 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1334 } 1335 return true; 1336 } 1337 case Intrinsic::dbg_label: { 1338 const DbgLabelInst *DI = cast<DbgLabelInst>(II); 1339 assert(DI->getLabel() && "Missing label"); 1340 if (!FuncInfo.MF->getMMI().hasDebugInfo()) { 1341 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1342 return true; 1343 } 1344 1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1346 TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel()); 1347 return true; 1348 } 1349 case Intrinsic::objectsize: 1350 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 1351 1352 case Intrinsic::is_constant: 1353 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 1354 1355 case Intrinsic::launder_invariant_group: 1356 case Intrinsic::strip_invariant_group: 1357 case Intrinsic::expect: { 1358 Register ResultReg = getRegForValue(II->getArgOperand(0)); 1359 if (!ResultReg) 1360 return false; 1361 updateValueMap(II, ResultReg); 1362 return true; 1363 } 1364 case Intrinsic::experimental_stackmap: 1365 return selectStackmap(II); 1366 case Intrinsic::experimental_patchpoint_void: 1367 case Intrinsic::experimental_patchpoint_i64: 1368 return selectPatchpoint(II); 1369 1370 case Intrinsic::xray_customevent: 1371 return selectXRayCustomEvent(II); 1372 case Intrinsic::xray_typedevent: 1373 return selectXRayTypedEvent(II); 1374 } 1375 1376 return fastLowerIntrinsicCall(II); 1377 } 1378 1379 bool FastISel::selectCast(const User *I, unsigned Opcode) { 1380 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1381 EVT DstVT = TLI.getValueType(DL, I->getType()); 1382 1383 if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other || 1384 !DstVT.isSimple()) 1385 // Unhandled type. Halt "fast" selection and bail. 1386 return false; 1387 1388 // Check if the destination type is legal. 1389 if (!TLI.isTypeLegal(DstVT)) 1390 return false; 1391 1392 // Check if the source operand is legal. 1393 if (!TLI.isTypeLegal(SrcVT)) 1394 return false; 1395 1396 Register InputReg = getRegForValue(I->getOperand(0)); 1397 if (!InputReg) 1398 // Unhandled operand. Halt "fast" selection and bail. 1399 return false; 1400 1401 bool InputRegIsKill = hasTrivialKill(I->getOperand(0)); 1402 1403 Register ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), 1404 Opcode, InputReg, InputRegIsKill); 1405 if (!ResultReg) 1406 return false; 1407 1408 updateValueMap(I, ResultReg); 1409 return true; 1410 } 1411 1412 bool FastISel::selectBitCast(const User *I) { 1413 // If the bitcast doesn't change the type, just use the operand value. 1414 if (I->getType() == I->getOperand(0)->getType()) { 1415 Register Reg = getRegForValue(I->getOperand(0)); 1416 if (!Reg) 1417 return false; 1418 updateValueMap(I, Reg); 1419 return true; 1420 } 1421 1422 // Bitcasts of other values become reg-reg copies or BITCAST operators. 1423 EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1424 EVT DstEVT = TLI.getValueType(DL, I->getType()); 1425 if (SrcEVT == MVT::Other || DstEVT == MVT::Other || 1426 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT)) 1427 // Unhandled type. Halt "fast" selection and bail. 1428 return false; 1429 1430 MVT SrcVT = SrcEVT.getSimpleVT(); 1431 MVT DstVT = DstEVT.getSimpleVT(); 1432 Register Op0 = getRegForValue(I->getOperand(0)); 1433 if (!Op0) // Unhandled operand. Halt "fast" selection and bail. 1434 return false; 1435 bool Op0IsKill = hasTrivialKill(I->getOperand(0)); 1436 1437 // First, try to perform the bitcast by inserting a reg-reg copy. 1438 Register ResultReg; 1439 if (SrcVT == DstVT) { 1440 const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT); 1441 const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT); 1442 // Don't attempt a cross-class copy. It will likely fail. 1443 if (SrcClass == DstClass) { 1444 ResultReg = createResultReg(DstClass); 1445 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1446 TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0); 1447 } 1448 } 1449 1450 // If the reg-reg copy failed, select a BITCAST opcode. 1451 if (!ResultReg) 1452 ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill); 1453 1454 if (!ResultReg) 1455 return false; 1456 1457 updateValueMap(I, ResultReg); 1458 return true; 1459 } 1460 1461 bool FastISel::selectFreeze(const User *I) { 1462 Register Reg = getRegForValue(I->getOperand(0)); 1463 if (!Reg) 1464 // Unhandled operand. 1465 return false; 1466 1467 EVT ETy = TLI.getValueType(DL, I->getOperand(0)->getType()); 1468 if (ETy == MVT::Other || !TLI.isTypeLegal(ETy)) 1469 // Unhandled type, bail out. 1470 return false; 1471 1472 MVT Ty = ETy.getSimpleVT(); 1473 const TargetRegisterClass *TyRegClass = TLI.getRegClassFor(Ty); 1474 Register ResultReg = createResultReg(TyRegClass); 1475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1476 TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg); 1477 1478 updateValueMap(I, ResultReg); 1479 return true; 1480 } 1481 1482 // Remove local value instructions starting from the instruction after 1483 // SavedLastLocalValue to the current function insert point. 1484 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue) 1485 { 1486 MachineInstr *CurLastLocalValue = getLastLocalValue(); 1487 if (CurLastLocalValue != SavedLastLocalValue) { 1488 // Find the first local value instruction to be deleted. 1489 // This is the instruction after SavedLastLocalValue if it is non-NULL. 1490 // Otherwise it's the first instruction in the block. 1491 MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue); 1492 if (SavedLastLocalValue) 1493 ++FirstDeadInst; 1494 else 1495 FirstDeadInst = FuncInfo.MBB->getFirstNonPHI(); 1496 setLastLocalValue(SavedLastLocalValue); 1497 removeDeadCode(FirstDeadInst, FuncInfo.InsertPt); 1498 } 1499 } 1500 1501 bool FastISel::selectInstruction(const Instruction *I) { 1502 // Flush the local value map before starting each instruction. 1503 // This improves locality and debugging, and can reduce spills. 1504 // Reuse of values across IR instructions is relatively uncommon. 1505 flushLocalValueMap(); 1506 1507 MachineInstr *SavedLastLocalValue = getLastLocalValue(); 1508 // Just before the terminator instruction, insert instructions to 1509 // feed PHI nodes in successor blocks. 1510 if (I->isTerminator()) { 1511 if (!handlePHINodesInSuccessorBlocks(I->getParent())) { 1512 // PHI node handling may have generated local value instructions, 1513 // even though it failed to handle all PHI nodes. 1514 // We remove these instructions because SelectionDAGISel will generate 1515 // them again. 1516 removeDeadLocalValueCode(SavedLastLocalValue); 1517 return false; 1518 } 1519 } 1520 1521 // FastISel does not handle any operand bundles except OB_funclet. 1522 if (auto *Call = dyn_cast<CallBase>(I)) 1523 for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i) 1524 if (Call->getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet) 1525 return false; 1526 1527 DbgLoc = I->getDebugLoc(); 1528 1529 SavedInsertPt = FuncInfo.InsertPt; 1530 1531 if (const auto *Call = dyn_cast<CallInst>(I)) { 1532 const Function *F = Call->getCalledFunction(); 1533 LibFunc Func; 1534 1535 // As a special case, don't handle calls to builtin library functions that 1536 // may be translated directly to target instructions. 1537 if (F && !F->hasLocalLinkage() && F->hasName() && 1538 LibInfo->getLibFunc(F->getName(), Func) && 1539 LibInfo->hasOptimizedCodeGen(Func)) 1540 return false; 1541 1542 // Don't handle Intrinsic::trap if a trap function is specified. 1543 if (F && F->getIntrinsicID() == Intrinsic::trap && 1544 Call->hasFnAttr("trap-func-name")) 1545 return false; 1546 } 1547 1548 // First, try doing target-independent selection. 1549 if (!SkipTargetIndependentISel) { 1550 if (selectOperator(I, I->getOpcode())) { 1551 ++NumFastIselSuccessIndependent; 1552 DbgLoc = DebugLoc(); 1553 return true; 1554 } 1555 // Remove dead code. 1556 recomputeInsertPt(); 1557 if (SavedInsertPt != FuncInfo.InsertPt) 1558 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1559 SavedInsertPt = FuncInfo.InsertPt; 1560 } 1561 // Next, try calling the target to attempt to handle the instruction. 1562 if (fastSelectInstruction(I)) { 1563 ++NumFastIselSuccessTarget; 1564 DbgLoc = DebugLoc(); 1565 return true; 1566 } 1567 // Remove dead code. 1568 recomputeInsertPt(); 1569 if (SavedInsertPt != FuncInfo.InsertPt) 1570 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt); 1571 1572 DbgLoc = DebugLoc(); 1573 // Undo phi node updates, because they will be added again by SelectionDAG. 1574 if (I->isTerminator()) { 1575 // PHI node handling may have generated local value instructions. 1576 // We remove them because SelectionDAGISel will generate them again. 1577 removeDeadLocalValueCode(SavedLastLocalValue); 1578 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 1579 } 1580 return false; 1581 } 1582 1583 /// Emit an unconditional branch to the given block, unless it is the immediate 1584 /// (fall-through) successor, and update the CFG. 1585 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, 1586 const DebugLoc &DbgLoc) { 1587 if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 && 1588 FuncInfo.MBB->isLayoutSuccessor(MSucc)) { 1589 // For more accurate line information if this is the only non-debug 1590 // instruction in the block then emit it, otherwise we have the 1591 // unconditional fall-through case, which needs no instructions. 1592 } else { 1593 // The unconditional branch case. 1594 TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr, 1595 SmallVector<MachineOperand, 0>(), DbgLoc); 1596 } 1597 if (FuncInfo.BPI) { 1598 auto BranchProbability = FuncInfo.BPI->getEdgeProbability( 1599 FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock()); 1600 FuncInfo.MBB->addSuccessor(MSucc, BranchProbability); 1601 } else 1602 FuncInfo.MBB->addSuccessorWithoutProb(MSucc); 1603 } 1604 1605 void FastISel::finishCondBranch(const BasicBlock *BranchBB, 1606 MachineBasicBlock *TrueMBB, 1607 MachineBasicBlock *FalseMBB) { 1608 // Add TrueMBB as successor unless it is equal to the FalseMBB: This can 1609 // happen in degenerate IR and MachineIR forbids to have a block twice in the 1610 // successor/predecessor lists. 1611 if (TrueMBB != FalseMBB) { 1612 if (FuncInfo.BPI) { 1613 auto BranchProbability = 1614 FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock()); 1615 FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability); 1616 } else 1617 FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB); 1618 } 1619 1620 fastEmitBranch(FalseMBB, DbgLoc); 1621 } 1622 1623 /// Emit an FNeg operation. 1624 bool FastISel::selectFNeg(const User *I, const Value *In) { 1625 Register OpReg = getRegForValue(In); 1626 if (!OpReg) 1627 return false; 1628 bool OpRegIsKill = hasTrivialKill(In); 1629 1630 // If the target has ISD::FNEG, use it. 1631 EVT VT = TLI.getValueType(DL, I->getType()); 1632 Register ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG, 1633 OpReg, OpRegIsKill); 1634 if (ResultReg) { 1635 updateValueMap(I, ResultReg); 1636 return true; 1637 } 1638 1639 // Bitcast the value to integer, twiddle the sign bit with xor, 1640 // and then bitcast it back to floating-point. 1641 if (VT.getSizeInBits() > 64) 1642 return false; 1643 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 1644 if (!TLI.isTypeLegal(IntVT)) 1645 return false; 1646 1647 Register IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 1648 ISD::BITCAST, OpReg, OpRegIsKill); 1649 if (!IntReg) 1650 return false; 1651 1652 Register IntResultReg = fastEmit_ri_( 1653 IntVT.getSimpleVT(), ISD::XOR, IntReg, /*Op0IsKill=*/true, 1654 UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT()); 1655 if (!IntResultReg) 1656 return false; 1657 1658 ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST, 1659 IntResultReg, /*Op0IsKill=*/true); 1660 if (!ResultReg) 1661 return false; 1662 1663 updateValueMap(I, ResultReg); 1664 return true; 1665 } 1666 1667 bool FastISel::selectExtractValue(const User *U) { 1668 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U); 1669 if (!EVI) 1670 return false; 1671 1672 // Make sure we only try to handle extracts with a legal result. But also 1673 // allow i1 because it's easy. 1674 EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true); 1675 if (!RealVT.isSimple()) 1676 return false; 1677 MVT VT = RealVT.getSimpleVT(); 1678 if (!TLI.isTypeLegal(VT) && VT != MVT::i1) 1679 return false; 1680 1681 const Value *Op0 = EVI->getOperand(0); 1682 Type *AggTy = Op0->getType(); 1683 1684 // Get the base result register. 1685 unsigned ResultReg; 1686 DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(Op0); 1687 if (I != FuncInfo.ValueMap.end()) 1688 ResultReg = I->second; 1689 else if (isa<Instruction>(Op0)) 1690 ResultReg = FuncInfo.InitializeRegForValue(Op0); 1691 else 1692 return false; // fast-isel can't handle aggregate constants at the moment 1693 1694 // Get the actual result register, which is an offset from the base register. 1695 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices()); 1696 1697 SmallVector<EVT, 4> AggValueVTs; 1698 ComputeValueVTs(TLI, DL, AggTy, AggValueVTs); 1699 1700 for (unsigned i = 0; i < VTIndex; i++) 1701 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]); 1702 1703 updateValueMap(EVI, ResultReg); 1704 return true; 1705 } 1706 1707 bool FastISel::selectOperator(const User *I, unsigned Opcode) { 1708 switch (Opcode) { 1709 case Instruction::Add: 1710 return selectBinaryOp(I, ISD::ADD); 1711 case Instruction::FAdd: 1712 return selectBinaryOp(I, ISD::FADD); 1713 case Instruction::Sub: 1714 return selectBinaryOp(I, ISD::SUB); 1715 case Instruction::FSub: 1716 return selectBinaryOp(I, ISD::FSUB); 1717 case Instruction::Mul: 1718 return selectBinaryOp(I, ISD::MUL); 1719 case Instruction::FMul: 1720 return selectBinaryOp(I, ISD::FMUL); 1721 case Instruction::SDiv: 1722 return selectBinaryOp(I, ISD::SDIV); 1723 case Instruction::UDiv: 1724 return selectBinaryOp(I, ISD::UDIV); 1725 case Instruction::FDiv: 1726 return selectBinaryOp(I, ISD::FDIV); 1727 case Instruction::SRem: 1728 return selectBinaryOp(I, ISD::SREM); 1729 case Instruction::URem: 1730 return selectBinaryOp(I, ISD::UREM); 1731 case Instruction::FRem: 1732 return selectBinaryOp(I, ISD::FREM); 1733 case Instruction::Shl: 1734 return selectBinaryOp(I, ISD::SHL); 1735 case Instruction::LShr: 1736 return selectBinaryOp(I, ISD::SRL); 1737 case Instruction::AShr: 1738 return selectBinaryOp(I, ISD::SRA); 1739 case Instruction::And: 1740 return selectBinaryOp(I, ISD::AND); 1741 case Instruction::Or: 1742 return selectBinaryOp(I, ISD::OR); 1743 case Instruction::Xor: 1744 return selectBinaryOp(I, ISD::XOR); 1745 1746 case Instruction::FNeg: 1747 return selectFNeg(I, I->getOperand(0)); 1748 1749 case Instruction::GetElementPtr: 1750 return selectGetElementPtr(I); 1751 1752 case Instruction::Br: { 1753 const BranchInst *BI = cast<BranchInst>(I); 1754 1755 if (BI->isUnconditional()) { 1756 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 1757 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc]; 1758 fastEmitBranch(MSucc, BI->getDebugLoc()); 1759 return true; 1760 } 1761 1762 // Conditional branches are not handed yet. 1763 // Halt "fast" selection and bail. 1764 return false; 1765 } 1766 1767 case Instruction::Unreachable: 1768 if (TM.Options.TrapUnreachable) 1769 return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0; 1770 else 1771 return true; 1772 1773 case Instruction::Alloca: 1774 // FunctionLowering has the static-sized case covered. 1775 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I))) 1776 return true; 1777 1778 // Dynamic-sized alloca is not handled yet. 1779 return false; 1780 1781 case Instruction::Call: 1782 // On AIX, call lowering uses the DAG-ISEL path currently so that the 1783 // callee of the direct function call instruction will be mapped to the 1784 // symbol for the function's entry point, which is distinct from the 1785 // function descriptor symbol. The latter is the symbol whose XCOFF symbol 1786 // name is the C-linkage name of the source level function. 1787 if (TM.getTargetTriple().isOSAIX()) 1788 return false; 1789 return selectCall(I); 1790 1791 case Instruction::BitCast: 1792 return selectBitCast(I); 1793 1794 case Instruction::FPToSI: 1795 return selectCast(I, ISD::FP_TO_SINT); 1796 case Instruction::ZExt: 1797 return selectCast(I, ISD::ZERO_EXTEND); 1798 case Instruction::SExt: 1799 return selectCast(I, ISD::SIGN_EXTEND); 1800 case Instruction::Trunc: 1801 return selectCast(I, ISD::TRUNCATE); 1802 case Instruction::SIToFP: 1803 return selectCast(I, ISD::SINT_TO_FP); 1804 1805 case Instruction::IntToPtr: // Deliberate fall-through. 1806 case Instruction::PtrToInt: { 1807 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 1808 EVT DstVT = TLI.getValueType(DL, I->getType()); 1809 if (DstVT.bitsGT(SrcVT)) 1810 return selectCast(I, ISD::ZERO_EXTEND); 1811 if (DstVT.bitsLT(SrcVT)) 1812 return selectCast(I, ISD::TRUNCATE); 1813 Register Reg = getRegForValue(I->getOperand(0)); 1814 if (!Reg) 1815 return false; 1816 updateValueMap(I, Reg); 1817 return true; 1818 } 1819 1820 case Instruction::ExtractValue: 1821 return selectExtractValue(I); 1822 1823 case Instruction::Freeze: 1824 return selectFreeze(I); 1825 1826 case Instruction::PHI: 1827 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 1828 1829 default: 1830 // Unhandled instruction. Halt "fast" selection and bail. 1831 return false; 1832 } 1833 } 1834 1835 FastISel::FastISel(FunctionLoweringInfo &FuncInfo, 1836 const TargetLibraryInfo *LibInfo, 1837 bool SkipTargetIndependentISel) 1838 : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()), 1839 MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()), 1840 TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()), 1841 TII(*MF->getSubtarget().getInstrInfo()), 1842 TLI(*MF->getSubtarget().getTargetLowering()), 1843 TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo), 1844 SkipTargetIndependentISel(SkipTargetIndependentISel), 1845 LastLocalValue(nullptr), EmitStartPt(nullptr) {} 1846 1847 FastISel::~FastISel() = default; 1848 1849 bool FastISel::fastLowerArguments() { return false; } 1850 1851 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; } 1852 1853 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) { 1854 return false; 1855 } 1856 1857 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; } 1858 1859 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/, 1860 bool /*Op0IsKill*/) { 1861 return 0; 1862 } 1863 1864 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/, 1865 bool /*Op0IsKill*/, unsigned /*Op1*/, 1866 bool /*Op1IsKill*/) { 1867 return 0; 1868 } 1869 1870 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 1871 return 0; 1872 } 1873 1874 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned, 1875 const ConstantFP * /*FPImm*/) { 1876 return 0; 1877 } 1878 1879 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/, 1880 bool /*Op0IsKill*/, uint64_t /*Imm*/) { 1881 return 0; 1882 } 1883 1884 /// This method is a wrapper of fastEmit_ri. It first tries to emit an 1885 /// instruction with an immediate operand using fastEmit_ri. 1886 /// If that fails, it materializes the immediate into a register and try 1887 /// fastEmit_rr instead. 1888 Register FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, 1889 bool Op0IsKill, uint64_t Imm, MVT ImmType) { 1890 // If this is a multiply by a power of two, emit this as a shift left. 1891 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) { 1892 Opcode = ISD::SHL; 1893 Imm = Log2_64(Imm); 1894 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) { 1895 // div x, 8 -> srl x, 3 1896 Opcode = ISD::SRL; 1897 Imm = Log2_64(Imm); 1898 } 1899 1900 // Horrible hack (to be removed), check to make sure shift amounts are 1901 // in-range. 1902 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) && 1903 Imm >= VT.getSizeInBits()) 1904 return 0; 1905 1906 // First check if immediate type is legal. If not, we can't use the ri form. 1907 Register ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm); 1908 if (ResultReg) 1909 return ResultReg; 1910 Register MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 1911 bool IsImmKill = true; 1912 if (!MaterialReg) { 1913 // This is a bit ugly/slow, but failing here means falling out of 1914 // fast-isel, which would be very slow. 1915 IntegerType *ITy = 1916 IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits()); 1917 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm)); 1918 if (!MaterialReg) 1919 return 0; 1920 // FIXME: If the materialized register here has no uses yet then this 1921 // will be the first use and we should be able to mark it as killed. 1922 // However, the local value area for materialising constant expressions 1923 // grows down, not up, which means that any constant expressions we generate 1924 // later which also use 'Imm' could be after this instruction and therefore 1925 // after this kill. 1926 IsImmKill = false; 1927 } 1928 return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill); 1929 } 1930 1931 Register FastISel::createResultReg(const TargetRegisterClass *RC) { 1932 return MRI.createVirtualRegister(RC); 1933 } 1934 1935 Register FastISel::constrainOperandRegClass(const MCInstrDesc &II, Register Op, 1936 unsigned OpNum) { 1937 if (Op.isVirtual()) { 1938 const TargetRegisterClass *RegClass = 1939 TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF); 1940 if (!MRI.constrainRegClass(Op, RegClass)) { 1941 // If it's not legal to COPY between the register classes, something 1942 // has gone very wrong before we got here. 1943 Register NewOp = createResultReg(RegClass); 1944 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1945 TII.get(TargetOpcode::COPY), NewOp).addReg(Op); 1946 return NewOp; 1947 } 1948 } 1949 return Op; 1950 } 1951 1952 Register FastISel::fastEmitInst_(unsigned MachineInstOpcode, 1953 const TargetRegisterClass *RC) { 1954 Register ResultReg = createResultReg(RC); 1955 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1956 1957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg); 1958 return ResultReg; 1959 } 1960 1961 Register FastISel::fastEmitInst_r(unsigned MachineInstOpcode, 1962 const TargetRegisterClass *RC, unsigned Op0, 1963 bool Op0IsKill) { 1964 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1965 1966 Register ResultReg = createResultReg(RC); 1967 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1968 1969 if (II.getNumDefs() >= 1) 1970 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1971 .addReg(Op0, getKillRegState(Op0IsKill)); 1972 else { 1973 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1974 .addReg(Op0, getKillRegState(Op0IsKill)); 1975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1976 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 1977 } 1978 1979 return ResultReg; 1980 } 1981 1982 Register FastISel::fastEmitInst_rr(unsigned MachineInstOpcode, 1983 const TargetRegisterClass *RC, unsigned Op0, 1984 bool Op0IsKill, unsigned Op1, 1985 bool Op1IsKill) { 1986 const MCInstrDesc &II = TII.get(MachineInstOpcode); 1987 1988 Register ResultReg = createResultReg(RC); 1989 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 1990 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 1991 1992 if (II.getNumDefs() >= 1) 1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 1994 .addReg(Op0, getKillRegState(Op0IsKill)) 1995 .addReg(Op1, getKillRegState(Op1IsKill)); 1996 else { 1997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1998 .addReg(Op0, getKillRegState(Op0IsKill)) 1999 .addReg(Op1, getKillRegState(Op1IsKill)); 2000 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2001 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2002 } 2003 return ResultReg; 2004 } 2005 2006 Register FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode, 2007 const TargetRegisterClass *RC, unsigned Op0, 2008 bool Op0IsKill, unsigned Op1, 2009 bool Op1IsKill, unsigned Op2, 2010 bool Op2IsKill) { 2011 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2012 2013 Register ResultReg = createResultReg(RC); 2014 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2015 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2016 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2); 2017 2018 if (II.getNumDefs() >= 1) 2019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2020 .addReg(Op0, getKillRegState(Op0IsKill)) 2021 .addReg(Op1, getKillRegState(Op1IsKill)) 2022 .addReg(Op2, getKillRegState(Op2IsKill)); 2023 else { 2024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2025 .addReg(Op0, getKillRegState(Op0IsKill)) 2026 .addReg(Op1, getKillRegState(Op1IsKill)) 2027 .addReg(Op2, getKillRegState(Op2IsKill)); 2028 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2029 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2030 } 2031 return ResultReg; 2032 } 2033 2034 Register FastISel::fastEmitInst_ri(unsigned MachineInstOpcode, 2035 const TargetRegisterClass *RC, unsigned Op0, 2036 bool Op0IsKill, uint64_t Imm) { 2037 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2038 2039 Register ResultReg = createResultReg(RC); 2040 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2041 2042 if (II.getNumDefs() >= 1) 2043 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2044 .addReg(Op0, getKillRegState(Op0IsKill)) 2045 .addImm(Imm); 2046 else { 2047 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2048 .addReg(Op0, getKillRegState(Op0IsKill)) 2049 .addImm(Imm); 2050 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2051 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2052 } 2053 return ResultReg; 2054 } 2055 2056 Register FastISel::fastEmitInst_rii(unsigned MachineInstOpcode, 2057 const TargetRegisterClass *RC, unsigned Op0, 2058 bool Op0IsKill, uint64_t Imm1, 2059 uint64_t Imm2) { 2060 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2061 2062 Register ResultReg = createResultReg(RC); 2063 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2064 2065 if (II.getNumDefs() >= 1) 2066 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2067 .addReg(Op0, getKillRegState(Op0IsKill)) 2068 .addImm(Imm1) 2069 .addImm(Imm2); 2070 else { 2071 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2072 .addReg(Op0, getKillRegState(Op0IsKill)) 2073 .addImm(Imm1) 2074 .addImm(Imm2); 2075 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2076 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2077 } 2078 return ResultReg; 2079 } 2080 2081 Register FastISel::fastEmitInst_f(unsigned MachineInstOpcode, 2082 const TargetRegisterClass *RC, 2083 const ConstantFP *FPImm) { 2084 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2085 2086 Register ResultReg = createResultReg(RC); 2087 2088 if (II.getNumDefs() >= 1) 2089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2090 .addFPImm(FPImm); 2091 else { 2092 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2093 .addFPImm(FPImm); 2094 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2095 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2096 } 2097 return ResultReg; 2098 } 2099 2100 Register FastISel::fastEmitInst_rri(unsigned MachineInstOpcode, 2101 const TargetRegisterClass *RC, unsigned Op0, 2102 bool Op0IsKill, unsigned Op1, 2103 bool Op1IsKill, uint64_t Imm) { 2104 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2105 2106 Register ResultReg = createResultReg(RC); 2107 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs()); 2108 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1); 2109 2110 if (II.getNumDefs() >= 1) 2111 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2112 .addReg(Op0, getKillRegState(Op0IsKill)) 2113 .addReg(Op1, getKillRegState(Op1IsKill)) 2114 .addImm(Imm); 2115 else { 2116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 2117 .addReg(Op0, getKillRegState(Op0IsKill)) 2118 .addReg(Op1, getKillRegState(Op1IsKill)) 2119 .addImm(Imm); 2120 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2121 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2122 } 2123 return ResultReg; 2124 } 2125 2126 Register FastISel::fastEmitInst_i(unsigned MachineInstOpcode, 2127 const TargetRegisterClass *RC, uint64_t Imm) { 2128 Register ResultReg = createResultReg(RC); 2129 const MCInstrDesc &II = TII.get(MachineInstOpcode); 2130 2131 if (II.getNumDefs() >= 1) 2132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg) 2133 .addImm(Imm); 2134 else { 2135 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm); 2136 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2137 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]); 2138 } 2139 return ResultReg; 2140 } 2141 2142 Register FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, 2143 bool Op0IsKill, uint32_t Idx) { 2144 Register ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 2145 assert(Register::isVirtualRegister(Op0) && 2146 "Cannot yet extract from physregs"); 2147 const TargetRegisterClass *RC = MRI.getRegClass(Op0); 2148 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx)); 2149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 2150 ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx); 2151 return ResultReg; 2152 } 2153 2154 /// Emit MachineInstrs to compute the value of Op with all but the least 2155 /// significant bit set to zero. 2156 Register FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) { 2157 return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1); 2158 } 2159 2160 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 2161 /// Emit code to ensure constants are copied into registers when needed. 2162 /// Remember the virtual registers that need to be added to the Machine PHI 2163 /// nodes as input. We cannot just directly add them, because expansion 2164 /// might result in multiple MBB's for one BB. As such, the start of the 2165 /// BB might correspond to a different MBB than the end. 2166 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 2167 const Instruction *TI = LLVMBB->getTerminator(); 2168 2169 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 2170 FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size(); 2171 2172 // Check successor nodes' PHI nodes that expect a constant to be available 2173 // from this block. 2174 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 2175 const BasicBlock *SuccBB = TI->getSuccessor(succ); 2176 if (!isa<PHINode>(SuccBB->begin())) 2177 continue; 2178 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 2179 2180 // If this terminator has multiple identical successors (common for 2181 // switches), only handle each succ once. 2182 if (!SuccsHandled.insert(SuccMBB).second) 2183 continue; 2184 2185 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 2186 2187 // At this point we know that there is a 1-1 correspondence between LLVM PHI 2188 // nodes and Machine PHI nodes, but the incoming operands have not been 2189 // emitted yet. 2190 for (const PHINode &PN : SuccBB->phis()) { 2191 // Ignore dead phi's. 2192 if (PN.use_empty()) 2193 continue; 2194 2195 // Only handle legal types. Two interesting things to note here. First, 2196 // by bailing out early, we may leave behind some dead instructions, 2197 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 2198 // own moves. Second, this check is necessary because FastISel doesn't 2199 // use CreateRegs to create registers, so it always creates 2200 // exactly one register for each non-void instruction. 2201 EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true); 2202 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 2203 // Handle integer promotions, though, because they're common and easy. 2204 if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) { 2205 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2206 return false; 2207 } 2208 } 2209 2210 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 2211 2212 // Set the DebugLoc for the copy. Prefer the location of the operand 2213 // if there is one; use the location of the PHI otherwise. 2214 DbgLoc = PN.getDebugLoc(); 2215 if (const auto *Inst = dyn_cast<Instruction>(PHIOp)) 2216 DbgLoc = Inst->getDebugLoc(); 2217 2218 Register Reg = getRegForValue(PHIOp); 2219 if (!Reg) { 2220 FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate); 2221 return false; 2222 } 2223 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg)); 2224 DbgLoc = DebugLoc(); 2225 } 2226 } 2227 2228 return true; 2229 } 2230 2231 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) { 2232 assert(LI->hasOneUse() && 2233 "tryToFoldLoad expected a LoadInst with a single use"); 2234 // We know that the load has a single use, but don't know what it is. If it 2235 // isn't one of the folded instructions, then we can't succeed here. Handle 2236 // this by scanning the single-use users of the load until we get to FoldInst. 2237 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs. 2238 2239 const Instruction *TheUser = LI->user_back(); 2240 while (TheUser != FoldInst && // Scan up until we find FoldInst. 2241 // Stay in the right block. 2242 TheUser->getParent() == FoldInst->getParent() && 2243 --MaxUsers) { // Don't scan too far. 2244 // If there are multiple or no uses of this instruction, then bail out. 2245 if (!TheUser->hasOneUse()) 2246 return false; 2247 2248 TheUser = TheUser->user_back(); 2249 } 2250 2251 // If we didn't find the fold instruction, then we failed to collapse the 2252 // sequence. 2253 if (TheUser != FoldInst) 2254 return false; 2255 2256 // Don't try to fold volatile loads. Target has to deal with alignment 2257 // constraints. 2258 if (LI->isVolatile()) 2259 return false; 2260 2261 // Figure out which vreg this is going into. If there is no assigned vreg yet 2262 // then there actually was no reference to it. Perhaps the load is referenced 2263 // by a dead instruction. 2264 Register LoadReg = getRegForValue(LI); 2265 if (!LoadReg) 2266 return false; 2267 2268 // We can't fold if this vreg has no uses or more than one use. Multiple uses 2269 // may mean that the instruction got lowered to multiple MIs, or the use of 2270 // the loaded value ended up being multiple operands of the result. 2271 if (!MRI.hasOneUse(LoadReg)) 2272 return false; 2273 2274 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg); 2275 MachineInstr *User = RI->getParent(); 2276 2277 // Set the insertion point properly. Folding the load can cause generation of 2278 // other random instructions (like sign extends) for addressing modes; make 2279 // sure they get inserted in a logical place before the new instruction. 2280 FuncInfo.InsertPt = User; 2281 FuncInfo.MBB = User->getParent(); 2282 2283 // Ask the target to try folding the load. 2284 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI); 2285 } 2286 2287 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) { 2288 // Must be an add. 2289 if (!isa<AddOperator>(Add)) 2290 return false; 2291 // Type size needs to match. 2292 if (DL.getTypeSizeInBits(GEP->getType()) != 2293 DL.getTypeSizeInBits(Add->getType())) 2294 return false; 2295 // Must be in the same basic block. 2296 if (isa<Instruction>(Add) && 2297 FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB) 2298 return false; 2299 // Must have a constant operand. 2300 return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1)); 2301 } 2302 2303 MachineMemOperand * 2304 FastISel::createMachineMemOperandFor(const Instruction *I) const { 2305 const Value *Ptr; 2306 Type *ValTy; 2307 MaybeAlign Alignment; 2308 MachineMemOperand::Flags Flags; 2309 bool IsVolatile; 2310 2311 if (const auto *LI = dyn_cast<LoadInst>(I)) { 2312 Alignment = LI->getAlign(); 2313 IsVolatile = LI->isVolatile(); 2314 Flags = MachineMemOperand::MOLoad; 2315 Ptr = LI->getPointerOperand(); 2316 ValTy = LI->getType(); 2317 } else if (const auto *SI = dyn_cast<StoreInst>(I)) { 2318 Alignment = SI->getAlign(); 2319 IsVolatile = SI->isVolatile(); 2320 Flags = MachineMemOperand::MOStore; 2321 Ptr = SI->getPointerOperand(); 2322 ValTy = SI->getValueOperand()->getType(); 2323 } else 2324 return nullptr; 2325 2326 bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal); 2327 bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load); 2328 bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable); 2329 const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range); 2330 2331 AAMDNodes AAInfo; 2332 I->getAAMetadata(AAInfo); 2333 2334 if (!Alignment) // Ensure that codegen never sees alignment 0. 2335 Alignment = DL.getABITypeAlign(ValTy); 2336 2337 unsigned Size = DL.getTypeStoreSize(ValTy); 2338 2339 if (IsVolatile) 2340 Flags |= MachineMemOperand::MOVolatile; 2341 if (IsNonTemporal) 2342 Flags |= MachineMemOperand::MONonTemporal; 2343 if (IsDereferenceable) 2344 Flags |= MachineMemOperand::MODereferenceable; 2345 if (IsInvariant) 2346 Flags |= MachineMemOperand::MOInvariant; 2347 2348 return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size, 2349 *Alignment, AAInfo, Ranges); 2350 } 2351 2352 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const { 2353 // If both operands are the same, then try to optimize or fold the cmp. 2354 CmpInst::Predicate Predicate = CI->getPredicate(); 2355 if (CI->getOperand(0) != CI->getOperand(1)) 2356 return Predicate; 2357 2358 switch (Predicate) { 2359 default: llvm_unreachable("Invalid predicate!"); 2360 case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break; 2361 case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break; 2362 case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break; 2363 case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break; 2364 case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break; 2365 case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break; 2366 case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break; 2367 case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break; 2368 case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break; 2369 case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break; 2370 case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break; 2371 case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2372 case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break; 2373 case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2374 case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break; 2375 case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break; 2376 2377 case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break; 2378 case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break; 2379 case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break; 2380 case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break; 2381 case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break; 2382 case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break; 2383 case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break; 2384 case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break; 2385 case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break; 2386 case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break; 2387 } 2388 2389 return Predicate; 2390 } 2391