Example #1
0
/// buildCFICheck - emits __cfi_check for the current module.
void CrossDSOCFI::buildCFICheck() {
  // FIXME: verify that __cfi_check ends up near the end of the code section,
  // but before the jump slots created in LowerBitSets.
  llvm::DenseSet<uint64_t> BitSetIds;
  NamedMDNode *BitSetNM = M->getNamedMetadata("llvm.bitsets");

  if (BitSetNM)
    for (unsigned I = 0, E = BitSetNM->getNumOperands(); I != E; ++I)
      if (ConstantInt *TypeId = extractBitSetTypeId(BitSetNM->getOperand(I)))
        BitSetIds.insert(TypeId->getZExtValue());

  LLVMContext &Ctx = M->getContext();
  Constant *C = M->getOrInsertFunction(
      "__cfi_check",
      FunctionType::get(
          Type::getVoidTy(Ctx),
          {Type::getInt64Ty(Ctx), PointerType::getUnqual(Type::getInt8Ty(Ctx))},
          false));
  Function *F = dyn_cast<Function>(C);
  F->setAlignment(4096);
  auto args = F->arg_begin();
  Argument &CallSiteTypeId = *(args++);
  CallSiteTypeId.setName("CallSiteTypeId");
  Argument &Addr = *(args++);
  Addr.setName("Addr");
  assert(args == F->arg_end());

  BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);

  BasicBlock *TrapBB = BasicBlock::Create(Ctx, "trap", F);
  IRBuilder<> IRBTrap(TrapBB);
  Function *TrapFn = Intrinsic::getDeclaration(M, Intrinsic::trap);
  llvm::CallInst *TrapCall = IRBTrap.CreateCall(TrapFn);
  TrapCall->setDoesNotReturn();
  TrapCall->setDoesNotThrow();
  IRBTrap.CreateUnreachable();

  BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
  IRBuilder<> IRBExit(ExitBB);
  IRBExit.CreateRetVoid();

  IRBuilder<> IRB(BB);
  SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, BitSetIds.size());
  for (uint64_t TypeId : BitSetIds) {
    ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
    BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
    IRBuilder<> IRBTest(TestBB);
    Function *BitsetTestFn =
        Intrinsic::getDeclaration(M, Intrinsic::bitset_test);

    Value *Test = IRBTest.CreateCall(
        BitsetTestFn, {&Addr, MetadataAsValue::get(
                                  Ctx, ConstantAsMetadata::get(CaseTypeId))});
    BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
    BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);

    SI->addCase(CaseTypeId, TestBB);
    ++TypeIds;
  }
}
Example #2
0
/// processModule - Process entire module and collect debug info.
void DebugInfoFinder::processModule(Module &M) {

  MetadataContext &TheMetadata = M.getContext().getMetadata();
  unsigned MDDbgKind = TheMetadata.getMDKind("dbg");

  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
      for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
           ++BI) {
        if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
          processDeclare(DDI);
        else if (MDDbgKind) 
          if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) 
            processLocation(DILocation(L));
      }

  NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
  if (!NMD)
    return;

  for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
    DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
    if (addGlobalVariable(DIG)) {
      addCompileUnit(DIG.getCompileUnit());
      processType(DIG.getType());
    }
  }
}
Example #3
0
DICompileUnit *DIBuilder::createCompileUnit(
    unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
    bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
    DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {

  assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
          (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
         "Invalid Language tag");
  assert(!Filename.empty() &&
         "Unable to create compile unit without filename");

  assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
  CUNode = DICompileUnit::getDistinct(
      VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
      isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
      nullptr, nullptr, nullptr, nullptr, DWOId);

  // Create a named metadata so that it is easier to find cu in a module.
  // Note that we only generate this when the caller wants to actually
  // emit debug information. When we are only interested in tracking
  // source line locations throughout the backend, we prevent codegen from
  // emitting debug info in the final output by not generating llvm.dbg.cu.
  if (EmitDebugInfo) {
    NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
    NMD->addOperand(CUNode);
  }

  trackIfUnresolved(CUNode);
  return CUNode;
}
Example #4
0
bool llvm::StripDebugInfo(Module &M) {
  bool Changed = false;

  for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
         NME = M.named_metadata_end(); NMI != NME;) {
    NamedMDNode *NMD = &*NMI;
    ++NMI;

    // We're stripping debug info, and without them, coverage information
    // doesn't quite make sense.
    if (NMD->getName().startswith("llvm.dbg.") ||
        NMD->getName() == "llvm.gcov") {
      NMD->eraseFromParent();
      Changed = true;
    }
  }

  for (Function &F : M)
    Changed |= stripDebugInfo(F);

  for (auto &GV : M.globals()) {
    SmallVector<MDNode *, 1> MDs;
    GV.getMetadata(LLVMContext::MD_dbg, MDs);
    if (!MDs.empty()) {
      GV.eraseMetadata(LLVMContext::MD_dbg);
      Changed = true;
    }
  }

  if (GVMaterializer *Materializer = M.getMaterializer())
    Materializer->setStripDebugInfo();

  return Changed;
}
Example #5
0
map<string, Variable*>* IRParser::parseParameters(Module* module){
    map<string, Variable*>* parameters = new map<string, Variable*>();

    NamedMDNode* inputsMD =  module->getNamedMetadata(IRConstant::KEY_PARAMETERS);
    if (inputsMD != NULL){
        for (unsigned i = 0, e = inputsMD->getNumOperands(); i != e; ++i) {

            //Parse a parameter
            MDNode* parameterNode = cast<MDNode>(inputsMD->getOperand(i));
            MDNode* details = cast<MDNode>(parameterNode->getOperand(0));
            MDString* nameMD = cast<MDString>(details->getOperand(0));

            Type* type = parseType(cast<MDNode>(parameterNode->getOperand(1)));

            GlobalVariable* variable = cast<GlobalVariable>(parameterNode->getOperand(2));

            //Parse create parameter
            StateVar* parameter = new StateVar(type, nameMD->getString(), false, variable);

            parameters->insert(pair<string, Variable*>(nameMD->getString(), parameter));
        }

    }
    return parameters;
}
Example #6
0
/// createVariable - Create a new descriptor for the specified variable.
DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
                                          StringRef Name, DIFile File,
                                          unsigned LineNo, DIType Ty,
                                          bool AlwaysPreserve, unsigned Flags,
                                          unsigned ArgNo) {
  Value *Elts[] = {
    GetTagConstant(VMContext, Tag),
    getNonCompileUnitScope(Scope),
    MDString::get(VMContext, Name),
    File,
    ConstantInt::get(Type::getInt32Ty(VMContext), (LineNo | (ArgNo << 24))),
    Ty,
    ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
    Constant::getNullValue(Type::getInt32Ty(VMContext))
  };
  MDNode *Node = MDNode::get(VMContext, Elts);
  if (AlwaysPreserve) {
    // The optimizer may remove local variable. If there is an interest
    // to preserve variable info in such situation then stash it in a
    // named mdnode.
    DISubprogram Fn(getDISubprogram(Scope));
    NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, Fn);
    FnLocals->addOperand(Node);
  }
  return DIVariable(Node);
}
Example #7
0
ActionScheduler* IRParser::parseActionScheduler(Module* module){
    NamedMDNode* inputsMD =  module->getNamedMetadata(IRConstant::KEY_ACTION_SCHED);

    MDNode* actionSchedulerMD = cast<MDNode>(inputsMD->getOperand(0));
    list<Action*>* actions = new list<Action*>();
    FSM* fsm = NULL;

    //Get actions outside fsm if present
    Value* actionsValue = actionSchedulerMD->getOperand(0);

    if (actionsValue != NULL){
        MDNode* actionsNode =  cast<MDNode>(actionsValue);
        for (unsigned i = 0, e = actionsNode->getNumOperands(); i != e; ++i) {
            actions->push_back(getAction(cast<MDNode>(actionsNode->getOperand(i))));
        }
    }

    //Get fsm if present
    Value* fsmValue = actionSchedulerMD->getOperand(1);

    if (fsmValue != NULL){
        fsm = parseFSM(cast<MDNode>(fsmValue));
    }

    return new ActionScheduler(actions, fsm);
}
Example #8
0
MoC* IRParser::parseMoC(Module* module){
    NamedMDNode* mocKeyMD =  module->getNamedMetadata(IRConstant::KEY_MOC);

    if (mocKeyMD == NULL) {
        return new DPNMoC(actor);
    }

    //Parse MoC type
    MDNode* node = mocKeyMD->getOperand(0);
    MDString* name = cast<MDString>(node->getOperand(0));
    StringRef nameStr = name->getString();

    if (nameStr == "SDF"){
        return parseCSDF(cast<MDNode>(node->getOperand(1)));
    }else if(nameStr == "CSDF"){
        return parseCSDF(cast<MDNode>(node->getOperand(1)));
    }else if(nameStr == "QuasiStatic"){
        return parseQSDF(node);
    }else if(nameStr == "KPN"){
        return new KPNMoC(actor);
    }else if(nameStr == "DPN"){
        return new DPNMoC(actor);
    }

    cerr << "Unsupported type of MoC" << endl;
    exit(1);
}
Example #9
0
/// CreateGlobalVariable - Create a new descriptor for the specified global.
DIGlobalVariable
DIFactory::CreateGlobalVariable(DIDescriptor Context, const char * Name,
                                const char * DisplayName,
                                const char * LinkageName,
                                DICompileUnit CompileUnit,
                                unsigned LineNo, DIType Type,bool isLocalToUnit,
                                bool isDefinition, llvm::GlobalVariable *Val) {
  Value *Elts[] = {
    GetTagConstant(dwarf::DW_TAG_variable),
    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
    Context.getNode(),
    MDString::get(VMContext, Name),
    MDString::get(VMContext, DisplayName),
    MDString::get(VMContext, LinkageName),
    CompileUnit.getNode(),
    ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
    Type.getNode(),
    ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
    ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
    Val
  };

  Value *const *Vs = &Elts[0];
  MDNode *Node = MDNode::get(VMContext,Vs, 12);

  // Create a named metadata so that we do not lose this mdnode.
  NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
  NMD->addElement(Node);

  return DIGlobalVariable(Node);
}
Example #10
0
void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name,
                                  LLVMMetadataRef Val) {
  NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name);
  if (!N)
    return;
  if (!Val)
    return;
  N->addOperand(unwrap<MDNode>(Val));
}
Example #11
0
static void
ModuleMetaSet(Module *module, StringRef MetaName, StringRef ValueStr) {
  NamedMDNode *node = module->getNamedMetadata(MetaName);
  if (node)
    module->eraseNamedMetadata(node);
  node = module->getOrInsertNamedMetadata(MetaName);
  MDString *value = MDString::get(module->getContext(), ValueStr);
  node->addOperand(MDNode::get(module->getContext(),
                   makeArrayRef(static_cast<Value*>(value))));
}
Example #12
0
  void
  SpecializationTable::initialize(Module* m)
  {
    assert(this->module == NULL);
    this->module = m;
#ifdef RECORD_IN_METADATA
    // Parse the module metadata to populate the table
    NamedMDNode* specs = m->getNamedMetadata("previrt::specializations");
    if (specs == NULL)
    return;

    errs() << "Specialization Count: " << specs->getNumOperands() << "\n";

    for (unsigned int i = 0; i < specs->getNumOperands(); ++i) {
      MDNode* funNode = specs->getOperand(i);
      if (funNode == NULL) {
        continue;
      }
      assert (funNode->getNumOperands() > 2);
      MDString* prinName = dyn_cast_or_null<MDString>(funNode->getOperand(0));
      MDString* specName = dyn_cast_or_null<MDString>(funNode->getOperand(1));
      if (prinName == NULL || specName == NULL) {
        errs() << "must skip " << (prinName == NULL ? "?" : prinName->getString()) << "\n";
        continue;
      }
      Function* prin = m->getFunction(prinName->getString());
      Function* spec = m->getFunction(specName->getString());
      if (prin == NULL || spec == NULL) {
        errs() << "must skip " << (prin == NULL ? "?" : prin->getName()) << "\n";
        continue;
      }

      const unsigned int arg_count = prin->getArgumentList().size();
      if (funNode->getNumOperands() != 2 + arg_count) {
        continue;
      }

      SpecScheme scheme = new Value*[arg_count];
      for (unsigned int i = 0; i < arg_count; i++) {
        Value* opr = funNode->getOperand(2 + i);
        if (opr == NULL) {
          scheme[i] = NULL;
        } else {
          assert (dyn_cast<Constant>(opr) != NULL);
          scheme[i] = opr;
        }
      }

      this->addSpecialization(prin, scheme, spec, false);
      errs() << "recording specialization of '" << prin->getName() << "' to '" << spec->getName() << "'\n";
    }
#endif /* RECORD_IN_METADATA */
  }
Example #13
0
/// Insert all of the named MDNodes in Src into the Dest module.
void IRLinker::linkNamedMDNodes() {
  const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  for (const NamedMDNode &NMD : SrcM->named_metadata()) {
    // Don't link module flags here. Do them separately.
    if (&NMD == SrcModFlags)
      continue;
    NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
    // Add Src elements into Dest node.
    for (const MDNode *Op : NMD.operands())
      DestNMD->addOperand(Mapper.mapMDNode(*Op));
  }
}
Example #14
0
static std::string
ModuleMetaGet(const Module *module, StringRef MetaName) {
  NamedMDNode *node = module->getNamedMetadata(MetaName);
  if (node == NULL)
    return "";
  assert(node->getNumOperands() == 1);
  MDNode *subnode = node->getOperand(0);
  assert(subnode->getNumOperands() == 1);
  MDString *value = dyn_cast<MDString>(subnode->getOperand(0));
  assert(value != NULL);
  return value->getString();
}
Example #15
0
Actor* IRParser::parseActor(string classz){
    //Get file and package of the actor
    string file = PackageMng::getSimpleName(classz);
    string packageName = PackageMng::getPackagesName(classz);
    Package* package = PackageMng::getPackage(packageName);

    //Parse the bitcode
    Module* module = parser->loadModule(package, file);

    if (module == 0){
        //Module not found
        cerr << "Error when parsing bytecode";
        exit(1);
    }

    //Empty action list
    actions.clear();
    untaggedActions.clear();

    // Parse name
    NamedMDNode* nameNMD =  module->getNamedMetadata(IRConstant::KEY_NAME);
    MDNode* nameMD = cast<MDNode>(nameNMD->getOperand(0));
    MDString* name = cast<MDString>(nameMD->getOperand(0));

    // Create the new actor
    actor = new Actor(name->getString(), module, classz);

    // Parse actor elements
    inputs = parsePorts(IRConstant::KEY_INPUTS, module);
    outputs = parsePorts(IRConstant::KEY_OUTPUTS, module);
    map<string, Variable*>* parameters =  parseParameters(module);
    map<string, StateVar*>* stateVars = parseStateVars(module);
    map<string, Procedure*>* procs = parseProcs(module);
    list<Action*>* initializes = parseActions(IRConstant::KEY_INITIALIZES, module);
    list<Action*>* actions = parseActions(IRConstant::KEY_ACTIONS, module);
    ActionScheduler* actionScheduler = parseActionScheduler(module);
    MoC* moc = parseMoC(module);

    //Set parameters of the actor
    actor->setInputs(inputs);
    actor->setOutputs(outputs);
    actor->setParameters(parameters);
    actor->setActions(actions);
    actor->setStateVars(stateVars);
    actor->setProcs(procs);
    actor->setActions(actions);
    actor->setInitializes(initializes);
    actor->setActionScheduler(actionScheduler);
    actor->setMoC(moc);

    return actor;
}
Example #16
0
/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
/// module.
void ModuleLinker::linkNamedMDNodes() {
  const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
  for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
       E = SrcM->named_metadata_end(); I != E; ++I) {
    // Don't link module flags here. Do them separately.
    if (&*I == SrcModFlags) continue;
    NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
    // Add Src elements into Dest node.
    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
      DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
                                   RF_None, &TypeMap));
  }
}
Example #17
0
DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
                                           StringRef Directory,
                                           StringRef Producer, bool isOptimized,
                                           StringRef Flags, unsigned RunTimeVer,
                                           StringRef SplitName,
                                           DebugEmissionKind Kind,
                                           bool EmitDebugInfo) {

  assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
          (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
         "Invalid Language tag");
  assert(!Filename.empty() &&
         "Unable to create compile unit without filename");
  Value *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
  TempEnumTypes = MDNode::getTemporary(VMContext, TElts);

  TempRetainTypes = MDNode::getTemporary(VMContext, TElts);

  TempSubprograms = MDNode::getTemporary(VMContext, TElts);

  TempGVs = MDNode::getTemporary(VMContext, TElts);

  TempImportedModules = MDNode::getTemporary(VMContext, TElts);

  Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
                       .concat(Lang)
                       .concat(Producer)
                       .concat(isOptimized)
                       .concat(Flags)
                       .concat(RunTimeVer)
                       .concat(SplitName)
                       .concat(Kind)
                       .get(VMContext),
                   createFilePathPair(VMContext, Filename, Directory),
                   TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
                   TempImportedModules};

  MDNode *CUNode = MDNode::get(VMContext, Elts);

  // Create a named metadata so that it is easier to find cu in a module.
  // Note that we only generate this when the caller wants to actually
  // emit debug information. When we are only interested in tracking
  // source line locations throughout the backend, we prevent codegen from
  // emitting debug info in the final output by not generating llvm.dbg.cu.
  if (EmitDebugInfo) {
    NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
    NMD->addOperand(CUNode);
  }

  return DICompileUnit(CUNode);
}
Example #18
0
/// Insert all of the named MDNodes in Src into the Dest module.
void IRLinker::linkNamedMDNodes() {
  const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
  for (const NamedMDNode &NMD : SrcM.named_metadata()) {
    // Don't link module flags here. Do them separately.
    if (&NMD == SrcModFlags)
      continue;
    NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
    // Add Src elements into Dest node.
    for (const MDNode *op : NMD.operands())
      DestNMD->addOperand(MapMetadata(
          op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
          &TypeMap, &GValMaterializer));
  }
}
Example #19
0
/// createCompileUnit - A CompileUnit provides an anchor for all debugging
/// information generated during this instance of compilation.
void DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
                                  StringRef Directory, StringRef Producer,
                                  bool isOptimized, StringRef Flags,
                                  unsigned RunTimeVer) {
  assert(((Lang <= dwarf::DW_LANG_Python && Lang >= dwarf::DW_LANG_C89) ||
          (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
         "Invalid Language tag");
  assert(!Filename.empty() &&
         "Unable to create compile unit without filename");
  Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) };
  TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
  Value *THElts[] = { TempEnumTypes };
  MDNode *EnumHolder = MDNode::get(VMContext, THElts);

  TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
  Value *TRElts[] = { TempRetainTypes };
  MDNode *RetainHolder = MDNode::get(VMContext, TRElts);

  TempSubprograms = MDNode::getTemporary(VMContext, TElts);
  Value *TSElts[] = { TempSubprograms };
  MDNode *SPHolder = MDNode::get(VMContext, TSElts);

  TempGVs = MDNode::getTemporary(VMContext, TElts);
  Value *TVElts[] = { TempGVs };
  MDNode *GVHolder = MDNode::get(VMContext, TVElts);

  Value *Elts[] = {
    GetTagConstant(VMContext, dwarf::DW_TAG_compile_unit),
    Constant::getNullValue(Type::getInt32Ty(VMContext)),
    ConstantInt::get(Type::getInt32Ty(VMContext), Lang),
    MDString::get(VMContext, Filename),
    MDString::get(VMContext, Directory),
    MDString::get(VMContext, Producer),
    // Deprecate isMain field.
    ConstantInt::get(Type::getInt1Ty(VMContext), true), // isMain
    ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
    MDString::get(VMContext, Flags),
    ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer),
    EnumHolder,
    RetainHolder,
    SPHolder,
    GVHolder
  };
  TheCU = DICompileUnit(MDNode::get(VMContext, Elts));

  // Create a named metadata so that it is easier to find cu in a module.
  NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
  NMD->addOperand(TheCU);
}
Example #20
0
/// Find the debug info descriptor corresponding to this function.
static Value *findDbgSubprogramDeclare(Function *V) {
  const Module *M = V->getParent();
  NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp");
  if (!NMD)
    return 0;

  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
    DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
    if (!DIG.isSubprogram())
      continue;
    if (DISubprogram(DIG).getFunction() == V)
      return DIG;
  }
  return 0;
}
Example #21
0
/// Find the debug info descriptor corresponding to this global variable.
static Value *findDbgGlobalDeclare(GlobalVariable *V) {
  const Module *M = V->getParent();
  NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
  if (!NMD)
    return 0;

  for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
    DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
    if (!DIG.isGlobalVariable())
      continue;
    if (DIGlobalVariable(DIG).getGlobal() == V)
      return DIG;
  }
  return 0;
}
Example #22
0
  Value *findDbgGlobalDeclare(GlobalVariable *V) {
    const Module *M = V->getParent();
    NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
    if (!NMD)
      return 0;

    for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
      DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
      if (DIG.isNull())
        continue;
      if (DIG.getGlobal() == V)
        return DIG.getNode();
    }
    return 0;
  }
Example #23
0
void Module::convertLibraryListToMetadata() const {
  if (LibraryList.size() == 0)
    return;
  // Get the DepLib node
  NamedMDNode *Node = getNamedMetadata("DepLibs");
  assert(Node && "DepLibs metadata node missing");
  // Erase all existing operands
  Node->dropAllReferences();
  // Add all libraries from the library list
  for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I) {
    MDString *value = MDString::get(getContext(), *I);
    Node->addOperand(MDNode::get(getContext(),
                                 makeArrayRef(static_cast<Value*>(value))));
  }
}
Example #24
0
// @LOCALMOD-BEGIN
void Module::convertMetadataToLibraryList() {
  LibraryList.clear();
  // Get the DepLib node
  NamedMDNode *Node = getNamedMetadata("DepLibs");
  if (!Node)
    return;
  for (unsigned i = 0; i < Node->getNumOperands(); i++) {
    MDString* Mds = dyn_cast_or_null<MDString>(
        Node->getOperand(i)->getOperand(0));
    assert(Mds && "Bad NamedMetadata operand");
    LibraryList.push_back(Mds->getString());
  }
  // Clear the metadata so the linker won't try to merge it
  Node->dropAllReferences();
}
Example #25
0
    CopyConnectedComponent(Module * dest_, Module * src_, llvmutil_Property copyGlobal_, void * data_, ValueToValueMapTy & VMap_)
    : dest(dest_), src(src_), copyGlobal(copyGlobal_), data(data_), VMap(VMap_), DI(NULL) {
        if(NamedMDNode * NMD = src->getNamedMetadata("llvm.module.flags")) {
            NamedMDNode * New = dest->getOrInsertNamedMetadata(NMD->getName());
            for (unsigned i = 0; i < NMD->getNumOperands(); i++) {
                New->addOperand(MapValue(NMD->getOperand(i), VMap));
            }
        }

        if(NamedMDNode * CUN = src->getNamedMetadata("llvm.dbg.cu")) {
            DI = new DIBuilder(*dest);
            DICompileUnit CU(CUN->getOperand(0));
            NCU = DI->createCompileUnit(CU.getLanguage(), CU.getFilename(), CU.getDirectory(), CU.getProducer(), CU.isOptimized(), CU.getFlags(), CU.getRunTimeVersion());
        }
    }
Example #26
0
bool ReduceCrashingNamedMDOps::TestNamedMDOps(
    std::vector<const MDNode *> &NamedMDOps) {
  // Convert list to set for fast lookup...
  SmallPtrSet<const MDNode *, 32> OldMDNodeOps;
  for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) {
    OldMDNodeOps.insert(NamedMDOps[i]);
  }

  outs() << "Checking for crash with only " << OldMDNodeOps.size();
  if (OldMDNodeOps.size() == 1)
    outs() << " named metadata operand: ";
  else
    outs() << " named metadata operands: ";

  ValueToValueMapTy VMap;
  Module *M = CloneModule(BD.getProgram(), VMap).release();

  // This is a little wasteful. In the future it might be good if we could have
  // these dropped during cloning.
  for (auto &NamedMD : BD.getProgram()->named_metadata()) {
    // Drop the old one and create a new one
    M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName()));
    NamedMDNode *NewNamedMDNode =
        M->getOrInsertNamedMetadata(NamedMD.getName());
    for (MDNode *op : NamedMD.operands())
      if (OldMDNodeOps.count(op))
        NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap)));
  }

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

  // Try running on the hacked up program...
  if (TestFn(BD, M)) {
    // Make sure to use instruction pointers that point into the now-current
    // module, and that they don't include any deleted blocks.
    NamedMDOps.clear();
    for (const MDNode *Node : OldMDNodeOps)
      NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node)));

    BD.setNewProgram(M); // It crashed, keep the trimmed version...
    return true;
  }
  delete M; // It didn't crash, try something else.
  return false;
}
Example #27
0
map<string, StateVar*>*  IRParser::parseStateVars(Module* module){
    map<string, StateVar*>* stateVars = new map<string, StateVar*>();

    NamedMDNode* stateVarsMD =  module->getNamedMetadata(IRConstant::KEY_STATE_VARS);

    if (stateVarsMD == NULL) {
        return stateVars;
    }

    for (unsigned i = 0, e = stateVarsMD->getNumOperands(); i != e; ++i) {
        StateVar* var = parseStateVar(stateVarsMD->getOperand(i));
        stateVars->insert(pair<string, StateVar*>(var->getName(), var));
    }

    return stateVars;
}
Example #28
0
list<Action*>* IRParser::parseActions(string key, Module* module){
    list<Action*>* actions = new list<Action*>();

    NamedMDNode* inputsMD =  module->getNamedMetadata(key);

    if (inputsMD == NULL) {
        return actions;
    }

    for (unsigned i = 0, e = inputsMD->getNumOperands(); i != e; ++i) {
        Action* action = parseAction(inputsMD->getOperand(i));
        actions->push_back(action);
    }

    return actions;
}
Example #29
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;
}
Example #30
0
  bool
  SpecializationTable::addSpecialization(Function* parent,
      ConstSpecScheme scheme, Function* specialization, bool record)
  {
    assert(parent != NULL);
    assert(specialization != NULL);

    SpecTable::iterator cursor = this->specialized.find(specialization);
    //Specialization* spec = this->specialized.lookup(specialization->getName());
    if (cursor != this->specialized.end()) {
      return false;
    }

    Specialization* parentSpec = this->getSpecialization(parent);

    Specialization* spec = new Specialization();
    spec->handle = specialization;
    spec->parent = parentSpec;
    spec->args = scheme;
    this->specialized[specialization] = spec;

    //.GetOrCreateValue(specialization->getName(), spec);
    parentSpec->children.push_back(spec);

#if RECORD_IN_METADATA
    // Add the meta-data
    if (record) {
      NamedMDNode* md = this->module->getOrInsertNamedMetadata(
          "previrt::specializations");

      const unsigned int arg_count = parent->getArgumentList().size();
      Value** vals = new Value*[2 + arg_count];
      vals[0] = MDString::get(parent->getContext(), parent->getName());
      vals[1] = MDString::get(parent->getContext(), specialization->getName());
      for (unsigned int i = 0; i < parent->getArgumentList().size(); ++i) {
        vals[i+2] = scheme[i];
      }

      ArrayRef<Value*> ar_vals(vals, vals+2+arg_count);
      MDNode* nde = MDNode::get(this->module->getContext(), ar_vals);

      md->addOperand(nde);
    }
#endif /* RECORD_IN_METADATA */

    return true;
  }