1 //===- OpenMPIRBuilder.cpp - Builder for LLVM-IR for OpenMP directives ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This file implements the OpenMPIRBuilder class, which is used as a
11 /// convenient way to create LLVM instructions for OpenMP directives.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
16 
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/MDBuilder.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/CodeExtractor.h"
27 
28 #include <sstream>
29 
30 #define DEBUG_TYPE "openmp-ir-builder"
31 
32 using namespace llvm;
33 using namespace omp;
34 
35 static cl::opt<bool>
36     OptimisticAttributes("openmp-ir-builder-optimistic-attributes", cl::Hidden,
37                          cl::desc("Use optimistic attributes describing "
38                                   "'as-if' properties of runtime calls."),
39                          cl::init(false));
40 
41 void OpenMPIRBuilder::addAttributes(omp::RuntimeFunction FnID, Function &Fn) {
42   LLVMContext &Ctx = Fn.getContext();
43 
44   // Get the function's current attributes.
45   auto Attrs = Fn.getAttributes();
46   auto FnAttrs = Attrs.getFnAttributes();
47   auto RetAttrs = Attrs.getRetAttributes();
48   SmallVector<AttributeSet, 4> ArgAttrs;
49   for (size_t ArgNo = 0; ArgNo < Fn.arg_size(); ++ArgNo)
50     ArgAttrs.emplace_back(Attrs.getParamAttributes(ArgNo));
51 
52 #define OMP_ATTRS_SET(VarName, AttrSet) AttributeSet VarName = AttrSet;
53 #include "llvm/Frontend/OpenMP/OMPKinds.def"
54 
55   // Add attributes to the function declaration.
56   switch (FnID) {
57 #define OMP_RTL_ATTRS(Enum, FnAttrSet, RetAttrSet, ArgAttrSets)                \
58   case Enum:                                                                   \
59     FnAttrs = FnAttrs.addAttributes(Ctx, FnAttrSet);                           \
60     RetAttrs = RetAttrs.addAttributes(Ctx, RetAttrSet);                        \
61     for (size_t ArgNo = 0; ArgNo < ArgAttrSets.size(); ++ArgNo)                \
62       ArgAttrs[ArgNo] =                                                        \
63           ArgAttrs[ArgNo].addAttributes(Ctx, ArgAttrSets[ArgNo]);              \
64     Fn.setAttributes(AttributeList::get(Ctx, FnAttrs, RetAttrs, ArgAttrs));    \
65     break;
66 #include "llvm/Frontend/OpenMP/OMPKinds.def"
67   default:
68     // Attributes are optional.
69     break;
70   }
71 }
72 
73 FunctionCallee
74 OpenMPIRBuilder::getOrCreateRuntimeFunction(Module &M, RuntimeFunction FnID) {
75   FunctionType *FnTy = nullptr;
76   Function *Fn = nullptr;
77 
78   // Try to find the declation in the module first.
79   switch (FnID) {
80 #define OMP_RTL(Enum, Str, IsVarArg, ReturnType, ...)                          \
81   case Enum:                                                                   \
82     FnTy = FunctionType::get(ReturnType, ArrayRef<Type *>{__VA_ARGS__},        \
83                              IsVarArg);                                        \
84     Fn = M.getFunction(Str);                                                   \
85     break;
86 #include "llvm/Frontend/OpenMP/OMPKinds.def"
87   }
88 
89   if (!Fn) {
90     // Create a new declaration if we need one.
91     switch (FnID) {
92 #define OMP_RTL(Enum, Str, ...)                                                \
93   case Enum:                                                                   \
94     Fn = Function::Create(FnTy, GlobalValue::ExternalLinkage, Str, M);         \
95     break;
96 #include "llvm/Frontend/OpenMP/OMPKinds.def"
97     }
98 
99     // Add information if the runtime function takes a callback function
100     if (FnID == OMPRTL___kmpc_fork_call || FnID == OMPRTL___kmpc_fork_teams) {
101       if (!Fn->hasMetadata(LLVMContext::MD_callback)) {
102         LLVMContext &Ctx = Fn->getContext();
103         MDBuilder MDB(Ctx);
104         // Annotate the callback behavior of the runtime function:
105         //  - The callback callee is argument number 2 (microtask).
106         //  - The first two arguments of the callback callee are unknown (-1).
107         //  - All variadic arguments to the runtime function are passed to the
108         //    callback callee.
109         Fn->addMetadata(
110             LLVMContext::MD_callback,
111             *MDNode::get(Ctx, {MDB.createCallbackEncoding(
112                                   2, {-1, -1}, /* VarArgsArePassed */ true)}));
113       }
114     }
115 
116     LLVM_DEBUG(dbgs() << "Created OpenMP runtime function " << Fn->getName()
117                       << " with type " << *Fn->getFunctionType() << "\n");
118     addAttributes(FnID, *Fn);
119 
120   } else {
121     LLVM_DEBUG(dbgs() << "Found OpenMP runtime function " << Fn->getName()
122                       << " with type " << *Fn->getFunctionType() << "\n");
123   }
124 
125   assert(Fn && "Failed to create OpenMP runtime function");
126 
127   // Cast the function to the expected type if necessary
128   Constant *C = ConstantExpr::getBitCast(Fn, FnTy->getPointerTo());
129   return {FnTy, C};
130 }
131 
132 Function *OpenMPIRBuilder::getOrCreateRuntimeFunctionPtr(RuntimeFunction FnID) {
133   FunctionCallee RTLFn = getOrCreateRuntimeFunction(M, FnID);
134   auto *Fn = dyn_cast<llvm::Function>(RTLFn.getCallee());
135   assert(Fn && "Failed to create OpenMP runtime function pointer");
136   return Fn;
137 }
138 
139 void OpenMPIRBuilder::initialize() { initializeTypes(M); }
140 
141 void OpenMPIRBuilder::finalize(Function *Fn, bool AllowExtractorSinking) {
142   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
143   SmallVector<BasicBlock *, 32> Blocks;
144   SmallVector<OutlineInfo, 16> DeferredOutlines;
145   for (OutlineInfo &OI : OutlineInfos) {
146     // Skip functions that have not finalized yet; may happen with nested
147     // function generation.
148     if (Fn && OI.getFunction() != Fn) {
149       DeferredOutlines.push_back(OI);
150       continue;
151     }
152 
153     ParallelRegionBlockSet.clear();
154     Blocks.clear();
155     OI.collectBlocks(ParallelRegionBlockSet, Blocks);
156 
157     Function *OuterFn = OI.getFunction();
158     CodeExtractorAnalysisCache CEAC(*OuterFn);
159     CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
160                             /* AggregateArgs */ false,
161                             /* BlockFrequencyInfo */ nullptr,
162                             /* BranchProbabilityInfo */ nullptr,
163                             /* AssumptionCache */ nullptr,
164                             /* AllowVarArgs */ true,
165                             /* AllowAlloca */ true,
166                             /* Suffix */ ".omp_par");
167 
168     LLVM_DEBUG(dbgs() << "Before     outlining: " << *OuterFn << "\n");
169     LLVM_DEBUG(dbgs() << "Entry " << OI.EntryBB->getName()
170                       << " Exit: " << OI.ExitBB->getName() << "\n");
171     assert(Extractor.isEligible() &&
172            "Expected OpenMP outlining to be possible!");
173 
174     Function *OutlinedFn = Extractor.extractCodeRegion(CEAC);
175 
176     LLVM_DEBUG(dbgs() << "After      outlining: " << *OuterFn << "\n");
177     LLVM_DEBUG(dbgs() << "   Outlined function: " << *OutlinedFn << "\n");
178     assert(OutlinedFn->getReturnType()->isVoidTy() &&
179            "OpenMP outlined functions should not return a value!");
180 
181     // For compability with the clang CG we move the outlined function after the
182     // one with the parallel region.
183     OutlinedFn->removeFromParent();
184     M.getFunctionList().insertAfter(OuterFn->getIterator(), OutlinedFn);
185 
186     // Remove the artificial entry introduced by the extractor right away, we
187     // made our own entry block after all.
188     {
189       BasicBlock &ArtificialEntry = OutlinedFn->getEntryBlock();
190       assert(ArtificialEntry.getUniqueSuccessor() == OI.EntryBB);
191       assert(OI.EntryBB->getUniquePredecessor() == &ArtificialEntry);
192       if (AllowExtractorSinking) {
193         // Move instructions from the to-be-deleted ArtificialEntry to the entry
194         // basic block of the parallel region. CodeExtractor may have sunk
195         // allocas/bitcasts for values that are solely used in the outlined
196         // region and do not escape.
197         assert(!ArtificialEntry.empty() &&
198                "Expected instructions to sink in the outlined region");
199         for (BasicBlock::iterator It = ArtificialEntry.begin(),
200                                   End = ArtificialEntry.end();
201              It != End;) {
202           Instruction &I = *It;
203           It++;
204 
205           if (I.isTerminator())
206             continue;
207 
208           I.moveBefore(*OI.EntryBB, OI.EntryBB->getFirstInsertionPt());
209         }
210       }
211       OI.EntryBB->moveBefore(&ArtificialEntry);
212       ArtificialEntry.eraseFromParent();
213     }
214     assert(&OutlinedFn->getEntryBlock() == OI.EntryBB);
215     assert(OutlinedFn && OutlinedFn->getNumUses() == 1);
216 
217     // Run a user callback, e.g. to add attributes.
218     if (OI.PostOutlineCB)
219       OI.PostOutlineCB(*OutlinedFn);
220   }
221 
222   // Remove work items that have been completed.
223   OutlineInfos = std::move(DeferredOutlines);
224 }
225 
226 OpenMPIRBuilder::~OpenMPIRBuilder() {
227   assert(OutlineInfos.empty() && "There must be no outstanding outlinings");
228 }
229 
230 Value *OpenMPIRBuilder::getOrCreateIdent(Constant *SrcLocStr,
231                                          IdentFlag LocFlags,
232                                          unsigned Reserve2Flags) {
233   // Enable "C-mode".
234   LocFlags |= OMP_IDENT_FLAG_KMPC;
235 
236   Value *&Ident =
237       IdentMap[{SrcLocStr, uint64_t(LocFlags) << 31 | Reserve2Flags}];
238   if (!Ident) {
239     Constant *I32Null = ConstantInt::getNullValue(Int32);
240     Constant *IdentData[] = {
241         I32Null, ConstantInt::get(Int32, uint32_t(LocFlags)),
242         ConstantInt::get(Int32, Reserve2Flags), I32Null, SrcLocStr};
243     Constant *Initializer = ConstantStruct::get(
244         cast<StructType>(IdentPtr->getPointerElementType()), IdentData);
245 
246     // Look for existing encoding of the location + flags, not needed but
247     // minimizes the difference to the existing solution while we transition.
248     for (GlobalVariable &GV : M.getGlobalList())
249       if (GV.getType() == IdentPtr && GV.hasInitializer())
250         if (GV.getInitializer() == Initializer)
251           return Ident = &GV;
252 
253     auto *GV = new GlobalVariable(M, IdentPtr->getPointerElementType(),
254                                   /* isConstant = */ true,
255                                   GlobalValue::PrivateLinkage, Initializer);
256     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
257     GV->setAlignment(Align(8));
258     Ident = GV;
259   }
260   return Builder.CreatePointerCast(Ident, IdentPtr);
261 }
262 
263 Type *OpenMPIRBuilder::getLanemaskType() {
264   LLVMContext &Ctx = M.getContext();
265   Triple triple(M.getTargetTriple());
266 
267   // This test is adequate until deviceRTL has finer grained lane widths
268   return triple.isAMDGCN() ? Type::getInt64Ty(Ctx) : Type::getInt32Ty(Ctx);
269 }
270 
271 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef LocStr) {
272   Constant *&SrcLocStr = SrcLocStrMap[LocStr];
273   if (!SrcLocStr) {
274     Constant *Initializer =
275         ConstantDataArray::getString(M.getContext(), LocStr);
276 
277     // Look for existing encoding of the location, not needed but minimizes the
278     // difference to the existing solution while we transition.
279     for (GlobalVariable &GV : M.getGlobalList())
280       if (GV.isConstant() && GV.hasInitializer() &&
281           GV.getInitializer() == Initializer)
282         return SrcLocStr = ConstantExpr::getPointerCast(&GV, Int8Ptr);
283 
284     SrcLocStr = Builder.CreateGlobalStringPtr(LocStr, /* Name */ "",
285                                               /* AddressSpace */ 0, &M);
286   }
287   return SrcLocStr;
288 }
289 
290 Constant *OpenMPIRBuilder::getOrCreateSrcLocStr(StringRef FunctionName,
291                                                 StringRef FileName,
292                                                 unsigned Line,
293                                                 unsigned Column) {
294   SmallString<128> Buffer;
295   Buffer.push_back(';');
296   Buffer.append(FileName);
297   Buffer.push_back(';');
298   Buffer.append(FunctionName);
299   Buffer.push_back(';');
300   Buffer.append(std::to_string(Line));
301   Buffer.push_back(';');
302   Buffer.append(std::to_string(Column));
303   Buffer.push_back(';');
304   Buffer.push_back(';');
305   return getOrCreateSrcLocStr(Buffer.str());
306 }
307 
308 Constant *OpenMPIRBuilder::getOrCreateDefaultSrcLocStr() {
309   return getOrCreateSrcLocStr(";unknown;unknown;0;0;;");
310 }
311 
312 Constant *
313 OpenMPIRBuilder::getOrCreateSrcLocStr(const LocationDescription &Loc) {
314   DILocation *DIL = Loc.DL.get();
315   if (!DIL)
316     return getOrCreateDefaultSrcLocStr();
317   StringRef FileName = M.getName();
318   if (DIFile *DIF = DIL->getFile())
319     if (Optional<StringRef> Source = DIF->getSource())
320       FileName = *Source;
321   StringRef Function = DIL->getScope()->getSubprogram()->getName();
322   Function =
323       !Function.empty() ? Function : Loc.IP.getBlock()->getParent()->getName();
324   return getOrCreateSrcLocStr(Function, FileName, DIL->getLine(),
325                               DIL->getColumn());
326 }
327 
328 Value *OpenMPIRBuilder::getOrCreateThreadID(Value *Ident) {
329   return Builder.CreateCall(
330       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num), Ident,
331       "omp_global_thread_num");
332 }
333 
334 OpenMPIRBuilder::InsertPointTy
335 OpenMPIRBuilder::createBarrier(const LocationDescription &Loc, Directive DK,
336                                bool ForceSimpleCall, bool CheckCancelFlag) {
337   if (!updateToLocation(Loc))
338     return Loc.IP;
339   return emitBarrierImpl(Loc, DK, ForceSimpleCall, CheckCancelFlag);
340 }
341 
342 OpenMPIRBuilder::InsertPointTy
343 OpenMPIRBuilder::emitBarrierImpl(const LocationDescription &Loc, Directive Kind,
344                                  bool ForceSimpleCall, bool CheckCancelFlag) {
345   // Build call __kmpc_cancel_barrier(loc, thread_id) or
346   //            __kmpc_barrier(loc, thread_id);
347 
348   IdentFlag BarrierLocFlags;
349   switch (Kind) {
350   case OMPD_for:
351     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_FOR;
352     break;
353   case OMPD_sections:
354     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SECTIONS;
355     break;
356   case OMPD_single:
357     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL_SINGLE;
358     break;
359   case OMPD_barrier:
360     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_EXPL;
361     break;
362   default:
363     BarrierLocFlags = OMP_IDENT_FLAG_BARRIER_IMPL;
364     break;
365   }
366 
367   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
368   Value *Args[] = {getOrCreateIdent(SrcLocStr, BarrierLocFlags),
369                    getOrCreateThreadID(getOrCreateIdent(SrcLocStr))};
370 
371   // If we are in a cancellable parallel region, barriers are cancellation
372   // points.
373   // TODO: Check why we would force simple calls or to ignore the cancel flag.
374   bool UseCancelBarrier =
375       !ForceSimpleCall && isLastFinalizationInfoCancellable(OMPD_parallel);
376 
377   Value *Result =
378       Builder.CreateCall(getOrCreateRuntimeFunctionPtr(
379                              UseCancelBarrier ? OMPRTL___kmpc_cancel_barrier
380                                               : OMPRTL___kmpc_barrier),
381                          Args);
382 
383   if (UseCancelBarrier && CheckCancelFlag)
384     emitCancelationCheckImpl(Result, OMPD_parallel);
385 
386   return Builder.saveIP();
387 }
388 
389 OpenMPIRBuilder::InsertPointTy
390 OpenMPIRBuilder::createCancel(const LocationDescription &Loc,
391                               Value *IfCondition,
392                               omp::Directive CanceledDirective) {
393   if (!updateToLocation(Loc))
394     return Loc.IP;
395 
396   // LLVM utilities like blocks with terminators.
397   auto *UI = Builder.CreateUnreachable();
398 
399   Instruction *ThenTI = UI, *ElseTI = nullptr;
400   if (IfCondition)
401     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
402   Builder.SetInsertPoint(ThenTI);
403 
404   Value *CancelKind = nullptr;
405   switch (CanceledDirective) {
406 #define OMP_CANCEL_KIND(Enum, Str, DirectiveEnum, Value)                       \
407   case DirectiveEnum:                                                          \
408     CancelKind = Builder.getInt32(Value);                                      \
409     break;
410 #include "llvm/Frontend/OpenMP/OMPKinds.def"
411   default:
412     llvm_unreachable("Unknown cancel kind!");
413   }
414 
415   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
416   Value *Ident = getOrCreateIdent(SrcLocStr);
417   Value *Args[] = {Ident, getOrCreateThreadID(Ident), CancelKind};
418   Value *Result = Builder.CreateCall(
419       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_cancel), Args);
420 
421   // The actual cancel logic is shared with others, e.g., cancel_barriers.
422   emitCancelationCheckImpl(Result, CanceledDirective);
423 
424   // Update the insertion point and remove the terminator we introduced.
425   Builder.SetInsertPoint(UI->getParent());
426   UI->eraseFromParent();
427 
428   return Builder.saveIP();
429 }
430 
431 void OpenMPIRBuilder::emitCancelationCheckImpl(
432     Value *CancelFlag, omp::Directive CanceledDirective) {
433   assert(isLastFinalizationInfoCancellable(CanceledDirective) &&
434          "Unexpected cancellation!");
435 
436   // For a cancel barrier we create two new blocks.
437   BasicBlock *BB = Builder.GetInsertBlock();
438   BasicBlock *NonCancellationBlock;
439   if (Builder.GetInsertPoint() == BB->end()) {
440     // TODO: This branch will not be needed once we moved to the
441     // OpenMPIRBuilder codegen completely.
442     NonCancellationBlock = BasicBlock::Create(
443         BB->getContext(), BB->getName() + ".cont", BB->getParent());
444   } else {
445     NonCancellationBlock = SplitBlock(BB, &*Builder.GetInsertPoint());
446     BB->getTerminator()->eraseFromParent();
447     Builder.SetInsertPoint(BB);
448   }
449   BasicBlock *CancellationBlock = BasicBlock::Create(
450       BB->getContext(), BB->getName() + ".cncl", BB->getParent());
451 
452   // Jump to them based on the return value.
453   Value *Cmp = Builder.CreateIsNull(CancelFlag);
454   Builder.CreateCondBr(Cmp, NonCancellationBlock, CancellationBlock,
455                        /* TODO weight */ nullptr, nullptr);
456 
457   // From the cancellation block we finalize all variables and go to the
458   // post finalization block that is known to the FiniCB callback.
459   Builder.SetInsertPoint(CancellationBlock);
460   auto &FI = FinalizationStack.back();
461   FI.FiniCB(Builder.saveIP());
462 
463   // The continuation block is where code generation continues.
464   Builder.SetInsertPoint(NonCancellationBlock, NonCancellationBlock->begin());
465 }
466 
467 IRBuilder<>::InsertPoint OpenMPIRBuilder::createParallel(
468     const LocationDescription &Loc, InsertPointTy OuterAllocaIP,
469     BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
470     FinalizeCallbackTy FiniCB, Value *IfCondition, Value *NumThreads,
471     omp::ProcBindKind ProcBind, bool IsCancellable) {
472   if (!updateToLocation(Loc))
473     return Loc.IP;
474 
475   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
476   Value *Ident = getOrCreateIdent(SrcLocStr);
477   Value *ThreadID = getOrCreateThreadID(Ident);
478 
479   if (NumThreads) {
480     // Build call __kmpc_push_num_threads(&Ident, global_tid, num_threads)
481     Value *Args[] = {
482         Ident, ThreadID,
483         Builder.CreateIntCast(NumThreads, Int32, /*isSigned*/ false)};
484     Builder.CreateCall(
485         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_num_threads), Args);
486   }
487 
488   if (ProcBind != OMP_PROC_BIND_default) {
489     // Build call __kmpc_push_proc_bind(&Ident, global_tid, proc_bind)
490     Value *Args[] = {
491         Ident, ThreadID,
492         ConstantInt::get(Int32, unsigned(ProcBind), /*isSigned=*/true)};
493     Builder.CreateCall(
494         getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_push_proc_bind), Args);
495   }
496 
497   BasicBlock *InsertBB = Builder.GetInsertBlock();
498   Function *OuterFn = InsertBB->getParent();
499 
500   // Save the outer alloca block because the insertion iterator may get
501   // invalidated and we still need this later.
502   BasicBlock *OuterAllocaBlock = OuterAllocaIP.getBlock();
503 
504   // Vector to remember instructions we used only during the modeling but which
505   // we want to delete at the end.
506   SmallVector<Instruction *, 4> ToBeDeleted;
507 
508   // Change the location to the outer alloca insertion point to create and
509   // initialize the allocas we pass into the parallel region.
510   Builder.restoreIP(OuterAllocaIP);
511   AllocaInst *TIDAddr = Builder.CreateAlloca(Int32, nullptr, "tid.addr");
512   AllocaInst *ZeroAddr = Builder.CreateAlloca(Int32, nullptr, "zero.addr");
513 
514   // If there is an if condition we actually use the TIDAddr and ZeroAddr in the
515   // program, otherwise we only need them for modeling purposes to get the
516   // associated arguments in the outlined function. In the former case,
517   // initialize the allocas properly, in the latter case, delete them later.
518   if (IfCondition) {
519     Builder.CreateStore(Constant::getNullValue(Int32), TIDAddr);
520     Builder.CreateStore(Constant::getNullValue(Int32), ZeroAddr);
521   } else {
522     ToBeDeleted.push_back(TIDAddr);
523     ToBeDeleted.push_back(ZeroAddr);
524   }
525 
526   // Create an artificial insertion point that will also ensure the blocks we
527   // are about to split are not degenerated.
528   auto *UI = new UnreachableInst(Builder.getContext(), InsertBB);
529 
530   Instruction *ThenTI = UI, *ElseTI = nullptr;
531   if (IfCondition)
532     SplitBlockAndInsertIfThenElse(IfCondition, UI, &ThenTI, &ElseTI);
533 
534   BasicBlock *ThenBB = ThenTI->getParent();
535   BasicBlock *PRegEntryBB = ThenBB->splitBasicBlock(ThenTI, "omp.par.entry");
536   BasicBlock *PRegBodyBB =
537       PRegEntryBB->splitBasicBlock(ThenTI, "omp.par.region");
538   BasicBlock *PRegPreFiniBB =
539       PRegBodyBB->splitBasicBlock(ThenTI, "omp.par.pre_finalize");
540   BasicBlock *PRegExitBB =
541       PRegPreFiniBB->splitBasicBlock(ThenTI, "omp.par.exit");
542 
543   auto FiniCBWrapper = [&](InsertPointTy IP) {
544     // Hide "open-ended" blocks from the given FiniCB by setting the right jump
545     // target to the region exit block.
546     if (IP.getBlock()->end() == IP.getPoint()) {
547       IRBuilder<>::InsertPointGuard IPG(Builder);
548       Builder.restoreIP(IP);
549       Instruction *I = Builder.CreateBr(PRegExitBB);
550       IP = InsertPointTy(I->getParent(), I->getIterator());
551     }
552     assert(IP.getBlock()->getTerminator()->getNumSuccessors() == 1 &&
553            IP.getBlock()->getTerminator()->getSuccessor(0) == PRegExitBB &&
554            "Unexpected insertion point for finalization call!");
555     return FiniCB(IP);
556   };
557 
558   FinalizationStack.push_back({FiniCBWrapper, OMPD_parallel, IsCancellable});
559 
560   // Generate the privatization allocas in the block that will become the entry
561   // of the outlined function.
562   Builder.SetInsertPoint(PRegEntryBB->getTerminator());
563   InsertPointTy InnerAllocaIP = Builder.saveIP();
564 
565   AllocaInst *PrivTIDAddr =
566       Builder.CreateAlloca(Int32, nullptr, "tid.addr.local");
567   Instruction *PrivTID = Builder.CreateLoad(Int32, PrivTIDAddr, "tid");
568 
569   // Add some fake uses for OpenMP provided arguments.
570   ToBeDeleted.push_back(Builder.CreateLoad(Int32, TIDAddr, "tid.addr.use"));
571   Instruction *ZeroAddrUse = Builder.CreateLoad(Int32, ZeroAddr,
572                                                 "zero.addr.use");
573   ToBeDeleted.push_back(ZeroAddrUse);
574 
575   // ThenBB
576   //   |
577   //   V
578   // PRegionEntryBB         <- Privatization allocas are placed here.
579   //   |
580   //   V
581   // PRegionBodyBB          <- BodeGen is invoked here.
582   //   |
583   //   V
584   // PRegPreFiniBB          <- The block we will start finalization from.
585   //   |
586   //   V
587   // PRegionExitBB          <- A common exit to simplify block collection.
588   //
589 
590   LLVM_DEBUG(dbgs() << "Before body codegen: " << *OuterFn << "\n");
591 
592   // Let the caller create the body.
593   assert(BodyGenCB && "Expected body generation callback!");
594   InsertPointTy CodeGenIP(PRegBodyBB, PRegBodyBB->begin());
595   BodyGenCB(InnerAllocaIP, CodeGenIP, *PRegPreFiniBB);
596 
597   LLVM_DEBUG(dbgs() << "After  body codegen: " << *OuterFn << "\n");
598 
599   FunctionCallee RTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_fork_call);
600   if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
601     if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
602       llvm::LLVMContext &Ctx = F->getContext();
603       MDBuilder MDB(Ctx);
604       // Annotate the callback behavior of the __kmpc_fork_call:
605       //  - The callback callee is argument number 2 (microtask).
606       //  - The first two arguments of the callback callee are unknown (-1).
607       //  - All variadic arguments to the __kmpc_fork_call are passed to the
608       //    callback callee.
609       F->addMetadata(
610           llvm::LLVMContext::MD_callback,
611           *llvm::MDNode::get(
612               Ctx, {MDB.createCallbackEncoding(2, {-1, -1},
613                                                /* VarArgsArePassed */ true)}));
614     }
615   }
616 
617   OutlineInfo OI;
618   OI.PostOutlineCB = [=](Function &OutlinedFn) {
619     // Add some known attributes.
620     OutlinedFn.addParamAttr(0, Attribute::NoAlias);
621     OutlinedFn.addParamAttr(1, Attribute::NoAlias);
622     OutlinedFn.addFnAttr(Attribute::NoUnwind);
623     OutlinedFn.addFnAttr(Attribute::NoRecurse);
624 
625     assert(OutlinedFn.arg_size() >= 2 &&
626            "Expected at least tid and bounded tid as arguments");
627     unsigned NumCapturedVars =
628         OutlinedFn.arg_size() - /* tid & bounded tid */ 2;
629 
630     CallInst *CI = cast<CallInst>(OutlinedFn.user_back());
631     CI->getParent()->setName("omp_parallel");
632     Builder.SetInsertPoint(CI);
633 
634     // Build call __kmpc_fork_call(Ident, n, microtask, var1, .., varn);
635     Value *ForkCallArgs[] = {
636         Ident, Builder.getInt32(NumCapturedVars),
637         Builder.CreateBitCast(&OutlinedFn, ParallelTaskPtr)};
638 
639     SmallVector<Value *, 16> RealArgs;
640     RealArgs.append(std::begin(ForkCallArgs), std::end(ForkCallArgs));
641     RealArgs.append(CI->arg_begin() + /* tid & bound tid */ 2, CI->arg_end());
642 
643     Builder.CreateCall(RTLFn, RealArgs);
644 
645     LLVM_DEBUG(dbgs() << "With fork_call placed: "
646                       << *Builder.GetInsertBlock()->getParent() << "\n");
647 
648     InsertPointTy ExitIP(PRegExitBB, PRegExitBB->end());
649 
650     // Initialize the local TID stack location with the argument value.
651     Builder.SetInsertPoint(PrivTID);
652     Function::arg_iterator OutlinedAI = OutlinedFn.arg_begin();
653     Builder.CreateStore(Builder.CreateLoad(Int32, OutlinedAI), PrivTIDAddr);
654 
655     // If no "if" clause was present we do not need the call created during
656     // outlining, otherwise we reuse it in the serialized parallel region.
657     if (!ElseTI) {
658       CI->eraseFromParent();
659     } else {
660 
661       // If an "if" clause was present we are now generating the serialized
662       // version into the "else" branch.
663       Builder.SetInsertPoint(ElseTI);
664 
665       // Build calls __kmpc_serialized_parallel(&Ident, GTid);
666       Value *SerializedParallelCallArgs[] = {Ident, ThreadID};
667       Builder.CreateCall(
668           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_serialized_parallel),
669           SerializedParallelCallArgs);
670 
671       // OutlinedFn(&GTid, &zero, CapturedStruct);
672       CI->removeFromParent();
673       Builder.Insert(CI);
674 
675       // __kmpc_end_serialized_parallel(&Ident, GTid);
676       Value *EndArgs[] = {Ident, ThreadID};
677       Builder.CreateCall(
678           getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_serialized_parallel),
679           EndArgs);
680 
681       LLVM_DEBUG(dbgs() << "With serialized parallel region: "
682                         << *Builder.GetInsertBlock()->getParent() << "\n");
683     }
684 
685     for (Instruction *I : ToBeDeleted)
686       I->eraseFromParent();
687   };
688 
689   // Adjust the finalization stack, verify the adjustment, and call the
690   // finalize function a last time to finalize values between the pre-fini
691   // block and the exit block if we left the parallel "the normal way".
692   auto FiniInfo = FinalizationStack.pop_back_val();
693   (void)FiniInfo;
694   assert(FiniInfo.DK == OMPD_parallel &&
695          "Unexpected finalization stack state!");
696 
697   Instruction *PRegPreFiniTI = PRegPreFiniBB->getTerminator();
698 
699   InsertPointTy PreFiniIP(PRegPreFiniBB, PRegPreFiniTI->getIterator());
700   FiniCB(PreFiniIP);
701 
702   OI.EntryBB = PRegEntryBB;
703   OI.ExitBB = PRegExitBB;
704 
705   SmallPtrSet<BasicBlock *, 32> ParallelRegionBlockSet;
706   SmallVector<BasicBlock *, 32> Blocks;
707   OI.collectBlocks(ParallelRegionBlockSet, Blocks);
708 
709   // Ensure a single exit node for the outlined region by creating one.
710   // We might have multiple incoming edges to the exit now due to finalizations,
711   // e.g., cancel calls that cause the control flow to leave the region.
712   BasicBlock *PRegOutlinedExitBB = PRegExitBB;
713   PRegExitBB = SplitBlock(PRegExitBB, &*PRegExitBB->getFirstInsertionPt());
714   PRegOutlinedExitBB->setName("omp.par.outlined.exit");
715   Blocks.push_back(PRegOutlinedExitBB);
716 
717   CodeExtractorAnalysisCache CEAC(*OuterFn);
718   CodeExtractor Extractor(Blocks, /* DominatorTree */ nullptr,
719                           /* AggregateArgs */ false,
720                           /* BlockFrequencyInfo */ nullptr,
721                           /* BranchProbabilityInfo */ nullptr,
722                           /* AssumptionCache */ nullptr,
723                           /* AllowVarArgs */ true,
724                           /* AllowAlloca */ true,
725                           /* Suffix */ ".omp_par");
726 
727   // Find inputs to, outputs from the code region.
728   BasicBlock *CommonExit = nullptr;
729   SetVector<Value *> Inputs, Outputs, SinkingCands, HoistingCands;
730   Extractor.findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
731   Extractor.findInputsOutputs(Inputs, Outputs, SinkingCands);
732 
733   LLVM_DEBUG(dbgs() << "Before privatization: " << *OuterFn << "\n");
734 
735   FunctionCallee TIDRTLFn =
736       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_global_thread_num);
737 
738   auto PrivHelper = [&](Value &V) {
739     if (&V == TIDAddr || &V == ZeroAddr)
740       return;
741 
742     SetVector<Use *> Uses;
743     for (Use &U : V.uses())
744       if (auto *UserI = dyn_cast<Instruction>(U.getUser()))
745         if (ParallelRegionBlockSet.count(UserI->getParent()))
746           Uses.insert(&U);
747 
748     // __kmpc_fork_call expects extra arguments as pointers. If the input
749     // already has a pointer type, everything is fine. Otherwise, store the
750     // value onto stack and load it back inside the to-be-outlined region. This
751     // will ensure only the pointer will be passed to the function.
752     // FIXME: if there are more than 15 trailing arguments, they must be
753     // additionally packed in a struct.
754     Value *Inner = &V;
755     if (!V.getType()->isPointerTy()) {
756       IRBuilder<>::InsertPointGuard Guard(Builder);
757       LLVM_DEBUG(llvm::dbgs() << "Forwarding input as pointer: " << V << "\n");
758 
759       Builder.restoreIP(OuterAllocaIP);
760       Value *Ptr =
761           Builder.CreateAlloca(V.getType(), nullptr, V.getName() + ".reloaded");
762 
763       // Store to stack at end of the block that currently branches to the entry
764       // block of the to-be-outlined region.
765       Builder.SetInsertPoint(InsertBB,
766                              InsertBB->getTerminator()->getIterator());
767       Builder.CreateStore(&V, Ptr);
768 
769       // Load back next to allocations in the to-be-outlined region.
770       Builder.restoreIP(InnerAllocaIP);
771       Inner = Builder.CreateLoad(V.getType(), Ptr);
772     }
773 
774     Value *ReplacementValue = nullptr;
775     CallInst *CI = dyn_cast<CallInst>(&V);
776     if (CI && CI->getCalledFunction() == TIDRTLFn.getCallee()) {
777       ReplacementValue = PrivTID;
778     } else {
779       Builder.restoreIP(
780           PrivCB(InnerAllocaIP, Builder.saveIP(), V, *Inner, ReplacementValue));
781       assert(ReplacementValue &&
782              "Expected copy/create callback to set replacement value!");
783       if (ReplacementValue == &V)
784         return;
785     }
786 
787     for (Use *UPtr : Uses)
788       UPtr->set(ReplacementValue);
789   };
790 
791   // Reset the inner alloca insertion as it will be used for loading the values
792   // wrapped into pointers before passing them into the to-be-outlined region.
793   // Configure it to insert immediately after the fake use of zero address so
794   // that they are available in the generated body and so that the
795   // OpenMP-related values (thread ID and zero address pointers) remain leading
796   // in the argument list.
797   InnerAllocaIP = IRBuilder<>::InsertPoint(
798       ZeroAddrUse->getParent(), ZeroAddrUse->getNextNode()->getIterator());
799 
800   // Reset the outer alloca insertion point to the entry of the relevant block
801   // in case it was invalidated.
802   OuterAllocaIP = IRBuilder<>::InsertPoint(
803       OuterAllocaBlock, OuterAllocaBlock->getFirstInsertionPt());
804 
805   for (Value *Input : Inputs) {
806     LLVM_DEBUG(dbgs() << "Captured input: " << *Input << "\n");
807     PrivHelper(*Input);
808   }
809   LLVM_DEBUG({
810     for (Value *Output : Outputs)
811       LLVM_DEBUG(dbgs() << "Captured output: " << *Output << "\n");
812   });
813   assert(Outputs.empty() &&
814          "OpenMP outlining should not produce live-out values!");
815 
816   LLVM_DEBUG(dbgs() << "After  privatization: " << *OuterFn << "\n");
817   LLVM_DEBUG({
818     for (auto *BB : Blocks)
819       dbgs() << " PBR: " << BB->getName() << "\n";
820   });
821 
822   // Register the outlined info.
823   addOutlineInfo(std::move(OI));
824 
825   InsertPointTy AfterIP(UI->getParent(), UI->getParent()->end());
826   UI->eraseFromParent();
827 
828   return AfterIP;
829 }
830 
831 void OpenMPIRBuilder::emitFlush(const LocationDescription &Loc) {
832   // Build call void __kmpc_flush(ident_t *loc)
833   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
834   Value *Args[] = {getOrCreateIdent(SrcLocStr)};
835 
836   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_flush), Args);
837 }
838 
839 void OpenMPIRBuilder::createFlush(const LocationDescription &Loc) {
840   if (!updateToLocation(Loc))
841     return;
842   emitFlush(Loc);
843 }
844 
845 void OpenMPIRBuilder::emitTaskwaitImpl(const LocationDescription &Loc) {
846   // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
847   // global_tid);
848   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
849   Value *Ident = getOrCreateIdent(SrcLocStr);
850   Value *Args[] = {Ident, getOrCreateThreadID(Ident)};
851 
852   // Ignore return result until untied tasks are supported.
853   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskwait),
854                      Args);
855 }
856 
857 void OpenMPIRBuilder::createTaskwait(const LocationDescription &Loc) {
858   if (!updateToLocation(Loc))
859     return;
860   emitTaskwaitImpl(Loc);
861 }
862 
863 void OpenMPIRBuilder::emitTaskyieldImpl(const LocationDescription &Loc) {
864   // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
865   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
866   Value *Ident = getOrCreateIdent(SrcLocStr);
867   Constant *I32Null = ConstantInt::getNullValue(Int32);
868   Value *Args[] = {Ident, getOrCreateThreadID(Ident), I32Null};
869 
870   Builder.CreateCall(getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_omp_taskyield),
871                      Args);
872 }
873 
874 void OpenMPIRBuilder::createTaskyield(const LocationDescription &Loc) {
875   if (!updateToLocation(Loc))
876     return;
877   emitTaskyieldImpl(Loc);
878 }
879 
880 OpenMPIRBuilder::InsertPointTy
881 OpenMPIRBuilder::createMaster(const LocationDescription &Loc,
882                               BodyGenCallbackTy BodyGenCB,
883                               FinalizeCallbackTy FiniCB) {
884 
885   if (!updateToLocation(Loc))
886     return Loc.IP;
887 
888   Directive OMPD = Directive::OMPD_master;
889   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
890   Value *Ident = getOrCreateIdent(SrcLocStr);
891   Value *ThreadId = getOrCreateThreadID(Ident);
892   Value *Args[] = {Ident, ThreadId};
893 
894   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_master);
895   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
896 
897   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_master);
898   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
899 
900   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
901                               /*Conditional*/ true, /*hasFinalize*/ true);
902 }
903 
904 OpenMPIRBuilder::InsertPointTy
905 OpenMPIRBuilder::createMasked(const LocationDescription &Loc,
906                               BodyGenCallbackTy BodyGenCB,
907                               FinalizeCallbackTy FiniCB, Value *Filter) {
908   if (!updateToLocation(Loc))
909     return Loc.IP;
910 
911   Directive OMPD = Directive::OMPD_masked;
912   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
913   Value *Ident = getOrCreateIdent(SrcLocStr);
914   Value *ThreadId = getOrCreateThreadID(Ident);
915   Value *Args[] = {Ident, ThreadId, Filter};
916   Value *ArgsEnd[] = {Ident, ThreadId};
917 
918   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_masked);
919   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
920 
921   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_masked);
922   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, ArgsEnd);
923 
924   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
925                               /*Conditional*/ true, /*hasFinalize*/ true);
926 }
927 
928 CanonicalLoopInfo *OpenMPIRBuilder::createLoopSkeleton(
929     DebugLoc DL, Value *TripCount, Function *F, BasicBlock *PreInsertBefore,
930     BasicBlock *PostInsertBefore, const Twine &Name) {
931   Module *M = F->getParent();
932   LLVMContext &Ctx = M->getContext();
933   Type *IndVarTy = TripCount->getType();
934 
935   // Create the basic block structure.
936   BasicBlock *Preheader =
937       BasicBlock::Create(Ctx, "omp_" + Name + ".preheader", F, PreInsertBefore);
938   BasicBlock *Header =
939       BasicBlock::Create(Ctx, "omp_" + Name + ".header", F, PreInsertBefore);
940   BasicBlock *Cond =
941       BasicBlock::Create(Ctx, "omp_" + Name + ".cond", F, PreInsertBefore);
942   BasicBlock *Body =
943       BasicBlock::Create(Ctx, "omp_" + Name + ".body", F, PreInsertBefore);
944   BasicBlock *Latch =
945       BasicBlock::Create(Ctx, "omp_" + Name + ".inc", F, PostInsertBefore);
946   BasicBlock *Exit =
947       BasicBlock::Create(Ctx, "omp_" + Name + ".exit", F, PostInsertBefore);
948   BasicBlock *After =
949       BasicBlock::Create(Ctx, "omp_" + Name + ".after", F, PostInsertBefore);
950 
951   // Use specified DebugLoc for new instructions.
952   Builder.SetCurrentDebugLocation(DL);
953 
954   Builder.SetInsertPoint(Preheader);
955   Builder.CreateBr(Header);
956 
957   Builder.SetInsertPoint(Header);
958   PHINode *IndVarPHI = Builder.CreatePHI(IndVarTy, 2, "omp_" + Name + ".iv");
959   IndVarPHI->addIncoming(ConstantInt::get(IndVarTy, 0), Preheader);
960   Builder.CreateBr(Cond);
961 
962   Builder.SetInsertPoint(Cond);
963   Value *Cmp =
964       Builder.CreateICmpULT(IndVarPHI, TripCount, "omp_" + Name + ".cmp");
965   Builder.CreateCondBr(Cmp, Body, Exit);
966 
967   Builder.SetInsertPoint(Body);
968   Builder.CreateBr(Latch);
969 
970   Builder.SetInsertPoint(Latch);
971   Value *Next = Builder.CreateAdd(IndVarPHI, ConstantInt::get(IndVarTy, 1),
972                                   "omp_" + Name + ".next", /*HasNUW=*/true);
973   Builder.CreateBr(Header);
974   IndVarPHI->addIncoming(Next, Latch);
975 
976   Builder.SetInsertPoint(Exit);
977   Builder.CreateBr(After);
978 
979   // Remember and return the canonical control flow.
980   LoopInfos.emplace_front();
981   CanonicalLoopInfo *CL = &LoopInfos.front();
982 
983   CL->Preheader = Preheader;
984   CL->Header = Header;
985   CL->Cond = Cond;
986   CL->Body = Body;
987   CL->Latch = Latch;
988   CL->Exit = Exit;
989   CL->After = After;
990 
991   CL->IsValid = true;
992 
993 #ifndef NDEBUG
994   CL->assertOK();
995 #endif
996   return CL;
997 }
998 
999 CanonicalLoopInfo *
1000 OpenMPIRBuilder::createCanonicalLoop(const LocationDescription &Loc,
1001                                      LoopBodyGenCallbackTy BodyGenCB,
1002                                      Value *TripCount, const Twine &Name) {
1003   BasicBlock *BB = Loc.IP.getBlock();
1004   BasicBlock *NextBB = BB->getNextNode();
1005 
1006   CanonicalLoopInfo *CL = createLoopSkeleton(Loc.DL, TripCount, BB->getParent(),
1007                                              NextBB, NextBB, Name);
1008   BasicBlock *After = CL->getAfter();
1009 
1010   // If location is not set, don't connect the loop.
1011   if (updateToLocation(Loc)) {
1012     // Split the loop at the insertion point: Branch to the preheader and move
1013     // every following instruction to after the loop (the After BB). Also, the
1014     // new successor is the loop's after block.
1015     Builder.CreateBr(CL->Preheader);
1016     After->getInstList().splice(After->begin(), BB->getInstList(),
1017                                 Builder.GetInsertPoint(), BB->end());
1018     After->replaceSuccessorsPhiUsesWith(BB, After);
1019   }
1020 
1021   // Emit the body content. We do it after connecting the loop to the CFG to
1022   // avoid that the callback encounters degenerate BBs.
1023   BodyGenCB(CL->getBodyIP(), CL->getIndVar());
1024 
1025 #ifndef NDEBUG
1026   CL->assertOK();
1027 #endif
1028   return CL;
1029 }
1030 
1031 CanonicalLoopInfo *OpenMPIRBuilder::createCanonicalLoop(
1032     const LocationDescription &Loc, LoopBodyGenCallbackTy BodyGenCB,
1033     Value *Start, Value *Stop, Value *Step, bool IsSigned, bool InclusiveStop,
1034     InsertPointTy ComputeIP, const Twine &Name) {
1035 
1036   // Consider the following difficulties (assuming 8-bit signed integers):
1037   //  * Adding \p Step to the loop counter which passes \p Stop may overflow:
1038   //      DO I = 1, 100, 50
1039   ///  * A \p Step of INT_MIN cannot not be normalized to a positive direction:
1040   //      DO I = 100, 0, -128
1041 
1042   // Start, Stop and Step must be of the same integer type.
1043   auto *IndVarTy = cast<IntegerType>(Start->getType());
1044   assert(IndVarTy == Stop->getType() && "Stop type mismatch");
1045   assert(IndVarTy == Step->getType() && "Step type mismatch");
1046 
1047   LocationDescription ComputeLoc =
1048       ComputeIP.isSet() ? LocationDescription(ComputeIP, Loc.DL) : Loc;
1049   updateToLocation(ComputeLoc);
1050 
1051   ConstantInt *Zero = ConstantInt::get(IndVarTy, 0);
1052   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
1053 
1054   // Like Step, but always positive.
1055   Value *Incr = Step;
1056 
1057   // Distance between Start and Stop; always positive.
1058   Value *Span;
1059 
1060   // Condition whether there are no iterations are executed at all, e.g. because
1061   // UB < LB.
1062   Value *ZeroCmp;
1063 
1064   if (IsSigned) {
1065     // Ensure that increment is positive. If not, negate and invert LB and UB.
1066     Value *IsNeg = Builder.CreateICmpSLT(Step, Zero);
1067     Incr = Builder.CreateSelect(IsNeg, Builder.CreateNeg(Step), Step);
1068     Value *LB = Builder.CreateSelect(IsNeg, Stop, Start);
1069     Value *UB = Builder.CreateSelect(IsNeg, Start, Stop);
1070     Span = Builder.CreateSub(UB, LB, "", false, true);
1071     ZeroCmp = Builder.CreateICmp(
1072         InclusiveStop ? CmpInst::ICMP_SLT : CmpInst::ICMP_SLE, UB, LB);
1073   } else {
1074     Span = Builder.CreateSub(Stop, Start, "", true);
1075     ZeroCmp = Builder.CreateICmp(
1076         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Stop, Start);
1077   }
1078 
1079   Value *CountIfLooping;
1080   if (InclusiveStop) {
1081     CountIfLooping = Builder.CreateAdd(Builder.CreateUDiv(Span, Incr), One);
1082   } else {
1083     // Avoid incrementing past stop since it could overflow.
1084     Value *CountIfTwo = Builder.CreateAdd(
1085         Builder.CreateUDiv(Builder.CreateSub(Span, One), Incr), One);
1086     Value *OneCmp = Builder.CreateICmp(
1087         InclusiveStop ? CmpInst::ICMP_ULT : CmpInst::ICMP_ULE, Span, Incr);
1088     CountIfLooping = Builder.CreateSelect(OneCmp, One, CountIfTwo);
1089   }
1090   Value *TripCount = Builder.CreateSelect(ZeroCmp, Zero, CountIfLooping,
1091                                           "omp_" + Name + ".tripcount");
1092 
1093   auto BodyGen = [=](InsertPointTy CodeGenIP, Value *IV) {
1094     Builder.restoreIP(CodeGenIP);
1095     Value *Span = Builder.CreateMul(IV, Step);
1096     Value *IndVar = Builder.CreateAdd(Span, Start);
1097     BodyGenCB(Builder.saveIP(), IndVar);
1098   };
1099   LocationDescription LoopLoc = ComputeIP.isSet() ? Loc.IP : Builder.saveIP();
1100   return createCanonicalLoop(LoopLoc, BodyGen, TripCount, Name);
1101 }
1102 
1103 // Returns an LLVM function to call for initializing loop bounds using OpenMP
1104 // static scheduling depending on `type`. Only i32 and i64 are supported by the
1105 // runtime. Always interpret integers as unsigned similarly to
1106 // CanonicalLoopInfo.
1107 static FunctionCallee getKmpcForStaticInitForType(Type *Ty, Module &M,
1108                                                   OpenMPIRBuilder &OMPBuilder) {
1109   unsigned Bitwidth = Ty->getIntegerBitWidth();
1110   if (Bitwidth == 32)
1111     return OMPBuilder.getOrCreateRuntimeFunction(
1112         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_4u);
1113   if (Bitwidth == 64)
1114     return OMPBuilder.getOrCreateRuntimeFunction(
1115         M, omp::RuntimeFunction::OMPRTL___kmpc_for_static_init_8u);
1116   llvm_unreachable("unknown OpenMP loop iterator bitwidth");
1117 }
1118 
1119 // Sets the number of loop iterations to the given value. This value must be
1120 // valid in the condition block (i.e., defined in the preheader) and is
1121 // interpreted as an unsigned integer.
1122 void setCanonicalLoopTripCount(CanonicalLoopInfo *CLI, Value *TripCount) {
1123   Instruction *CmpI = &CLI->getCond()->front();
1124   assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
1125   CmpI->setOperand(1, TripCount);
1126   CLI->assertOK();
1127 }
1128 
1129 CanonicalLoopInfo *OpenMPIRBuilder::createStaticWorkshareLoop(
1130     const LocationDescription &Loc, CanonicalLoopInfo *CLI,
1131     InsertPointTy AllocaIP, bool NeedsBarrier, Value *Chunk) {
1132   // Set up the source location value for OpenMP runtime.
1133   if (!updateToLocation(Loc))
1134     return nullptr;
1135 
1136   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1137   Value *SrcLoc = getOrCreateIdent(SrcLocStr);
1138 
1139   // Declare useful OpenMP runtime functions.
1140   Value *IV = CLI->getIndVar();
1141   Type *IVTy = IV->getType();
1142   FunctionCallee StaticInit = getKmpcForStaticInitForType(IVTy, M, *this);
1143   FunctionCallee StaticFini =
1144       getOrCreateRuntimeFunction(M, omp::OMPRTL___kmpc_for_static_fini);
1145 
1146   // Allocate space for computed loop bounds as expected by the "init" function.
1147   Builder.restoreIP(AllocaIP);
1148   Type *I32Type = Type::getInt32Ty(M.getContext());
1149   Value *PLastIter = Builder.CreateAlloca(I32Type, nullptr, "p.lastiter");
1150   Value *PLowerBound = Builder.CreateAlloca(IVTy, nullptr, "p.lowerbound");
1151   Value *PUpperBound = Builder.CreateAlloca(IVTy, nullptr, "p.upperbound");
1152   Value *PStride = Builder.CreateAlloca(IVTy, nullptr, "p.stride");
1153 
1154   // At the end of the preheader, prepare for calling the "init" function by
1155   // storing the current loop bounds into the allocated space. A canonical loop
1156   // always iterates from 0 to trip-count with step 1. Note that "init" expects
1157   // and produces an inclusive upper bound.
1158   Builder.SetInsertPoint(CLI->getPreheader()->getTerminator());
1159   Constant *Zero = ConstantInt::get(IVTy, 0);
1160   Constant *One = ConstantInt::get(IVTy, 1);
1161   Builder.CreateStore(Zero, PLowerBound);
1162   Value *UpperBound = Builder.CreateSub(CLI->getTripCount(), One);
1163   Builder.CreateStore(UpperBound, PUpperBound);
1164   Builder.CreateStore(One, PStride);
1165 
1166   if (!Chunk)
1167     Chunk = One;
1168 
1169   Value *ThreadNum = getOrCreateThreadID(SrcLoc);
1170 
1171   // TODO: extract scheduling type and map it to OMP constant. This is curently
1172   // happening in kmp.h and its ilk and needs to be moved to OpenMP.td first.
1173   constexpr int StaticSchedType = 34;
1174   Constant *SchedulingType = ConstantInt::get(I32Type, StaticSchedType);
1175 
1176   // Call the "init" function and update the trip count of the loop with the
1177   // value it produced.
1178   Builder.CreateCall(StaticInit,
1179                      {SrcLoc, ThreadNum, SchedulingType, PLastIter, PLowerBound,
1180                       PUpperBound, PStride, One, Chunk});
1181   Value *LowerBound = Builder.CreateLoad(IVTy, PLowerBound);
1182   Value *InclusiveUpperBound = Builder.CreateLoad(IVTy, PUpperBound);
1183   Value *TripCountMinusOne = Builder.CreateSub(InclusiveUpperBound, LowerBound);
1184   Value *TripCount = Builder.CreateAdd(TripCountMinusOne, One);
1185   setCanonicalLoopTripCount(CLI, TripCount);
1186 
1187   // Update all uses of the induction variable except the one in the condition
1188   // block that compares it with the actual upper bound, and the increment in
1189   // the latch block.
1190   // TODO: this can eventually move to CanonicalLoopInfo or to a new
1191   // CanonicalLoopInfoUpdater interface.
1192   Builder.SetInsertPoint(CLI->getBody(), CLI->getBody()->getFirstInsertionPt());
1193   Value *UpdatedIV = Builder.CreateAdd(IV, LowerBound);
1194   IV->replaceUsesWithIf(UpdatedIV, [&](Use &U) {
1195     auto *Instr = dyn_cast<Instruction>(U.getUser());
1196     return !Instr ||
1197            (Instr->getParent() != CLI->getCond() &&
1198             Instr->getParent() != CLI->getLatch() && Instr != UpdatedIV);
1199   });
1200 
1201   // In the "exit" block, call the "fini" function.
1202   Builder.SetInsertPoint(CLI->getExit(),
1203                          CLI->getExit()->getTerminator()->getIterator());
1204   Builder.CreateCall(StaticFini, {SrcLoc, ThreadNum});
1205 
1206   // Add the barrier if requested.
1207   if (NeedsBarrier)
1208     createBarrier(LocationDescription(Builder.saveIP(), Loc.DL),
1209                   omp::Directive::OMPD_for, /* ForceSimpleCall */ false,
1210                   /* CheckCancelFlag */ false);
1211 
1212   CLI->assertOK();
1213   return CLI;
1214 }
1215 
1216 CanonicalLoopInfo *OpenMPIRBuilder::createWorkshareLoop(
1217     const LocationDescription &Loc, CanonicalLoopInfo *CLI,
1218     InsertPointTy AllocaIP, bool NeedsBarrier) {
1219   // Currently only supports static schedules.
1220   return createStaticWorkshareLoop(Loc, CLI, AllocaIP, NeedsBarrier);
1221 }
1222 
1223 /// Make \p Source branch to \p Target.
1224 ///
1225 /// Handles two situations:
1226 /// * \p Source already has an unconditional branch.
1227 /// * \p Source is a degenerate block (no terminator because the BB is
1228 ///             the current head of the IR construction).
1229 static void redirectTo(BasicBlock *Source, BasicBlock *Target, DebugLoc DL) {
1230   if (Instruction *Term = Source->getTerminator()) {
1231     auto *Br = cast<BranchInst>(Term);
1232     assert(!Br->isConditional() &&
1233            "BB's terminator must be an unconditional branch (or degenerate)");
1234     BasicBlock *Succ = Br->getSuccessor(0);
1235     Succ->removePredecessor(Source, /*KeepOneInputPHIs=*/true);
1236     Br->setSuccessor(0, Target);
1237     return;
1238   }
1239 
1240   auto *NewBr = BranchInst::Create(Target, Source);
1241   NewBr->setDebugLoc(DL);
1242 }
1243 
1244 /// Redirect all edges that branch to \p OldTarget to \p NewTarget. That is,
1245 /// after this \p OldTarget will be orphaned.
1246 static void redirectAllPredecessorsTo(BasicBlock *OldTarget,
1247                                       BasicBlock *NewTarget, DebugLoc DL) {
1248   for (BasicBlock *Pred : make_early_inc_range(predecessors(OldTarget)))
1249     redirectTo(Pred, NewTarget, DL);
1250 }
1251 
1252 /// Determine which blocks in \p BBs are reachable from outside and remove the
1253 /// ones that are not reachable from the function.
1254 static void removeUnusedBlocksFromParent(ArrayRef<BasicBlock *> BBs) {
1255   SmallPtrSet<BasicBlock *, 6> BBsToErase{BBs.begin(), BBs.end()};
1256   auto HasRemainingUses = [&BBsToErase](BasicBlock *BB) {
1257     for (Use &U : BB->uses()) {
1258       auto *UseInst = dyn_cast<Instruction>(U.getUser());
1259       if (!UseInst)
1260         continue;
1261       if (BBsToErase.count(UseInst->getParent()))
1262         continue;
1263       return true;
1264     }
1265     return false;
1266   };
1267 
1268   while (true) {
1269     bool Changed = false;
1270     for (BasicBlock *BB : make_early_inc_range(BBsToErase)) {
1271       if (HasRemainingUses(BB)) {
1272         BBsToErase.erase(BB);
1273         Changed = true;
1274       }
1275     }
1276     if (!Changed)
1277       break;
1278   }
1279 
1280   SmallVector<BasicBlock *, 7> BBVec(BBsToErase.begin(), BBsToErase.end());
1281   DeleteDeadBlocks(BBVec);
1282 }
1283 
1284 CanonicalLoopInfo *
1285 OpenMPIRBuilder::collapseLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1286                                InsertPointTy ComputeIP) {
1287   assert(Loops.size() >= 1 && "At least one loop required");
1288   size_t NumLoops = Loops.size();
1289 
1290   // Nothing to do if there is already just one loop.
1291   if (NumLoops == 1)
1292     return Loops.front();
1293 
1294   CanonicalLoopInfo *Outermost = Loops.front();
1295   CanonicalLoopInfo *Innermost = Loops.back();
1296   BasicBlock *OrigPreheader = Outermost->getPreheader();
1297   BasicBlock *OrigAfter = Outermost->getAfter();
1298   Function *F = OrigPreheader->getParent();
1299 
1300   // Setup the IRBuilder for inserting the trip count computation.
1301   Builder.SetCurrentDebugLocation(DL);
1302   if (ComputeIP.isSet())
1303     Builder.restoreIP(ComputeIP);
1304   else
1305     Builder.restoreIP(Outermost->getPreheaderIP());
1306 
1307   // Derive the collapsed' loop trip count.
1308   // TODO: Find common/largest indvar type.
1309   Value *CollapsedTripCount = nullptr;
1310   for (CanonicalLoopInfo *L : Loops) {
1311     Value *OrigTripCount = L->getTripCount();
1312     if (!CollapsedTripCount) {
1313       CollapsedTripCount = OrigTripCount;
1314       continue;
1315     }
1316 
1317     // TODO: Enable UndefinedSanitizer to diagnose an overflow here.
1318     CollapsedTripCount = Builder.CreateMul(CollapsedTripCount, OrigTripCount,
1319                                            {}, /*HasNUW=*/true);
1320   }
1321 
1322   // Create the collapsed loop control flow.
1323   CanonicalLoopInfo *Result =
1324       createLoopSkeleton(DL, CollapsedTripCount, F,
1325                          OrigPreheader->getNextNode(), OrigAfter, "collapsed");
1326 
1327   // Build the collapsed loop body code.
1328   // Start with deriving the input loop induction variables from the collapsed
1329   // one, using a divmod scheme. To preserve the original loops' order, the
1330   // innermost loop use the least significant bits.
1331   Builder.restoreIP(Result->getBodyIP());
1332 
1333   Value *Leftover = Result->getIndVar();
1334   SmallVector<Value *> NewIndVars;
1335   NewIndVars.set_size(NumLoops);
1336   for (int i = NumLoops - 1; i >= 1; --i) {
1337     Value *OrigTripCount = Loops[i]->getTripCount();
1338 
1339     Value *NewIndVar = Builder.CreateURem(Leftover, OrigTripCount);
1340     NewIndVars[i] = NewIndVar;
1341 
1342     Leftover = Builder.CreateUDiv(Leftover, OrigTripCount);
1343   }
1344   // Outermost loop gets all the remaining bits.
1345   NewIndVars[0] = Leftover;
1346 
1347   // Construct the loop body control flow.
1348   // We progressively construct the branch structure following in direction of
1349   // the control flow, from the leading in-between code, the loop nest body, the
1350   // trailing in-between code, and rejoining the collapsed loop's latch.
1351   // ContinueBlock and ContinuePred keep track of the source(s) of next edge. If
1352   // the ContinueBlock is set, continue with that block. If ContinuePred, use
1353   // its predecessors as sources.
1354   BasicBlock *ContinueBlock = Result->getBody();
1355   BasicBlock *ContinuePred = nullptr;
1356   auto ContinueWith = [&ContinueBlock, &ContinuePred, DL](BasicBlock *Dest,
1357                                                           BasicBlock *NextSrc) {
1358     if (ContinueBlock)
1359       redirectTo(ContinueBlock, Dest, DL);
1360     else
1361       redirectAllPredecessorsTo(ContinuePred, Dest, DL);
1362 
1363     ContinueBlock = nullptr;
1364     ContinuePred = NextSrc;
1365   };
1366 
1367   // The code before the nested loop of each level.
1368   // Because we are sinking it into the nest, it will be executed more often
1369   // that the original loop. More sophisticated schemes could keep track of what
1370   // the in-between code is and instantiate it only once per thread.
1371   for (size_t i = 0; i < NumLoops - 1; ++i)
1372     ContinueWith(Loops[i]->getBody(), Loops[i + 1]->getHeader());
1373 
1374   // Connect the loop nest body.
1375   ContinueWith(Innermost->getBody(), Innermost->getLatch());
1376 
1377   // The code after the nested loop at each level.
1378   for (size_t i = NumLoops - 1; i > 0; --i)
1379     ContinueWith(Loops[i]->getAfter(), Loops[i - 1]->getLatch());
1380 
1381   // Connect the finished loop to the collapsed loop latch.
1382   ContinueWith(Result->getLatch(), nullptr);
1383 
1384   // Replace the input loops with the new collapsed loop.
1385   redirectTo(Outermost->getPreheader(), Result->getPreheader(), DL);
1386   redirectTo(Result->getAfter(), Outermost->getAfter(), DL);
1387 
1388   // Replace the input loop indvars with the derived ones.
1389   for (size_t i = 0; i < NumLoops; ++i)
1390     Loops[i]->getIndVar()->replaceAllUsesWith(NewIndVars[i]);
1391 
1392   // Remove unused parts of the input loops.
1393   SmallVector<BasicBlock *, 12> OldControlBBs;
1394   OldControlBBs.reserve(6 * Loops.size());
1395   for (CanonicalLoopInfo *Loop : Loops)
1396     Loop->collectControlBlocks(OldControlBBs);
1397   removeUnusedBlocksFromParent(OldControlBBs);
1398 
1399 #ifndef NDEBUG
1400   Result->assertOK();
1401 #endif
1402   return Result;
1403 }
1404 
1405 std::vector<CanonicalLoopInfo *>
1406 OpenMPIRBuilder::tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
1407                            ArrayRef<Value *> TileSizes) {
1408   assert(TileSizes.size() == Loops.size() &&
1409          "Must pass as many tile sizes as there are loops");
1410   int NumLoops = Loops.size();
1411   assert(NumLoops >= 1 && "At least one loop to tile required");
1412 
1413   CanonicalLoopInfo *OutermostLoop = Loops.front();
1414   CanonicalLoopInfo *InnermostLoop = Loops.back();
1415   Function *F = OutermostLoop->getBody()->getParent();
1416   BasicBlock *InnerEnter = InnermostLoop->getBody();
1417   BasicBlock *InnerLatch = InnermostLoop->getLatch();
1418 
1419   // Collect original trip counts and induction variable to be accessible by
1420   // index. Also, the structure of the original loops is not preserved during
1421   // the construction of the tiled loops, so do it before we scavenge the BBs of
1422   // any original CanonicalLoopInfo.
1423   SmallVector<Value *, 4> OrigTripCounts, OrigIndVars;
1424   for (CanonicalLoopInfo *L : Loops) {
1425     OrigTripCounts.push_back(L->getTripCount());
1426     OrigIndVars.push_back(L->getIndVar());
1427   }
1428 
1429   // Collect the code between loop headers. These may contain SSA definitions
1430   // that are used in the loop nest body. To be usable with in the innermost
1431   // body, these BasicBlocks will be sunk into the loop nest body. That is,
1432   // these instructions may be executed more often than before the tiling.
1433   // TODO: It would be sufficient to only sink them into body of the
1434   // corresponding tile loop.
1435   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> InbetweenCode;
1436   for (int i = 0; i < NumLoops - 1; ++i) {
1437     CanonicalLoopInfo *Surrounding = Loops[i];
1438     CanonicalLoopInfo *Nested = Loops[i + 1];
1439 
1440     BasicBlock *EnterBB = Surrounding->getBody();
1441     BasicBlock *ExitBB = Nested->getHeader();
1442     InbetweenCode.emplace_back(EnterBB, ExitBB);
1443   }
1444 
1445   // Compute the trip counts of the floor loops.
1446   Builder.SetCurrentDebugLocation(DL);
1447   Builder.restoreIP(OutermostLoop->getPreheaderIP());
1448   SmallVector<Value *, 4> FloorCount, FloorRems;
1449   for (int i = 0; i < NumLoops; ++i) {
1450     Value *TileSize = TileSizes[i];
1451     Value *OrigTripCount = OrigTripCounts[i];
1452     Type *IVType = OrigTripCount->getType();
1453 
1454     Value *FloorTripCount = Builder.CreateUDiv(OrigTripCount, TileSize);
1455     Value *FloorTripRem = Builder.CreateURem(OrigTripCount, TileSize);
1456 
1457     // 0 if tripcount divides the tilesize, 1 otherwise.
1458     // 1 means we need an additional iteration for a partial tile.
1459     //
1460     // Unfortunately we cannot just use the roundup-formula
1461     //   (tripcount + tilesize - 1)/tilesize
1462     // because the summation might overflow. We do not want introduce undefined
1463     // behavior when the untiled loop nest did not.
1464     Value *FloorTripOverflow =
1465         Builder.CreateICmpNE(FloorTripRem, ConstantInt::get(IVType, 0));
1466 
1467     FloorTripOverflow = Builder.CreateZExt(FloorTripOverflow, IVType);
1468     FloorTripCount =
1469         Builder.CreateAdd(FloorTripCount, FloorTripOverflow,
1470                           "omp_floor" + Twine(i) + ".tripcount", true);
1471 
1472     // Remember some values for later use.
1473     FloorCount.push_back(FloorTripCount);
1474     FloorRems.push_back(FloorTripRem);
1475   }
1476 
1477   // Generate the new loop nest, from the outermost to the innermost.
1478   std::vector<CanonicalLoopInfo *> Result;
1479   Result.reserve(NumLoops * 2);
1480 
1481   // The basic block of the surrounding loop that enters the nest generated
1482   // loop.
1483   BasicBlock *Enter = OutermostLoop->getPreheader();
1484 
1485   // The basic block of the surrounding loop where the inner code should
1486   // continue.
1487   BasicBlock *Continue = OutermostLoop->getAfter();
1488 
1489   // Where the next loop basic block should be inserted.
1490   BasicBlock *OutroInsertBefore = InnermostLoop->getExit();
1491 
1492   auto EmbeddNewLoop =
1493       [this, DL, F, InnerEnter, &Enter, &Continue, &OutroInsertBefore](
1494           Value *TripCount, const Twine &Name) -> CanonicalLoopInfo * {
1495     CanonicalLoopInfo *EmbeddedLoop = createLoopSkeleton(
1496         DL, TripCount, F, InnerEnter, OutroInsertBefore, Name);
1497     redirectTo(Enter, EmbeddedLoop->getPreheader(), DL);
1498     redirectTo(EmbeddedLoop->getAfter(), Continue, DL);
1499 
1500     // Setup the position where the next embedded loop connects to this loop.
1501     Enter = EmbeddedLoop->getBody();
1502     Continue = EmbeddedLoop->getLatch();
1503     OutroInsertBefore = EmbeddedLoop->getLatch();
1504     return EmbeddedLoop;
1505   };
1506 
1507   auto EmbeddNewLoops = [&Result, &EmbeddNewLoop](ArrayRef<Value *> TripCounts,
1508                                                   const Twine &NameBase) {
1509     for (auto P : enumerate(TripCounts)) {
1510       CanonicalLoopInfo *EmbeddedLoop =
1511           EmbeddNewLoop(P.value(), NameBase + Twine(P.index()));
1512       Result.push_back(EmbeddedLoop);
1513     }
1514   };
1515 
1516   EmbeddNewLoops(FloorCount, "floor");
1517 
1518   // Within the innermost floor loop, emit the code that computes the tile
1519   // sizes.
1520   Builder.SetInsertPoint(Enter->getTerminator());
1521   SmallVector<Value *, 4> TileCounts;
1522   for (int i = 0; i < NumLoops; ++i) {
1523     CanonicalLoopInfo *FloorLoop = Result[i];
1524     Value *TileSize = TileSizes[i];
1525 
1526     Value *FloorIsEpilogue =
1527         Builder.CreateICmpEQ(FloorLoop->getIndVar(), FloorCount[i]);
1528     Value *TileTripCount =
1529         Builder.CreateSelect(FloorIsEpilogue, FloorRems[i], TileSize);
1530 
1531     TileCounts.push_back(TileTripCount);
1532   }
1533 
1534   // Create the tile loops.
1535   EmbeddNewLoops(TileCounts, "tile");
1536 
1537   // Insert the inbetween code into the body.
1538   BasicBlock *BodyEnter = Enter;
1539   BasicBlock *BodyEntered = nullptr;
1540   for (std::pair<BasicBlock *, BasicBlock *> P : InbetweenCode) {
1541     BasicBlock *EnterBB = P.first;
1542     BasicBlock *ExitBB = P.second;
1543 
1544     if (BodyEnter)
1545       redirectTo(BodyEnter, EnterBB, DL);
1546     else
1547       redirectAllPredecessorsTo(BodyEntered, EnterBB, DL);
1548 
1549     BodyEnter = nullptr;
1550     BodyEntered = ExitBB;
1551   }
1552 
1553   // Append the original loop nest body into the generated loop nest body.
1554   if (BodyEnter)
1555     redirectTo(BodyEnter, InnerEnter, DL);
1556   else
1557     redirectAllPredecessorsTo(BodyEntered, InnerEnter, DL);
1558   redirectAllPredecessorsTo(InnerLatch, Continue, DL);
1559 
1560   // Replace the original induction variable with an induction variable computed
1561   // from the tile and floor induction variables.
1562   Builder.restoreIP(Result.back()->getBodyIP());
1563   for (int i = 0; i < NumLoops; ++i) {
1564     CanonicalLoopInfo *FloorLoop = Result[i];
1565     CanonicalLoopInfo *TileLoop = Result[NumLoops + i];
1566     Value *OrigIndVar = OrigIndVars[i];
1567     Value *Size = TileSizes[i];
1568 
1569     Value *Scale =
1570         Builder.CreateMul(Size, FloorLoop->getIndVar(), {}, /*HasNUW=*/true);
1571     Value *Shift =
1572         Builder.CreateAdd(Scale, TileLoop->getIndVar(), {}, /*HasNUW=*/true);
1573     OrigIndVar->replaceAllUsesWith(Shift);
1574   }
1575 
1576   // Remove unused parts of the original loops.
1577   SmallVector<BasicBlock *, 12> OldControlBBs;
1578   OldControlBBs.reserve(6 * Loops.size());
1579   for (CanonicalLoopInfo *Loop : Loops)
1580     Loop->collectControlBlocks(OldControlBBs);
1581   removeUnusedBlocksFromParent(OldControlBBs);
1582 
1583 #ifndef NDEBUG
1584   for (CanonicalLoopInfo *GenL : Result)
1585     GenL->assertOK();
1586 #endif
1587   return Result;
1588 }
1589 
1590 OpenMPIRBuilder::InsertPointTy
1591 OpenMPIRBuilder::createCopyPrivate(const LocationDescription &Loc,
1592                                    llvm::Value *BufSize, llvm::Value *CpyBuf,
1593                                    llvm::Value *CpyFn, llvm::Value *DidIt) {
1594   if (!updateToLocation(Loc))
1595     return Loc.IP;
1596 
1597   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1598   Value *Ident = getOrCreateIdent(SrcLocStr);
1599   Value *ThreadId = getOrCreateThreadID(Ident);
1600 
1601   llvm::Value *DidItLD = Builder.CreateLoad(Builder.getInt32Ty(), DidIt);
1602 
1603   Value *Args[] = {Ident, ThreadId, BufSize, CpyBuf, CpyFn, DidItLD};
1604 
1605   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_copyprivate);
1606   Builder.CreateCall(Fn, Args);
1607 
1608   return Builder.saveIP();
1609 }
1610 
1611 OpenMPIRBuilder::InsertPointTy
1612 OpenMPIRBuilder::createSingle(const LocationDescription &Loc,
1613                               BodyGenCallbackTy BodyGenCB,
1614                               FinalizeCallbackTy FiniCB, llvm::Value *DidIt) {
1615 
1616   if (!updateToLocation(Loc))
1617     return Loc.IP;
1618 
1619   // If needed (i.e. not null), initialize `DidIt` with 0
1620   if (DidIt) {
1621     Builder.CreateStore(Builder.getInt32(0), DidIt);
1622   }
1623 
1624   Directive OMPD = Directive::OMPD_single;
1625   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1626   Value *Ident = getOrCreateIdent(SrcLocStr);
1627   Value *ThreadId = getOrCreateThreadID(Ident);
1628   Value *Args[] = {Ident, ThreadId};
1629 
1630   Function *EntryRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_single);
1631   Instruction *EntryCall = Builder.CreateCall(EntryRTLFn, Args);
1632 
1633   Function *ExitRTLFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_single);
1634   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1635 
1636   // generates the following:
1637   // if (__kmpc_single()) {
1638   //		.... single region ...
1639   // 		__kmpc_end_single
1640   // }
1641 
1642   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1643                               /*Conditional*/ true, /*hasFinalize*/ true);
1644 }
1645 
1646 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCritical(
1647     const LocationDescription &Loc, BodyGenCallbackTy BodyGenCB,
1648     FinalizeCallbackTy FiniCB, StringRef CriticalName, Value *HintInst) {
1649 
1650   if (!updateToLocation(Loc))
1651     return Loc.IP;
1652 
1653   Directive OMPD = Directive::OMPD_critical;
1654   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1655   Value *Ident = getOrCreateIdent(SrcLocStr);
1656   Value *ThreadId = getOrCreateThreadID(Ident);
1657   Value *LockVar = getOMPCriticalRegionLock(CriticalName);
1658   Value *Args[] = {Ident, ThreadId, LockVar};
1659 
1660   SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), std::end(Args));
1661   Function *RTFn = nullptr;
1662   if (HintInst) {
1663     // Add Hint to entry Args and create call
1664     EnterArgs.push_back(HintInst);
1665     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical_with_hint);
1666   } else {
1667     RTFn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_critical);
1668   }
1669   Instruction *EntryCall = Builder.CreateCall(RTFn, EnterArgs);
1670 
1671   Function *ExitRTLFn =
1672       getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_end_critical);
1673   Instruction *ExitCall = Builder.CreateCall(ExitRTLFn, Args);
1674 
1675   return EmitOMPInlinedRegion(OMPD, EntryCall, ExitCall, BodyGenCB, FiniCB,
1676                               /*Conditional*/ false, /*hasFinalize*/ true);
1677 }
1678 
1679 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::EmitOMPInlinedRegion(
1680     Directive OMPD, Instruction *EntryCall, Instruction *ExitCall,
1681     BodyGenCallbackTy BodyGenCB, FinalizeCallbackTy FiniCB, bool Conditional,
1682     bool HasFinalize) {
1683 
1684   if (HasFinalize)
1685     FinalizationStack.push_back({FiniCB, OMPD, /*IsCancellable*/ false});
1686 
1687   // Create inlined region's entry and body blocks, in preparation
1688   // for conditional creation
1689   BasicBlock *EntryBB = Builder.GetInsertBlock();
1690   Instruction *SplitPos = EntryBB->getTerminator();
1691   if (!isa_and_nonnull<BranchInst>(SplitPos))
1692     SplitPos = new UnreachableInst(Builder.getContext(), EntryBB);
1693   BasicBlock *ExitBB = EntryBB->splitBasicBlock(SplitPos, "omp_region.end");
1694   BasicBlock *FiniBB =
1695       EntryBB->splitBasicBlock(EntryBB->getTerminator(), "omp_region.finalize");
1696 
1697   Builder.SetInsertPoint(EntryBB->getTerminator());
1698   emitCommonDirectiveEntry(OMPD, EntryCall, ExitBB, Conditional);
1699 
1700   // generate body
1701   BodyGenCB(/* AllocaIP */ InsertPointTy(),
1702             /* CodeGenIP */ Builder.saveIP(), *FiniBB);
1703 
1704   // If we didn't emit a branch to FiniBB during body generation, it means
1705   // FiniBB is unreachable (e.g. while(1);). stop generating all the
1706   // unreachable blocks, and remove anything we are not going to use.
1707   auto SkipEmittingRegion = FiniBB->hasNPredecessors(0);
1708   if (SkipEmittingRegion) {
1709     FiniBB->eraseFromParent();
1710     ExitCall->eraseFromParent();
1711     // Discard finalization if we have it.
1712     if (HasFinalize) {
1713       assert(!FinalizationStack.empty() &&
1714              "Unexpected finalization stack state!");
1715       FinalizationStack.pop_back();
1716     }
1717   } else {
1718     // emit exit call and do any needed finalization.
1719     auto FinIP = InsertPointTy(FiniBB, FiniBB->getFirstInsertionPt());
1720     assert(FiniBB->getTerminator()->getNumSuccessors() == 1 &&
1721            FiniBB->getTerminator()->getSuccessor(0) == ExitBB &&
1722            "Unexpected control flow graph state!!");
1723     emitCommonDirectiveExit(OMPD, FinIP, ExitCall, HasFinalize);
1724     assert(FiniBB->getUniquePredecessor()->getUniqueSuccessor() == FiniBB &&
1725            "Unexpected Control Flow State!");
1726     MergeBlockIntoPredecessor(FiniBB);
1727   }
1728 
1729   // If we are skipping the region of a non conditional, remove the exit
1730   // block, and clear the builder's insertion point.
1731   assert(SplitPos->getParent() == ExitBB &&
1732          "Unexpected Insertion point location!");
1733   if (!Conditional && SkipEmittingRegion) {
1734     ExitBB->eraseFromParent();
1735     Builder.ClearInsertionPoint();
1736   } else {
1737     auto merged = MergeBlockIntoPredecessor(ExitBB);
1738     BasicBlock *ExitPredBB = SplitPos->getParent();
1739     auto InsertBB = merged ? ExitPredBB : ExitBB;
1740     if (!isa_and_nonnull<BranchInst>(SplitPos))
1741       SplitPos->eraseFromParent();
1742     Builder.SetInsertPoint(InsertBB);
1743   }
1744 
1745   return Builder.saveIP();
1746 }
1747 
1748 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveEntry(
1749     Directive OMPD, Value *EntryCall, BasicBlock *ExitBB, bool Conditional) {
1750 
1751   // if nothing to do, Return current insertion point.
1752   if (!Conditional)
1753     return Builder.saveIP();
1754 
1755   BasicBlock *EntryBB = Builder.GetInsertBlock();
1756   Value *CallBool = Builder.CreateIsNotNull(EntryCall);
1757   auto *ThenBB = BasicBlock::Create(M.getContext(), "omp_region.body");
1758   auto *UI = new UnreachableInst(Builder.getContext(), ThenBB);
1759 
1760   // Emit thenBB and set the Builder's insertion point there for
1761   // body generation next. Place the block after the current block.
1762   Function *CurFn = EntryBB->getParent();
1763   CurFn->getBasicBlockList().insertAfter(EntryBB->getIterator(), ThenBB);
1764 
1765   // Move Entry branch to end of ThenBB, and replace with conditional
1766   // branch (If-stmt)
1767   Instruction *EntryBBTI = EntryBB->getTerminator();
1768   Builder.CreateCondBr(CallBool, ThenBB, ExitBB);
1769   EntryBBTI->removeFromParent();
1770   Builder.SetInsertPoint(UI);
1771   Builder.Insert(EntryBBTI);
1772   UI->eraseFromParent();
1773   Builder.SetInsertPoint(ThenBB->getTerminator());
1774 
1775   // return an insertion point to ExitBB.
1776   return IRBuilder<>::InsertPoint(ExitBB, ExitBB->getFirstInsertionPt());
1777 }
1778 
1779 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::emitCommonDirectiveExit(
1780     omp::Directive OMPD, InsertPointTy FinIP, Instruction *ExitCall,
1781     bool HasFinalize) {
1782 
1783   Builder.restoreIP(FinIP);
1784 
1785   // If there is finalization to do, emit it before the exit call
1786   if (HasFinalize) {
1787     assert(!FinalizationStack.empty() &&
1788            "Unexpected finalization stack state!");
1789 
1790     FinalizationInfo Fi = FinalizationStack.pop_back_val();
1791     assert(Fi.DK == OMPD && "Unexpected Directive for Finalization call!");
1792 
1793     Fi.FiniCB(FinIP);
1794 
1795     BasicBlock *FiniBB = FinIP.getBlock();
1796     Instruction *FiniBBTI = FiniBB->getTerminator();
1797 
1798     // set Builder IP for call creation
1799     Builder.SetInsertPoint(FiniBBTI);
1800   }
1801 
1802   // place the Exitcall as last instruction before Finalization block terminator
1803   ExitCall->removeFromParent();
1804   Builder.Insert(ExitCall);
1805 
1806   return IRBuilder<>::InsertPoint(ExitCall->getParent(),
1807                                   ExitCall->getIterator());
1808 }
1809 
1810 OpenMPIRBuilder::InsertPointTy OpenMPIRBuilder::createCopyinClauseBlocks(
1811     InsertPointTy IP, Value *MasterAddr, Value *PrivateAddr,
1812     llvm::IntegerType *IntPtrTy, bool BranchtoEnd) {
1813   if (!IP.isSet())
1814     return IP;
1815 
1816   IRBuilder<>::InsertPointGuard IPG(Builder);
1817 
1818   // creates the following CFG structure
1819   //	   OMP_Entry : (MasterAddr != PrivateAddr)?
1820   //       F     T
1821   //       |      \
1822   //       |     copin.not.master
1823   //       |      /
1824   //       v     /
1825   //   copyin.not.master.end
1826   //		     |
1827   //         v
1828   //   OMP.Entry.Next
1829 
1830   BasicBlock *OMP_Entry = IP.getBlock();
1831   Function *CurFn = OMP_Entry->getParent();
1832   BasicBlock *CopyBegin =
1833       BasicBlock::Create(M.getContext(), "copyin.not.master", CurFn);
1834   BasicBlock *CopyEnd = nullptr;
1835 
1836   // If entry block is terminated, split to preserve the branch to following
1837   // basic block (i.e. OMP.Entry.Next), otherwise, leave everything as is.
1838   if (isa_and_nonnull<BranchInst>(OMP_Entry->getTerminator())) {
1839     CopyEnd = OMP_Entry->splitBasicBlock(OMP_Entry->getTerminator(),
1840                                          "copyin.not.master.end");
1841     OMP_Entry->getTerminator()->eraseFromParent();
1842   } else {
1843     CopyEnd =
1844         BasicBlock::Create(M.getContext(), "copyin.not.master.end", CurFn);
1845   }
1846 
1847   Builder.SetInsertPoint(OMP_Entry);
1848   Value *MasterPtr = Builder.CreatePtrToInt(MasterAddr, IntPtrTy);
1849   Value *PrivatePtr = Builder.CreatePtrToInt(PrivateAddr, IntPtrTy);
1850   Value *cmp = Builder.CreateICmpNE(MasterPtr, PrivatePtr);
1851   Builder.CreateCondBr(cmp, CopyBegin, CopyEnd);
1852 
1853   Builder.SetInsertPoint(CopyBegin);
1854   if (BranchtoEnd)
1855     Builder.SetInsertPoint(Builder.CreateBr(CopyEnd));
1856 
1857   return Builder.saveIP();
1858 }
1859 
1860 CallInst *OpenMPIRBuilder::createOMPAlloc(const LocationDescription &Loc,
1861                                           Value *Size, Value *Allocator,
1862                                           std::string Name) {
1863   IRBuilder<>::InsertPointGuard IPG(Builder);
1864   Builder.restoreIP(Loc.IP);
1865 
1866   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1867   Value *Ident = getOrCreateIdent(SrcLocStr);
1868   Value *ThreadId = getOrCreateThreadID(Ident);
1869   Value *Args[] = {ThreadId, Size, Allocator};
1870 
1871   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_alloc);
1872 
1873   return Builder.CreateCall(Fn, Args, Name);
1874 }
1875 
1876 CallInst *OpenMPIRBuilder::createOMPFree(const LocationDescription &Loc,
1877                                          Value *Addr, Value *Allocator,
1878                                          std::string Name) {
1879   IRBuilder<>::InsertPointGuard IPG(Builder);
1880   Builder.restoreIP(Loc.IP);
1881 
1882   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1883   Value *Ident = getOrCreateIdent(SrcLocStr);
1884   Value *ThreadId = getOrCreateThreadID(Ident);
1885   Value *Args[] = {ThreadId, Addr, Allocator};
1886   Function *Fn = getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_free);
1887   return Builder.CreateCall(Fn, Args, Name);
1888 }
1889 
1890 CallInst *OpenMPIRBuilder::createCachedThreadPrivate(
1891     const LocationDescription &Loc, llvm::Value *Pointer,
1892     llvm::ConstantInt *Size, const llvm::Twine &Name) {
1893   IRBuilder<>::InsertPointGuard IPG(Builder);
1894   Builder.restoreIP(Loc.IP);
1895 
1896   Constant *SrcLocStr = getOrCreateSrcLocStr(Loc);
1897   Value *Ident = getOrCreateIdent(SrcLocStr);
1898   Value *ThreadId = getOrCreateThreadID(Ident);
1899   Constant *ThreadPrivateCache =
1900       getOrCreateOMPInternalVariable(Int8PtrPtr, Name);
1901   llvm::Value *Args[] = {Ident, ThreadId, Pointer, Size, ThreadPrivateCache};
1902 
1903   Function *Fn =
1904   		getOrCreateRuntimeFunctionPtr(OMPRTL___kmpc_threadprivate_cached);
1905 
1906   return Builder.CreateCall(Fn, Args);
1907 }
1908 
1909 std::string OpenMPIRBuilder::getNameWithSeparators(ArrayRef<StringRef> Parts,
1910                                                    StringRef FirstSeparator,
1911                                                    StringRef Separator) {
1912   SmallString<128> Buffer;
1913   llvm::raw_svector_ostream OS(Buffer);
1914   StringRef Sep = FirstSeparator;
1915   for (StringRef Part : Parts) {
1916     OS << Sep << Part;
1917     Sep = Separator;
1918   }
1919   return OS.str().str();
1920 }
1921 
1922 Constant *OpenMPIRBuilder::getOrCreateOMPInternalVariable(
1923     llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
1924   // TODO: Replace the twine arg with stringref to get rid of the conversion
1925   // logic. However This is taken from current implementation in clang as is.
1926   // Since this method is used in many places exclusively for OMP internal use
1927   // we will keep it as is for temporarily until we move all users to the
1928   // builder and then, if possible, fix it everywhere in one go.
1929   SmallString<256> Buffer;
1930   llvm::raw_svector_ostream Out(Buffer);
1931   Out << Name;
1932   StringRef RuntimeName = Out.str();
1933   auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
1934   if (Elem.second) {
1935     assert(Elem.second->getType()->getPointerElementType() == Ty &&
1936            "OMP internal variable has different type than requested");
1937   } else {
1938     // TODO: investigate the appropriate linkage type used for the global
1939     // variable for possibly changing that to internal or private, or maybe
1940     // create different versions of the function for different OMP internal
1941     // variables.
1942     Elem.second = new llvm::GlobalVariable(
1943         M, Ty, /*IsConstant*/ false, llvm::GlobalValue::CommonLinkage,
1944         llvm::Constant::getNullValue(Ty), Elem.first(),
1945         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
1946         AddressSpace);
1947   }
1948 
1949   return Elem.second;
1950 }
1951 
1952 Value *OpenMPIRBuilder::getOMPCriticalRegionLock(StringRef CriticalName) {
1953   std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
1954   std::string Name = getNameWithSeparators({Prefix, "var"}, ".", ".");
1955   return getOrCreateOMPInternalVariable(KmpCriticalNameTy, Name);
1956 }
1957 
1958 // Create all simple and struct types exposed by the runtime and remember
1959 // the llvm::PointerTypes of them for easy access later.
1960 void OpenMPIRBuilder::initializeTypes(Module &M) {
1961   LLVMContext &Ctx = M.getContext();
1962   StructType *T;
1963 #define OMP_TYPE(VarName, InitValue) VarName = InitValue;
1964 #define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize)                             \
1965   VarName##Ty = ArrayType::get(ElemTy, ArraySize);                             \
1966   VarName##PtrTy = PointerType::getUnqual(VarName##Ty);
1967 #define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...)                  \
1968   VarName = FunctionType::get(ReturnType, {__VA_ARGS__}, IsVarArg);            \
1969   VarName##Ptr = PointerType::getUnqual(VarName);
1970 #define OMP_STRUCT_TYPE(VarName, StructName, ...)                              \
1971   T = StructType::getTypeByName(Ctx, StructName);                              \
1972   if (!T)                                                                      \
1973     T = StructType::create(Ctx, {__VA_ARGS__}, StructName);                    \
1974   VarName = T;                                                                 \
1975   VarName##Ptr = PointerType::getUnqual(T);
1976 #include "llvm/Frontend/OpenMP/OMPKinds.def"
1977 }
1978 
1979 void OpenMPIRBuilder::OutlineInfo::collectBlocks(
1980     SmallPtrSetImpl<BasicBlock *> &BlockSet,
1981     SmallVectorImpl<BasicBlock *> &BlockVector) {
1982   SmallVector<BasicBlock *, 32> Worklist;
1983   BlockSet.insert(EntryBB);
1984   BlockSet.insert(ExitBB);
1985 
1986   Worklist.push_back(EntryBB);
1987   while (!Worklist.empty()) {
1988     BasicBlock *BB = Worklist.pop_back_val();
1989     BlockVector.push_back(BB);
1990     for (BasicBlock *SuccBB : successors(BB))
1991       if (BlockSet.insert(SuccBB).second)
1992         Worklist.push_back(SuccBB);
1993   }
1994 }
1995 
1996 void CanonicalLoopInfo::collectControlBlocks(
1997     SmallVectorImpl<BasicBlock *> &BBs) {
1998   // We only count those BBs as control block for which we do not need to
1999   // reverse the CFG, i.e. not the loop body which can contain arbitrary control
2000   // flow. For consistency, this also means we do not add the Body block, which
2001   // is just the entry to the body code.
2002   BBs.reserve(BBs.size() + 6);
2003   BBs.append({Preheader, Header, Cond, Latch, Exit, After});
2004 }
2005 
2006 void CanonicalLoopInfo::assertOK() const {
2007 #ifndef NDEBUG
2008   if (!IsValid)
2009     return;
2010 
2011   // Verify standard control-flow we use for OpenMP loops.
2012   assert(Preheader);
2013   assert(isa<BranchInst>(Preheader->getTerminator()) &&
2014          "Preheader must terminate with unconditional branch");
2015   assert(Preheader->getSingleSuccessor() == Header &&
2016          "Preheader must jump to header");
2017 
2018   assert(Header);
2019   assert(isa<BranchInst>(Header->getTerminator()) &&
2020          "Header must terminate with unconditional branch");
2021   assert(Header->getSingleSuccessor() == Cond &&
2022          "Header must jump to exiting block");
2023 
2024   assert(Cond);
2025   assert(Cond->getSinglePredecessor() == Header &&
2026          "Exiting block only reachable from header");
2027 
2028   assert(isa<BranchInst>(Cond->getTerminator()) &&
2029          "Exiting block must terminate with conditional branch");
2030   assert(size(successors(Cond)) == 2 &&
2031          "Exiting block must have two successors");
2032   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(0) == Body &&
2033          "Exiting block's first successor jump to the body");
2034   assert(cast<BranchInst>(Cond->getTerminator())->getSuccessor(1) == Exit &&
2035          "Exiting block's second successor must exit the loop");
2036 
2037   assert(Body);
2038   assert(Body->getSinglePredecessor() == Cond &&
2039          "Body only reachable from exiting block");
2040   assert(!isa<PHINode>(Body->front()));
2041 
2042   assert(Latch);
2043   assert(isa<BranchInst>(Latch->getTerminator()) &&
2044          "Latch must terminate with unconditional branch");
2045   assert(Latch->getSingleSuccessor() == Header && "Latch must jump to header");
2046   // TODO: To support simple redirecting of the end of the body code that has
2047   // multiple; introduce another auxiliary basic block like preheader and after.
2048   assert(Latch->getSinglePredecessor() != nullptr);
2049   assert(!isa<PHINode>(Latch->front()));
2050 
2051   assert(Exit);
2052   assert(isa<BranchInst>(Exit->getTerminator()) &&
2053          "Exit block must terminate with unconditional branch");
2054   assert(Exit->getSingleSuccessor() == After &&
2055          "Exit block must jump to after block");
2056 
2057   assert(After);
2058   assert(After->getSinglePredecessor() == Exit &&
2059          "After block only reachable from exit block");
2060   assert(After->empty() || !isa<PHINode>(After->front()));
2061 
2062   Instruction *IndVar = getIndVar();
2063   assert(IndVar && "Canonical induction variable not found?");
2064   assert(isa<IntegerType>(IndVar->getType()) &&
2065          "Induction variable must be an integer");
2066   assert(cast<PHINode>(IndVar)->getParent() == Header &&
2067          "Induction variable must be a PHI in the loop header");
2068   assert(cast<PHINode>(IndVar)->getIncomingBlock(0) == Preheader);
2069   assert(
2070       cast<ConstantInt>(cast<PHINode>(IndVar)->getIncomingValue(0))->isZero());
2071   assert(cast<PHINode>(IndVar)->getIncomingBlock(1) == Latch);
2072 
2073   auto *NextIndVar = cast<PHINode>(IndVar)->getIncomingValue(1);
2074   assert(cast<Instruction>(NextIndVar)->getParent() == Latch);
2075   assert(cast<BinaryOperator>(NextIndVar)->getOpcode() == BinaryOperator::Add);
2076   assert(cast<BinaryOperator>(NextIndVar)->getOperand(0) == IndVar);
2077   assert(cast<ConstantInt>(cast<BinaryOperator>(NextIndVar)->getOperand(1))
2078              ->isOne());
2079 
2080   Value *TripCount = getTripCount();
2081   assert(TripCount && "Loop trip count not found?");
2082   assert(IndVar->getType() == TripCount->getType() &&
2083          "Trip count and induction variable must have the same type");
2084 
2085   auto *CmpI = cast<CmpInst>(&Cond->front());
2086   assert(CmpI->getPredicate() == CmpInst::ICMP_ULT &&
2087          "Exit condition must be a signed less-than comparison");
2088   assert(CmpI->getOperand(0) == IndVar &&
2089          "Exit condition must compare the induction variable");
2090   assert(CmpI->getOperand(1) == TripCount &&
2091          "Exit condition must compare with the trip count");
2092 #endif
2093 }
2094