/// \brief Find string metadata for loop /// /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an /// operand or null otherwise. If the string metadata is not found return /// Optional's not-a-value. Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop, StringRef Name) { MDNode *LoopID = TheLoop->getLoopID(); // Return none if LoopID is false. if (!LoopID) return None; // First operand should refer to the loop id itself. assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); // Iterate over LoopID operands and look for MDString Metadata for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (!MD) continue; MDString *S = dyn_cast<MDString>(MD->getOperand(0)); if (!S) continue; // Return true if MDString holds expected MetaData. if (Name.equals(S->getString())) switch (MD->getNumOperands()) { case 1: return nullptr; case 2: return &MD->getOperand(1); default: llvm_unreachable("loop metadata has 0 or 1 operand"); } } return None; }
/// parseMetadata - Parse metadata from the module void LTOModule::parseMetadata() { // Linker Options if (Metadata *Val = getModule().getModuleFlag("Linker Options")) { MDNode *LinkerOptions = cast<MDNode>(Val); for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); // FIXME: Make StringSet::insert match Self-Associative Container // requirements, returning <iter,bool> rather than bool, and use that // here. StringRef Op = _linkeropt_strings.insert(MDOption->getString()).first->first(); StringRef DepLibName = _target->getSubtargetImpl() ->getTargetLowering() ->getObjFileLowering() .getDepLibFromLinkerOpt(Op); if (!DepLibName.empty()) _deplibs.push_back(DepLibName.data()); else if (!Op.empty()) _linkeropts.push_back(Op.data()); } } } // Add other interesting metadata here. }
/// parseMetadata - Parse metadata from the module void LTOModule::parseMetadata() { raw_string_ostream OS(LinkerOpts); // Linker Options if (Metadata *Val = getModule().getModuleFlag("Linker Options")) { MDNode *LinkerOptions = cast<MDNode>(Val); for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); OS << " " << MDOption->getString(); } } } // Globals Mangler Mang; for (const NameAndAttributes &Sym : _symbols) { if (!Sym.symbol) continue; _target->getObjFileLowering()->emitLinkerFlagsForGlobal(OS, Sym.symbol, Mang); } // Add other interesting metadata here. }
void TargetLoweringObjectFileCOFF:: emitModuleFlags(MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags, Mangler &Mang, const TargetMachine &TM) const { MDNode *LinkerOptions = nullptr; // Look for the "Linker Options" flag, since it's the only one we support. for (ArrayRef<Module::ModuleFlagEntry>::iterator i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { const Module::ModuleFlagEntry &MFE = *i; StringRef Key = MFE.Key->getString(); Metadata *Val = MFE.Val; if (Key == "Linker Options") { LinkerOptions = cast<MDNode>(Val); break; } } if (!LinkerOptions) return; // Emit the linker options to the linker .drectve section. According to the // spec, this section is a space-separated string containing flags for linker. const MCSection *Sec = getDrectveSection(); Streamer.SwitchSection(Sec); for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); // Lead with a space for consistency with our dllexport implementation. std::string Directive(" "); Directive.append(MDOption->getString()); Streamer.EmitBytes(Directive); } } }
// Propagate existing explicit probabilities from either profile data or // 'expect' intrinsic processing. bool BranchProbabilityAnalysis::calcMetadataWeights(BasicBlock *BB) { TerminatorInst *TI = BB->getTerminator(); if (TI->getNumSuccessors() == 1) return false; if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) return false; MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); if (!WeightsNode) return false; // Ensure there are weights for all of the successors. Note that the first // operand to the metadata node is a name, not a weight. if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1) return false; // Build up the final weights that will be used in a temporary buffer, but // don't add them until all weihts are present. Each weight value is clamped // to [1, getMaxWeightFor(BB)]. uint32_t WeightLimit = getMaxWeightFor(BB); SmallVector<uint32_t, 2> Weights; Weights.reserve(TI->getNumSuccessors()); for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) { ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i)); if (!Weight) return false; Weights.push_back( std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit))); } assert(Weights.size() == TI->getNumSuccessors() && "Checked above"); for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) BP->setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]); return true; }
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) { if (!A || !B) return NULL; if (A == B) return A; SmallVector<MDNode *, 4> PathA; MDNode *T = A; while (T) { PathA.push_back(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0; } SmallVector<MDNode *, 4> PathB; T = B; while (T) { PathB.push_back(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0; } int IA = PathA.size() - 1; int IB = PathB.size() - 1; MDNode *Ret = 0; while (IA >= 0 && IB >=0) { if (PathA[IA] == PathB[IB]) Ret = PathA[IA]; else break; --IA; --IB; } return Ret; }
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) { if (!A || !B) return nullptr; if (A == B) return A; // For struct-path aware TBAA, we use the access type of the tag. bool StructPath = isStructPathTBAA(A) && isStructPathTBAA(B); if (StructPath) { A = cast_or_null<MDNode>(A->getOperand(1)); if (!A) return nullptr; B = cast_or_null<MDNode>(B->getOperand(1)); if (!B) return nullptr; } SmallSetVector<MDNode *, 4> PathA; MDNode *T = A; while (T) { if (PathA.count(T)) report_fatal_error("Cycle found in TBAA metadata."); PathA.insert(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : nullptr; } SmallSetVector<MDNode *, 4> PathB; T = B; while (T) { if (PathB.count(T)) report_fatal_error("Cycle found in TBAA metadata."); PathB.insert(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : nullptr; } int IA = PathA.size() - 1; int IB = PathB.size() - 1; MDNode *Ret = nullptr; while (IA >= 0 && IB >=0) { if (PathA[IA] == PathB[IB]) Ret = PathA[IA]; else break; --IA; --IB; } if (!StructPath) return Ret; if (!Ret) return nullptr; // We need to convert from a type node to a tag node. Type *Int64 = IntegerType::get(A->getContext(), 64); Metadata *Ops[3] = {Ret, Ret, ConstantAsMetadata::get(ConstantInt::get(Int64, 0))}; return MDNode::get(A->getContext(), Ops); }
// Propagate existing explicit probabilities from either profile data or // 'expect' intrinsic processing. bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) { TerminatorInst *TI = BB->getTerminator(); if (TI->getNumSuccessors() == 1) return false; if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) return false; MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof); if (!WeightsNode) return false; // Check that the number of successors is manageable. assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors"); // Ensure there are weights for all of the successors. Note that the first // operand to the metadata node is a name, not a weight. if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1) return false; // Build up the final weights that will be used in a temporary buffer. // Compute the sum of all weights to later decide whether they need to // be scaled to fit in 32 bits. uint64_t WeightSum = 0; SmallVector<uint32_t, 2> Weights; Weights.reserve(TI->getNumSuccessors()); for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) { ConstantInt *Weight = mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i)); if (!Weight) return false; assert(Weight->getValue().getActiveBits() <= 32 && "Too many bits for uint32_t"); Weights.push_back(Weight->getZExtValue()); WeightSum += Weights.back(); } assert(Weights.size() == TI->getNumSuccessors() && "Checked above"); // If the sum of weights does not fit in 32 bits, scale every weight down // accordingly. uint64_t ScalingFactor = (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1; WeightSum = 0; for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) { uint32_t W = Weights[i] / ScalingFactor; WeightSum += W; setEdgeWeight(BB, i, W); } assert(WeightSum <= UINT32_MAX && "Expected weights to scale down to 32 bits"); return true; }
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 */ }
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) { if (!A || !B) return NULL; if (A == B) return A; // For struct-path aware TBAA, we use the access type of the tag. bool StructPath = isStructPathTBAA(A); if (StructPath) { A = cast_or_null<MDNode>(A->getOperand(1)); if (!A) return 0; B = cast_or_null<MDNode>(B->getOperand(1)); if (!B) return 0; } SmallVector<MDNode *, 4> PathA; MDNode *T = A; while (T) { PathA.push_back(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0; } SmallVector<MDNode *, 4> PathB; T = B; while (T) { PathB.push_back(T); T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0; } int IA = PathA.size() - 1; int IB = PathB.size() - 1; MDNode *Ret = 0; while (IA >= 0 && IB >=0) { if (PathA[IA] == PathB[IB]) Ret = PathA[IA]; else break; --IA; --IB; } if (!StructPath) return Ret; if (!Ret) return 0; // We need to convert from a type node to a tag node. Type *Int64 = IntegerType::get(A->getContext(), 64); Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) }; return MDNode::get(A->getContext(), Ops); }
Action* IRParser::getAction(llvm::MDNode* node) { Value* idValue = node->getOperand(0); if (idValue == NULL){ map<Function*, Action*>::iterator it; // Action has not tag, find it by its function name Function* function = getBodyFunction(node); it = untaggedActions.find(function); return it->second; } //Get identifiers of action tag map<std::string, Action*>::iterator it; ActionTag tag; MDNode* idNode = cast<MDNode>(idValue); for (unsigned i = 0, e = idNode->getNumOperands(); i != e; ++i){ MDString* tagMD = cast<MDString>(idNode->getOperand(i)); tag.add(tagMD->getString()); } it = actions.find(tag.getIdentifier()); return it->second; }
MDNode *Loop::getLoopID() const { MDNode *LoopID = nullptr; if (isLoopSimplifyForm()) { LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName); } else { // Go through each predecessor of the loop header and check the // terminator for the metadata. BasicBlock *H = getHeader(); for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) { TerminatorInst *TI = (*I)->getTerminator(); MDNode *MD = nullptr; // Check if this terminator branches to the loop header. for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) { if (TI->getSuccessor(i) == H) { MD = TI->getMetadata(LoopMDName); break; } } if (!MD) return nullptr; if (!LoopID) LoopID = MD; else if (MD != LoopID) return nullptr; } } if (!LoopID || LoopID->getNumOperands() == 0 || LoopID->getOperand(0) != LoopID) return nullptr; return LoopID; }
MDNode *Loop::getLoopID() const { MDNode *LoopID = nullptr; if (isLoopSimplifyForm()) { LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop); } else { // Go through each predecessor of the loop header and check the // terminator for the metadata. BasicBlock *H = getHeader(); for (BasicBlock *BB : this->blocks()) { TerminatorInst *TI = BB->getTerminator(); MDNode *MD = nullptr; // Check if this terminator branches to the loop header. for (BasicBlock *Successor : TI->successors()) { if (Successor == H) { MD = TI->getMetadata(LLVMContext::MD_loop); break; } } if (!MD) return nullptr; if (!LoopID) LoopID = MD; else if (MD != LoopID) return nullptr; } } if (!LoopID || LoopID->getNumOperands() == 0 || LoopID->getOperand(0) != LoopID) return nullptr; return LoopID; }
/// parseMetadata - Parse metadata from the module void LTOModule::parseMetadata() { raw_string_ostream OS(LinkerOpts); // Linker Options if (NamedMDNode *LinkerOptions = getModule().getNamedMetadata("llvm.linker.options")) { for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { MDNode *MDOptions = LinkerOptions->getOperand(i); for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); OS << " " << MDOption->getString(); } } } // Globals - we only need to do this for COFF. const Triple TT(_target->getTargetTriple()); if (!TT.isOSBinFormatCOFF()) return; Mangler M; for (const NameAndAttributes &Sym : _symbols) { if (!Sym.symbol) continue; emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M); } // Add other interesting metadata here. }
/// Remap the operands of an MDNode. /// /// If \c Node is temporary, uniquing cycles are ignored. If \c Node is /// distinct, uniquing cycles are resolved as they're found. /// /// \pre \c Node.isDistinct() or \c Node.isTemporary(). static bool remapOperands(MDNode &Node, SmallVectorImpl<MDNode *> &DistinctWorklist, ValueToValueMapTy &VM, RemapFlags Flags, ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer) { assert(!Node.isUniqued() && "Expected temporary or distinct node"); const bool IsDistinct = Node.isDistinct(); bool AnyChanged = false; for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) { Metadata *Old = Node.getOperand(I); Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper, Materializer); if (Old != New) { AnyChanged = true; Node.replaceOperandWith(I, New); // Resolve uniquing cycles underneath distinct nodes on the fly so they // don't infect later operands. if (IsDistinct) resolveCycles(New); } } return AnyChanged; }
// Remove existing unroll metadata and add unroll disable metadata to // indicate the loop has already been unrolled. This prevents a loop // from being unrolled more than is directed by a pragma if the loop // unrolling pass is run more than once (which it generally is). static void SetLoopAlreadyUnrolled(Loop *L) { MDNode *LoopID = L->getLoopID(); if (!LoopID) return; // First remove any existing loop unrolling metadata. SmallVector<Metadata *, 4> MDs; // Reserve first location for self reference to the LoopID metadata node. MDs.push_back(nullptr); for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { bool IsUnrollMetadata = false; MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (MD) { const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); } if (!IsUnrollMetadata) MDs.push_back(LoopID->getOperand(i)); } // Add unroll(disable) metadata to disable future unrolling. LLVMContext &Context = L->getHeader()->getContext(); SmallVector<Metadata *, 1> DisableOperands; DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); MDNode *DisableNode = MDNode::get(Context, DisableOperands); MDs.push_back(DisableNode); MDNode *NewLoopID = MDNode::get(Context, MDs); // Set operand 0 to refer to the loop id itself. NewLoopID->replaceOperandWith(0, NewLoopID); L->setLoopID(NewLoopID); }
MDNode *llvm::findOptionMDForLoopID(MDNode *LoopID, StringRef Name) { // No loop metadata node, no loop properties. if (!LoopID) return nullptr; // First operand should refer to the metadata node itself, for legacy reasons. assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); // Iterate over the metdata node operands and look for MDString metadata. for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); if (!MD || MD->getNumOperands() < 1) continue; MDString *S = dyn_cast<MDString>(MD->getOperand(0)); if (!S) continue; // Return the operand node if MDString holds expected metadata. if (Name.equals(S->getString())) return MD; } // Loop property not found. return nullptr; }
std::string GCOVProfiler::mangleName(const DICompileUnit *CU, const char *NewStem) { if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) { for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) { MDNode *N = GCov->getOperand(i); if (N->getNumOperands() != 2) continue; MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0)); MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1)); if (!GCovFile || !CompileUnit) continue; if (CompileUnit == CU) { SmallString<128> Filename = GCovFile->getString(); sys::path::replace_extension(Filename, NewStem); return Filename.str(); } } } SmallString<128> Filename = CU->getFilename(); sys::path::replace_extension(Filename, NewStem); StringRef FName = sys::path::filename(Filename); SmallString<128> CurPath; if (sys::fs::current_path(CurPath)) return FName; sys::path::append(CurPath, FName); return CurPath.str(); }
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); }
void TargetLoweringObjectFileCOFF:: emitModuleFlags(MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags, Mangler &Mang, const TargetMachine &TM) const { MDNode *LinkerOptions = nullptr; // Look for the "Linker Options" flag, since it's the only one we support. for (ArrayRef<Module::ModuleFlagEntry>::iterator i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) { const Module::ModuleFlagEntry &MFE = *i; StringRef Key = MFE.Key->getString(); Value *Val = MFE.Val; if (Key == "Linker Options") { LinkerOptions = cast<MDNode>(Val); break; } } if (!LinkerOptions) return; // Emit the linker options to the linker .drectve section. According to the // spec, this section is a space-separated string containing flags for linker. const MCSection *Sec = getDrectveSection(); Streamer.SwitchSection(Sec); for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); StringRef Op = MDOption->getString(); // Lead with a space for consistency with our dllexport implementation. std::string Escaped(" "); if (Op.find(" ") != StringRef::npos) { // The PE-COFF spec says args with spaces must be quoted. It doesn't say // how to escape quotes, but it probably uses this algorithm: // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx // FIXME: Reuse escaping code from Support/Windows/Program.inc Escaped.push_back('\"'); Escaped.append(Op); Escaped.push_back('\"'); } else { Escaped.append(Op); } Streamer.EmitBytes(Escaped); } } }
FSM* IRParser::parseFSM(llvm::MDNode* node){ FSM* fsm = new FSM(); //Parse initial state MDString* initialState = cast<MDString>(node->getOperand(0)); //Parse all fsm state MDNode* stateArray = cast<MDNode>(node->getOperand(1)); for (unsigned i = 0, e = stateArray->getNumOperands(); i != e; ++i){ MDString* stateMD = cast<MDString>(stateArray->getOperand(i)); fsm->addState(stateMD->getString()); } // set the initial state after initializing the states fsm->setInitialState(initialState->getString()); //Parse transition MDNode* transitionsArray = cast<MDNode>(node->getOperand(2)); for (unsigned i = 0, e = transitionsArray->getNumOperands(); i != e; ++i){ MDNode* transitionArray = cast<MDNode>(transitionsArray->getOperand(i)); MDString* source = cast<MDString>(transitionArray->getOperand(0)); Value* targetValue = transitionArray->getOperand(1); //In case of "undefined" state, no target are given if (targetValue != NULL){ MDNode* targetsArray = cast<MDNode>(targetValue); for (unsigned j = 0, f = targetsArray->getNumOperands() ; j != f; ++j){ MDNode* targetArray = cast<MDNode>(targetsArray->getOperand(j)); Action* action = getAction(cast<MDNode>(targetArray->getOperand(0))); MDString* target = cast<MDString>(targetArray->getOperand(1)); fsm->addTransition(source->getString(), target->getString(), action); } } } return fsm; }
/// categorizeModuleFlagNodes - bool ModuleLinker:: categorizeModuleFlagNodes(const NamedMDNode *ModFlags, DenseMap<MDString*, MDNode*> &ErrorNode, DenseMap<MDString*, MDNode*> &WarningNode, DenseMap<MDString*, MDNode*> &OverrideNode, DenseMap<MDString*, SmallSetVector<MDNode*, 8> > &RequireNodes, SmallSetVector<MDString*, 16> &SeenIDs) { bool HasErr = false; for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) { MDNode *Op = ModFlags->getOperand(I); assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!"); assert(isa<ConstantInt>(Op->getOperand(0)) && "Module flag's first operand must be an integer!"); assert(isa<MDString>(Op->getOperand(1)) && "Module flag's second operand must be an MDString!"); ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); MDString *ID = cast<MDString>(Op->getOperand(1)); Value *Val = Op->getOperand(2); switch (Behavior->getZExtValue()) { default: assert(false && "Invalid behavior in module flag metadata!"); break; case Module::Error: { MDNode *&ErrNode = ErrorNode[ID]; if (!ErrNode) ErrNode = Op; if (ErrNode->getOperand(2) != Val) HasErr = emitError("linking module flags '" + ID->getString() + "': IDs have conflicting values"); break; } case Module::Warning: { MDNode *&WarnNode = WarningNode[ID]; if (!WarnNode) WarnNode = Op; if (WarnNode->getOperand(2) != Val) errs() << "WARNING: linking module flags '" << ID->getString() << "': IDs have conflicting values"; break; } case Module::Require: RequireNodes[ID].insert(Op); break; case Module::Override: { MDNode *&OvrNode = OverrideNode[ID]; if (!OvrNode) OvrNode = Op; if (OvrNode->getOperand(2) != Val) HasErr = emitError("linking module flags '" + ID->getString() + "': IDs have conflicting override values"); break; } } SeenIDs.insert(ID); } return HasErr; }
unsigned IDManager::getInstructionID(const Instruction *I) const { MDNode *Node = I->getMetadata("ins_id"); if (!Node) return INVALID_ID; assert(Node->getNumOperands() == 1); ConstantInt *CI = dyn_cast<ConstantInt>(Node->getOperand(0)); assert(CI); return CI->getZExtValue(); }
unsigned getMetadataNumOperands(llvm::Instruction* i, std::string mKind) { MDNode* mdn = i->getMetadata(mKind); if(mdn) { return mdn->getNumOperands(); } assert(false && "getMetadataOperand: No metadata with that kind"); }
void ScopAnnotator::annotateLoopLatch(BranchInst *B, Loop *L, bool IsParallel) const { if (!IsParallel) return; assert(!ParallelLoops.empty() && "Expected a parallel loop to annotate"); MDNode *Ids = ParallelLoops.back(); MDNode *Id = cast<MDNode>(Ids->getOperand(Ids->getNumOperands() - 1)); B->setMetadata("llvm.loop", Id); }
void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) { assert(!N.isUniqued() && "Expected distinct or temporary nodes"); for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) { Metadata *Old = N.getOperand(I); Metadata *New = mapOperand(Old); if (Old != New) N.replaceOperandWith(I, New); } }
std::string GCOVProfiler::mangleName(const DICompileUnit *CU, GCovFileType OutputType) { bool Notes = OutputType == GCovFileType::GCNO; if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) { for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) { MDNode *N = GCov->getOperand(i); bool ThreeElement = N->getNumOperands() == 3; if (!ThreeElement && N->getNumOperands() != 2) continue; if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU) continue; if (ThreeElement) { // These nodes have no mangling to apply, it's stored mangled in the // bitcode. MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0)); MDString *DataFile = dyn_cast<MDString>(N->getOperand(1)); if (!NotesFile || !DataFile) continue; return Notes ? NotesFile->getString() : DataFile->getString(); } MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0)); if (!GCovFile) continue; SmallString<128> Filename = GCovFile->getString(); sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda"); return Filename.str(); } } SmallString<128> Filename = CU->getFilename(); sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda"); StringRef FName = sys::path::filename(Filename); SmallString<128> CurPath; if (sys::fs::current_path(CurPath)) return FName; sys::path::append(CurPath, FName); return CurPath.str(); }
// If loop has an unroll_count pragma return the (necessarily // positive) value from the pragma. Otherwise return 0. static unsigned UnrollCountPragmaValue(const Loop *L) { MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); if (MD) { assert(MD->getNumOperands() == 2 && "Unroll count hint metadata should have two operands."); unsigned Count = mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); assert(Count >= 1 && "Unroll count must be positive."); return Count; } return 0; }
ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) { const unsigned NumRanges = Ranges.getNumOperands() / 2; assert(NumRanges >= 1 && "Must have at least one range!"); assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs"); auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0)); auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1)); ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue()); for (unsigned i = 1; i < NumRanges; ++i) { auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0)); auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1)); // Note: unionWith will potentially create a range that contains values not // contained in any of the original N ranges. CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue())); } return CR; }
static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty, unsigned FlagsToSet) { SmallVector<Value *, 9> Elts; MDNode *N = Ty; assert(N && "Unexpected input DIType!"); // Update header field. Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context)); for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I) Elts.push_back(N->getOperand(I)); return DIType(MDNode::get(Context, Elts)); }