// Convert the given function to use normalized argument/return types.
static bool ConvertFunction(Function *Func) {
  FunctionType *FTy = Func->getFunctionType();
  FunctionType *NFTy = NormalizeFunctionType(FTy);
  if (NFTy == FTy)
    return false; // No change needed.
  Function *NewFunc = RecreateFunction(Func, NFTy);

  // Move the arguments across to the new function.
  for (Function::arg_iterator Arg = Func->arg_begin(), E = Func->arg_end(),
         NewArg = NewFunc->arg_begin();
       Arg != E; ++Arg, ++NewArg) {
    NewArg->takeName(Arg);
    if (Arg->getType() == NewArg->getType()) {
      Arg->replaceAllUsesWith(NewArg);
    } else {
      Instruction *Trunc = new TruncInst(
          NewArg, Arg->getType(), NewArg->getName() + ".arg_trunc",
          NewFunc->getEntryBlock().getFirstInsertionPt());
      Arg->replaceAllUsesWith(Trunc);
    }
  }

  if (FTy->getReturnType() != NFTy->getReturnType()) {
    // Fix up return instructions.
    Instruction::CastOps CastType =
        Func->getAttributes().hasAttribute(0, Attribute::SExt) ?
        Instruction::SExt : Instruction::ZExt;
    for (Function::iterator BB = NewFunc->begin(), E = NewFunc->end();
         BB != E;
         ++BB) {
      for (BasicBlock::iterator Iter = BB->begin(), E = BB->end();
           Iter != E; ) {
        Instruction *Inst = Iter++;
        if (ReturnInst *Ret = dyn_cast<ReturnInst>(Inst)) {
          Value *Ext = CopyDebug(
              CastInst::Create(CastType, Ret->getReturnValue(),
                               NFTy->getReturnType(),
                               Ret->getReturnValue()->getName() + ".ret_ext",
                               Ret),
              Ret);
          CopyDebug(ReturnInst::Create(Ret->getContext(), Ext, Ret), Ret);
          Ret->eraseFromParent();
        }
      }
    }
  }

  Func->eraseFromParent();
  return true;
}
Esempio n. 2
0
bool SSIEverything::runOnFunction(Function &F) {
  SmallVector<Instruction *, 16> Insts;
  SSI &ssi = getAnalysis<SSI>();

  if (F.isDeclaration() || F.isIntrinsic()) return false;

  for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B)
    for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I)
      if (!I->getType()->isVoidTy())
        Insts.push_back(I);

  ssi.createSSI(Insts);
  return true;
}
Esempio n. 3
0
void StructFieldReach::CollectLiveInput(Function * pFunction, vector< pair<MemFootPrint *, int> > & vecLiveInput )
{
	ReturnInst * pRet = NULL;
	for(Function::iterator BB = pFunction->begin(); BB != pFunction->end(); BB++)
	{
		for(BasicBlock::iterator II = BB->begin(); II != BB->end(); II ++)
		{
			if(ReturnInst * pR = dyn_cast<ReturnInst>(II))
			{
				pRet = pR;
			}
		}
	}

	vector<Argument *> vecArgument;

	for(Function::arg_iterator argBe = pFunction->arg_begin(); argBe != pFunction->arg_end(); argBe ++ )
	{
		vecArgument.push_back(argBe);
		
	}


	set<MemFootPrint *>::iterator itSetBegin = this->InstBeforeSetMapping[pRet].begin();
	set<MemFootPrint *>::iterator itSetEnd = this->InstBeforeSetMapping[pRet].end();

	for(; itSetBegin != itSetEnd; itSetBegin ++ )
	{


		vector<Argument *>::iterator itVecArgBegin = vecArgument.begin();
		vector<Argument *>::iterator itVecArgEnd = vecArgument.end();

		int iIndex = 0;

		for(; itVecArgBegin != itVecArgEnd; itVecArgBegin++)
		{
			if(*itVecArgBegin == (*itSetBegin)->pBaseObject)
			{
				pair<MemFootPrint *, int> pairTmp;
				pairTmp.first = *itSetBegin;
				pairTmp.second = iIndex;
				vecLiveInput.push_back(pairTmp);
			}

			iIndex ++;
		}
	}

}
Esempio n. 4
0
bool ReduceCrashingInstructions::TestInsts(std::vector<const Instruction*>
                                           &Insts) {
  // Clone the program to try hacking it apart...
  ValueToValueMapTy VMap;
  Module *M = CloneModule(BD.getProgram(), VMap);

  // Convert list to set for fast lookup...
  SmallPtrSet<Instruction*, 64> Instructions;
  for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
    assert(!isa<TerminatorInst>(Insts[i]));
    Instructions.insert(cast<Instruction>(VMap[Insts[i]]));
  }

  outs() << "Checking for crash with only " << Instructions.size();
  if (Instructions.size() == 1)
    outs() << " instruction: ";
  else
    outs() << " instructions: ";

  for (Module::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
    for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE; ++FI)
      for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E;) {
        Instruction *Inst = &*I++;
        if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
            !Inst->isEHPad()) {
          if (!Inst->getType()->isVoidTy())
            Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
          Inst->eraseFromParent();
        }
      }

  // Verify that this is still valid.
  legacy::PassManager Passes;
  Passes.add(createVerifierPass());
  Passes.run(*M);

  // Try running on the hacked up program...
  if (TestFn(BD, M)) {
    BD.setNewProgram(M);      // It crashed, keep the trimmed version...

    // Make sure to use instruction pointers that point into the now-current
    // module, and that they don't include any deleted blocks.
    Insts.clear();
    for (Instruction *Inst : Instructions)
      Insts.push_back(Inst);
    return true;
  }
  delete M;  // It didn't crash, try something else.
  return false;
}
Esempio n. 5
0
void LLSTDebuggingPass::insertLoadInstCheck(Function& F)
{
    Value* BrokenPointerMessage = m_builder->CreateGlobalStringPtr("\npointer is broken\n");

    InstructionVector Loads;
    for (Function::iterator BB = F.begin(); BB != F.end(); ++BB)
    {
        for(BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
        {
            if (LoadInst* Load = dyn_cast<LoadInst>(II)) {
                Loads.push_back(Load);
            }
        }
    }

    for(std::size_t i = 0; i < Loads.size(); i++)
    {
        LoadInst* Load = dyn_cast<LoadInst>(Loads[i]);
        if (belongsToSmalltalkType( Load->getType() )) {

            //split BB right after load inst. The new BB contains code that will be executed if pointer is OK
            BasicBlock* PointerIsOkBB = Load->getParent()->splitBasicBlock(++( static_cast<BasicBlock::iterator>(Load) ));
            BasicBlock* PointerIsBrokenBB = BasicBlock::Create(m_module->getContext(), "", &F, PointerIsOkBB);
            BasicBlock* PointerIsNotSmallIntBB = BasicBlock::Create(m_module->getContext(), "", &F, PointerIsBrokenBB);

            Instruction* branchToPointerIsOkBB = ++( static_cast<BasicBlock::iterator>(Load) );
            //branchToPointerIsOkBB is created by splitBasicBlock() just after load inst
            //We force builder to insert instructions before branchToPointerIsOkBB
            m_builder->SetInsertPoint(branchToPointerIsOkBB);

            //If pointer to class is null, jump to PointerIsBroken, otherwise to PointerIsOkBB
            Value* objectPtr = m_builder->CreateBitCast( Load, m_baseTypes.object->getPointerTo());

            Value* isSmallInt = m_builder->CreateCall(isSmallInteger, objectPtr);
            m_builder->CreateCondBr(isSmallInt, PointerIsOkBB, PointerIsNotSmallIntBB);

            m_builder->SetInsertPoint(PointerIsNotSmallIntBB);
            Value* klassPtr = m_builder->CreateCall(getObjectClass, objectPtr);
            Value* pointerIsNull = m_builder->CreateICmpEQ(klassPtr, ConstantPointerNull::get(m_baseTypes.klass->getPointerTo()) );
            m_builder->CreateCondBr(pointerIsNull, PointerIsBrokenBB, PointerIsOkBB);

            branchToPointerIsOkBB->eraseFromParent(); //We don't need it anymore

            m_builder->SetInsertPoint(PointerIsBrokenBB);
            m_builder->CreateCall(_printf, BrokenPointerMessage);
            m_builder->CreateBr(PointerIsOkBB);
        }
    }
}
Esempio n. 6
0
virtual bool runOnFunction(Function &F) {
  bool isChanged = false;
  for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) {
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
        Instruction *instr = I;
      ++I;
      if (instr->getOpcode() == Instruction::UDiv) {
        isChanged |= lowerUDiv(instr);
      } else if (instr->getOpcode() == Instruction::SDiv) {
        isChanged |= lowerSDiv(instr);
      }
    }
  }
  return isChanged;
}
Esempio n. 7
0
bool AdvancedInstCounter::runOnModule(Module &M) {
  unsigned NumIndirectCalls = 0;
  for (Module::iterator F = M.begin(); F != M.end(); ++F) {
    for (Function::iterator B = F->begin(); B != F->end(); ++B) {
      for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) {
        CallSite CS(I);
        if (CS && CS.getCalledFunction() == NULL) {
          ++NumIndirectCalls;
        }
      }
    }
  }
  errs() << "# of indirect calls = " << NumIndirectCalls << "\n";
  return false;
}
Esempio n. 8
0
void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
{
    // add to list of defined symbols
    addDefinedSymbol(f, mangler, true); 

    // add external symbols referenced by this function.
    for (Function::iterator b = f->begin(); b != f->end(); ++b) {
        for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
            for (unsigned count = 0, total = i->getNumOperands(); 
                                        count != total; ++count) {
                findExternalRefs(i->getOperand(count), mangler);
            }
        }
    }
}
Esempio n. 9
0
void StructFieldReach::BuildMemFootPrintMapping(Function * pFunction)
{
	for(Function::iterator BB = pFunction->begin(); BB != pFunction->end(); BB ++ )
	{
		for(BasicBlock::iterator II = BB->begin(); II != BB->end(); II ++ )
		{
			if(isa<LoadInst>(II) || isa<StoreInst>(II) || isa<MemIntrinsic>(II))
			{
				MemFootPrint foot;
				CalMemFootPrint(II, &foot, this->pDL);
				this->InstMemFootPrintMapping[II] = foot;
			}
		}
	}
}
Esempio n. 10
0
/// GlobalIsNeeded - the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
  // If the global is already in the set, no need to reprocess it.
  if (!AliveGlobals.insert(G).second)
    return;

  Module *M = G->getParent();
  if (Comdat *C = G->getComdat()) {
    for (Function &F : *M)
      if (F.getComdat() == C)
        GlobalIsNeeded(&F);
    for (GlobalVariable &GV : M->globals())
      if (GV.getComdat() == C)
        GlobalIsNeeded(&GV);
    for (GlobalAlias &GA : M->aliases())
      if (GA.getComdat() == C)
        GlobalIsNeeded(&GA);
  }

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
    // If this is a global variable, we must make sure to add any global values
    // referenced by the initializer to the alive set.
    if (GV->hasInitializer())
      MarkUsedGlobalsAsNeeded(GV->getInitializer());
  } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
    // The target of a global alias is needed.
    MarkUsedGlobalsAsNeeded(GA->getAliasee());
  } else {
    // Otherwise this must be a function object.  We have to scan the body of
    // the function looking for constants and global values which are used as
    // operands.  Any operands of these types must be processed to ensure that
    // any globals used will be marked as needed.
    Function *F = cast<Function>(G);

    if (F->hasPrefixData())
      MarkUsedGlobalsAsNeeded(F->getPrefixData());

    if (F->hasPrologueData())
      MarkUsedGlobalsAsNeeded(F->getPrologueData());

    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
        for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
          if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
            GlobalIsNeeded(GV);
          else if (Constant *C = dyn_cast<Constant>(*U))
            MarkUsedGlobalsAsNeeded(C);
  }
}
bool SeparateConstOffsetFromGEP::runOnFunction(Function &F) {
  if (DisableSeparateConstOffsetFromGEP)
    return false;

  bool Changed = false;
  for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B) {
    for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ) {
      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I++)) {
        Changed |= splitGEP(GEP);
      }
      // No need to split GEP ConstantExprs because all its indices are constant
      // already.
    }
  }
  return Changed;
}
bool DynInstMarker::runOnModule(Module& m) {
  bool retVal = initInstrumentation(m);
  errs() << retVal << "\n";
  for (Module::iterator fi = m.begin(), fe = m.end(); fi != fe; ++fi) {
    errs().write_escaped(fi->getName()) << "\n";
    for (Function::iterator bi = fi->begin(), be = fi->end(); bi != be; ++bi) {
      for (BasicBlock::iterator ii = bi->begin(), ie = bi->end(); ii != ie; ++ii) {
        if (isa<LoadInst>(*ii) && 
            !fi->getName().equals(StringRef("_Z13resMarkerFuncv"))) { // TODO: optimize this
          insertInstrumentation(ii, bi, &m);
        }
      }
    }
  }
  return retVal;
}
Esempio n. 13
0
//
// Method: preprocess()
//
// Description:
//  %p = bitcast %p1 to T1
//  gep(%p) ...
// ->
//  gep (bitcast %p1 to T1), ...
//
// Inputs:
//  M - A reference to the LLVM module to process
//
// Outputs:
//  M - The transformed LLVM module.
//
static void preprocess(Module& M) {
  for (Module::iterator F = M.begin(); F != M.end(); ++F){
    for (Function::iterator B = F->begin(), FE = F->end(); B != FE; ++B) {      
      for (BasicBlock::iterator I = B->begin(), BE = B->end(); I != BE; I++) {
        if(!(isa<GetElementPtrInst>(I)))
          continue;
        GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
        if(BitCastInst *BI = dyn_cast<BitCastInst>(GEP->getOperand(0))) {
          if(Constant *C = dyn_cast<Constant>(BI->getOperand(0))) {
            GEP->setOperand(0, ConstantExpr::getBitCast(C, BI->getType()));
          }
        }
      }
    }
  }
}
Esempio n. 14
0
/** returns the first calledfunction from paralle_for_hetero */
Function* HeterotbbTransform::get_hetero_func(Module &M, CallSite &CS) {

    Function *f = CS.getCalledFunction();
    for (Function::iterator BBI = f->begin(), BBE = f->end(); BBI != BBE; ++BBI) {
        for (BasicBlock::iterator INSNI = BBI->begin(), INSNE = BBI->end(); INSNI != INSNE; ++INSNI) {
            if (isa<CallInst>(INSNI) || isa<InvokeInst>(INSNI)) {
                CallSite CI(cast<Instruction>(INSNI));
                //	CastInst *StrucCast = CastInst::Create(Instruction::BitCast, CI.getArgument(1),
                //			PointerType::get(Type::getInt8Ty(M.getContext()), 0), "temp_cast", INSNI);

                return CI.getCalledFunction();
            }
        }
    }
    return NULL;
}
Esempio n. 15
0
void Preparer::replaceUndefsWithNull(Module &M) {
  ValueSet Replaced;
  for (Module::global_iterator GI = M.global_begin(); GI != M.global_end();
       ++GI) {
    if (GI->hasInitializer()) {
      replaceUndefsWithNull(GI->getInitializer(), Replaced);
    }
  }
  for (Module::iterator F = M.begin(); F != M.end(); ++F) {
    for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) {
      for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins) {
        replaceUndefsWithNull(Ins, Replaced);
      }
    }
  }
}
Esempio n. 16
0
// StripDebugInfo - Strip debug info in the module if it exists.  
// To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and 
// llvm.dbg.region.end calls, and any globals they point to if now dead.
static bool StripDebugInfo(Module &M) {

  bool Changed = false;

  // Remove all of the calls to the debugger intrinsics, and remove them from
  // the module.
  if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
    while (!Declare->use_empty()) {
      CallInst *CI = cast<CallInst>(Declare->use_back());
      CI->eraseFromParent();
    }
    Declare->eraseFromParent();
    Changed = true;
  }

  if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
    while (!DbgVal->use_empty()) {
      CallInst *CI = cast<CallInst>(DbgVal->use_back());
      CI->eraseFromParent();
    }
    DbgVal->eraseFromParent();
    Changed = true;
  }

  for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
         NME = M.named_metadata_end(); NMI != NME;) {
    NamedMDNode *NMD = NMI;
    ++NMI;
    if (NMD->getName().startswith("llvm.dbg.")) {
      NMD->eraseFromParent();
      Changed = true;
    }
  }

  for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
    for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
         ++FI)
      for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
           ++BI) {
        if (!BI->getDebugLoc().isUnknown()) {
          Changed = true;
          BI->setDebugLoc(DebugLoc());
        }
      }

  return Changed;
}
Esempio n. 17
0
string getSourceFileName(Function *f){
	for(Function::iterator bb = f->begin(); bb != f->end(); bb++)
	for(BasicBlock::iterator i = bb->begin(); i != bb->end(); i++){
		if (MDNode *N = i->getMetadata("dbg")) { // this if is never executed
			DILocation Loc(N);
			string dir = Loc.getDirectory().str();
			string name = Loc.getFilename().str();
			stringstream fileName;
			fileName<<dir<<name;
			errs() << fileName.str() << "\n";
			return fileName.str();
			//return ConstantInt::get(Type::getInt32Ty(I->getContext()), Line);
		}

	}
	return "";
}
Esempio n. 18
0
/** very pathetic for now -- TODO */
Function* HeterotbbTransform::get_join_func(Module &M, CallSite &CS) {

    Function *f = CS.getCalledFunction();
    int count=0;
    for (Function::iterator BBI = f->begin(), BBE = f->end(); BBI != BBE; ++BBI) {
        for (BasicBlock::iterator INSNI = BBI->begin(), INSNE = BBI->end(); INSNI != INSNE; ++INSNI) {
            if (isa<CallInst>(INSNI) || isa<InvokeInst>(INSNI)) {
                count++;
                if(count==2) {
                    CallSite CI(cast<Instruction>(INSNI));
                    return CI.getCalledFunction();
                }
            }
        }
    }
    return NULL;
}
Esempio n. 19
0
bool NVPTXAllocaHoisting::runOnFunction(Function &function) {
  bool functionModified = false;
  Function::iterator I = function.begin();
  TerminatorInst *firstTerminatorInst = (I++)->getTerminator();

  for (Function::iterator E = function.end(); I != E; ++I) {
    for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
      AllocaInst *allocaInst = dyn_cast<AllocaInst>(BI++);
      if (allocaInst && isa<ConstantInt>(allocaInst->getArraySize())) {
        allocaInst->moveBefore(firstTerminatorInst);
        functionModified = true;
      }
    }
  }

  return functionModified;
}
Esempio n. 20
0
void LLSTDebuggingPass::insertSelfInSendMessageCheck(Function& F)
{
    Value* BrokenSelfMessage = m_builder->CreateGlobalStringPtr("\nself is broken\n");

    InstructionVector Calls;
    for (Function::iterator BB = F.begin(); BB != F.end(); ++BB)
    {
        for(BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II)
        {
            if (CallInst* Call = dyn_cast<CallInst>(II)) {
                if (Call->getCalledFunction()->getName() == "sendMessage")
                    Calls.push_back(Call);
            }
        }
    }

    for(std::size_t i = 0; i < Calls.size(); i++)
    {
        CallInst* Call = dyn_cast<CallInst>(Calls[i]);

        BasicBlock* PointerIsOkBB = Call->getParent()->splitBasicBlock( static_cast<BasicBlock::iterator>(Call) );
        BasicBlock* PointerIsBrokenBB = BasicBlock::Create(m_module->getContext(), "", &F, PointerIsOkBB);
        BasicBlock* PointerIsNotSmallIntBB = BasicBlock::Create(m_module->getContext(), "", &F, PointerIsBrokenBB);

        Instruction* branchToPointerIsOkBB = & PointerIsOkBB->getSinglePredecessor()->back();
        m_builder->SetInsertPoint(branchToPointerIsOkBB);


        Value* argsPtr = m_builder->CreateBitCast( Call->getArgOperand(2), m_baseTypes.object->getPointerTo());
        Value* self = m_builder->CreateCall2(getObjectField, argsPtr, m_builder->getInt32(0));

        Value* isSmallInt = m_builder->CreateCall(isSmallInteger, self);
        m_builder->CreateCondBr(isSmallInt, PointerIsOkBB, PointerIsNotSmallIntBB);


        m_builder->SetInsertPoint(PointerIsNotSmallIntBB);
        Value* klassPtr = m_builder->CreateCall(getObjectClass, self);
        Value* pointerIsNull = m_builder->CreateICmpEQ(klassPtr, ConstantPointerNull::get(m_baseTypes.klass->getPointerTo()) );
        m_builder->CreateCondBr(pointerIsNull, PointerIsBrokenBB, PointerIsOkBB);
        branchToPointerIsOkBB->eraseFromParent();

        m_builder->SetInsertPoint(PointerIsBrokenBB);
        m_builder->CreateCall(_printf, BrokenSelfMessage);
        m_builder->CreateBr(PointerIsOkBB);
    }
}
Esempio n. 21
0
void CostModelAnalysis::print(raw_ostream &OS, const Module*) const {
  if (!F)
    return;

  for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
    for (BasicBlock::iterator it = B->begin(), e = B->end(); it != e; ++it) {
      Instruction *Inst = it;
      unsigned Cost = getInstructionCost(Inst);
      if (Cost != (unsigned)-1)
        OS << "Cost Model: Found an estimated cost of " << Cost;
      else
        OS << "Cost Model: Unknown cost";

      OS << " for instruction: "<< *Inst << "\n";
    }
  }
}
Esempio n. 22
0
bool IDManager::runOnModule(Module &M) {
	IDMapping.clear();
	for (Module::iterator F = M.begin(); F != M.end(); ++F) {
		for (Function::iterator B = F->begin(); B != F->end(); ++B) {
			for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I) {
				unsigned InsID = getInstructionID(I);
				if (InsID != INVALID_ID)
					IDMapping[InsID].push_back(I);
			}
		}
	}

	if (size() == 0)
		errs() << "[Warning] No ID information in this program.\n";

	return false;
}
Esempio n. 23
0
void StructFieldReach::CalLoadDependentStore(Function * pFunction)
{
	int iLoad = 0;

	for(Function::iterator BB = pFunction->begin(); BB != pFunction->end(); BB ++)
	{
		for(BasicBlock::iterator II = BB->begin(); II != BB->end(); II ++)
		{
			if(LoadInst * pLoad = dyn_cast<LoadInst>(II))
			{
				iLoad ++;
				set<Instruction *> setDependentInst;

				set< MemFootPrint *>::iterator itFootSetBegin = this->InstBeforeSetMapping[pLoad].begin();
				set< MemFootPrint *>::iterator itFootSetEnd = this->InstBeforeSetMapping[pLoad].end();

				for(; itFootSetBegin != itFootSetEnd; itFootSetBegin ++)
				{
					MemRelationKind resultKind = CalIntraMemWriteRelation(&(this->InstMemFootPrintMapping[pLoad]), *itFootSetBegin);

					if(resultKind == MR_IDENTICAL || resultKind == MR_COVER || resultKind == MR_COVERED || resultKind == MR_OVERLAP)
					{
						setDependentInst.insert((*itFootSetBegin)->pI);
					}
				}

				itFootSetBegin = this->InstBeforeExtendSetMapping[pLoad].begin();
				itFootSetEnd = this->InstBeforeExtendSetMapping[pLoad].end();

				for(; itFootSetBegin != itFootSetEnd; itFootSetBegin++ )
				{
					MemRelationKind resultKind = CalInterMemWriteRelation(&(this->InstMemFootPrintMapping[pLoad]), *itFootSetBegin);

					if(resultKind == MR_IDENTICAL || resultKind == MR_COVER || resultKind == MR_COVERED || resultKind == MR_OVERLAP)
					{
						setDependentInst.insert((*itFootSetBegin)->pI);
					}
				}

				this->LoadDependentInstMapping[pLoad] = setDependentInst;

			}
		}
	}
}
Esempio n. 24
0
bool DivCheckPass::runOnModule(Module &M) { 
  Function *divZeroCheckFunction = 0;
  LLVMContext &ctx = M.getContext();

  bool moduleChanged = false;
  
  for (Module::iterator f = M.begin(), fe = M.end(); f != fe; ++f) {
    for (Function::iterator b = f->begin(), be = f->end(); b != be; ++b) {
      for (BasicBlock::iterator i = b->begin(), ie = b->end(); i != ie; ++i) {     
          if (BinaryOperator* binOp = dyn_cast<BinaryOperator>(i)) {
          // find all [s|u][div|mod] instructions
          Instruction::BinaryOps opcode = binOp->getOpcode();
          if (opcode == Instruction::SDiv || opcode == Instruction::UDiv ||
              opcode == Instruction::SRem || opcode == Instruction::URem) {
            
            CastInst *denominator =
              CastInst::CreateIntegerCast(i->getOperand(1),
                                          Type::getInt64Ty(ctx),
                                          false,  /* sign doesn't matter */
                                          "int_cast_to_i64",
                                          &*i);
            
            // Lazily bind the function to avoid always importing it.
            if (!divZeroCheckFunction) {
              Constant *fc = M.getOrInsertFunction("klee_div_zero_check", 
                                                   Type::getVoidTy(ctx),
                                                   Type::getInt64Ty(ctx),
                                                   NULL);
              divZeroCheckFunction = cast<Function>(fc);
            }

            CallInst * ci = CallInst::Create(divZeroCheckFunction, denominator, "", &*i);

            // Set debug location of checking call to that of the div/rem
            // operation so error locations are reported in the correct
            // location.
            ci->setDebugLoc(binOp->getDebugLoc());
            moduleChanged = true;
          }
        }
      }
    }
  }
  return moduleChanged;
}
void stripFunctionAttrs(DataLayout *DL, Function *Func) {
  CheckAttributes(Func->getAttributes());
  Func->setAttributes(AttributeSet());
  Func->setCallingConv(CallingConv::C);
  Func->setAlignment(0);

  for (Function::iterator BB = Func->begin(), E = Func->end();
       BB != E; ++BB) {
    for (BasicBlock::iterator Inst = BB->begin(), E = BB->end();
         Inst != E; ++Inst) {
      CallSite Call(Inst);
      if (Call) {
        CheckAttributes(Call.getAttributes());
        Call.setAttributes(AttributeSet());
        Call.setCallingConv(CallingConv::C);

#if 0 // EMSCRIPTEN: we do support alignment info in these calls
        // Set memcpy(), memmove() and memset() to use pessimistic
        // alignment assumptions.
        if (MemIntrinsic *MemOp = dyn_cast<MemIntrinsic>(Inst)) {
          Type *AlignTy = MemOp->getAlignmentCst()->getType();
          MemOp->setAlignment(ConstantInt::get(AlignTy, 1));
        }
#endif
      } else if (OverflowingBinaryOperator *Op =
                     dyn_cast<OverflowingBinaryOperator>(Inst)) {
        cast<BinaryOperator>(Op)->setHasNoUnsignedWrap(false);
        cast<BinaryOperator>(Op)->setHasNoSignedWrap(false);
      } else if (PossiblyExactOperator *Op =
                     dyn_cast<PossiblyExactOperator>(Inst)) {
        cast<BinaryOperator>(Op)->setIsExact(false);
      } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
        Load->setAlignment(normalizeAlignment(
                               DL, Load->getAlignment(),
                               Load->getType(),
                               Load->isAtomic()));
      } else if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
        Store->setAlignment(normalizeAlignment(
                                DL, Store->getAlignment(),
                                Store->getValueOperand()->getType(),
                                Store->isAtomic()));
      }
    }
  }
}
Esempio n. 26
0
bool llvm::InputValues::runOnModule(Module& M) {

	module = &M;

	initializeWhiteList();

    collectMainArguments();

	for(Module::iterator Fit = M.begin(), Fend = M.end(); Fit != Fend; Fit++){

		for (Function::iterator BBit = Fit->begin(), BBend = Fit->end(); BBit != BBend; BBit++) {

			for (BasicBlock::iterator Iit = BBit->begin(), Iend = BBit->end(); Iit != Iend; Iit++) {

				if (CallInst *CI = dyn_cast<CallInst>(Iit)) {

					if (isMarkedCallInst(CI)){

						//Values returned by marked instructions
						insertInInputDepValues(CI);

						for(unsigned int i = 0; i < CI->getNumOperands(); i++){

							if (CI->getOperand(i)->getType()->isPointerTy()){
								//Arguments with pointer type of marked functions
								insertInInputDepValues(CI->getOperand(i));
							}

						}

					}

				}

			}

		}

	}

	NumInputValues = inputValues.size();

	//We don't modify anything, so we must return false;
	return false;
}
Esempio n. 27
0
void Matcher::processInst(Function *F)
{
  for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; FI++) {
    /** Get each instruction's scope information **/
    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; BI++) {
      DebugLoc Loc = BI->getDebugLoc();
      if (Loc.isUnknown())
        continue;
      LLVMContext & Ctx = BI->getContext();

      DIDescriptor Scope(Loc.getScope(Ctx));
      if (Scope.isLexicalBlock()) {
        DILexicalBlock DILB(Scope);
        errs() << "Block :" << DILB.getLineNumber() << ", " << DILB.getColumnNumber() << "\n";
      }
    }
  }
}
Esempio n. 28
0
bool RPR::DoRaisePass(Function &F) {
  bool Changed = false;
  for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
    for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
      DEBUG(std::cerr << "LevelRaising: " << *BI);
      if (dceInstruction(BI) || doConstantPropagation(BI)) {
        Changed = true; 
        ++NumDCEorCP;
        DEBUG(std::cerr << "***\t\t^^-- Dead code eliminated!\n");
      } else if (PeepholeOptimize(BB, BI)) {
        Changed = true;
      } else {
        ++BI;
      }
    }

  return Changed;
}
Esempio n. 29
0
extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) {
  for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E;
       ++GV) {
    GV->setDoesNotThrow();
    Function *F = dyn_cast<Function>(GV);
    if (F == nullptr)
      continue;

    for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) {
      for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) {
        if (isa<InvokeInst>(I)) {
          InvokeInst *CI = cast<InvokeInst>(I);
          CI->setDoesNotThrow();
        }
      }
    }
  }
}
Esempio n. 30
0
void SparseSolver::Print(Function &F, raw_ostream &OS) const {
  OS << "\nFUNCTION: " << F.getName() << "\n";
  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
    if (!BBExecutable.count(BB))
      OS << "INFEASIBLE: ";
    OS << "\t";
    if (BB->hasName())
      OS << BB->getName() << ":\n";
    else
      OS << "; anon bb\n";
    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
      LatticeFunc->PrintValue(getLatticeState(I), OS);
      OS << *I << "\n";
    }

    OS << "\n";
  }
}