[LLVMdev] Replacing instruction in LLVM IR by an intrinsics

ihusar ihusar at fit.vutbr.cz
Thu Jun 25 03:36:35 PDT 2009


On Thu, 25 Jun 2009 02:18:23 +0200, Eli Friedman <eli.friedman at gmail.com> wrote:

> On Thu, Jun 25, 2009 at 12:32 AM, ihusar<ihusar at fit.vutbr.cz> wrote:
>>                //now i need to create an instruction that represents a call to a intrinsic
>>                Function* FIntr = Intrinsic::getDeclaration(&M, Intrinsic::regread_i32);
>>
>>                // here it fails: void llvm::CallInst::init(llvm::Value*):
>>                //Assertion `FTy->getNumParams() == 0 && "Calling a function with bad signature"' failed.
>>                Instruction* Instr = CallInst::Create(FIntr);
>
> You have to include the operands in the call to CallInst::Create.
>
> -Eli


Hi, I created arguments as you told and now everything works fine. If someone would be interested, I am putting the code here.

Adam


void CGInstrOpRewriter::replaceByIntrinsic(Module& M, Instruction* instrToReplace, const Intrinsic::ID intrId, const int arg1, const int arg2)
{
	//create function and its arguments
	Function* FIntr = Intrinsic::getDeclaration(&M, intrId); 
	
	SmallVector<Value*, 2> Args(2);
	
	Args[0] = ConstantInt::get(Type::Int32Ty, arg1);  
	Args[1] = ConstantInt::get(Type::Int32Ty, arg2);
	
	//now create and replace original instruction
	Instruction* IntrI = CallInst::Create(FIntr, Args.begin(), Args.end());
	
	ReplaceInstWithInst(instrToReplace, IntrI);
}

bool CGInstrOpRewriter::runOnModule(Module &M) 
{
	if (!bLoaded)
	{
		llvm::cerr << "CG: Error: Ignoring module\n"; //should not happen
		return false;
	}
	
	//for each function in module
	for(Module::iterator FuncIt = M.getFunctionList().begin(); FuncIt != M.getFunctionList().end(); FuncIt++)
	{
		Function* F = FuncIt;
	
		llvm::cerr << "Original ---- \n" << *F << "\n";
		
		//and for each instruction of a function
		for (inst_iterator It = inst_begin(F), E = inst_end(F); It != E; ++It)
		{
			//previous iterator
			inst_iterator PrevIt; 
			bool bFirst = false;
			if (It == inst_begin(F))
			{
				bFirst = true;
			}
			else
			{
				PrevIt = It;
				--PrevIt;
			}
			
			Instruction* CurrI = &(*It);

			llvm::cerr << "Processing " << *CurrI << "\n";
			
			if (isa<LoadInst>(CurrI))
			{

				//replace - intrinsics ID (from Intrinsics.def) and some int arguments
				replaceByIntrinsic(M, CurrI, Intrinsic::regread_i32, 1, 2);
				
				//renew iterator because we removed previous instruction to which it was pointing
				if (!bFirst)
				{
					It = ++PrevIt;
				}
				else
				{
					It = ++inst_begin(F);
				}
			}
			
		}

		llvm::cerr << "Modified ---- \n" << *F << "\n";
	}

	return true;
}





More information about the llvm-dev mailing list