Index: llvm/lib/Analysis/LoopInfo.cpp =================================================================== --- llvm/lib/Analysis/LoopInfo.cpp +++ llvm/lib/Analysis/LoopInfo.cpp @@ -211,24 +211,18 @@ // 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; - + for (BasicBlock *BB : predecessors(H)) { // 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 (!this->contains(BB)) + continue; - if (!LoopID) - LoopID = MD; - else if (MD != LoopID) - return nullptr; + TerminatorInst *TI = BB->getTerminator(); + if (MDNode *MD = TI->getMetadata(LLVMContext::MD_loop)) { + if (!LoopID) + LoopID = MD; + else if (MD != LoopID) // Multiple MD_loop found => corrupt metadata. + return nullptr; + } } } if (!LoopID || LoopID->getNumOperands() == 0 || @@ -248,12 +242,16 @@ } BasicBlock *H = getHeader(); - for (BasicBlock *BB : this->blocks()) { + bool MDSet = false; + for (BasicBlock *BB : predecessors(H)) { + // Check if this terminator branches to the loop header. + if (!this->contains(BB)) + continue; + TerminatorInst *TI = BB->getTerminator(); - for (BasicBlock *Successor : TI->successors()) { - if (Successor == H) - TI->setMetadata(LLVMContext::MD_loop, LoopID); - } + TI->setMetadata(LLVMContext::MD_loop, LoopID); + assert(!MDSet && "Multiple branches to loop header from within loop."); + MDSet = true; } }