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/ScopeExit.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 19 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 20 #include "llvm/CodeGen/Analysis.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineFrameInfo.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetPassConfig.h" 26 #include "llvm/IR/Constant.h" 27 #include "llvm/IR/DebugInfo.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/IR/Value.h" 33 #include "llvm/Target/TargetFrameLowering.h" 34 #include "llvm/Target/TargetIntrinsicInfo.h" 35 #include "llvm/Target/TargetLowering.h" 36 37 #define DEBUG_TYPE "irtranslator" 38 39 using namespace llvm; 40 41 char IRTranslator::ID = 0; 42 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 43 false, false) 44 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 45 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 46 false, false) 47 48 static void reportTranslationError(MachineFunction &MF, 49 const TargetPassConfig &TPC, 50 OptimizationRemarkEmitter &ORE, 51 OptimizationRemarkMissed &R) { 52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 53 54 // Print the function name explicitly if we don't have a debug location (which 55 // makes the diagnostic less useful) or if we're going to emit a raw error. 56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 57 R << (" (in function: " + MF.getName() + ")").str(); 58 59 if (TPC.isGlobalISelAbortEnabled()) 60 report_fatal_error(R.getMsg()); 61 else 62 ORE.emit(R); 63 } 64 65 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) { 66 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 67 } 68 69 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 70 AU.addRequired<TargetPassConfig>(); 71 MachineFunctionPass::getAnalysisUsage(AU); 72 } 73 74 75 unsigned IRTranslator::getOrCreateVReg(const Value &Val) { 76 unsigned &ValReg = ValToVReg[&Val]; 77 78 if (ValReg) 79 return ValReg; 80 81 // Fill ValRegsSequence with the sequence of registers 82 // we need to concat together to produce the value. 83 assert(Val.getType()->isSized() && 84 "Don't know how to create an empty vreg"); 85 unsigned VReg = 86 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL)); 87 ValReg = VReg; 88 89 if (auto CV = dyn_cast<Constant>(&Val)) { 90 bool Success = translate(*CV, VReg); 91 if (!Success) { 92 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 93 MF->getFunction()->getSubprogram(), 94 &MF->getFunction()->getEntryBlock()); 95 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 96 reportTranslationError(*MF, *TPC, *ORE, R); 97 return VReg; 98 } 99 } 100 101 return VReg; 102 } 103 104 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 105 if (FrameIndices.find(&AI) != FrameIndices.end()) 106 return FrameIndices[&AI]; 107 108 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 109 unsigned Size = 110 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 111 112 // Always allocate at least one byte. 113 Size = std::max(Size, 1u); 114 115 unsigned Alignment = AI.getAlignment(); 116 if (!Alignment) 117 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 118 119 int &FI = FrameIndices[&AI]; 120 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 121 return FI; 122 } 123 124 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 125 unsigned Alignment = 0; 126 Type *ValTy = nullptr; 127 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 128 Alignment = SI->getAlignment(); 129 ValTy = SI->getValueOperand()->getType(); 130 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 131 Alignment = LI->getAlignment(); 132 ValTy = LI->getType(); 133 } else { 134 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 135 R << "unable to translate memop: " << ore::NV("Opcode", &I); 136 reportTranslationError(*MF, *TPC, *ORE, R); 137 return 1; 138 } 139 140 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 141 } 142 143 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 144 MachineBasicBlock *&MBB = BBToMBB[&BB]; 145 assert(MBB && "BasicBlock was not encountered before"); 146 return *MBB; 147 } 148 149 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 150 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 151 MachinePreds[Edge].push_back(NewPred); 152 } 153 154 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 155 MachineIRBuilder &MIRBuilder) { 156 // FIXME: handle signed/unsigned wrapping flags. 157 158 // Get or create a virtual register for each value. 159 // Unless the value is a Constant => loadimm cst? 160 // or inline constant each time? 161 // Creation of a virtual register needs to have a size. 162 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 163 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 164 unsigned Res = getOrCreateVReg(U); 165 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 166 return true; 167 } 168 169 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 170 // -0.0 - X --> G_FNEG 171 if (isa<Constant>(U.getOperand(0)) && 172 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 173 MIRBuilder.buildInstr(TargetOpcode::G_FNEG) 174 .addDef(getOrCreateVReg(U)) 175 .addUse(getOrCreateVReg(*U.getOperand(1))); 176 return true; 177 } 178 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 179 } 180 181 bool IRTranslator::translateCompare(const User &U, 182 MachineIRBuilder &MIRBuilder) { 183 const CmpInst *CI = dyn_cast<CmpInst>(&U); 184 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 185 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 186 unsigned Res = getOrCreateVReg(U); 187 CmpInst::Predicate Pred = 188 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 189 cast<ConstantExpr>(U).getPredicate()); 190 if (CmpInst::isIntPredicate(Pred)) 191 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 192 else if (Pred == CmpInst::FCMP_FALSE) 193 MIRBuilder.buildCopy( 194 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType()))); 195 else if (Pred == CmpInst::FCMP_TRUE) 196 MIRBuilder.buildCopy( 197 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType()))); 198 else 199 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 200 201 return true; 202 } 203 204 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 205 const ReturnInst &RI = cast<ReturnInst>(U); 206 const Value *Ret = RI.getReturnValue(); 207 // The target may mess up with the insertion point, but 208 // this is not important as a return is the last instruction 209 // of the block anyway. 210 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret)); 211 } 212 213 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 214 const BranchInst &BrInst = cast<BranchInst>(U); 215 unsigned Succ = 0; 216 if (!BrInst.isUnconditional()) { 217 // We want a G_BRCOND to the true BB followed by an unconditional branch. 218 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 219 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 220 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 221 MIRBuilder.buildBrCond(Tst, TrueBB); 222 } 223 224 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 225 MachineBasicBlock &TgtBB = getMBB(BrTgt); 226 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 227 228 // If the unconditional target is the layout successor, fallthrough. 229 if (!CurBB.isLayoutSuccessor(&TgtBB)) 230 MIRBuilder.buildBr(TgtBB); 231 232 // Link successors. 233 for (const BasicBlock *Succ : BrInst.successors()) 234 CurBB.addSuccessor(&getMBB(*Succ)); 235 return true; 236 } 237 238 bool IRTranslator::translateSwitch(const User &U, 239 MachineIRBuilder &MIRBuilder) { 240 // For now, just translate as a chain of conditional branches. 241 // FIXME: could we share most of the logic/code in 242 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel? 243 // At first sight, it seems most of the logic in there is independent of 244 // SelectionDAG-specifics and a lot of work went in to optimize switch 245 // lowering in there. 246 247 const SwitchInst &SwInst = cast<SwitchInst>(U); 248 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition()); 249 const BasicBlock *OrigBB = SwInst.getParent(); 250 251 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL); 252 for (auto &CaseIt : SwInst.cases()) { 253 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue()); 254 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1); 255 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue); 256 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 257 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor(); 258 MachineBasicBlock &TrueMBB = getMBB(*TrueBB); 259 260 MIRBuilder.buildBrCond(Tst, TrueMBB); 261 CurMBB.addSuccessor(&TrueMBB); 262 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB); 263 264 MachineBasicBlock *FalseMBB = 265 MF->CreateMachineBasicBlock(SwInst.getParent()); 266 // Insert the comparison blocks one after the other. 267 MF->insert(std::next(CurMBB.getIterator()), FalseMBB); 268 MIRBuilder.buildBr(*FalseMBB); 269 CurMBB.addSuccessor(FalseMBB); 270 271 MIRBuilder.setMBB(*FalseMBB); 272 } 273 // handle default case 274 const BasicBlock *DefaultBB = SwInst.getDefaultDest(); 275 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB); 276 MIRBuilder.buildBr(DefaultMBB); 277 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 278 CurMBB.addSuccessor(&DefaultMBB); 279 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB); 280 281 return true; 282 } 283 284 bool IRTranslator::translateIndirectBr(const User &U, 285 MachineIRBuilder &MIRBuilder) { 286 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 287 288 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress()); 289 MIRBuilder.buildBrIndirect(Tgt); 290 291 // Link successors. 292 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 293 for (const BasicBlock *Succ : BrInst.successors()) 294 CurBB.addSuccessor(&getMBB(*Succ)); 295 296 return true; 297 } 298 299 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 300 const LoadInst &LI = cast<LoadInst>(U); 301 302 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 303 : MachineMemOperand::MONone; 304 Flags |= MachineMemOperand::MOLoad; 305 306 unsigned Res = getOrCreateVReg(LI); 307 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand()); 308 309 MIRBuilder.buildLoad( 310 Res, Addr, 311 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()), 312 Flags, DL->getTypeStoreSize(LI.getType()), 313 getMemOpAlignment(LI), AAMDNodes(), nullptr, 314 LI.getSynchScope(), LI.getOrdering())); 315 return true; 316 } 317 318 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 319 const StoreInst &SI = cast<StoreInst>(U); 320 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 321 : MachineMemOperand::MONone; 322 Flags |= MachineMemOperand::MOStore; 323 324 unsigned Val = getOrCreateVReg(*SI.getValueOperand()); 325 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand()); 326 327 MIRBuilder.buildStore( 328 Val, Addr, 329 *MF->getMachineMemOperand( 330 MachinePointerInfo(SI.getPointerOperand()), Flags, 331 DL->getTypeStoreSize(SI.getValueOperand()->getType()), 332 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(), 333 SI.getOrdering())); 334 return true; 335 } 336 337 bool IRTranslator::translateExtractValue(const User &U, 338 MachineIRBuilder &MIRBuilder) { 339 const Value *Src = U.getOperand(0); 340 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 341 SmallVector<Value *, 1> Indices; 342 343 // If Src is a single element ConstantStruct, translate extractvalue 344 // to that element to avoid inserting a cast instruction. 345 if (auto CS = dyn_cast<ConstantStruct>(Src)) 346 if (CS->getNumOperands() == 1) { 347 unsigned Res = getOrCreateVReg(*CS->getOperand(0)); 348 ValToVReg[&U] = Res; 349 return true; 350 } 351 352 // getIndexedOffsetInType is designed for GEPs, so the first index is the 353 // usual array element rather than looking into the actual aggregate. 354 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 355 356 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 357 for (auto Idx : EVI->indices()) 358 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 359 } else { 360 for (unsigned i = 1; i < U.getNumOperands(); ++i) 361 Indices.push_back(U.getOperand(i)); 362 } 363 364 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 365 366 unsigned Res = getOrCreateVReg(U); 367 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset); 368 369 return true; 370 } 371 372 bool IRTranslator::translateInsertValue(const User &U, 373 MachineIRBuilder &MIRBuilder) { 374 const Value *Src = U.getOperand(0); 375 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 376 SmallVector<Value *, 1> Indices; 377 378 // getIndexedOffsetInType is designed for GEPs, so the first index is the 379 // usual array element rather than looking into the actual aggregate. 380 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 381 382 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 383 for (auto Idx : IVI->indices()) 384 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 385 } else { 386 for (unsigned i = 2; i < U.getNumOperands(); ++i) 387 Indices.push_back(U.getOperand(i)); 388 } 389 390 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 391 392 unsigned Res = getOrCreateVReg(U); 393 unsigned Inserted = getOrCreateVReg(*U.getOperand(1)); 394 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), Inserted, Offset); 395 396 return true; 397 } 398 399 bool IRTranslator::translateSelect(const User &U, 400 MachineIRBuilder &MIRBuilder) { 401 unsigned Res = getOrCreateVReg(U); 402 unsigned Tst = getOrCreateVReg(*U.getOperand(0)); 403 unsigned Op0 = getOrCreateVReg(*U.getOperand(1)); 404 unsigned Op1 = getOrCreateVReg(*U.getOperand(2)); 405 MIRBuilder.buildSelect(Res, Tst, Op0, Op1); 406 return true; 407 } 408 409 bool IRTranslator::translateBitCast(const User &U, 410 MachineIRBuilder &MIRBuilder) { 411 // If we're bitcasting to the source type, we can reuse the source vreg. 412 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 413 getLLTForType(*U.getType(), *DL)) { 414 // Get the source vreg now, to avoid invalidating ValToVReg. 415 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0)); 416 unsigned &Reg = ValToVReg[&U]; 417 // If we already assigned a vreg for this bitcast, we can't change that. 418 // Emit a copy to satisfy the users we already emitted. 419 if (Reg) 420 MIRBuilder.buildCopy(Reg, SrcReg); 421 else 422 Reg = SrcReg; 423 return true; 424 } 425 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 426 } 427 428 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 429 MachineIRBuilder &MIRBuilder) { 430 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 431 unsigned Res = getOrCreateVReg(U); 432 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 433 return true; 434 } 435 436 bool IRTranslator::translateGetElementPtr(const User &U, 437 MachineIRBuilder &MIRBuilder) { 438 // FIXME: support vector GEPs. 439 if (U.getType()->isVectorTy()) 440 return false; 441 442 Value &Op0 = *U.getOperand(0); 443 unsigned BaseReg = getOrCreateVReg(Op0); 444 Type *PtrIRTy = Op0.getType(); 445 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 446 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 447 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 448 449 int64_t Offset = 0; 450 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 451 GTI != E; ++GTI) { 452 const Value *Idx = GTI.getOperand(); 453 if (StructType *StTy = GTI.getStructTypeOrNull()) { 454 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 455 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 456 continue; 457 } else { 458 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 459 460 // If this is a scalar constant or a splat vector of constants, 461 // handle it quickly. 462 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 463 Offset += ElementSize * CI->getSExtValue(); 464 continue; 465 } 466 467 if (Offset != 0) { 468 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 469 unsigned OffsetReg = 470 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 471 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 472 473 BaseReg = NewBaseReg; 474 Offset = 0; 475 } 476 477 // N = N + Idx * ElementSize; 478 unsigned ElementSizeReg = 479 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize)); 480 481 unsigned IdxReg = getOrCreateVReg(*Idx); 482 if (MRI->getType(IdxReg) != OffsetTy) { 483 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 484 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 485 IdxReg = NewIdxReg; 486 } 487 488 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 489 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg); 490 491 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 492 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 493 BaseReg = NewBaseReg; 494 } 495 } 496 497 if (Offset != 0) { 498 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 499 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 500 return true; 501 } 502 503 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 504 return true; 505 } 506 507 bool IRTranslator::translateMemfunc(const CallInst &CI, 508 MachineIRBuilder &MIRBuilder, 509 unsigned ID) { 510 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL); 511 Type *DstTy = CI.getArgOperand(0)->getType(); 512 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 || 513 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 514 return false; 515 516 SmallVector<CallLowering::ArgInfo, 8> Args; 517 for (int i = 0; i < 3; ++i) { 518 const auto &Arg = CI.getArgOperand(i); 519 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 520 } 521 522 const char *Callee; 523 switch (ID) { 524 case Intrinsic::memmove: 525 case Intrinsic::memcpy: { 526 Type *SrcTy = CI.getArgOperand(1)->getType(); 527 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0) 528 return false; 529 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove"; 530 break; 531 } 532 case Intrinsic::memset: 533 Callee = "memset"; 534 break; 535 default: 536 return false; 537 } 538 539 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(), 540 MachineOperand::CreateES(Callee), 541 CallLowering::ArgInfo(0, CI.getType()), Args); 542 } 543 544 void IRTranslator::getStackGuard(unsigned DstReg, 545 MachineIRBuilder &MIRBuilder) { 546 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 547 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 548 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 549 MIB.addDef(DstReg); 550 551 auto &TLI = *MF->getSubtarget().getTargetLowering(); 552 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent()); 553 if (!Global) 554 return; 555 556 MachinePointerInfo MPInfo(Global); 557 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1); 558 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 559 MachineMemOperand::MODereferenceable; 560 *MemRefs = 561 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 562 DL->getPointerABIAlignment()); 563 MIB.setMemRefs(MemRefs, MemRefs + 1); 564 } 565 566 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 567 MachineIRBuilder &MIRBuilder) { 568 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL); 569 LLT s1 = LLT::scalar(1); 570 unsigned Width = Ty.getSizeInBits(); 571 unsigned Res = MRI->createGenericVirtualRegister(Ty); 572 unsigned Overflow = MRI->createGenericVirtualRegister(s1); 573 auto MIB = MIRBuilder.buildInstr(Op) 574 .addDef(Res) 575 .addDef(Overflow) 576 .addUse(getOrCreateVReg(*CI.getOperand(0))) 577 .addUse(getOrCreateVReg(*CI.getOperand(1))); 578 579 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) { 580 unsigned Zero = getOrCreateVReg( 581 *Constant::getNullValue(Type::getInt1Ty(CI.getContext()))); 582 MIB.addUse(Zero); 583 } 584 585 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width); 586 return true; 587 } 588 589 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 590 MachineIRBuilder &MIRBuilder) { 591 switch (ID) { 592 default: 593 break; 594 case Intrinsic::lifetime_start: 595 case Intrinsic::lifetime_end: 596 // Stack coloring is not enabled in O0 (which we care about now) so we can 597 // drop these. Make sure someone notices when we start compiling at higher 598 // opts though. 599 if (MF->getTarget().getOptLevel() != CodeGenOpt::None) 600 return false; 601 return true; 602 case Intrinsic::dbg_declare: { 603 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 604 assert(DI.getVariable() && "Missing variable"); 605 606 const Value *Address = DI.getAddress(); 607 if (!Address || isa<UndefValue>(Address)) { 608 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 609 return true; 610 } 611 612 assert(DI.getVariable()->isValidLocationForIntrinsic( 613 MIRBuilder.getDebugLoc()) && 614 "Expected inlined-at fields to agree"); 615 auto AI = dyn_cast<AllocaInst>(Address); 616 if (AI && AI->isStaticAlloca()) { 617 // Static allocas are tracked at the MF level, no need for DBG_VALUE 618 // instructions (in fact, they get ignored if they *do* exist). 619 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 620 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 621 } else 622 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address), 623 DI.getVariable(), DI.getExpression()); 624 return true; 625 } 626 case Intrinsic::vaend: 627 // No target I know of cares about va_end. Certainly no in-tree target 628 // does. Simplest intrinsic ever! 629 return true; 630 case Intrinsic::vastart: { 631 auto &TLI = *MF->getSubtarget().getTargetLowering(); 632 Value *Ptr = CI.getArgOperand(0); 633 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 634 635 MIRBuilder.buildInstr(TargetOpcode::G_VASTART) 636 .addUse(getOrCreateVReg(*Ptr)) 637 .addMemOperand(MF->getMachineMemOperand( 638 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0)); 639 return true; 640 } 641 case Intrinsic::dbg_value: { 642 // This form of DBG_VALUE is target-independent. 643 const DbgValueInst &DI = cast<DbgValueInst>(CI); 644 const Value *V = DI.getValue(); 645 assert(DI.getVariable()->isValidLocationForIntrinsic( 646 MIRBuilder.getDebugLoc()) && 647 "Expected inlined-at fields to agree"); 648 if (!V) { 649 // Currently the optimizer can produce this; insert an undef to 650 // help debugging. Probably the optimizer should not do this. 651 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(), 652 DI.getExpression()); 653 } else if (const auto *CI = dyn_cast<Constant>(V)) { 654 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(), 655 DI.getExpression()); 656 } else { 657 unsigned Reg = getOrCreateVReg(*V); 658 // FIXME: This does not handle register-indirect values at offset 0. The 659 // direct/indirect thing shouldn't really be handled by something as 660 // implicit as reg+noreg vs reg+imm in the first palce, but it seems 661 // pretty baked in right now. 662 if (DI.getOffset() != 0) 663 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(), 664 DI.getExpression()); 665 else 666 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), 667 DI.getExpression()); 668 } 669 return true; 670 } 671 case Intrinsic::uadd_with_overflow: 672 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder); 673 case Intrinsic::sadd_with_overflow: 674 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 675 case Intrinsic::usub_with_overflow: 676 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder); 677 case Intrinsic::ssub_with_overflow: 678 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 679 case Intrinsic::umul_with_overflow: 680 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 681 case Intrinsic::smul_with_overflow: 682 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 683 case Intrinsic::pow: 684 MIRBuilder.buildInstr(TargetOpcode::G_FPOW) 685 .addDef(getOrCreateVReg(CI)) 686 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 687 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 688 return true; 689 case Intrinsic::memcpy: 690 case Intrinsic::memmove: 691 case Intrinsic::memset: 692 return translateMemfunc(CI, MIRBuilder, ID); 693 case Intrinsic::eh_typeid_for: { 694 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 695 unsigned Reg = getOrCreateVReg(CI); 696 unsigned TypeID = MF->getTypeIDFor(GV); 697 MIRBuilder.buildConstant(Reg, TypeID); 698 return true; 699 } 700 case Intrinsic::objectsize: { 701 // If we don't know by now, we're never going to know. 702 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 703 704 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 705 return true; 706 } 707 case Intrinsic::stackguard: 708 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 709 return true; 710 case Intrinsic::stackprotector: { 711 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 712 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 713 getStackGuard(GuardVal, MIRBuilder); 714 715 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 716 MIRBuilder.buildStore( 717 GuardVal, getOrCreateVReg(*Slot), 718 *MF->getMachineMemOperand( 719 MachinePointerInfo::getFixedStack(*MF, 720 getOrCreateFrameIndex(*Slot)), 721 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 722 PtrTy.getSizeInBits() / 8, 8)); 723 return true; 724 } 725 } 726 return false; 727 } 728 729 bool IRTranslator::translateInlineAsm(const CallInst &CI, 730 MachineIRBuilder &MIRBuilder) { 731 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue()); 732 if (!IA.getConstraintString().empty()) 733 return false; 734 735 unsigned ExtraInfo = 0; 736 if (IA.hasSideEffects()) 737 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 738 if (IA.getDialect() == InlineAsm::AD_Intel) 739 ExtraInfo |= InlineAsm::Extra_AsmDialect; 740 741 MIRBuilder.buildInstr(TargetOpcode::INLINEASM) 742 .addExternalSymbol(IA.getAsmString().c_str()) 743 .addImm(ExtraInfo); 744 745 return true; 746 } 747 748 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 749 const CallInst &CI = cast<CallInst>(U); 750 auto TII = MF->getTarget().getIntrinsicInfo(); 751 const Function *F = CI.getCalledFunction(); 752 753 if (CI.isInlineAsm()) 754 return translateInlineAsm(CI, MIRBuilder); 755 756 if (!F || !F->isIntrinsic()) { 757 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 758 SmallVector<unsigned, 8> Args; 759 for (auto &Arg: CI.arg_operands()) 760 Args.push_back(getOrCreateVReg(*Arg)); 761 762 MF->getFrameInfo().setHasCalls(true); 763 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() { 764 return getOrCreateVReg(*CI.getCalledValue()); 765 }); 766 } 767 768 Intrinsic::ID ID = F->getIntrinsicID(); 769 if (TII && ID == Intrinsic::not_intrinsic) 770 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 771 772 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 773 774 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 775 return true; 776 777 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 778 MachineInstrBuilder MIB = 779 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 780 781 for (auto &Arg : CI.arg_operands()) { 782 // Some intrinsics take metadata parameters. Reject them. 783 if (isa<MetadataAsValue>(Arg)) 784 return false; 785 MIB.addUse(getOrCreateVReg(*Arg)); 786 } 787 return true; 788 } 789 790 bool IRTranslator::translateInvoke(const User &U, 791 MachineIRBuilder &MIRBuilder) { 792 const InvokeInst &I = cast<InvokeInst>(U); 793 MCContext &Context = MF->getContext(); 794 795 const BasicBlock *ReturnBB = I.getSuccessor(0); 796 const BasicBlock *EHPadBB = I.getSuccessor(1); 797 798 const Value *Callee = I.getCalledValue(); 799 const Function *Fn = dyn_cast<Function>(Callee); 800 if (isa<InlineAsm>(Callee)) 801 return false; 802 803 // FIXME: support invoking patchpoint and statepoint intrinsics. 804 if (Fn && Fn->isIntrinsic()) 805 return false; 806 807 // FIXME: support whatever these are. 808 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 809 return false; 810 811 // FIXME: support Windows exception handling. 812 if (!isa<LandingPadInst>(EHPadBB->front())) 813 return false; 814 815 816 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 817 // the region covered by the try. 818 MCSymbol *BeginSymbol = Context.createTempSymbol(); 819 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 820 821 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I); 822 SmallVector<unsigned, 8> Args; 823 for (auto &Arg: I.arg_operands()) 824 Args.push_back(getOrCreateVReg(*Arg)); 825 826 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args, 827 [&]() { return getOrCreateVReg(*I.getCalledValue()); })) 828 return false; 829 830 MCSymbol *EndSymbol = Context.createTempSymbol(); 831 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 832 833 // FIXME: track probabilities. 834 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 835 &ReturnMBB = getMBB(*ReturnBB); 836 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 837 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 838 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 839 MIRBuilder.buildBr(ReturnMBB); 840 841 return true; 842 } 843 844 bool IRTranslator::translateLandingPad(const User &U, 845 MachineIRBuilder &MIRBuilder) { 846 const LandingPadInst &LP = cast<LandingPadInst>(U); 847 848 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 849 addLandingPadInfo(LP, MBB); 850 851 MBB.setIsEHPad(); 852 853 // If there aren't registers to copy the values into (e.g., during SjLj 854 // exceptions), then don't bother. 855 auto &TLI = *MF->getSubtarget().getTargetLowering(); 856 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn(); 857 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 858 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 859 return true; 860 861 // If landingpad's return type is token type, we don't create DAG nodes 862 // for its exception pointer and selector value. The extraction of exception 863 // pointer or selector value from token type landingpads is not currently 864 // supported. 865 if (LP.getType()->isTokenTy()) 866 return true; 867 868 // Add a label to mark the beginning of the landing pad. Deletion of the 869 // landing pad can thus be detected via the MachineModuleInfo. 870 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 871 .addSym(MF->addLandingPad(&MBB)); 872 873 LLT Ty = getLLTForType(*LP.getType(), *DL); 874 unsigned Undef = MRI->createGenericVirtualRegister(Ty); 875 MIRBuilder.buildUndef(Undef); 876 877 SmallVector<LLT, 2> Tys; 878 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 879 Tys.push_back(getLLTForType(*Ty, *DL)); 880 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 881 882 // Mark exception register as live in. 883 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 884 if (!ExceptionReg) 885 return false; 886 887 MBB.addLiveIn(ExceptionReg); 888 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]), 889 Tmp = MRI->createGenericVirtualRegister(Ty); 890 MIRBuilder.buildCopy(VReg, ExceptionReg); 891 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0); 892 893 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 894 if (!SelectorReg) 895 return false; 896 897 MBB.addLiveIn(SelectorReg); 898 899 // N.b. the exception selector register always has pointer type and may not 900 // match the actual IR-level type in the landingpad so an extra cast is 901 // needed. 902 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 903 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 904 905 VReg = MRI->createGenericVirtualRegister(Tys[1]); 906 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg); 907 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg, 908 Tys[0].getSizeInBits()); 909 return true; 910 } 911 912 bool IRTranslator::translateAlloca(const User &U, 913 MachineIRBuilder &MIRBuilder) { 914 auto &AI = cast<AllocaInst>(U); 915 916 if (AI.isStaticAlloca()) { 917 unsigned Res = getOrCreateVReg(AI); 918 int FI = getOrCreateFrameIndex(AI); 919 MIRBuilder.buildFrameIndex(Res, FI); 920 return true; 921 } 922 923 // Now we're in the harder dynamic case. 924 Type *Ty = AI.getAllocatedType(); 925 unsigned Align = 926 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment()); 927 928 unsigned NumElts = getOrCreateVReg(*AI.getArraySize()); 929 930 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 931 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 932 if (MRI->getType(NumElts) != IntPtrTy) { 933 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 934 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 935 NumElts = ExtElts; 936 } 937 938 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 939 unsigned TySize = 940 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty))); 941 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 942 943 LLT PtrTy = getLLTForType(*AI.getType(), *DL); 944 auto &TLI = *MF->getSubtarget().getTargetLowering(); 945 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 946 947 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy); 948 MIRBuilder.buildCopy(SPTmp, SPReg); 949 950 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy); 951 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize); 952 953 // Handle alignment. We have to realign if the allocation granule was smaller 954 // than stack alignment, or the specific alloca requires more than stack 955 // alignment. 956 unsigned StackAlign = 957 MF->getSubtarget().getFrameLowering()->getStackAlignment(); 958 Align = std::max(Align, StackAlign); 959 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) { 960 // Round the size of the allocation up to the stack alignment size 961 // by add SA-1 to the size. This doesn't overflow because we're computing 962 // an address inside an alloca. 963 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy); 964 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align)); 965 AllocTmp = AlignedAlloc; 966 } 967 968 MIRBuilder.buildCopy(SPReg, AllocTmp); 969 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp); 970 971 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI); 972 assert(MF->getFrameInfo().hasVarSizedObjects()); 973 return true; 974 } 975 976 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 977 // FIXME: We may need more info about the type. Because of how LLT works, 978 // we're completely discarding the i64/double distinction here (amongst 979 // others). Fortunately the ABIs I know of where that matters don't use va_arg 980 // anyway but that's not guaranteed. 981 MIRBuilder.buildInstr(TargetOpcode::G_VAARG) 982 .addDef(getOrCreateVReg(U)) 983 .addUse(getOrCreateVReg(*U.getOperand(0))) 984 .addImm(DL->getABITypeAlignment(U.getType())); 985 return true; 986 } 987 988 bool IRTranslator::translateInsertElement(const User &U, 989 MachineIRBuilder &MIRBuilder) { 990 // If it is a <1 x Ty> vector, use the scalar as it is 991 // not a legal vector type in LLT. 992 if (U.getType()->getVectorNumElements() == 1) { 993 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 994 ValToVReg[&U] = Elt; 995 return true; 996 } 997 unsigned Res = getOrCreateVReg(U); 998 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 999 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1000 unsigned Idx = getOrCreateVReg(*U.getOperand(2)); 1001 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 1002 return true; 1003 } 1004 1005 bool IRTranslator::translateExtractElement(const User &U, 1006 MachineIRBuilder &MIRBuilder) { 1007 // If it is a <1 x Ty> vector, use the scalar as it is 1008 // not a legal vector type in LLT. 1009 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) { 1010 unsigned Elt = getOrCreateVReg(*U.getOperand(0)); 1011 ValToVReg[&U] = Elt; 1012 return true; 1013 } 1014 unsigned Res = getOrCreateVReg(U); 1015 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1016 unsigned Idx = getOrCreateVReg(*U.getOperand(1)); 1017 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 1018 return true; 1019 } 1020 1021 bool IRTranslator::translateShuffleVector(const User &U, 1022 MachineIRBuilder &MIRBuilder) { 1023 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR) 1024 .addDef(getOrCreateVReg(U)) 1025 .addUse(getOrCreateVReg(*U.getOperand(0))) 1026 .addUse(getOrCreateVReg(*U.getOperand(1))) 1027 .addUse(getOrCreateVReg(*U.getOperand(2))); 1028 return true; 1029 } 1030 1031 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 1032 const PHINode &PI = cast<PHINode>(U); 1033 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI); 1034 MIB.addDef(getOrCreateVReg(PI)); 1035 1036 PendingPHIs.emplace_back(&PI, MIB.getInstr()); 1037 return true; 1038 } 1039 1040 void IRTranslator::finishPendingPhis() { 1041 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) { 1042 const PHINode *PI = Phi.first; 1043 MachineInstrBuilder MIB(*MF, Phi.second); 1044 1045 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 1046 // won't create extra control flow here, otherwise we need to find the 1047 // dominating predecessor here (or perhaps force the weirder IRTranslators 1048 // to provide a simple boundary). 1049 SmallSet<const BasicBlock *, 4> HandledPreds; 1050 1051 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 1052 auto IRPred = PI->getIncomingBlock(i); 1053 if (HandledPreds.count(IRPred)) 1054 continue; 1055 1056 HandledPreds.insert(IRPred); 1057 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i)); 1058 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 1059 assert(Pred->isSuccessor(MIB->getParent()) && 1060 "incorrect CFG at MachineBasicBlock level"); 1061 MIB.addUse(ValReg); 1062 MIB.addMBB(Pred); 1063 } 1064 } 1065 } 1066 } 1067 1068 bool IRTranslator::translate(const Instruction &Inst) { 1069 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 1070 switch(Inst.getOpcode()) { 1071 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1072 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 1073 #include "llvm/IR/Instruction.def" 1074 default: 1075 return false; 1076 } 1077 } 1078 1079 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 1080 if (auto CI = dyn_cast<ConstantInt>(&C)) 1081 EntryBuilder.buildConstant(Reg, *CI); 1082 else if (auto CF = dyn_cast<ConstantFP>(&C)) 1083 EntryBuilder.buildFConstant(Reg, *CF); 1084 else if (isa<UndefValue>(C)) 1085 EntryBuilder.buildUndef(Reg); 1086 else if (isa<ConstantPointerNull>(C)) 1087 EntryBuilder.buildConstant(Reg, 0); 1088 else if (auto GV = dyn_cast<GlobalValue>(&C)) 1089 EntryBuilder.buildGlobalValue(Reg, GV); 1090 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 1091 if (!CAZ->getType()->isVectorTy()) 1092 return false; 1093 // Return the scalar if it is a <1 x Ty> vector. 1094 if (CAZ->getNumElements() == 1) 1095 return translate(*CAZ->getElementValue(0u), Reg); 1096 std::vector<unsigned> Ops; 1097 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 1098 Constant &Elt = *CAZ->getElementValue(i); 1099 Ops.push_back(getOrCreateVReg(Elt)); 1100 } 1101 EntryBuilder.buildMerge(Reg, Ops); 1102 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 1103 // Return the scalar if it is a <1 x Ty> vector. 1104 if (CV->getNumElements() == 1) 1105 return translate(*CV->getElementAsConstant(0), Reg); 1106 std::vector<unsigned> Ops; 1107 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 1108 Constant &Elt = *CV->getElementAsConstant(i); 1109 Ops.push_back(getOrCreateVReg(Elt)); 1110 } 1111 EntryBuilder.buildMerge(Reg, Ops); 1112 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 1113 switch(CE->getOpcode()) { 1114 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1115 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 1116 #include "llvm/IR/Instruction.def" 1117 default: 1118 return false; 1119 } 1120 } else if (auto CS = dyn_cast<ConstantStruct>(&C)) { 1121 // Return the element if it is a single element ConstantStruct. 1122 if (CS->getNumOperands() == 1) { 1123 unsigned EltReg = getOrCreateVReg(*CS->getOperand(0)); 1124 EntryBuilder.buildCast(Reg, EltReg); 1125 return true; 1126 } 1127 SmallVector<unsigned, 4> Ops; 1128 SmallVector<uint64_t, 4> Indices; 1129 uint64_t Offset = 0; 1130 for (unsigned i = 0; i < CS->getNumOperands(); ++i) { 1131 unsigned OpReg = getOrCreateVReg(*CS->getOperand(i)); 1132 Ops.push_back(OpReg); 1133 Indices.push_back(Offset); 1134 Offset += MRI->getType(OpReg).getSizeInBits(); 1135 } 1136 EntryBuilder.buildSequence(Reg, Ops, Indices); 1137 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 1138 if (CV->getNumOperands() == 1) 1139 return translate(*CV->getOperand(0), Reg); 1140 SmallVector<unsigned, 4> Ops; 1141 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 1142 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 1143 } 1144 EntryBuilder.buildMerge(Reg, Ops); 1145 } else 1146 return false; 1147 1148 return true; 1149 } 1150 1151 void IRTranslator::finalizeFunction() { 1152 // Release the memory used by the different maps we 1153 // needed during the translation. 1154 PendingPHIs.clear(); 1155 ValToVReg.clear(); 1156 FrameIndices.clear(); 1157 MachinePreds.clear(); 1158 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 1159 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 1160 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 1161 EntryBuilder = MachineIRBuilder(); 1162 CurBuilder = MachineIRBuilder(); 1163 } 1164 1165 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 1166 MF = &CurMF; 1167 const Function &F = *MF->getFunction(); 1168 if (F.empty()) 1169 return false; 1170 CLI = MF->getSubtarget().getCallLowering(); 1171 CurBuilder.setMF(*MF); 1172 EntryBuilder.setMF(*MF); 1173 MRI = &MF->getRegInfo(); 1174 DL = &F.getParent()->getDataLayout(); 1175 TPC = &getAnalysis<TargetPassConfig>(); 1176 ORE = make_unique<OptimizationRemarkEmitter>(&F); 1177 1178 assert(PendingPHIs.empty() && "stale PHIs"); 1179 1180 // Release the per-function state when we return, whether we succeeded or not. 1181 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 1182 1183 // Setup a separate basic-block for the arguments and constants 1184 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 1185 MF->push_back(EntryBB); 1186 EntryBuilder.setMBB(*EntryBB); 1187 1188 // Create all blocks, in IR order, to preserve the layout. 1189 for (const BasicBlock &BB: F) { 1190 auto *&MBB = BBToMBB[&BB]; 1191 1192 MBB = MF->CreateMachineBasicBlock(&BB); 1193 MF->push_back(MBB); 1194 1195 if (BB.hasAddressTaken()) 1196 MBB->setHasAddressTaken(); 1197 } 1198 1199 // Make our arguments/constants entry block fallthrough to the IR entry block. 1200 EntryBB->addSuccessor(&getMBB(F.front())); 1201 1202 // Lower the actual args into this basic block. 1203 SmallVector<unsigned, 8> VRegArgs; 1204 for (const Argument &Arg: F.args()) 1205 VRegArgs.push_back(getOrCreateVReg(Arg)); 1206 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) { 1207 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1208 MF->getFunction()->getSubprogram(), 1209 &MF->getFunction()->getEntryBlock()); 1210 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 1211 reportTranslationError(*MF, *TPC, *ORE, R); 1212 return false; 1213 } 1214 1215 // And translate the function! 1216 for (const BasicBlock &BB: F) { 1217 MachineBasicBlock &MBB = getMBB(BB); 1218 // Set the insertion point of all the following translations to 1219 // the end of this basic block. 1220 CurBuilder.setMBB(MBB); 1221 1222 for (const Instruction &Inst: BB) { 1223 if (translate(Inst)) 1224 continue; 1225 1226 std::string InstStrStorage; 1227 raw_string_ostream InstStr(InstStrStorage); 1228 InstStr << Inst; 1229 1230 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1231 Inst.getDebugLoc(), &BB); 1232 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst) 1233 << ": '" << InstStr.str() << "'"; 1234 reportTranslationError(*MF, *TPC, *ORE, R); 1235 return false; 1236 } 1237 } 1238 1239 finishPendingPhis(); 1240 1241 // Merge the argument lowering and constants block with its single 1242 // successor, the LLVM-IR entry block. We want the basic block to 1243 // be maximal. 1244 assert(EntryBB->succ_size() == 1 && 1245 "Custom BB used for lowering should have only one successor"); 1246 // Get the successor of the current entry block. 1247 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 1248 assert(NewEntryBB.pred_size() == 1 && 1249 "LLVM-IR entry block has a predecessor!?"); 1250 // Move all the instruction from the current entry block to the 1251 // new entry block. 1252 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 1253 EntryBB->end()); 1254 1255 // Update the live-in information for the new entry block. 1256 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 1257 NewEntryBB.addLiveIn(LiveIn); 1258 NewEntryBB.sortUniqueLiveIns(); 1259 1260 // Get rid of the now empty basic block. 1261 EntryBB->removeSuccessor(&NewEntryBB); 1262 MF->remove(EntryBB); 1263 MF->DeleteMachineBasicBlock(EntryBB); 1264 1265 assert(&MF->front() == &NewEntryBB && 1266 "New entry wasn't next in the list of basic block!"); 1267 1268 return false; 1269 } 1270