1 //===-- SIAnnotateControlFlow.cpp - ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// Annotates the control flow with hardware specific intrinsics. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "AMDGPU.h" 16 #include "llvm/ADT/DepthFirstIterator.h" 17 #include "llvm/Analysis/DivergenceAnalysis.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 25 #include "llvm/Transforms/Utils/SSAUpdater.h" 26 27 using namespace llvm; 28 29 #define DEBUG_TYPE "si-annotate-control-flow" 30 31 namespace { 32 33 // Complex types used in this pass 34 typedef std::pair<BasicBlock *, Value *> StackEntry; 35 typedef SmallVector<StackEntry, 16> StackVector; 36 37 // Intrinsic names the control flow is annotated with 38 static const char *const IfIntrinsic = "llvm.amdgcn.if"; 39 static const char *const ElseIntrinsic = "llvm.amdgcn.else"; 40 static const char *const BreakIntrinsic = "llvm.amdgcn.break"; 41 static const char *const IfBreakIntrinsic = "llvm.amdgcn.if.break"; 42 static const char *const ElseBreakIntrinsic = "llvm.amdgcn.else.break"; 43 static const char *const LoopIntrinsic = "llvm.amdgcn.loop"; 44 static const char *const EndCfIntrinsic = "llvm.amdgcn.end.cf"; 45 46 class SIAnnotateControlFlow : public FunctionPass { 47 DivergenceAnalysis *DA; 48 49 Type *Boolean; 50 Type *Void; 51 Type *Int64; 52 Type *ReturnStruct; 53 54 ConstantInt *BoolTrue; 55 ConstantInt *BoolFalse; 56 UndefValue *BoolUndef; 57 Constant *Int64Zero; 58 59 Constant *If; 60 Constant *Else; 61 Constant *Break; 62 Constant *IfBreak; 63 Constant *ElseBreak; 64 Constant *Loop; 65 Constant *EndCf; 66 67 DominatorTree *DT; 68 StackVector Stack; 69 70 LoopInfo *LI; 71 72 bool isUniform(BranchInst *T); 73 74 bool isTopOfStack(BasicBlock *BB); 75 76 Value *popSaved(); 77 78 void push(BasicBlock *BB, Value *Saved); 79 80 bool isElse(PHINode *Phi); 81 82 void eraseIfUnused(PHINode *Phi); 83 84 void openIf(BranchInst *Term); 85 86 void insertElse(BranchInst *Term); 87 88 Value *handleLoopCondition(Value *Cond, PHINode *Broken, 89 llvm::Loop *L, BranchInst *Term); 90 91 void handleLoop(BranchInst *Term); 92 93 void closeControlFlow(BasicBlock *BB); 94 95 public: 96 static char ID; 97 98 SIAnnotateControlFlow(): 99 FunctionPass(ID) { } 100 101 bool doInitialization(Module &M) override; 102 103 bool runOnFunction(Function &F) override; 104 105 StringRef getPassName() const override { return "SI annotate control flow"; } 106 107 void getAnalysisUsage(AnalysisUsage &AU) const override { 108 AU.addRequired<LoopInfoWrapperPass>(); 109 AU.addRequired<DominatorTreeWrapperPass>(); 110 AU.addRequired<DivergenceAnalysis>(); 111 AU.addPreserved<DominatorTreeWrapperPass>(); 112 FunctionPass::getAnalysisUsage(AU); 113 } 114 115 }; 116 117 } // end anonymous namespace 118 119 INITIALIZE_PASS_BEGIN(SIAnnotateControlFlow, DEBUG_TYPE, 120 "Annotate SI Control Flow", false, false) 121 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 122 INITIALIZE_PASS_DEPENDENCY(DivergenceAnalysis) 123 INITIALIZE_PASS_END(SIAnnotateControlFlow, DEBUG_TYPE, 124 "Annotate SI Control Flow", false, false) 125 126 char SIAnnotateControlFlow::ID = 0; 127 128 /// \brief Initialize all the types and constants used in the pass 129 bool SIAnnotateControlFlow::doInitialization(Module &M) { 130 LLVMContext &Context = M.getContext(); 131 132 Void = Type::getVoidTy(Context); 133 Boolean = Type::getInt1Ty(Context); 134 Int64 = Type::getInt64Ty(Context); 135 ReturnStruct = StructType::get(Boolean, Int64, (Type *)nullptr); 136 137 BoolTrue = ConstantInt::getTrue(Context); 138 BoolFalse = ConstantInt::getFalse(Context); 139 BoolUndef = UndefValue::get(Boolean); 140 Int64Zero = ConstantInt::get(Int64, 0); 141 142 If = M.getOrInsertFunction( 143 IfIntrinsic, ReturnStruct, Boolean, (Type *)nullptr); 144 145 Else = M.getOrInsertFunction( 146 ElseIntrinsic, ReturnStruct, Int64, (Type *)nullptr); 147 148 Break = M.getOrInsertFunction( 149 BreakIntrinsic, Int64, Int64, (Type *)nullptr); 150 cast<Function>(Break)->setDoesNotAccessMemory(); 151 152 IfBreak = M.getOrInsertFunction( 153 IfBreakIntrinsic, Int64, Boolean, Int64, (Type *)nullptr); 154 cast<Function>(IfBreak)->setDoesNotAccessMemory();; 155 156 ElseBreak = M.getOrInsertFunction( 157 ElseBreakIntrinsic, Int64, Int64, Int64, (Type *)nullptr); 158 cast<Function>(ElseBreak)->setDoesNotAccessMemory(); 159 160 Loop = M.getOrInsertFunction( 161 LoopIntrinsic, Boolean, Int64, (Type *)nullptr); 162 163 EndCf = M.getOrInsertFunction( 164 EndCfIntrinsic, Void, Int64, (Type *)nullptr); 165 166 return false; 167 } 168 169 /// \brief Is the branch condition uniform or did the StructurizeCFG pass 170 /// consider it as such? 171 bool SIAnnotateControlFlow::isUniform(BranchInst *T) { 172 return DA->isUniform(T->getCondition()) || 173 T->getMetadata("structurizecfg.uniform") != nullptr; 174 } 175 176 /// \brief Is BB the last block saved on the stack ? 177 bool SIAnnotateControlFlow::isTopOfStack(BasicBlock *BB) { 178 return !Stack.empty() && Stack.back().first == BB; 179 } 180 181 /// \brief Pop the last saved value from the control flow stack 182 Value *SIAnnotateControlFlow::popSaved() { 183 return Stack.pop_back_val().second; 184 } 185 186 /// \brief Push a BB and saved value to the control flow stack 187 void SIAnnotateControlFlow::push(BasicBlock *BB, Value *Saved) { 188 Stack.push_back(std::make_pair(BB, Saved)); 189 } 190 191 /// \brief Can the condition represented by this PHI node treated like 192 /// an "Else" block? 193 bool SIAnnotateControlFlow::isElse(PHINode *Phi) { 194 BasicBlock *IDom = DT->getNode(Phi->getParent())->getIDom()->getBlock(); 195 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 196 if (Phi->getIncomingBlock(i) == IDom) { 197 198 if (Phi->getIncomingValue(i) != BoolTrue) 199 return false; 200 201 } else { 202 if (Phi->getIncomingValue(i) != BoolFalse) 203 return false; 204 205 } 206 } 207 return true; 208 } 209 210 // \brief Erase "Phi" if it is not used any more 211 void SIAnnotateControlFlow::eraseIfUnused(PHINode *Phi) { 212 if (!Phi->hasNUsesOrMore(1)) 213 Phi->eraseFromParent(); 214 } 215 216 /// \brief Open a new "If" block 217 void SIAnnotateControlFlow::openIf(BranchInst *Term) { 218 if (isUniform(Term)) { 219 return; 220 } 221 Value *Ret = CallInst::Create(If, Term->getCondition(), "", Term); 222 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term)); 223 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term)); 224 } 225 226 /// \brief Close the last "If" block and open a new "Else" block 227 void SIAnnotateControlFlow::insertElse(BranchInst *Term) { 228 if (isUniform(Term)) { 229 return; 230 } 231 Value *Ret = CallInst::Create(Else, popSaved(), "", Term); 232 Term->setCondition(ExtractValueInst::Create(Ret, 0, "", Term)); 233 push(Term->getSuccessor(1), ExtractValueInst::Create(Ret, 1, "", Term)); 234 } 235 236 /// \brief Recursively handle the condition leading to a loop 237 Value *SIAnnotateControlFlow::handleLoopCondition(Value *Cond, PHINode *Broken, 238 llvm::Loop *L, BranchInst *Term) { 239 240 // Only search through PHI nodes which are inside the loop. If we try this 241 // with PHI nodes that are outside of the loop, we end up inserting new PHI 242 // nodes outside of the loop which depend on values defined inside the loop. 243 // This will break the module with 244 // 'Instruction does not dominate all users!' errors. 245 PHINode *Phi = nullptr; 246 if ((Phi = dyn_cast<PHINode>(Cond)) && L->contains(Phi)) { 247 248 BasicBlock *Parent = Phi->getParent(); 249 PHINode *NewPhi = PHINode::Create(Int64, 0, "", &Parent->front()); 250 Value *Ret = NewPhi; 251 252 // Handle all non-constant incoming values first 253 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 254 Value *Incoming = Phi->getIncomingValue(i); 255 BasicBlock *From = Phi->getIncomingBlock(i); 256 if (isa<ConstantInt>(Incoming)) { 257 NewPhi->addIncoming(Broken, From); 258 continue; 259 } 260 261 Phi->setIncomingValue(i, BoolFalse); 262 Value *PhiArg = handleLoopCondition(Incoming, Broken, L, Term); 263 NewPhi->addIncoming(PhiArg, From); 264 } 265 266 BasicBlock *IDom = DT->getNode(Parent)->getIDom()->getBlock(); 267 268 for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) { 269 270 Value *Incoming = Phi->getIncomingValue(i); 271 if (Incoming != BoolTrue) 272 continue; 273 274 BasicBlock *From = Phi->getIncomingBlock(i); 275 if (From == IDom) { 276 // We're in the following situation: 277 // IDom/From 278 // | \ 279 // | If-block 280 // | / 281 // Parent 282 // where we want to break out of the loop if the If-block is not taken. 283 // Due to the depth-first traversal, there should be an end.cf 284 // intrinsic in Parent, and we insert an else.break before it. 285 // 286 // Note that the end.cf need not be the first non-phi instruction 287 // of parent, particularly when we're dealing with a multi-level 288 // break, but it should occur within a group of intrinsic calls 289 // at the beginning of the block. 290 CallInst *OldEnd = dyn_cast<CallInst>(Parent->getFirstInsertionPt()); 291 while (OldEnd && OldEnd->getCalledFunction() != EndCf) 292 OldEnd = dyn_cast<CallInst>(OldEnd->getNextNode()); 293 if (OldEnd && OldEnd->getCalledFunction() == EndCf) { 294 Value *Args[] = { OldEnd->getArgOperand(0), NewPhi }; 295 Ret = CallInst::Create(ElseBreak, Args, "", OldEnd); 296 continue; 297 } 298 } 299 TerminatorInst *Insert = From->getTerminator(); 300 Value *PhiArg = CallInst::Create(Break, Broken, "", Insert); 301 NewPhi->setIncomingValue(i, PhiArg); 302 } 303 eraseIfUnused(Phi); 304 return Ret; 305 306 } else if (Instruction *Inst = dyn_cast<Instruction>(Cond)) { 307 BasicBlock *Parent = Inst->getParent(); 308 Instruction *Insert; 309 if (L->contains(Inst)) { 310 Insert = Parent->getTerminator(); 311 } else { 312 Insert = L->getHeader()->getFirstNonPHIOrDbgOrLifetime(); 313 } 314 Value *Args[] = { Cond, Broken }; 315 return CallInst::Create(IfBreak, Args, "", Insert); 316 317 // Insert IfBreak before TERM for constant COND. 318 } else if (isa<ConstantInt>(Cond)) { 319 Value *Args[] = { Cond, Broken }; 320 return CallInst::Create(IfBreak, Args, "", Term); 321 322 } else { 323 llvm_unreachable("Unhandled loop condition!"); 324 } 325 return nullptr; 326 } 327 328 /// \brief Handle a back edge (loop) 329 void SIAnnotateControlFlow::handleLoop(BranchInst *Term) { 330 if (isUniform(Term)) { 331 return; 332 } 333 334 BasicBlock *BB = Term->getParent(); 335 llvm::Loop *L = LI->getLoopFor(BB); 336 if (!L) 337 return; 338 BasicBlock *Target = Term->getSuccessor(1); 339 PHINode *Broken = PHINode::Create(Int64, 0, "", &Target->front()); 340 341 Value *Cond = Term->getCondition(); 342 Term->setCondition(BoolTrue); 343 Value *Arg = handleLoopCondition(Cond, Broken, L, Term); 344 345 for (pred_iterator PI = pred_begin(Target), PE = pred_end(Target); 346 PI != PE; ++PI) { 347 348 Broken->addIncoming(*PI == BB ? Arg : Int64Zero, *PI); 349 } 350 351 Term->setCondition(CallInst::Create(Loop, Arg, "", Term)); 352 push(Term->getSuccessor(0), Arg); 353 }/// \brief Close the last opened control flow 354 void SIAnnotateControlFlow::closeControlFlow(BasicBlock *BB) { 355 llvm::Loop *L = LI->getLoopFor(BB); 356 357 assert(Stack.back().first == BB); 358 359 if (L && L->getHeader() == BB) { 360 // We can't insert an EndCF call into a loop header, because it will 361 // get executed on every iteration of the loop, when it should be 362 // executed only once before the loop. 363 SmallVector <BasicBlock*, 8> Latches; 364 L->getLoopLatches(Latches); 365 366 std::vector<BasicBlock*> Preds; 367 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { 368 if (!is_contained(Latches, *PI)) 369 Preds.push_back(*PI); 370 } 371 BB = llvm::SplitBlockPredecessors(BB, Preds, "endcf.split", DT, LI, false); 372 } 373 374 Value *Exec = popSaved(); 375 if (!isa<UndefValue>(Exec)) 376 CallInst::Create(EndCf, Exec, "", &*BB->getFirstInsertionPt()); 377 } 378 379 /// \brief Annotate the control flow with intrinsics so the backend can 380 /// recognize if/then/else and loops. 381 bool SIAnnotateControlFlow::runOnFunction(Function &F) { 382 383 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 384 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 385 DA = &getAnalysis<DivergenceAnalysis>(); 386 387 for (df_iterator<BasicBlock *> I = df_begin(&F.getEntryBlock()), 388 E = df_end(&F.getEntryBlock()); I != E; ++I) { 389 390 BranchInst *Term = dyn_cast<BranchInst>((*I)->getTerminator()); 391 392 if (!Term || Term->isUnconditional()) { 393 if (isTopOfStack(*I)) 394 closeControlFlow(*I); 395 396 continue; 397 } 398 399 if (I.nodeVisited(Term->getSuccessor(1))) { 400 if (isTopOfStack(*I)) 401 closeControlFlow(*I); 402 403 handleLoop(Term); 404 continue; 405 } 406 407 if (isTopOfStack(*I)) { 408 PHINode *Phi = dyn_cast<PHINode>(Term->getCondition()); 409 if (Phi && Phi->getParent() == *I && isElse(Phi)) { 410 insertElse(Term); 411 eraseIfUnused(Phi); 412 continue; 413 } 414 closeControlFlow(*I); 415 } 416 openIf(Term); 417 } 418 419 assert(Stack.empty()); 420 return true; 421 } 422 423 /// \brief Create the annotation pass 424 FunctionPass *llvm::createSIAnnotateControlFlowPass() { 425 return new SIAnnotateControlFlow(); 426 } 427