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