Difficulty in Porting cloneLoop in LoopUnswitch

Hi All,

Though the LoopUnswitch pass was not ported to the new pass manager by community, we internally at AMD are in need to do that. While doing this we are facing issues to have a counterpart for the cloneLoop function, the body of which is given below.

Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
LoopInfo *LI, LPPassManager *LPM) {
Loop &New = *LI->AllocateLoop();
if (PL)

if (LPM)

// Add all of the blocks in L to the new loop.
for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
I != E; ++I)
if (LI->getLoopFor(*I) == L)
New.addBasicBlockToLoop(cast(VM[*I]), *LI);

// Add all of the subloops to the new loop.
for (Loop *I : *L)
cloneLoop(I, &New, VM, LI, LPM);

return &New;

In the new pass manager flow, we are trying to use LPMUpdater’s addSiblingLoops in place of addLoop, which will be invoked only for the top level loop (loop to be unswitched). According to the comments given in AddSiblingLoops the loops nested inside will be traversed by the pass manager anyway. In that assumption we are not adding the subloops. With this we are facing assertion failures further.

We also tried capturing all the newly created loops and adding it towards the end of the LoopUnswitch pass, as done in the SimpleLoopUnswitch pass. That also did not help.

Another approach we tried is not to add the cloned loops at all to the pass manager… This worked but not sure about its implications. We might miss further optimization opportunities on these loops.

It would be a great help if someone could point out the right way to go about it.


The new PM’s equivalent of LoopUnswitch is the (not super well named) SimpleLoopUnswitch. Is there something specific that SimpleLoopUnswitch doesn’t handle?

Hi Arthur,

There are significant amounts of code that we added internally to LoopUnswitch. I presume we will be able to move that to SimpleUnswitch, but in the interest of time we thought of porting LoopUnswitch first.


Hi Raghesh,

I have also ported code for partially invariant condition from LoopUnswitch to SimpleLoopUnswitch. https://reviews.llvm.org/D99354 The SimpleLoopUnswitch clones unswitchable path of loop rather than cloning whole loop but the main logic is similar. It could be better to port your code to SimpleLoopUnswitch because the new pass manager is default.


JinGu Kang