1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==// 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 /// \file 10 /// This file implements the IRTranslator class. 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 14 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 17 #include "llvm/CodeGen/Analysis.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/TargetPassConfig.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Type.h" 28 #include "llvm/IR/Value.h" 29 #include "llvm/Target/TargetIntrinsicInfo.h" 30 #include "llvm/Target/TargetLowering.h" 31 32 #define DEBUG_TYPE "irtranslator" 33 34 using namespace llvm; 35 36 char IRTranslator::ID = 0; 37 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 38 false, false) 39 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 40 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 41 false, false) 42 43 static void reportTranslationError(const Value &V, const Twine &Message) { 44 std::string ErrStorage; 45 raw_string_ostream Err(ErrStorage); 46 Err << Message << ": " << V << '\n'; 47 report_fatal_error(Err.str()); 48 } 49 50 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) { 51 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 52 } 53 54 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 55 AU.addRequired<TargetPassConfig>(); 56 MachineFunctionPass::getAnalysisUsage(AU); 57 } 58 59 60 unsigned IRTranslator::getOrCreateVReg(const Value &Val) { 61 unsigned &ValReg = ValToVReg[&Val]; 62 // Check if this is the first time we see Val. 63 if (!ValReg) { 64 // Fill ValRegsSequence with the sequence of registers 65 // we need to concat together to produce the value. 66 assert(Val.getType()->isSized() && 67 "Don't know how to create an empty vreg"); 68 unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL}); 69 ValReg = VReg; 70 71 if (auto CV = dyn_cast<Constant>(&Val)) { 72 bool Success = translate(*CV, VReg); 73 if (!Success) { 74 if (!TPC->isGlobalISelAbortEnabled()) { 75 MF->getProperties().set( 76 MachineFunctionProperties::Property::FailedISel); 77 return VReg; 78 } 79 reportTranslationError(Val, "unable to translate constant"); 80 } 81 } 82 } 83 return ValReg; 84 } 85 86 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 87 if (FrameIndices.find(&AI) != FrameIndices.end()) 88 return FrameIndices[&AI]; 89 90 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 91 unsigned Size = 92 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 93 94 // Always allocate at least one byte. 95 Size = std::max(Size, 1u); 96 97 unsigned Alignment = AI.getAlignment(); 98 if (!Alignment) 99 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 100 101 int &FI = FrameIndices[&AI]; 102 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 103 return FI; 104 } 105 106 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 107 unsigned Alignment = 0; 108 Type *ValTy = nullptr; 109 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 110 Alignment = SI->getAlignment(); 111 ValTy = SI->getValueOperand()->getType(); 112 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 113 Alignment = LI->getAlignment(); 114 ValTy = LI->getType(); 115 } else if (!TPC->isGlobalISelAbortEnabled()) { 116 MF->getProperties().set( 117 MachineFunctionProperties::Property::FailedISel); 118 return 1; 119 } else 120 llvm_unreachable("unhandled memory instruction"); 121 122 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 123 } 124 125 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) { 126 MachineBasicBlock *&MBB = BBToMBB[&BB]; 127 if (!MBB) { 128 MBB = MF->CreateMachineBasicBlock(); 129 MF->push_back(MBB); 130 } 131 return *MBB; 132 } 133 134 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 135 MachineIRBuilder &MIRBuilder) { 136 // FIXME: handle signed/unsigned wrapping flags. 137 138 // Get or create a virtual register for each value. 139 // Unless the value is a Constant => loadimm cst? 140 // or inline constant each time? 141 // Creation of a virtual register needs to have a size. 142 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 143 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 144 unsigned Res = getOrCreateVReg(U); 145 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 146 return true; 147 } 148 149 bool IRTranslator::translateCompare(const User &U, 150 MachineIRBuilder &MIRBuilder) { 151 const CmpInst *CI = dyn_cast<CmpInst>(&U); 152 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 153 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 154 unsigned Res = getOrCreateVReg(U); 155 CmpInst::Predicate Pred = 156 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 157 cast<ConstantExpr>(U).getPredicate()); 158 159 if (CmpInst::isIntPredicate(Pred)) 160 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 161 else 162 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 163 164 return true; 165 } 166 167 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 168 const ReturnInst &RI = cast<ReturnInst>(U); 169 const Value *Ret = RI.getReturnValue(); 170 // The target may mess up with the insertion point, but 171 // this is not important as a return is the last instruction 172 // of the block anyway. 173 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret)); 174 } 175 176 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 177 const BranchInst &BrInst = cast<BranchInst>(U); 178 unsigned Succ = 0; 179 if (!BrInst.isUnconditional()) { 180 // We want a G_BRCOND to the true BB followed by an unconditional branch. 181 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 182 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 183 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt); 184 MIRBuilder.buildBrCond(Tst, TrueBB); 185 } 186 187 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 188 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt); 189 MIRBuilder.buildBr(TgtBB); 190 191 // Link successors. 192 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 193 for (const BasicBlock *Succ : BrInst.successors()) 194 CurBB.addSuccessor(&getOrCreateBB(*Succ)); 195 return true; 196 } 197 198 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 199 const LoadInst &LI = cast<LoadInst>(U); 200 201 if (!TPC->isGlobalISelAbortEnabled() && LI.isAtomic()) 202 return false; 203 204 assert(!LI.isAtomic() && "only non-atomic loads are supported at the moment"); 205 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 206 : MachineMemOperand::MONone; 207 Flags |= MachineMemOperand::MOLoad; 208 209 unsigned Res = getOrCreateVReg(LI); 210 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand()); 211 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL}; 212 MIRBuilder.buildLoad( 213 Res, Addr, 214 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()), 215 Flags, DL->getTypeStoreSize(LI.getType()), 216 getMemOpAlignment(LI))); 217 return true; 218 } 219 220 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 221 const StoreInst &SI = cast<StoreInst>(U); 222 223 if (!TPC->isGlobalISelAbortEnabled() && SI.isAtomic()) 224 return false; 225 226 assert(!SI.isAtomic() && "only non-atomic stores supported at the moment"); 227 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 228 : MachineMemOperand::MONone; 229 Flags |= MachineMemOperand::MOStore; 230 231 unsigned Val = getOrCreateVReg(*SI.getValueOperand()); 232 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand()); 233 LLT VTy{*SI.getValueOperand()->getType(), *DL}, 234 PTy{*SI.getPointerOperand()->getType(), *DL}; 235 236 MIRBuilder.buildStore( 237 Val, Addr, 238 *MF->getMachineMemOperand( 239 MachinePointerInfo(SI.getPointerOperand()), Flags, 240 DL->getTypeStoreSize(SI.getValueOperand()->getType()), 241 getMemOpAlignment(SI))); 242 return true; 243 } 244 245 bool IRTranslator::translateExtractValue(const User &U, 246 MachineIRBuilder &MIRBuilder) { 247 const Value *Src = U.getOperand(0); 248 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 249 SmallVector<Value *, 1> Indices; 250 251 // getIndexedOffsetInType is designed for GEPs, so the first index is the 252 // usual array element rather than looking into the actual aggregate. 253 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 254 255 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 256 for (auto Idx : EVI->indices()) 257 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 258 } else { 259 for (unsigned i = 1; i < U.getNumOperands(); ++i) 260 Indices.push_back(U.getOperand(i)); 261 } 262 263 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 264 265 unsigned Res = getOrCreateVReg(U); 266 MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src)); 267 268 return true; 269 } 270 271 bool IRTranslator::translateInsertValue(const User &U, 272 MachineIRBuilder &MIRBuilder) { 273 const Value *Src = U.getOperand(0); 274 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 275 SmallVector<Value *, 1> Indices; 276 277 // getIndexedOffsetInType is designed for GEPs, so the first index is the 278 // usual array element rather than looking into the actual aggregate. 279 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 280 281 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 282 for (auto Idx : IVI->indices()) 283 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 284 } else { 285 for (unsigned i = 2; i < U.getNumOperands(); ++i) 286 Indices.push_back(U.getOperand(i)); 287 } 288 289 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 290 291 unsigned Res = getOrCreateVReg(U); 292 const Value &Inserted = *U.getOperand(1); 293 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted), 294 Offset); 295 296 return true; 297 } 298 299 bool IRTranslator::translateSelect(const User &U, 300 MachineIRBuilder &MIRBuilder) { 301 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)), 302 getOrCreateVReg(*U.getOperand(1)), 303 getOrCreateVReg(*U.getOperand(2))); 304 return true; 305 } 306 307 bool IRTranslator::translateBitCast(const User &U, 308 MachineIRBuilder &MIRBuilder) { 309 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) { 310 unsigned &Reg = ValToVReg[&U]; 311 if (Reg) 312 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0))); 313 else 314 Reg = getOrCreateVReg(*U.getOperand(0)); 315 return true; 316 } 317 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 318 } 319 320 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 321 MachineIRBuilder &MIRBuilder) { 322 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 323 unsigned Res = getOrCreateVReg(U); 324 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 325 return true; 326 } 327 328 bool IRTranslator::translateGetElementPtr(const User &U, 329 MachineIRBuilder &MIRBuilder) { 330 // FIXME: support vector GEPs. 331 if (U.getType()->isVectorTy()) 332 return false; 333 334 Value &Op0 = *U.getOperand(0); 335 unsigned BaseReg = getOrCreateVReg(Op0); 336 LLT PtrTy{*Op0.getType(), *DL}; 337 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace()); 338 LLT OffsetTy = LLT::scalar(PtrSize); 339 340 int64_t Offset = 0; 341 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 342 GTI != E; ++GTI) { 343 const Value *Idx = GTI.getOperand(); 344 if (StructType *StTy = GTI.getStructTypeOrNull()) { 345 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 346 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 347 continue; 348 } else { 349 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 350 351 // If this is a scalar constant or a splat vector of constants, 352 // handle it quickly. 353 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 354 Offset += ElementSize * CI->getSExtValue(); 355 continue; 356 } 357 358 if (Offset != 0) { 359 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 360 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 361 MIRBuilder.buildConstant(OffsetReg, Offset); 362 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 363 364 BaseReg = NewBaseReg; 365 Offset = 0; 366 } 367 368 // N = N + Idx * ElementSize; 369 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy); 370 MIRBuilder.buildConstant(ElementSizeReg, ElementSize); 371 372 unsigned IdxReg = getOrCreateVReg(*Idx); 373 if (MRI->getType(IdxReg) != OffsetTy) { 374 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 375 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 376 IdxReg = NewIdxReg; 377 } 378 379 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 380 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg); 381 382 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 383 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 384 BaseReg = NewBaseReg; 385 } 386 } 387 388 if (Offset != 0) { 389 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 390 MIRBuilder.buildConstant(OffsetReg, Offset); 391 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 392 return true; 393 } 394 395 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 396 return true; 397 } 398 399 bool IRTranslator::translateMemcpy(const CallInst &CI, 400 MachineIRBuilder &MIRBuilder) { 401 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL}; 402 if (cast<PointerType>(CI.getArgOperand(0)->getType())->getAddressSpace() != 403 0 || 404 cast<PointerType>(CI.getArgOperand(1)->getType())->getAddressSpace() != 405 0 || 406 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 407 return false; 408 409 SmallVector<CallLowering::ArgInfo, 8> Args; 410 for (int i = 0; i < 3; ++i) { 411 const auto &Arg = CI.getArgOperand(i); 412 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 413 } 414 415 MachineOperand Callee = MachineOperand::CreateES("memcpy"); 416 417 return CLI->lowerCall(MIRBuilder, Callee, 418 CallLowering::ArgInfo(0, CI.getType()), Args); 419 } 420 421 void IRTranslator::getStackGuard(unsigned DstReg, 422 MachineIRBuilder &MIRBuilder) { 423 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 424 MIB.addDef(DstReg); 425 426 auto &TLI = *MF->getSubtarget().getTargetLowering(); 427 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent()); 428 if (!Global) 429 return; 430 431 MachinePointerInfo MPInfo(Global); 432 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1); 433 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 434 MachineMemOperand::MODereferenceable; 435 *MemRefs = 436 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 437 DL->getPointerABIAlignment()); 438 MIB.setMemRefs(MemRefs, MemRefs + 1); 439 } 440 441 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 442 MachineIRBuilder &MIRBuilder) { 443 unsigned Op = 0; 444 switch (ID) { 445 default: return false; 446 case Intrinsic::uadd_with_overflow: Op = TargetOpcode::G_UADDE; break; 447 case Intrinsic::sadd_with_overflow: Op = TargetOpcode::G_SADDO; break; 448 case Intrinsic::usub_with_overflow: Op = TargetOpcode::G_USUBE; break; 449 case Intrinsic::ssub_with_overflow: Op = TargetOpcode::G_SSUBO; break; 450 case Intrinsic::umul_with_overflow: Op = TargetOpcode::G_UMULO; break; 451 case Intrinsic::smul_with_overflow: Op = TargetOpcode::G_SMULO; break; 452 case Intrinsic::memcpy: 453 return translateMemcpy(CI, MIRBuilder); 454 case Intrinsic::eh_typeid_for: { 455 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 456 unsigned Reg = getOrCreateVReg(CI); 457 unsigned TypeID = MF->getTypeIDFor(GV); 458 MIRBuilder.buildConstant(Reg, TypeID); 459 return true; 460 } 461 case Intrinsic::objectsize: { 462 // If we don't know by now, we're never going to know. 463 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 464 465 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 466 return true; 467 } 468 case Intrinsic::stackguard: 469 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 470 return true; 471 case Intrinsic::stackprotector: { 472 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL}; 473 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 474 getStackGuard(GuardVal, MIRBuilder); 475 476 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 477 MIRBuilder.buildStore( 478 GuardVal, getOrCreateVReg(*Slot), 479 *MF->getMachineMemOperand( 480 MachinePointerInfo::getFixedStack(*MF, 481 getOrCreateFrameIndex(*Slot)), 482 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 483 PtrTy.getSizeInBits() / 8, 8)); 484 return true; 485 } 486 } 487 488 LLT Ty{*CI.getOperand(0)->getType(), *DL}; 489 LLT s1 = LLT::scalar(1); 490 unsigned Width = Ty.getSizeInBits(); 491 unsigned Res = MRI->createGenericVirtualRegister(Ty); 492 unsigned Overflow = MRI->createGenericVirtualRegister(s1); 493 auto MIB = MIRBuilder.buildInstr(Op) 494 .addDef(Res) 495 .addDef(Overflow) 496 .addUse(getOrCreateVReg(*CI.getOperand(0))) 497 .addUse(getOrCreateVReg(*CI.getOperand(1))); 498 499 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) { 500 unsigned Zero = MRI->createGenericVirtualRegister(s1); 501 EntryBuilder.buildConstant(Zero, 0); 502 MIB.addUse(Zero); 503 } 504 505 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width); 506 return true; 507 } 508 509 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 510 const CallInst &CI = cast<CallInst>(U); 511 auto TII = MF->getTarget().getIntrinsicInfo(); 512 const Function *F = CI.getCalledFunction(); 513 514 if (!F || !F->isIntrinsic()) { 515 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 516 SmallVector<unsigned, 8> Args; 517 for (auto &Arg: CI.arg_operands()) 518 Args.push_back(getOrCreateVReg(*Arg)); 519 520 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() { 521 return getOrCreateVReg(*CI.getCalledValue()); 522 }); 523 } 524 525 Intrinsic::ID ID = F->getIntrinsicID(); 526 if (TII && ID == Intrinsic::not_intrinsic) 527 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 528 529 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 530 531 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 532 return true; 533 534 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 535 MachineInstrBuilder MIB = 536 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 537 538 for (auto &Arg : CI.arg_operands()) { 539 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) 540 MIB.addImm(CI->getSExtValue()); 541 else 542 MIB.addUse(getOrCreateVReg(*Arg)); 543 } 544 return true; 545 } 546 547 bool IRTranslator::translateInvoke(const User &U, 548 MachineIRBuilder &MIRBuilder) { 549 const InvokeInst &I = cast<InvokeInst>(U); 550 MCContext &Context = MF->getContext(); 551 552 const BasicBlock *ReturnBB = I.getSuccessor(0); 553 const BasicBlock *EHPadBB = I.getSuccessor(1); 554 555 const Value *Callee(I.getCalledValue()); 556 const Function *Fn = dyn_cast<Function>(Callee); 557 if (isa<InlineAsm>(Callee)) 558 return false; 559 560 // FIXME: support invoking patchpoint and statepoint intrinsics. 561 if (Fn && Fn->isIntrinsic()) 562 return false; 563 564 // FIXME: support whatever these are. 565 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 566 return false; 567 568 // FIXME: support Windows exception handling. 569 if (!isa<LandingPadInst>(EHPadBB->front())) 570 return false; 571 572 573 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 574 // the region covered by the try. 575 MCSymbol *BeginSymbol = Context.createTempSymbol(); 576 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 577 578 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I); 579 SmallVector<CallLowering::ArgInfo, 8> Args; 580 for (auto &Arg: I.arg_operands()) 581 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 582 583 if (!CLI->lowerCall(MIRBuilder, MachineOperand::CreateGA(Fn, 0), 584 CallLowering::ArgInfo(Res, I.getType()), Args)) 585 return false; 586 587 MCSymbol *EndSymbol = Context.createTempSymbol(); 588 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 589 590 // FIXME: track probabilities. 591 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB), 592 &ReturnMBB = getOrCreateBB(*ReturnBB); 593 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 594 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 595 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 596 597 return true; 598 } 599 600 bool IRTranslator::translateLandingPad(const User &U, 601 MachineIRBuilder &MIRBuilder) { 602 const LandingPadInst &LP = cast<LandingPadInst>(U); 603 604 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 605 addLandingPadInfo(LP, MBB); 606 607 MBB.setIsEHPad(); 608 609 // If there aren't registers to copy the values into (e.g., during SjLj 610 // exceptions), then don't bother. 611 auto &TLI = *MF->getSubtarget().getTargetLowering(); 612 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn(); 613 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 614 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 615 return true; 616 617 // If landingpad's return type is token type, we don't create DAG nodes 618 // for its exception pointer and selector value. The extraction of exception 619 // pointer or selector value from token type landingpads is not currently 620 // supported. 621 if (LP.getType()->isTokenTy()) 622 return true; 623 624 // Add a label to mark the beginning of the landing pad. Deletion of the 625 // landing pad can thus be detected via the MachineModuleInfo. 626 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 627 .addSym(MF->addLandingPad(&MBB)); 628 629 // Mark exception register as live in. 630 SmallVector<unsigned, 2> Regs; 631 SmallVector<uint64_t, 2> Offsets; 632 LLT p0 = LLT::pointer(0, DL->getPointerSizeInBits()); 633 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) { 634 unsigned VReg = MRI->createGenericVirtualRegister(p0); 635 MIRBuilder.buildCopy(VReg, Reg); 636 Regs.push_back(VReg); 637 Offsets.push_back(0); 638 } 639 640 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) { 641 unsigned VReg = MRI->createGenericVirtualRegister(p0); 642 MIRBuilder.buildCopy(VReg, Reg); 643 Regs.push_back(VReg); 644 Offsets.push_back(p0.getSizeInBits()); 645 } 646 647 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets); 648 return true; 649 } 650 651 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI, 652 MachineIRBuilder &MIRBuilder) { 653 if (!TPC->isGlobalISelAbortEnabled() && !AI.isStaticAlloca()) 654 return false; 655 656 assert(AI.isStaticAlloca() && "only handle static allocas now"); 657 unsigned Res = getOrCreateVReg(AI); 658 int FI = getOrCreateFrameIndex(AI); 659 MIRBuilder.buildFrameIndex(Res, FI); 660 return true; 661 } 662 663 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 664 const PHINode &PI = cast<PHINode>(U); 665 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI); 666 MIB.addDef(getOrCreateVReg(PI)); 667 668 PendingPHIs.emplace_back(&PI, MIB.getInstr()); 669 return true; 670 } 671 672 void IRTranslator::finishPendingPhis() { 673 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) { 674 const PHINode *PI = Phi.first; 675 MachineInstrBuilder MIB(*MF, Phi.second); 676 677 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 678 // won't create extra control flow here, otherwise we need to find the 679 // dominating predecessor here (or perhaps force the weirder IRTranslators 680 // to provide a simple boundary). 681 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 682 assert(BBToMBB[PI->getIncomingBlock(i)]->isSuccessor(MIB->getParent()) && 683 "I appear to have misunderstood Machine PHIs"); 684 MIB.addUse(getOrCreateVReg(*PI->getIncomingValue(i))); 685 MIB.addMBB(BBToMBB[PI->getIncomingBlock(i)]); 686 } 687 } 688 } 689 690 bool IRTranslator::translate(const Instruction &Inst) { 691 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 692 switch(Inst.getOpcode()) { 693 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 694 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 695 #include "llvm/IR/Instruction.def" 696 default: 697 if (!TPC->isGlobalISelAbortEnabled()) 698 return false; 699 llvm_unreachable("unknown opcode"); 700 } 701 } 702 703 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 704 if (auto CI = dyn_cast<ConstantInt>(&C)) 705 EntryBuilder.buildConstant(Reg, *CI); 706 else if (auto CF = dyn_cast<ConstantFP>(&C)) 707 EntryBuilder.buildFConstant(Reg, *CF); 708 else if (isa<UndefValue>(C)) 709 EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg); 710 else if (isa<ConstantPointerNull>(C)) 711 EntryBuilder.buildConstant(Reg, 0); 712 else if (auto GV = dyn_cast<GlobalValue>(&C)) 713 EntryBuilder.buildGlobalValue(Reg, GV); 714 else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 715 switch(CE->getOpcode()) { 716 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 717 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 718 #include "llvm/IR/Instruction.def" 719 default: 720 if (!TPC->isGlobalISelAbortEnabled()) 721 return false; 722 llvm_unreachable("unknown opcode"); 723 } 724 } else if (!TPC->isGlobalISelAbortEnabled()) 725 return false; 726 else 727 llvm_unreachable("unhandled constant kind"); 728 729 return true; 730 } 731 732 void IRTranslator::finalizeFunction() { 733 // Release the memory used by the different maps we 734 // needed during the translation. 735 PendingPHIs.clear(); 736 ValToVReg.clear(); 737 FrameIndices.clear(); 738 Constants.clear(); 739 } 740 741 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 742 MF = &CurMF; 743 const Function &F = *MF->getFunction(); 744 if (F.empty()) 745 return false; 746 CLI = MF->getSubtarget().getCallLowering(); 747 CurBuilder.setMF(*MF); 748 EntryBuilder.setMF(*MF); 749 MRI = &MF->getRegInfo(); 750 DL = &F.getParent()->getDataLayout(); 751 TPC = &getAnalysis<TargetPassConfig>(); 752 753 assert(PendingPHIs.empty() && "stale PHIs"); 754 755 // Setup a separate basic-block for the arguments and constants, falling 756 // through to the IR-level Function's entry block. 757 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 758 MF->push_back(EntryBB); 759 EntryBB->addSuccessor(&getOrCreateBB(F.front())); 760 EntryBuilder.setMBB(*EntryBB); 761 762 // Lower the actual args into this basic block. 763 SmallVector<unsigned, 8> VRegArgs; 764 for (const Argument &Arg: F.args()) 765 VRegArgs.push_back(getOrCreateVReg(Arg)); 766 bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs); 767 if (!Succeeded) { 768 if (!TPC->isGlobalISelAbortEnabled()) { 769 MF->getProperties().set( 770 MachineFunctionProperties::Property::FailedISel); 771 finalizeFunction(); 772 return false; 773 } 774 report_fatal_error("Unable to lower arguments"); 775 } 776 777 // And translate the function! 778 for (const BasicBlock &BB: F) { 779 MachineBasicBlock &MBB = getOrCreateBB(BB); 780 // Set the insertion point of all the following translations to 781 // the end of this basic block. 782 CurBuilder.setMBB(MBB); 783 784 for (const Instruction &Inst: BB) { 785 Succeeded &= translate(Inst); 786 if (!Succeeded) { 787 if (TPC->isGlobalISelAbortEnabled()) 788 reportTranslationError(Inst, "unable to translate instruction"); 789 MF->getProperties().set( 790 MachineFunctionProperties::Property::FailedISel); 791 break; 792 } 793 } 794 } 795 796 if (Succeeded) { 797 finishPendingPhis(); 798 799 // Now that the MachineFrameInfo has been configured, no further changes to 800 // the reserved registers are possible. 801 MRI->freezeReservedRegs(*MF); 802 } 803 804 finalizeFunction(); 805 806 return false; 807 } 808