Polly 24.0.0git
BlockGenerators.cpp
Go to the documentation of this file.
1//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
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//
9// This file implements the BlockGenerator and VectorBlockGenerator classes,
10// which generate sequential code and vectorized code for a polyhedral
11// statement, respectively.
12//
13//===----------------------------------------------------------------------===//
14
18#include "polly/Options.h"
19#include "polly/ScopInfo.h"
23#include "llvm/Analysis/DomTreeUpdater.h"
24#include "llvm/Analysis/LoopInfo.h"
25#include "llvm/Analysis/RegionInfo.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
29#include "isl/ast.h"
30#include <deque>
31
32using namespace llvm;
33using namespace polly;
34
35static cl::opt<bool> Aligned("enable-polly-aligned",
36 cl::desc("Assumed aligned memory accesses."),
37 cl::Hidden, cl::cat(PollyCategory));
38
40static cl::opt<bool, true> DebugPrintingX(
41 "polly-codegen-add-debug-printing",
42 cl::desc("Add printf calls that show the values loaded/stored."),
43 cl::location(PollyDebugPrinting), cl::Hidden, cl::cat(PollyCategory));
44
46static cl::opt<bool, true> TraceStmtsX(
47 "polly-codegen-trace-stmts",
48 cl::desc("Add printf calls that print the statement being executed"),
49 cl::location(TraceStmts), cl::Hidden, cl::cat(PollyCategory));
50
51static cl::opt<bool> TraceScalars(
52 "polly-codegen-trace-scalars",
53 cl::desc("Add printf calls that print the values of all scalar values "
54 "used in a statement. Requires -polly-codegen-trace-stmts."),
55 cl::Hidden, cl::cat(PollyCategory));
56
64
66 ValueMapT &BBMap,
67 LoopToScevMapT &LTS,
68 Loop *L) const {
69 if (!SE.isSCEVable(Old->getType()))
70 return nullptr;
71
72 const SCEV *Scev = SE.getSCEVAtScope(Old, L);
73 if (!Scev)
74 return nullptr;
75
76 if (isa<SCEVCouldNotCompute>(Scev))
77 return nullptr;
78
79 ValueMapT VTV;
80 VTV.insert_range(BBMap);
81 VTV.insert_range(GlobalMap);
82
83 Scop &S = *Stmt.getParent();
84 const DataLayout &DL = S.getFunction().getDataLayout();
85 auto IP = Builder.GetInsertPoint();
86
87 assert(IP != Builder.GetInsertBlock()->end() &&
88 "Only instructions can be insert points for SCEVExpander");
89 Value *Expanded = expandCodeFor(
90 S, SE, Builder.GetInsertBlock()->getParent(), *GenSE, DL, "polly", Scev,
91 Old->getType(), IP, &VTV, &LTS, StartBlock->getSinglePredecessor());
92
93 BBMap[Old] = Expanded;
94 return Expanded;
95}
96
98 LoopToScevMapT &LTS, Loop *L) const {
99
100 auto lookupGlobally = [this](Value *Old) -> Value * {
101 Value *New = GlobalMap.lookup(Old);
102 if (!New)
103 return nullptr;
104
105 // Required by:
106 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll
107 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll
108 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll
109 // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll
110 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
111 // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
112 // GlobalMap should be a mapping from (value in original SCoP) to (copied
113 // value in generated SCoP), without intermediate mappings, which might
114 // easily require transitiveness as well.
115 if (Value *NewRemapped = GlobalMap.lookup(New))
116 New = NewRemapped;
117
118 // No test case for this code.
119 if (Old->getType()->getScalarSizeInBits() <
120 New->getType()->getScalarSizeInBits())
121 New = Builder.CreateTruncOrBitCast(New, Old->getType());
122
123 return New;
124 };
125
126 Value *New = nullptr;
127 auto VUse = VirtualUse::create(&Stmt, L, Old, true);
128 switch (VUse.getKind()) {
130 // BasicBlock are constants, but the BlockGenerator copies them.
131 New = BBMap.lookup(Old);
132 break;
133
135 // Used by:
136 // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll
137 // Constants should not be redefined. In this case, the GlobalMap just
138 // contains a mapping to the same constant, which is unnecessary, but
139 // harmless.
140 if ((New = lookupGlobally(Old)))
141 break;
142
143 assert(!BBMap.count(Old));
144 New = Old;
145 break;
146
148 assert(!GlobalMap.count(Old));
149
150 // Required for:
151 // * Isl/CodeGen/MemAccess/create_arrays.ll
152 // * Isl/CodeGen/read-only-scalars.ll
153 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
154 // For some reason these reload a read-only value. The reloaded value ends
155 // up in BBMap, buts its value should be identical.
156 //
157 // Required for:
158 // * Isl/CodeGen/OpenMP/single_loop_with_param.ll
159 // The parallel subfunctions need to reference the read-only value from the
160 // parent function, this is done by reloading them locally.
161 if ((New = BBMap.lookup(Old)))
162 break;
163
164 New = Old;
165 break;
166
168 // Used by:
169 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
170 // * Isl/CodeGen/OpenMP/recomputed-srem.ll
171 // * Isl/CodeGen/OpenMP/reference-other-bb.ll
172 // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll
173 // For some reason synthesizable values end up in GlobalMap. Their values
174 // are the same as trySynthesizeNewValue would return. The legacy
175 // implementation prioritized GlobalMap, so this is what we do here as well.
176 // Ideally, synthesizable values should not end up in GlobalMap.
177 if ((New = lookupGlobally(Old)))
178 break;
179
180 // Required for:
181 // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll
182 // * Isl/CodeGen/getNumberOfIterations.ll
183 // * Isl/CodeGen/non_affine_float_compare.ll
184 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
185 // Ideally, synthesizable values are synthesized by trySynthesizeNewValue,
186 // not precomputed (SCEVExpander has its own caching mechanism).
187 // These tests fail without this, but I think trySynthesizeNewValue would
188 // just re-synthesize the same instructions.
189 if ((New = BBMap.lookup(Old)))
190 break;
191
192 New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L);
193 break;
194
196 // TODO: Hoisted invariant loads should be found in GlobalMap only, but not
197 // redefined locally (which will be ignored anyway). That is, the following
198 // assertion should apply: assert(!BBMap.count(Old))
199
200 New = lookupGlobally(Old);
201 break;
202
205 assert(!GlobalMap.count(Old) &&
206 "Intra and inter-stmt values are never global");
207 New = BBMap.lookup(Old);
208 break;
209 }
210 assert(New && "Unexpected scalar dependence in region!");
211 return New;
212}
213
214void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
215 ValueMapT &BBMap, LoopToScevMapT &LTS) {
216 Instruction *NewInst = Inst->clone();
217
218 // Replace old operands with the new ones.
219 for (Value *OldOperand : Inst->operands()) {
220 Value *NewOperand =
221 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
222
223 if (!NewOperand) {
224 assert(!isa<StoreInst>(NewInst) &&
225 "Store instructions are always needed!");
226 NewInst->deleteValue();
227 return;
228 }
229
230 // FIXME: We will encounter "NewOperand" again if used twice. getNewValue()
231 // is meant to be called on old values only.
232 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
233 }
234
235 Builder.Insert(NewInst);
236 BBMap[Inst] = NewInst;
237
238 assert(NewInst->getModule() == Inst->getModule() &&
239 "Expecting instructions to be in the same module");
240
241 if (!NewInst->getType()->isVoidTy())
242 NewInst->setName("p_" + Inst->getName());
243}
244
245Value *
247 ValueMapT &BBMap, LoopToScevMapT &LTS,
248 isl_id_to_ast_expr *NewAccesses) {
249 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
251 Stmt, getLoopForStmt(Stmt),
252 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
253 NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
254}
255
257 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
258 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
259 Type *ExpectedType) {
260 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
261
262 if (AccessExpr) {
263 AccessExpr = isl_ast_expr_address_of(AccessExpr);
264 return ExprBuilder->create(AccessExpr);
265 }
266 assert(
267 Pointer &&
268 "If expression was not generated, must use the original pointer value");
269 return getNewValue(Stmt, Pointer, BBMap, LTS, L);
270}
271
272Value *
274 LoopToScevMapT &LTS, ValueMapT &BBMap,
275 __isl_keep isl_id_to_ast_expr *NewAccesses) {
276 if (Access.isLatestArrayKind())
277 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
278 LTS, NewAccesses, Access.getId().release(),
279 Access.getAccessValue()->getType());
280
281 return getOrCreateAlloca(Access);
282}
283
284Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
285 auto *StmtBB = Stmt.getEntryBlock();
286 return LI.getLoopFor(StmtBB);
287}
288
290 ValueMapT &BBMap, LoopToScevMapT &LTS,
291 isl_id_to_ast_expr *NewAccesses) {
292 if (Value *PreloadLoad = GlobalMap.lookup(Load))
293 return PreloadLoad;
294
295 Value *NewPointer =
296 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
297 Value *ScalarLoad =
298 Builder.CreateAlignedLoad(Load->getType(), NewPointer, Load->getAlign(),
299 Load->getName() + "_p_scalar_");
300
302 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
303 ": ", ScalarLoad, "\n");
304
305 return ScalarLoad;
306}
307
308void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
309 ValueMapT &BBMap, LoopToScevMapT &LTS,
310 isl_id_to_ast_expr *NewAccesses) {
311 MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
312 isl::set AccDom = MA.getAccessRelation().domain();
313 std::string Subject = MA.getId().get_name();
314
315 generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
316 Value *NewPointer =
317 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
318 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
319 LTS, getLoopForStmt(Stmt));
320
321 if (PollyDebugPrinting)
322 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
323 ": ", ValueOperand, "\n");
324
325 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlign());
326 });
327}
328
329bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
330 Loop *L = getLoopForStmt(Stmt);
331 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
332 canSynthesize(Inst, *Stmt.getParent(), &SE, L);
333}
334
335void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
336 ValueMapT &BBMap, LoopToScevMapT &LTS,
337 isl_id_to_ast_expr *NewAccesses) {
338 // Terminator instructions control the control flow. They are explicitly
339 // expressed in the clast and do not need to be copied.
340 if (Inst->isTerminator())
341 return;
342
343 // Synthesizable statements will be generated on-demand.
344 if (canSyntheziseInStmt(Stmt, Inst))
345 return;
346
347 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
348 Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
349 // Compute NewLoad before its insertion in BBMap to make the insertion
350 // deterministic.
351 BBMap[Load] = NewLoad;
352 return;
353 }
354
355 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
356 // Identified as redundant by -polly-simplify.
357 if (!Stmt.getArrayAccessOrNULLFor(Store))
358 return;
359
360 generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
361 return;
362 }
363
364 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
365 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
366 return;
367 }
368
369 // Skip some special intrinsics for which we do not adjust the semantics to
370 // the new schedule. All others are handled like every other instruction.
371 if (isIgnoredIntrinsic(Inst))
372 return;
373
374 copyInstScalar(Stmt, Inst, BBMap, LTS);
375}
376
378 auto NewBB = Builder.GetInsertBlock();
379 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
380 Instruction *NewInst = &*I;
381
382 if (!isInstructionTriviallyDead(NewInst))
383 continue;
384
385 BBMap.remove_if([&](const auto &Pair) { return Pair.second == NewInst; });
386
387 NewInst->eraseFromParent();
388 I = NewBB->rbegin();
389 }
390}
391
393 __isl_keep isl_id_to_ast_expr *NewAccesses) {
394 assert(Stmt.isBlockStmt() &&
395 "Only block statements can be copied by the block generator");
396
397 ValueMapT BBMap;
398
399 BasicBlock *BB = Stmt.getBasicBlock();
400 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
401 removeDeadInstructions(BB, BBMap);
402}
403
404BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
405 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
406 Builder.GetInsertPoint(), GenDT, GenLI);
407 CopyBB->setName("polly.stmt." + BB->getName());
408 return CopyBB;
409}
410
411BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
412 ValueMapT &BBMap, LoopToScevMapT &LTS,
413 isl_id_to_ast_expr *NewAccesses) {
414 BasicBlock *CopyBB = splitBB(BB);
415 Builder.SetInsertPoint(CopyBB->begin());
416 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
417 generateBeginStmtTrace(Stmt, LTS, BBMap);
418
419 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
420
421 // After a basic block was copied store all scalars that escape this block in
422 // their alloca.
423 generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
424 return CopyBB;
425}
426
427void BlockGenerator::switchGeneratedFunc(Function *GenFn, DominatorTree *GenDT,
428 LoopInfo *GenLI,
429 ScalarEvolution *GenSE) {
430 assert(GenFn == GenDT->getRoot()->getParent());
431 assert(GenLI->getTopLevelLoops().empty() ||
432 GenFn == GenLI->getTopLevelLoops().front()->getHeader()->getParent());
433 this->GenDT = GenDT;
434 this->GenLI = GenLI;
435 this->GenSE = GenSE;
436}
437
438void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
439 ValueMapT &BBMap, LoopToScevMapT &LTS,
440 isl_id_to_ast_expr *NewAccesses) {
441 // Block statements and the entry blocks of region statement are code
442 // generated from instruction lists. This allow us to optimize the
443 // instructions that belong to a certain scop statement. As the code
444 // structure of region statements might be arbitrary complex, optimizing the
445 // instruction list is not yet supported.
446 if (Stmt.isBlockStmt() || (Stmt.isRegionStmt() && Stmt.getEntryBlock() == BB))
447 for (Instruction *Inst : Stmt.getInstructions())
448 copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
449 else
450 for (Instruction &Inst : *BB)
451 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
452}
453
455 assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
456
458}
459
461 assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
462
463 auto &Addr = ScalarMap[Array];
464
465 if (Addr) {
466 // Allow allocas to be (temporarily) redirected once by adding a new
467 // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
468 // is used for example by the OpenMP code generation where a first use
469 // of a scalar while still in the host code allocates a normal alloca with
470 // getOrCreateAlloca. When the values of this scalar are accessed during
471 // the generation of the parallel subfunction, these values are copied over
472 // to the parallel subfunction and each request for a scalar alloca slot
473 // must be forwarded to the temporary in-subfunction slot. This mapping is
474 // removed when the subfunction has been generated and again normal host
475 // code is generated. Due to the following reasons it is not possible to
476 // perform the GlobalMap lookup right after creating the alloca below, but
477 // instead we need to check GlobalMap at each call to getOrCreateAlloca:
478 //
479 // 1) GlobalMap may be changed multiple times (for each parallel loop),
480 // 2) The temporary mapping is commonly only known after the initial
481 // alloca has already been generated, and
482 // 3) The original alloca value must be restored after leaving the
483 // sub-function.
484 if (Value *NewAddr = GlobalMap.lookup(&*Addr))
485 return NewAddr;
486 return Addr;
487 }
488
489 Type *Ty = Array->getElementType();
490 Value *ScalarBase = Array->getBasePtr();
491 std::string NameExt;
492 if (Array->isPHIKind())
493 NameExt = ".phiops";
494 else
495 NameExt = ".s2a";
496
497 const DataLayout &DL = Builder.getDataLayout();
498
499 Addr =
500 new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr,
501 DL.getPrefTypeAlign(Ty), ScalarBase->getName() + NameExt);
502 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
503 Addr->insertBefore(EntryBB->getFirstInsertionPt());
504
505 return Addr;
506}
507
509 Instruction *Inst = cast<Instruction>(Array->getBasePtr());
510
511 // If there are escape users we get the alloca for this instruction and put it
512 // in the EscapeMap for later finalization. Lastly, if the instruction was
513 // copied multiple times we already did this and can exit.
514 if (EscapeMap.count(Inst))
515 return;
516
517 EscapeUserVectorTy EscapeUsers;
518 for (User *U : Inst->users()) {
519
520 // Non-instruction user will never escape.
521 Instruction *UI = dyn_cast<Instruction>(U);
522 if (!UI)
523 continue;
524
525 if (S.contains(UI))
526 continue;
527
528 EscapeUsers.push_back(UI);
529 }
530
531 // Exit if no escape uses were found.
532 if (EscapeUsers.empty())
533 return;
534
535 // Get or create an escape alloca for this instruction.
536 auto *ScalarAddr = getOrCreateAlloca(Array);
537
538 // Remember that this instruction has escape uses and the escape alloca.
539 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
540}
541
543 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
544 __isl_keep isl_id_to_ast_expr *NewAccesses) {
545 for (MemoryAccess *MA : Stmt) {
546 if (MA->isOriginalArrayKind() || MA->isWrite())
547 continue;
548
549#ifndef NDEBUG
550 auto StmtDom =
552 // Restrict to defined behavior context to match DeLICM's contract:
553 // new read accesses are only required to cover the defined-behavior
554 // subset of the domain.
555 StmtDom = StmtDom.intersect_params(
557 auto AccDom = MA->getAccessRelation().domain();
558 assert(!StmtDom.is_subset(AccDom).is_false() &&
559 "Scalar must be loaded in all statement instances");
560#endif
561
562 auto *Address =
563 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
564 BBMap[MA->getAccessValue()] = Builder.CreateLoad(
565 MA->getElementType(), Address, Address->getName() + ".reload");
566 }
567}
568
570 const isl::set &Subdomain) {
571 isl::ast_build AstBuild = Stmt.getAstBuild();
572 isl::set Domain = Stmt.getDomain();
573
574 isl::union_map USchedule = AstBuild.get_schedule();
575 USchedule = USchedule.intersect_domain(Domain);
576
577 assert(!USchedule.is_empty());
578 isl::map Schedule = isl::map::from_union_map(USchedule);
579
580 isl::set ScheduledDomain = Schedule.range();
581 isl::set ScheduledSet = Subdomain.apply(Schedule);
582
583 isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
584
585 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
586 Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
587 IsInSetExpr = Builder.CreateICmpNE(
588 IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
589
590 return IsInSetExpr;
591}
592
594 ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
595 const std::function<void()> &GenThenFunc) {
596 isl::set StmtDom = Stmt.getDomain();
597
598 // If the condition is a tautology, don't generate a condition around the
599 // code.
600 bool IsPartialWrite =
601 !StmtDom.intersect_params(Stmt.getParent()->getContext())
602 .is_subset(Subdomain);
603 if (!IsPartialWrite) {
604 GenThenFunc();
605 return;
606 }
607
608 // Generate the condition.
609 Value *Cond = buildContainsCondition(Stmt, Subdomain);
610
611 // Don't call GenThenFunc if it is never executed. An ast index expression
612 // might not be defined in this case.
613 if (auto *Const = dyn_cast<ConstantInt>(Cond))
614 if (Const->isZero())
615 return;
616
617 BasicBlock *HeadBlock = Builder.GetInsertBlock();
618 StringRef BlockName = HeadBlock->getName();
619
620 // Generate the conditional block.
621 DomTreeUpdater DTU(GenDT, DomTreeUpdater::UpdateStrategy::Eager);
622 SplitBlockAndInsertIfThen(Cond, Builder.GetInsertPoint(), false, nullptr,
623 &DTU, GenLI);
624 CondBrInst *Branch = cast<CondBrInst>(HeadBlock->getTerminator());
625 BasicBlock *ThenBlock = Branch->getSuccessor(0);
626 BasicBlock *TailBlock = Branch->getSuccessor(1);
627
628 // Assign descriptive names.
629 if (auto *CondInst = dyn_cast<Instruction>(Cond))
630 CondInst->setName("polly." + Subject + ".cond");
631 ThenBlock->setName(BlockName + "." + Subject + ".partial");
632 TailBlock->setName(BlockName + ".cont");
633
634 // Put the client code into the conditional block and continue in the merge
635 // block afterwards.
636 Builder.SetInsertPoint(ThenBlock->getFirstInsertionPt());
637 GenThenFunc();
638 Builder.SetInsertPoint(TailBlock->getFirstInsertionPt());
639}
640
641static std::string getInstName(Value *Val) {
642 std::string Result;
643 raw_string_ostream OS(Result);
644 Val->printAsOperand(OS, false);
645 return Result;
646}
647
649 ValueMapT &BBMap) {
650 if (!TraceStmts)
651 return;
652
653 Scop *S = Stmt.getParent();
654 const char *BaseName = Stmt.getBaseName();
655
656 isl::ast_build AstBuild = Stmt.getAstBuild();
657 isl::set Domain = Stmt.getDomain();
658
659 isl::union_map USchedule = AstBuild.get_schedule().intersect_domain(Domain);
660 isl::map Schedule = isl::map::from_union_map(USchedule);
661 assert(Schedule.is_empty().is_false() &&
662 "The stmt must have a valid instance");
663
664 isl::multi_pw_aff ScheduleMultiPwAff =
666 isl::ast_build RestrictedBuild = AstBuild.restrict(Schedule.range());
667
668 // Sequence of strings to print.
669 SmallVector<llvm::Value *, 8> Values;
670
671 // Print the name of the statement.
672 // TODO: Indent by the depth of the statement instance in the schedule tree.
673 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, BaseName));
674 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "("));
675
676 // Add the coordinate of the statement instance.
677 for (unsigned i : rangeIslSize(0, ScheduleMultiPwAff.dim(isl::dim::out))) {
678 if (i > 0)
679 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ","));
680
681 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduleMultiPwAff.at(i));
682 Values.push_back(ExprBuilder->create(IsInSet.copy()));
683 }
684
685 if (TraceScalars) {
686 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")"));
687 DenseSet<Instruction *> Encountered;
688
689 // Add the value of each scalar (and the result of PHIs) used in the
690 // statement.
691 // TODO: Values used in region-statements.
692 for (Instruction *Inst : Stmt.insts()) {
693 if (!RuntimeDebugBuilder::isPrintable(Inst->getType()))
694 continue;
695
696 if (isa<PHINode>(Inst)) {
697 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " "));
699 Builder, getInstName(Inst)));
700 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "="));
701 Values.push_back(getNewValue(Stmt, Inst, BBMap, LTS,
702 LI.getLoopFor(Inst->getParent())));
703 } else {
704 for (Value *Op : Inst->operand_values()) {
705 // Do not print values that cannot change during the execution of the
706 // SCoP.
707 auto *OpInst = dyn_cast<Instruction>(Op);
708 if (!OpInst)
709 continue;
710 if (!S->contains(OpInst))
711 continue;
712
713 // Print each scalar at most once, and exclude values defined in the
714 // statement itself.
715 if (Encountered.count(OpInst))
716 continue;
717
718 Values.push_back(
721 Builder, getInstName(OpInst)));
722 Values.push_back(
724 Values.push_back(getNewValue(Stmt, OpInst, BBMap, LTS,
725 LI.getLoopFor(Inst->getParent())));
726 Encountered.insert(OpInst);
727 }
728 }
729
730 Encountered.insert(Inst);
731 }
732
733 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n"));
734 } else {
735 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")\n"));
736 }
737
738 RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values));
739}
740
742 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
743 __isl_keep isl_id_to_ast_expr *NewAccesses) {
744 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
745
746 assert(Stmt.isBlockStmt() &&
747 "Region statements need to use the generateScalarStores() function in "
748 "the RegionGenerator");
749
750 for (MemoryAccess *MA : Stmt) {
751 if (MA->isOriginalArrayKind() || MA->isRead())
752 continue;
753
754 isl::set AccDom = MA->getAccessRelation().domain();
755 std::string Subject = MA->getId().get_name();
756
758 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
759 Value *Val = MA->getAccessValue();
760 if (MA->isAnyPHIKind()) {
761 assert(MA->getIncoming().size() >= 1 &&
762 "Block statements have exactly one exiting block, or "
763 "multiple but "
764 "with same incoming block and value");
765 assert(std::all_of(MA->getIncoming().begin(),
766 MA->getIncoming().end(),
767 [&](std::pair<BasicBlock *, Value *> p) -> bool {
768 return p.first == Stmt.getBasicBlock();
769 }) &&
770 "Incoming block must be statement's block");
771 Val = MA->getIncoming()[0].second;
772 }
773 auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
774 BBMap, NewAccesses);
775
776 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
777 assert((!isa<Instruction>(Val) ||
778 GenDT->dominates(cast<Instruction>(Val)->getParent(),
779 Builder.GetInsertBlock())) &&
780 "Domination violation");
781 assert((!isa<Instruction>(Address) ||
782 GenDT->dominates(cast<Instruction>(Address)->getParent(),
783 Builder.GetInsertBlock())) &&
784 "Domination violation");
785
786 Builder.CreateStore(Val, Address);
787 });
788 }
789}
790
792 BasicBlock *ExitBB = S.getExit();
793 BasicBlock *PreEntryBB = S.getEnteringBlock();
794
795 Builder.SetInsertPoint(StartBlock->begin());
796
797 for (auto &Array : S.arrays()) {
798 if (Array->getNumberOfDimensions() != 0)
799 continue;
800 if (Array->isPHIKind()) {
801 // For PHI nodes, the only values we need to store are the ones that
802 // reach the PHI node from outside the region. In general there should
803 // only be one such incoming edge and this edge should enter through
804 // 'PreEntryBB'.
805 auto PHI = cast<PHINode>(Array->getBasePtr());
806
807 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
808 if (!S.contains(*BI) && *BI != PreEntryBB)
809 llvm_unreachable("Incoming edges from outside the scop should always "
810 "come from PreEntryBB");
811
812 int Idx = PHI->getBasicBlockIndex(PreEntryBB);
813 if (Idx < 0)
814 continue;
815
816 Value *ScalarValue = PHI->getIncomingValue(Idx);
817
818 Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
819 continue;
820 }
821
822 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
823
824 if (Inst && S.contains(Inst))
825 continue;
826
827 // PHI nodes that are not marked as such in their SAI object are either exit
828 // PHI nodes we model as common scalars but without initialization, or
829 // incoming phi nodes that need to be initialized. Check if the first is the
830 // case for Inst and do not create and initialize memory if so.
831 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
832 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
833 continue;
834
835 Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
836 }
837}
838
840 // The exit block of the __unoptimized__ region.
841 BasicBlock *ExitBB = S.getExitingBlock();
842 // The merge block __just after__ the region and the optimized region.
843 BasicBlock *MergeBB = S.getExit();
844
845 // The exit block of the __optimized__ region.
846 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
847 if (OptExitBB == ExitBB)
848 OptExitBB = *(++pred_begin(MergeBB));
849
850 Builder.SetInsertPoint(OptExitBB->getTerminator()->getIterator());
851 for (const auto &EscapeMapping : EscapeMap) {
852 // Extract the escaping instruction and the escaping users as well as the
853 // alloca the instruction was demoted to.
854 Instruction *EscapeInst = EscapeMapping.first;
855 const auto &EscapeMappingValue = EscapeMapping.second;
856 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
857 auto *ScalarAddr = cast<AllocaInst>(&*EscapeMappingValue.first);
858
859 // Reload the demoted instruction in the optimized version of the SCoP.
860 Value *EscapeInstReload =
861 Builder.CreateLoad(ScalarAddr->getAllocatedType(), ScalarAddr,
862 EscapeInst->getName() + ".final_reload");
863 EscapeInstReload =
864 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
865
866 // Create the merge PHI that merges the optimized and unoptimized version.
867 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
868 EscapeInst->getName() + ".merge");
869 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
870
871 // Add the respective values to the merge PHI.
872 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
873 MergePHI->addIncoming(EscapeInst, ExitBB);
874
875 // The information of scalar evolution about the escaping instruction needs
876 // to be revoked so the new merged instruction will be used.
877 if (SE.isSCEVable(EscapeInst->getType()))
878 SE.forgetValue(EscapeInst);
879
880 // Replace all uses of the demoted instruction with the merge PHI.
881 for (Instruction *EUser : EscapeUsers)
882 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
883 }
884}
885
887 for (auto &Array : S.arrays()) {
888
889 if (Array->getNumberOfDimensions() != 0)
890 continue;
891
892 if (Array->isPHIKind())
893 continue;
894
895 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
896
897 if (!Inst)
898 continue;
899
900 // Scop invariant hoisting moves some of the base pointers out of the scop.
901 // We can ignore these, as the invariant load hoisting already registers the
902 // relevant outside users.
903 if (!S.contains(Inst))
904 continue;
905
907 }
908}
909
911 if (S.hasSingleExitEdge())
912 return;
913
914 auto *ExitBB = S.getExitingBlock();
915 auto *MergeBB = S.getExit();
916 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
917 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
918 if (OptExitBB == ExitBB)
919 OptExitBB = *(++pred_begin(MergeBB));
920
921 Builder.SetInsertPoint(OptExitBB->getTerminator()->getIterator());
922
923 for (auto &SAI : S.arrays()) {
924 auto *Val = SAI->getBasePtr();
925
926 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
927 // the original PHI's value or the reloaded incoming values from the
928 // generated code. An llvm::Value is merged between the original code's
929 // value or the generated one.
930 if (!SAI->isExitPHIKind())
931 continue;
932
933 PHINode *PHI = dyn_cast<PHINode>(Val);
934 if (!PHI)
935 continue;
936
937 if (PHI->getParent() != AfterMergeBB)
938 continue;
939
940 std::string Name = PHI->getName().str();
941 Value *ScalarAddr = getOrCreateAlloca(SAI);
942 Value *Reload = Builder.CreateLoad(SAI->getElementType(), ScalarAddr,
943 Name + ".ph.final_reload");
944 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
945 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
946 assert((!isa<Instruction>(OriginalValue) ||
947 cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
948 "Original value must no be one we just generated.");
949 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
950 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
951 MergePHI->addIncoming(Reload, OptExitBB);
952 MergePHI->addIncoming(OriginalValue, ExitBB);
953 int Idx = PHI->getBasicBlockIndex(MergeBB);
954 PHI->setIncomingValue(Idx, MergePHI);
955 }
956}
957
959 for (auto &Stmt : S)
960 if (Stmt.isCopyStmt())
961 continue;
962 else if (Stmt.isBlockStmt())
963 for (auto &Inst : *Stmt.getBasicBlock())
964 SE.forgetValue(&Inst);
965 else if (Stmt.isRegionStmt())
966 for (auto *BB : Stmt.getRegion()->blocks())
967 for (auto &Inst : *BB)
968 SE.forgetValue(&Inst);
969 else
970 llvm_unreachable("Unexpected statement type found");
971
972 // Invalidate SCEV of loops surrounding the EscapeUsers.
973 for (const auto &EscapeMapping : EscapeMap) {
974 const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
975 for (Instruction *EUser : EscapeUsers) {
976 if (Loop *L = LI.getLoopFor(EUser->getParent()))
977 while (L) {
978 SE.forgetLoop(L);
979 L = L->getParentLoop();
980 }
981 }
982 }
983}
984
992
993BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
994 BasicBlock *BBCopy) {
995
996 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
997 BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
998
999 if (BBCopyIDom)
1000 GenDT->changeImmediateDominator(BBCopy, BBCopyIDom);
1001
1002 return StartBlockMap.lookup(BBIDom);
1003}
1004
1005// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1006// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1007// does not work in cases where the exit block has edges from outside the
1008// region. In that case the llvm::Value would never be usable in in the exit
1009// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1010// for the subregion's exiting edges only. We need to determine whether an
1011// llvm::Value is usable in there. We do this by checking whether it dominates
1012// all exiting blocks individually.
1013static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1014 BasicBlock *BB) {
1015 for (auto ExitingBB : predecessors(R->getExit())) {
1016 // Check for non-subregion incoming edges.
1017 if (!R->contains(ExitingBB))
1018 continue;
1019
1020 if (!DT.dominates(BB, ExitingBB))
1021 return false;
1022 }
1023
1024 return true;
1025}
1026
1027// Find the direct dominator of the subregion's exit block if the subregion was
1028// simplified.
1029static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1030 BasicBlock *Common = nullptr;
1031 for (auto ExitingBB : predecessors(R->getExit())) {
1032 // Check for non-subregion incoming edges.
1033 if (!R->contains(ExitingBB))
1034 continue;
1035
1036 // First exiting edge.
1037 if (!Common) {
1038 Common = ExitingBB;
1039 continue;
1040 }
1041
1042 Common = DT.findNearestCommonDominator(Common, ExitingBB);
1043 }
1044
1045 assert(Common && R->contains(Common));
1046 return Common;
1047}
1048
1050 __isl_keep isl_id_to_ast_expr *IdToAstExp) {
1051 assert(Stmt.isRegionStmt() &&
1052 "Only region statements can be copied by the region generator");
1053
1054 // Forget all old mappings.
1055 StartBlockMap.clear();
1056 EndBlockMap.clear();
1057 RegionMaps.clear();
1058 IncompletePHINodeMap.clear();
1059
1060 // Collection of all values related to this subregion.
1061 ValueMapT ValueMap;
1062
1063 // The region represented by the statement.
1064 Region *R = Stmt.getRegion();
1065
1066 // Create a dedicated entry for the region where we can reload all demoted
1067 // inputs.
1068 BasicBlock *EntryBB = R->getEntry();
1069 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1070 Builder.GetInsertPoint(), GenDT, GenLI);
1071 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1072 Builder.SetInsertPoint(EntryBBCopy->begin());
1073
1074 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1075 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1076 generateBeginStmtTrace(Stmt, LTS, EntryBBMap);
1077
1078 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1079 if (!R->contains(*PI)) {
1080 StartBlockMap[*PI] = EntryBBCopy;
1081 EndBlockMap[*PI] = EntryBBCopy;
1082 }
1083
1084 // Iterate over all blocks in the region in a breadth-first search.
1085 std::deque<BasicBlock *> Blocks;
1086 SmallSetVector<BasicBlock *, 8> SeenBlocks;
1087 Blocks.push_back(EntryBB);
1088 SeenBlocks.insert(EntryBB);
1089
1090 while (!Blocks.empty()) {
1091 BasicBlock *BB = Blocks.front();
1092 Blocks.pop_front();
1093
1094 // First split the block and update dominance information.
1095 BasicBlock *BBCopy = splitBB(BB);
1096 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1097
1098 // Get the mapping for this block and initialize it with either the scalar
1099 // loads from the generated entering block (which dominates all blocks of
1100 // this subregion) or the maps of the immediate dominator, if part of the
1101 // subregion. The latter necessarily includes the former.
1102 ValueMapT *InitBBMap;
1103 if (BBCopyIDom) {
1104 assert(RegionMaps.count(BBCopyIDom));
1105 InitBBMap = &RegionMaps[BBCopyIDom];
1106 } else
1107 InitBBMap = &EntryBBMap;
1108 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1109 ValueMapT &RegionMap = Inserted.first->second;
1110
1111 // Copy the block with the BlockGenerator.
1112 Builder.SetInsertPoint(BBCopy->begin());
1113 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1114
1115 // In order to remap PHI nodes we store also basic block mappings.
1116 StartBlockMap[BB] = BBCopy;
1117 EndBlockMap[BB] = Builder.GetInsertBlock();
1118
1119 // Add values to incomplete PHI nodes waiting for this block to be copied.
1120 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1121 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1122 IncompletePHINodeMap[BB].clear();
1123
1124 // And continue with new successors inside the region.
1125 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1126 if (R->contains(*SI) && SeenBlocks.insert(*SI))
1127 Blocks.push_back(*SI);
1128
1129 // Remember value in case it is visible after this subregion.
1130 if (isDominatingSubregionExit(DT, R, BB))
1131 ValueMap.insert_range(RegionMap);
1132 }
1133
1134 // Now create a new dedicated region exit block and add it to the region map.
1135 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1136 Builder.GetInsertPoint(), GenDT, GenLI);
1137 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1138 StartBlockMap[R->getExit()] = ExitBBCopy;
1139 EndBlockMap[R->getExit()] = ExitBBCopy;
1140
1141 BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1142 assert(ExitDomBBCopy &&
1143 "Common exit dominator must be within region; at least the entry node "
1144 "must match");
1145 GenDT->changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1146
1147 // As the block generator doesn't handle control flow we need to add the
1148 // region control flow by hand after all blocks have been copied.
1149 for (BasicBlock *BB : SeenBlocks) {
1150
1151 BasicBlock *BBCopyStart = StartBlockMap[BB];
1152 BasicBlock *BBCopyEnd = EndBlockMap[BB];
1153 Instruction *TI = BB->getTerminator();
1154 if (isa<UnreachableInst>(TI)) {
1155 while (!BBCopyEnd->empty())
1156 BBCopyEnd->begin()->eraseFromParent();
1157 new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1158 continue;
1159 }
1160
1161 Instruction *BICopy = BBCopyEnd->getTerminator();
1162
1163 ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1164 RegionMap.insert_range(StartBlockMap);
1165
1166 Builder.SetInsertPoint(BICopy->getIterator());
1167 copyInstScalar(Stmt, TI, RegionMap, LTS);
1168 BICopy->eraseFromParent();
1169 }
1170
1171 // Add counting PHI nodes to all loops in the region that can be used as
1172 // replacement for SCEVs referring to the old loop.
1173 for (BasicBlock *BB : SeenBlocks) {
1174 Loop *L = LI.getLoopFor(BB);
1175 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1176 continue;
1177
1178 BasicBlock *BBCopy = StartBlockMap[BB];
1179 Value *NullVal = Builder.getInt32(0);
1180 PHINode *LoopPHI =
1181 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1182 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1183 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1184 LoopPHI->insertBefore(BBCopy->begin());
1185 LoopPHIInc->insertBefore(BBCopy->getTerminator()->getIterator());
1186
1187 for (auto *PredBB : predecessors(BB)) {
1188 if (!R->contains(PredBB))
1189 continue;
1190 if (L->contains(PredBB))
1191 LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1192 else
1193 LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1194 }
1195
1196 for (auto *PredBBCopy : predecessors(BBCopy))
1197 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1198 LoopPHI->addIncoming(NullVal, PredBBCopy);
1199
1200 LTS[L] = SE.getUnknown(LoopPHI);
1201 }
1202
1203 // Continue generating code in the exit block.
1204 Builder.SetInsertPoint(ExitBBCopy->getFirstInsertionPt());
1205
1206 // Write values visible to other statements.
1207 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1208 StartBlockMap.clear();
1209 EndBlockMap.clear();
1210 RegionMaps.clear();
1211 IncompletePHINodeMap.clear();
1212}
1213
1215 ValueMapT &BBMap, Loop *L) {
1216 ScopStmt *Stmt = MA->getStatement();
1217 Region *SubR = Stmt->getRegion();
1218 auto Incoming = MA->getIncoming();
1219
1220 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1221 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1222 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1223
1224 // This can happen if the subregion is simplified after the ScopStmts
1225 // have been created; simplification happens as part of CodeGeneration.
1226 if (OrigPHI->getParent() != SubR->getExit()) {
1227 BasicBlock *FormerExit = SubR->getExitingBlock();
1228 if (FormerExit)
1229 NewSubregionExit = StartBlockMap.lookup(FormerExit);
1230 }
1231
1232 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1233 "polly." + OrigPHI->getName(),
1234 NewSubregionExit->getFirstNonPHIIt());
1235
1236 // Add the incoming values to the PHI.
1237 for (auto &Pair : Incoming) {
1238 BasicBlock *OrigIncomingBlock = Pair.first;
1239 BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1240 BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1241 Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator()->getIterator());
1242 assert(RegionMaps.count(NewIncomingBlockStart));
1243 assert(RegionMaps.count(NewIncomingBlockEnd));
1244 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1245
1246 Value *OrigIncomingValue = Pair.second;
1247 Value *NewIncomingValue =
1248 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1249 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1250 }
1251
1252 return NewPHI;
1253}
1254
1256 ValueMapT &BBMap) {
1257 ScopStmt *Stmt = MA->getStatement();
1258
1259 // TODO: Add some test cases that ensure this is really the right choice.
1260 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1261
1262 if (MA->isAnyPHIKind()) {
1263 auto Incoming = MA->getIncoming();
1264 assert(!Incoming.empty() &&
1265 "PHI WRITEs must have originate from at least one incoming block");
1266
1267 // If there is only one incoming value, we do not need to create a PHI.
1268 if (Incoming.size() == 1) {
1269 Value *OldVal = Incoming[0].second;
1270 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1271 }
1272
1273 return buildExitPHI(MA, LTS, BBMap, L);
1274 }
1275
1276 // MemoryKind::Value accesses leaving the subregion must dominate the exit
1277 // block; just pass the copied value.
1278 Value *OldVal = MA->getAccessValue();
1279 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1280}
1281
1283 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1284 __isl_keep isl_id_to_ast_expr *NewAccesses) {
1285 assert(Stmt.getRegion() &&
1286 "Block statements need to use the generateScalarStores() "
1287 "function in the BlockGenerator");
1288
1289 // Get the exit scalar values before generating the writes.
1290 // This is necessary because RegionGenerator::getExitScalar may insert
1291 // PHINodes that depend on the region's exiting blocks. But
1292 // BlockGenerator::generateConditionalExecution may insert a new basic block
1293 // such that the current basic block is not a direct successor of the exiting
1294 // blocks anymore. Hence, build the PHINodes while the current block is still
1295 // the direct successor.
1296 SmallDenseMap<MemoryAccess *, Value *> NewExitScalars;
1297 for (MemoryAccess *MA : Stmt) {
1298 if (MA->isOriginalArrayKind() || MA->isRead())
1299 continue;
1300
1301 Value *NewVal = getExitScalar(MA, LTS, BBMap);
1302 NewExitScalars[MA] = NewVal;
1303 }
1304
1305 for (MemoryAccess *MA : Stmt) {
1306 if (MA->isOriginalArrayKind() || MA->isRead())
1307 continue;
1308
1309 isl::set AccDom = MA->getAccessRelation().domain();
1310 std::string Subject = MA->getId().get_name();
1312 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1313 Value *NewVal = NewExitScalars.lookup(MA);
1314 assert(NewVal && "The exit scalar must be determined before");
1315 Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1316 BBMap, NewAccesses);
1317 assert((!isa<Instruction>(NewVal) ||
1318 GenDT->dominates(cast<Instruction>(NewVal)->getParent(),
1319 Builder.GetInsertBlock())) &&
1320 "Domination violation");
1321 assert((!isa<Instruction>(Address) ||
1322 GenDT->dominates(cast<Instruction>(Address)->getParent(),
1323 Builder.GetInsertBlock())) &&
1324 "Domination violation");
1325 Builder.CreateStore(NewVal, Address);
1326 });
1327 }
1328}
1329
1331 PHINode *PHICopy, BasicBlock *IncomingBB,
1332 LoopToScevMapT &LTS) {
1333 // If the incoming block was not yet copied mark this PHI as incomplete.
1334 // Once the block will be copied the incoming value will be added.
1335 BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1336 BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1337 if (!BBCopyStart) {
1338 assert(!BBCopyEnd);
1339 assert(Stmt.represents(IncomingBB) &&
1340 "Bad incoming block for PHI in non-affine region");
1341 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1342 return;
1343 }
1344
1345 assert(RegionMaps.count(BBCopyStart) &&
1346 "Incoming PHI block did not have a BBMap");
1347 ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1348
1349 Value *OpCopy = nullptr;
1350
1351 if (Stmt.represents(IncomingBB)) {
1352 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1353
1354 // If the current insert block is different from the PHIs incoming block
1355 // change it, otherwise do not.
1356 auto IP = Builder.GetInsertPoint();
1357 if (IP->getParent() != BBCopyEnd)
1358 Builder.SetInsertPoint(BBCopyEnd->getTerminator()->getIterator());
1359 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1360 if (IP->getParent() != BBCopyEnd)
1361 Builder.SetInsertPoint(IP);
1362 } else {
1363 // All edges from outside the non-affine region become a single edge
1364 // in the new copy of the non-affine region. Make sure to only add the
1365 // corresponding edge the first time we encounter a basic block from
1366 // outside the non-affine region.
1367 if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1368 return;
1369
1370 // Get the reloaded value.
1371 OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1372 }
1373
1374 assert(OpCopy && "Incoming PHI value was not copied properly");
1375 PHICopy->addIncoming(OpCopy, BBCopyEnd);
1376}
1377
1379 ValueMapT &BBMap,
1380 LoopToScevMapT &LTS) {
1381 unsigned NumIncoming = PHI->getNumIncomingValues();
1382 PHINode *PHICopy =
1383 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1384 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHIIt());
1385 BBMap[PHI] = PHICopy;
1386
1387 for (BasicBlock *IncomingBB : PHI->blocks())
1388 addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1389}
static cl::opt< bool > Aligned("enable-polly-aligned", cl::desc("Assumed aligned memory accesses."), cl::Hidden, cl::cat(PollyCategory))
static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, BasicBlock *BB)
static BasicBlock * findExitDominator(DominatorTree &DT, Region *R)
static cl::opt< bool, true > TraceStmtsX("polly-codegen-trace-stmts", cl::desc("Add printf calls that print the statement being executed"), cl::location(TraceStmts), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool, true > DebugPrintingX("polly-codegen-add-debug-printing", cl::desc("Add printf calls that show the values loaded/stored."), cl::location(PollyDebugPrinting), cl::Hidden, cl::cat(PollyCategory))
static std::string getInstName(Value *Val)
static cl::opt< bool > TraceScalars("polly-codegen-trace-scalars", cl::desc("Add printf calls that print the values of all scalar values " "used in a statement. Requires -polly-codegen-trace-stmts."), cl::Hidden, cl::cat(PollyCategory))
llvm::cl::OptionCategory PollyCategory
bool TraceStmts
bool PollyDebugPrinting
__isl_give isl_ast_expr * isl_ast_expr_address_of(__isl_take isl_ast_expr *expr)
Definition isl_ast.c:649
isl::checked::union_map get_schedule() const
isl::checked::ast_expr expr_from(isl::checked::pw_aff pa) const
__isl_give isl_ast_expr * copy() const &
bool is_false() const
Definition cpp-checked.h:76
__isl_give isl_id * release()
std::string get_name() const
isl::checked::map reverse() const
isl::checked::set range() const
isl::checked::set domain() const
boolean is_empty() const
isl::checked::pw_aff at(int pos) const
isl::checked::set intersect_params(isl::checked::set params) const
boolean is_subset(const isl::checked::set &set2) const
isl::checked::set apply(isl::checked::map map) const
isl::checked::union_map intersect_domain(isl::checked::space space) const
boolean is_empty() const
static isl::map from_union_map(isl::union_map umap)
static isl::pw_multi_aff from_map(isl::map map)
Loop * getLoopForStmt(const ScopStmt &Stmt) const
Get the innermost loop that surrounds the statement Stmt.
EscapeUsersAllocaMapTy & EscapeMap
Map from instructions to their escape users as well as the alloca.
Value * getImplicitAddress(MemoryAccess &Access, Loop *L, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate the pointer value that is accesses by Access.
DominatorTree & DT
The dominator tree of this function.
BasicBlock * splitBB(BasicBlock *BB)
Split BB to create a new one we can use to clone BB in.
void generateBeginStmtTrace(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap)
When statement tracing is enabled, build the print instructions for printing the current statement in...
Value * trySynthesizeNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, LoopToScevMapT &LTS, Loop *L) const
Try to synthesize a new value.
void generateScalarLoads(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate reload of scalars demoted to memory and needed by Stmt.
AllocaMapTy & ScalarMap
Map to resolve scalar dependences for PHI operands and scalars.
PollyIRBuilder & Builder
DenseMap< const ScopArrayInfo *, AssertingVH< AllocaInst > > AllocaMapTy
Map types to resolve scalar dependences.
void createExitPHINodeMerges(Scop &S)
Create exit PHI node merges for PHI nodes with more than two edges from inside the scop.
void copyInstScalar(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS)
Value * generateArrayLoad(ScopStmt &Stmt, LoadInst *load, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Value * buildContainsCondition(ScopStmt &Stmt, const isl::set &Subdomain)
Generate instructions that compute whether one instance of Set is executed.
void finalizeSCoP(Scop &S)
Finalize the code generation for the SCoP S.
void createScalarInitialization(Scop &S)
Initialize the memory of demoted scalars.
SmallVector< Instruction *, 4 > EscapeUserVectorTy
Simple vector of instructions to store escape users.
bool canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst)
Helper to determine if Inst can be synthesized in Stmt.
virtual void generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate the scalar stores for the given statement.
ScalarEvolution & SE
IslExprBuilder * ExprBuilder
void handleOutsideUsers(const Scop &S, ScopArrayInfo *Array)
Handle users of Array outside the SCoP.
void createScalarFinalization(Scop &S)
Promote the values of demoted scalars after the SCoP.
void switchGeneratedFunc(Function *GenFn, DominatorTree *GenDT, LoopInfo *GenLI, ScalarEvolution *GenSE)
Change the function that code is emitted into.
Value * getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, LoopToScevMapT &LTS, Loop *L) const
Get the new version of a value.
ValueMapT & GlobalMap
A map from llvm::Values referenced in the old code to a new set of llvm::Values, which is used to rep...
void findOutsideUsers(Scop &S)
Find scalar statements that have outside users.
void generateArrayStore(ScopStmt &Stmt, StoreInst *store, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
DominatorTree * GenDT
Relates to the region where the code is emitted into.
MapVector< Instruction *, std::pair< AssertingVH< Value >, EscapeUserVectorTy > > EscapeUsersAllocaMapTy
Map type to resolve escaping users for scalar instructions.
BasicBlock * copyBB(ScopStmt &Stmt, BasicBlock *BB, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy the given basic block.
virtual void copyPHIInstruction(ScopStmt &, PHINode *, ValueMapT &, LoopToScevMapT &)
Copy a single PHI instruction.
void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy the basic block.
BasicBlock * StartBlock
The first basic block after the RTC.
void copyInstruction(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy a single Instruction.
void invalidateScalarEvolution(Scop &S)
Invalidate the scalar evolution expressions for a scop.
BlockGenerator(PollyIRBuilder &Builder, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT, AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap, ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
Create a generator for basic blocks.
ScalarEvolution * GenSE
void removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap)
Remove dead instructions generated for BB.
Value * generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Generate the operand address.
Value * getOrCreateAlloca(const MemoryAccess &Access)
Return the alloca for Access.
void generateConditionalExecution(ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject, const std::function< void()> &GenThenFunc)
Generate code that executes in a subset of Stmt's domain.
LLVM-IR generator for isl_ast_expr[essions].
Utility proxy to wrap the common members of LoadInst and StoreInst.
Definition ScopHelper.h:141
bool isNull() const
Definition ScopHelper.h:306
llvm::Value * getPointerOperand() const
Definition ScopHelper.h:249
Represent memory accesses in statements.
Definition ScopInfo.h:428
const ScopArrayInfo * getLatestScopArrayInfo() const
Get the ScopArrayInfo object for the base address, or the one set by setNewAccessRelation().
Definition ScopInfo.cpp:610
bool isAnyPHIKind() const
Old name of isOriginalAnyPHIKind().
Definition ScopInfo.h:1025
bool isLatestArrayKind() const
Whether storage memory is either an custom .s2a/.phiops alloca (false) or an existing pointer into an...
Definition ScopInfo.h:947
Instruction * getAccessInstruction() const
Return the access instruction of this memory access.
Definition ScopInfo.h:882
isl::id getId() const
Get identifier for the memory access.
Definition ScopInfo.cpp:967
ArrayRef< std::pair< BasicBlock *, Value * > > getIncoming() const
Return the list of possible PHI/ExitPHI values.
Definition ScopInfo.h:745
ScopStmt * getStatement() const
Get the statement that contains this memory access.
Definition ScopInfo.h:1028
isl::map getAccessRelation() const
Old name of getLatestAccessRelation().
Definition ScopInfo.h:792
Value * getAccessValue() const
Return the access value of this memory access.
Definition ScopInfo.h:864
std::pair< PHINode *, PHINode * > PHINodePairTy
Mapping to remember PHI nodes that still need incoming values.
void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS, __isl_keep isl_id_to_ast_expr *IdToAstExp)
Copy the region statement Stmt.
DenseMap< BasicBlock *, SmallVector< PHINodePairTy, 4 > > IncompletePHINodeMap
void addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, PHINode *PHICopy, BasicBlock *IncomingBB, LoopToScevMapT &LTS)
Add the new operand from the copy of IncomingBB to PHICopy.
void copyPHIInstruction(ScopStmt &Stmt, PHINode *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS) override
Copy a single PHI instruction.
DenseMap< BasicBlock *, BasicBlock * > EndBlockMap
A map from old to the last new block in the region, that was created to model the old basic block.
Value * getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap)
DenseMap< BasicBlock *, BasicBlock * > StartBlockMap
A map from old to the first new block in the region, that was created to model the old basic block.
void generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMAp, __isl_keep isl_id_to_ast_expr *NewAccesses) override
Generate the scalar stores for the given statement.
DenseMap< BasicBlock *, ValueMapT > RegionMaps
The "BBMaps" for the whole region (one for each block).
PHINode * buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap, Loop *L)
Create a PHI that combines the incoming values from all incoming blocks that are in the subregion.
BasicBlock * repairDominance(BasicBlock *BB, BasicBlock *BBCopy)
Repair the dominance tree after we created a copy block for BB.
A class to store information about arrays in the SCoP.
Definition ScopInfo.h:216
Statement of the Scop.
Definition ScopInfo.h:1137
MemoryAccess & getArrayAccessFor(const Instruction *Inst) const
Return the only array access for Inst.
Definition ScopInfo.h:1431
Scop * getParent()
Definition ScopInfo.h:1525
BasicBlock * getEntryBlock() const
Return a BasicBlock from this statement.
const std::vector< Instruction * > & getInstructions() const
Definition ScopInfo.h:1528
bool isBlockStmt() const
Return true if this statement represents a single basic block.
Definition ScopInfo.h:1318
Region * getRegion() const
Get the region represented by this ScopStmt (if any).
Definition ScopInfo.h:1327
bool represents(BasicBlock *BB) const
Return whether this statement represents BB.
Definition ScopInfo.h:1348
iterator_range< std::vector< Instruction * >::const_iterator > insts() const
The range of instructions in this statement.
Definition ScopInfo.h:1547
BasicBlock * getBasicBlock() const
Get the BasicBlock represented by this ScopStmt (if any).
Definition ScopInfo.h:1315
const char * getBaseName() const
isl::ast_build getAstBuild() const
Get the isl AST build.
Definition ScopInfo.h:1562
MemoryAccess * getArrayAccessOrNULLFor(const Instruction *Inst) const
Return the only array access for Inst, if existing.
Definition ScopInfo.h:1408
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1330
isl::set getDomain() const
Get the iteration domain of this ScopStmt.
Static Control Part.
Definition ScopInfo.h:1627
isl::set getBestKnownDefinedBehaviorContext() const
Return the define behavior context, or if not available, its approximation from all other contexts.
Definition ScopInfo.h:2171
isl::set getContext() const
Get the constraint on parameter of this Scop.
static VirtualUse create(Scop *S, const Use &U, LoopInfo *LI, bool Virtual)
Get a VirtualUse for an llvm::Use.
#define __isl_take
Definition ctx.h:23
#define __isl_keep
Definition ctx.h:26
B()
#define assert(exp)
llvm::Value * expandCodeFor(Scop &S, llvm::ScalarEvolution &SE, llvm::Function *GenFn, llvm::ScalarEvolution &GenSE, const llvm::DataLayout &DL, const char *Name, const llvm::SCEV *E, llvm::Type *Ty, llvm::BasicBlock::iterator IP, ValueMapT *VMap, LoopToScevMapT *LoopMap, llvm::BasicBlock *RTCBB)
Wrapper for SCEVExpander extended to all Polly features.
@ Array
MemoryKind::Array: Models a one or multi-dimensional array.
Definition ScopInfo.h:112
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
@ PHI
MemoryKind::PHI: Models PHI nodes within the SCoP.
Definition ScopInfo.h:188
llvm::iota_range< unsigned > rangeIslSize(unsigned Begin, isl::size End)
Check that End is valid and return an iterator from Begin to End.
Definition ISLTools.cpp:597
llvm::IRBuilder< llvm::ConstantFolder, IRInserter > PollyIRBuilder
Definition IRBuilder.h:143
llvm::DenseMap< const llvm::Loop *, llvm::SCEVUse > LoopToScevMapT
Same as llvm/Analysis/ScalarEvolutionExpressions.h.
Definition ScopHelper.h:41
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > ValueMapT
Type to remap values.
Definition ScopHelper.h:106
bool isIgnoredIntrinsic(const llvm::Value *V)
Return true iff V is an intrinsic that we ignore during code generation.
bool canSynthesize(const llvm::Value *V, const Scop &S, llvm::ScalarEvolution *SE, llvm::Loop *Scope)
Check whether a value an be synthesized by the code generator.
static void createCPUPrinter(PollyIRBuilder &Builder, Args... args)
Print a set of LLVM-IR Values or StringRefs via printf.
static bool isPrintable(llvm::Type *Ty)
Return whether an llvm::Value of the type Ty is printable for debugging.
static llvm::Value * getPrintableString(PollyIRBuilder &Builder, llvm::StringRef Str)
Generate a constant string into the builder's llvm::Module which can be passed to createCPUPrinter().
static TupleKindPtr Domain("Domain")