Polly 23.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 // We do not generate debug intrinsics as we did not investigate how to
217 // copy them correctly. At the current state, they just crash the code
218 // generation as the meta-data operands are not correctly copied.
219 if (isa<DbgInfoIntrinsic>(Inst))
220 return;
221
222 Instruction *NewInst = Inst->clone();
223
224 // Replace old operands with the new ones.
225 for (Value *OldOperand : Inst->operands()) {
226 Value *NewOperand =
227 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
228
229 if (!NewOperand) {
230 assert(!isa<StoreInst>(NewInst) &&
231 "Store instructions are always needed!");
232 NewInst->deleteValue();
233 return;
234 }
235
236 // FIXME: We will encounter "NewOperand" again if used twice. getNewValue()
237 // is meant to be called on old values only.
238 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
239 }
240
241 Builder.Insert(NewInst);
242 BBMap[Inst] = NewInst;
243
244 assert(NewInst->getModule() == Inst->getModule() &&
245 "Expecting instructions to be in the same module");
246
247 if (!NewInst->getType()->isVoidTy())
248 NewInst->setName("p_" + Inst->getName());
249}
250
251Value *
253 ValueMapT &BBMap, LoopToScevMapT &LTS,
254 isl_id_to_ast_expr *NewAccesses) {
255 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
257 Stmt, getLoopForStmt(Stmt),
258 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
259 NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
260}
261
263 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
264 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
265 Type *ExpectedType) {
266 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
267
268 if (AccessExpr) {
269 AccessExpr = isl_ast_expr_address_of(AccessExpr);
270 return ExprBuilder->create(AccessExpr);
271 }
272 assert(
273 Pointer &&
274 "If expression was not generated, must use the original pointer value");
275 return getNewValue(Stmt, Pointer, BBMap, LTS, L);
276}
277
278Value *
280 LoopToScevMapT &LTS, ValueMapT &BBMap,
281 __isl_keep isl_id_to_ast_expr *NewAccesses) {
282 if (Access.isLatestArrayKind())
283 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
284 LTS, NewAccesses, Access.getId().release(),
285 Access.getAccessValue()->getType());
286
287 return getOrCreateAlloca(Access);
288}
289
290Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
291 auto *StmtBB = Stmt.getEntryBlock();
292 return LI.getLoopFor(StmtBB);
293}
294
296 ValueMapT &BBMap, LoopToScevMapT &LTS,
297 isl_id_to_ast_expr *NewAccesses) {
298 if (Value *PreloadLoad = GlobalMap.lookup(Load))
299 return PreloadLoad;
300
301 Value *NewPointer =
302 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
303 Value *ScalarLoad =
304 Builder.CreateAlignedLoad(Load->getType(), NewPointer, Load->getAlign(),
305 Load->getName() + "_p_scalar_");
306
308 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
309 ": ", ScalarLoad, "\n");
310
311 return ScalarLoad;
312}
313
314void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
315 ValueMapT &BBMap, LoopToScevMapT &LTS,
316 isl_id_to_ast_expr *NewAccesses) {
317 MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
318 isl::set AccDom = MA.getAccessRelation().domain();
319 std::string Subject = MA.getId().get_name();
320
321 generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
322 Value *NewPointer =
323 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
324 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
325 LTS, getLoopForStmt(Stmt));
326
327 if (PollyDebugPrinting)
328 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
329 ": ", ValueOperand, "\n");
330
331 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlign());
332 });
333}
334
335bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
336 Loop *L = getLoopForStmt(Stmt);
337 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
338 canSynthesize(Inst, *Stmt.getParent(), &SE, L);
339}
340
341void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
342 ValueMapT &BBMap, LoopToScevMapT &LTS,
343 isl_id_to_ast_expr *NewAccesses) {
344 // Terminator instructions control the control flow. They are explicitly
345 // expressed in the clast and do not need to be copied.
346 if (Inst->isTerminator())
347 return;
348
349 // Synthesizable statements will be generated on-demand.
350 if (canSyntheziseInStmt(Stmt, Inst))
351 return;
352
353 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
354 Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
355 // Compute NewLoad before its insertion in BBMap to make the insertion
356 // deterministic.
357 BBMap[Load] = NewLoad;
358 return;
359 }
360
361 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
362 // Identified as redundant by -polly-simplify.
363 if (!Stmt.getArrayAccessOrNULLFor(Store))
364 return;
365
366 generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
367 return;
368 }
369
370 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
371 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
372 return;
373 }
374
375 // Skip some special intrinsics for which we do not adjust the semantics to
376 // the new schedule. All others are handled like every other instruction.
377 if (isIgnoredIntrinsic(Inst))
378 return;
379
380 copyInstScalar(Stmt, Inst, BBMap, LTS);
381}
382
384 auto NewBB = Builder.GetInsertBlock();
385 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
386 Instruction *NewInst = &*I;
387
388 if (!isInstructionTriviallyDead(NewInst))
389 continue;
390
391 for (auto Pair : BBMap)
392 if (Pair.second == NewInst) {
393 BBMap.erase(Pair.first);
394 }
395
396 NewInst->eraseFromParent();
397 I = NewBB->rbegin();
398 }
399}
400
402 __isl_keep isl_id_to_ast_expr *NewAccesses) {
403 assert(Stmt.isBlockStmt() &&
404 "Only block statements can be copied by the block generator");
405
406 ValueMapT BBMap;
407
408 BasicBlock *BB = Stmt.getBasicBlock();
409 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
410 removeDeadInstructions(BB, BBMap);
411}
412
413BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
414 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
415 Builder.GetInsertPoint(), GenDT, GenLI);
416 CopyBB->setName("polly.stmt." + BB->getName());
417 return CopyBB;
418}
419
420BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
421 ValueMapT &BBMap, LoopToScevMapT &LTS,
422 isl_id_to_ast_expr *NewAccesses) {
423 BasicBlock *CopyBB = splitBB(BB);
424 Builder.SetInsertPoint(CopyBB, CopyBB->begin());
425 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
426 generateBeginStmtTrace(Stmt, LTS, BBMap);
427
428 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
429
430 // After a basic block was copied store all scalars that escape this block in
431 // their alloca.
432 generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
433 return CopyBB;
434}
435
436void BlockGenerator::switchGeneratedFunc(Function *GenFn, DominatorTree *GenDT,
437 LoopInfo *GenLI,
438 ScalarEvolution *GenSE) {
439 assert(GenFn == GenDT->getRoot()->getParent());
440 assert(GenLI->getTopLevelLoops().empty() ||
441 GenFn == GenLI->getTopLevelLoops().front()->getHeader()->getParent());
442 this->GenDT = GenDT;
443 this->GenLI = GenLI;
444 this->GenSE = GenSE;
445}
446
447void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
448 ValueMapT &BBMap, LoopToScevMapT &LTS,
449 isl_id_to_ast_expr *NewAccesses) {
450 // Block statements and the entry blocks of region statement are code
451 // generated from instruction lists. This allow us to optimize the
452 // instructions that belong to a certain scop statement. As the code
453 // structure of region statements might be arbitrary complex, optimizing the
454 // instruction list is not yet supported.
455 if (Stmt.isBlockStmt() || (Stmt.isRegionStmt() && Stmt.getEntryBlock() == BB))
456 for (Instruction *Inst : Stmt.getInstructions())
457 copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
458 else
459 for (Instruction &Inst : *BB)
460 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
461}
462
464 assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
465
467}
468
470 assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
471
472 auto &Addr = ScalarMap[Array];
473
474 if (Addr) {
475 // Allow allocas to be (temporarily) redirected once by adding a new
476 // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
477 // is used for example by the OpenMP code generation where a first use
478 // of a scalar while still in the host code allocates a normal alloca with
479 // getOrCreateAlloca. When the values of this scalar are accessed during
480 // the generation of the parallel subfunction, these values are copied over
481 // to the parallel subfunction and each request for a scalar alloca slot
482 // must be forwarded to the temporary in-subfunction slot. This mapping is
483 // removed when the subfunction has been generated and again normal host
484 // code is generated. Due to the following reasons it is not possible to
485 // perform the GlobalMap lookup right after creating the alloca below, but
486 // instead we need to check GlobalMap at each call to getOrCreateAlloca:
487 //
488 // 1) GlobalMap may be changed multiple times (for each parallel loop),
489 // 2) The temporary mapping is commonly only known after the initial
490 // alloca has already been generated, and
491 // 3) The original alloca value must be restored after leaving the
492 // sub-function.
493 if (Value *NewAddr = GlobalMap.lookup(&*Addr))
494 return NewAddr;
495 return Addr;
496 }
497
498 Type *Ty = Array->getElementType();
499 Value *ScalarBase = Array->getBasePtr();
500 std::string NameExt;
501 if (Array->isPHIKind())
502 NameExt = ".phiops";
503 else
504 NameExt = ".s2a";
505
506 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
507
508 Addr =
509 new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr,
510 DL.getPrefTypeAlign(Ty), ScalarBase->getName() + NameExt);
511 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
512 Addr->insertBefore(EntryBB->getFirstInsertionPt());
513
514 return Addr;
515}
516
518 Instruction *Inst = cast<Instruction>(Array->getBasePtr());
519
520 // If there are escape users we get the alloca for this instruction and put it
521 // in the EscapeMap for later finalization. Lastly, if the instruction was
522 // copied multiple times we already did this and can exit.
523 if (EscapeMap.count(Inst))
524 return;
525
526 EscapeUserVectorTy EscapeUsers;
527 for (User *U : Inst->users()) {
528
529 // Non-instruction user will never escape.
530 Instruction *UI = dyn_cast<Instruction>(U);
531 if (!UI)
532 continue;
533
534 if (S.contains(UI))
535 continue;
536
537 EscapeUsers.push_back(UI);
538 }
539
540 // Exit if no escape uses were found.
541 if (EscapeUsers.empty())
542 return;
543
544 // Get or create an escape alloca for this instruction.
545 auto *ScalarAddr = getOrCreateAlloca(Array);
546
547 // Remember that this instruction has escape uses and the escape alloca.
548 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
549}
550
552 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
553 __isl_keep isl_id_to_ast_expr *NewAccesses) {
554 for (MemoryAccess *MA : Stmt) {
555 if (MA->isOriginalArrayKind() || MA->isWrite())
556 continue;
557
558#ifndef NDEBUG
559 auto StmtDom =
561 auto AccDom = MA->getAccessRelation().domain();
562 assert(!StmtDom.is_subset(AccDom).is_false() &&
563 "Scalar must be loaded in all statement instances");
564#endif
565
566 auto *Address =
567 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
568 BBMap[MA->getAccessValue()] = Builder.CreateLoad(
569 MA->getElementType(), Address, Address->getName() + ".reload");
570 }
571}
572
574 const isl::set &Subdomain) {
575 isl::ast_build AstBuild = Stmt.getAstBuild();
576 isl::set Domain = Stmt.getDomain();
577
578 isl::union_map USchedule = AstBuild.get_schedule();
579 USchedule = USchedule.intersect_domain(Domain);
580
581 assert(!USchedule.is_empty());
582 isl::map Schedule = isl::map::from_union_map(USchedule);
583
584 isl::set ScheduledDomain = Schedule.range();
585 isl::set ScheduledSet = Subdomain.apply(Schedule);
586
587 isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
588
589 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
590 Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
591 IsInSetExpr = Builder.CreateICmpNE(
592 IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
593
594 return IsInSetExpr;
595}
596
598 ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
599 const std::function<void()> &GenThenFunc) {
600 isl::set StmtDom = Stmt.getDomain();
601
602 // If the condition is a tautology, don't generate a condition around the
603 // code.
604 bool IsPartialWrite =
605 !StmtDom.intersect_params(Stmt.getParent()->getContext())
606 .is_subset(Subdomain);
607 if (!IsPartialWrite) {
608 GenThenFunc();
609 return;
610 }
611
612 // Generate the condition.
613 Value *Cond = buildContainsCondition(Stmt, Subdomain);
614
615 // Don't call GenThenFunc if it is never executed. An ast index expression
616 // might not be defined in this case.
617 if (auto *Const = dyn_cast<ConstantInt>(Cond))
618 if (Const->isZero())
619 return;
620
621 BasicBlock *HeadBlock = Builder.GetInsertBlock();
622 StringRef BlockName = HeadBlock->getName();
623
624 // Generate the conditional block.
625 DomTreeUpdater DTU(GenDT, DomTreeUpdater::UpdateStrategy::Eager);
626 SplitBlockAndInsertIfThen(Cond, Builder.GetInsertPoint(), false, nullptr,
627 &DTU, GenLI);
628 CondBrInst *Branch = cast<CondBrInst>(HeadBlock->getTerminator());
629 BasicBlock *ThenBlock = Branch->getSuccessor(0);
630 BasicBlock *TailBlock = Branch->getSuccessor(1);
631
632 // Assign descriptive names.
633 if (auto *CondInst = dyn_cast<Instruction>(Cond))
634 CondInst->setName("polly." + Subject + ".cond");
635 ThenBlock->setName(BlockName + "." + Subject + ".partial");
636 TailBlock->setName(BlockName + ".cont");
637
638 // Put the client code into the conditional block and continue in the merge
639 // block afterwards.
640 Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
641 GenThenFunc();
642 Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
643}
644
645static std::string getInstName(Value *Val) {
646 std::string Result;
647 raw_string_ostream OS(Result);
648 Val->printAsOperand(OS, false);
649 return Result;
650}
651
653 ValueMapT &BBMap) {
654 if (!TraceStmts)
655 return;
656
657 Scop *S = Stmt.getParent();
658 const char *BaseName = Stmt.getBaseName();
659
660 isl::ast_build AstBuild = Stmt.getAstBuild();
661 isl::set Domain = Stmt.getDomain();
662
663 isl::union_map USchedule = AstBuild.get_schedule().intersect_domain(Domain);
664 isl::map Schedule = isl::map::from_union_map(USchedule);
665 assert(Schedule.is_empty().is_false() &&
666 "The stmt must have a valid instance");
667
668 isl::multi_pw_aff ScheduleMultiPwAff =
670 isl::ast_build RestrictedBuild = AstBuild.restrict(Schedule.range());
671
672 // Sequence of strings to print.
673 SmallVector<llvm::Value *, 8> Values;
674
675 // Print the name of the statement.
676 // TODO: Indent by the depth of the statement instance in the schedule tree.
677 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, BaseName));
678 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "("));
679
680 // Add the coordinate of the statement instance.
681 for (unsigned i : rangeIslSize(0, ScheduleMultiPwAff.dim(isl::dim::out))) {
682 if (i > 0)
683 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ","));
684
685 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduleMultiPwAff.at(i));
686 Values.push_back(ExprBuilder->create(IsInSet.copy()));
687 }
688
689 if (TraceScalars) {
690 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")"));
691 DenseSet<Instruction *> Encountered;
692
693 // Add the value of each scalar (and the result of PHIs) used in the
694 // statement.
695 // TODO: Values used in region-statements.
696 for (Instruction *Inst : Stmt.insts()) {
697 if (!RuntimeDebugBuilder::isPrintable(Inst->getType()))
698 continue;
699
700 if (isa<PHINode>(Inst)) {
701 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " "));
703 Builder, getInstName(Inst)));
704 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "="));
705 Values.push_back(getNewValue(Stmt, Inst, BBMap, LTS,
706 LI.getLoopFor(Inst->getParent())));
707 } else {
708 for (Value *Op : Inst->operand_values()) {
709 // Do not print values that cannot change during the execution of the
710 // SCoP.
711 auto *OpInst = dyn_cast<Instruction>(Op);
712 if (!OpInst)
713 continue;
714 if (!S->contains(OpInst))
715 continue;
716
717 // Print each scalar at most once, and exclude values defined in the
718 // statement itself.
719 if (Encountered.count(OpInst))
720 continue;
721
722 Values.push_back(
725 Builder, getInstName(OpInst)));
726 Values.push_back(
728 Values.push_back(getNewValue(Stmt, OpInst, BBMap, LTS,
729 LI.getLoopFor(Inst->getParent())));
730 Encountered.insert(OpInst);
731 }
732 }
733
734 Encountered.insert(Inst);
735 }
736
737 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n"));
738 } else {
739 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")\n"));
740 }
741
742 RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values));
743}
744
746 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
747 __isl_keep isl_id_to_ast_expr *NewAccesses) {
748 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
749
750 assert(Stmt.isBlockStmt() &&
751 "Region statements need to use the generateScalarStores() function in "
752 "the RegionGenerator");
753
754 for (MemoryAccess *MA : Stmt) {
755 if (MA->isOriginalArrayKind() || MA->isRead())
756 continue;
757
758 isl::set AccDom = MA->getAccessRelation().domain();
759 std::string Subject = MA->getId().get_name();
760
762 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
763 Value *Val = MA->getAccessValue();
764 if (MA->isAnyPHIKind()) {
765 assert(MA->getIncoming().size() >= 1 &&
766 "Block statements have exactly one exiting block, or "
767 "multiple but "
768 "with same incoming block and value");
769 assert(std::all_of(MA->getIncoming().begin(),
770 MA->getIncoming().end(),
771 [&](std::pair<BasicBlock *, Value *> p) -> bool {
772 return p.first == Stmt.getBasicBlock();
773 }) &&
774 "Incoming block must be statement's block");
775 Val = MA->getIncoming()[0].second;
776 }
777 auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
778 BBMap, NewAccesses);
779
780 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
781 assert((!isa<Instruction>(Val) ||
782 GenDT->dominates(cast<Instruction>(Val)->getParent(),
783 Builder.GetInsertBlock())) &&
784 "Domination violation");
785 assert((!isa<Instruction>(Address) ||
786 GenDT->dominates(cast<Instruction>(Address)->getParent(),
787 Builder.GetInsertBlock())) &&
788 "Domination violation");
789
790 Builder.CreateStore(Val, Address);
791 });
792 }
793}
794
796 BasicBlock *ExitBB = S.getExit();
797 BasicBlock *PreEntryBB = S.getEnteringBlock();
798
799 Builder.SetInsertPoint(StartBlock, StartBlock->begin());
800
801 for (auto &Array : S.arrays()) {
802 if (Array->getNumberOfDimensions() != 0)
803 continue;
804 if (Array->isPHIKind()) {
805 // For PHI nodes, the only values we need to store are the ones that
806 // reach the PHI node from outside the region. In general there should
807 // only be one such incoming edge and this edge should enter through
808 // 'PreEntryBB'.
809 auto PHI = cast<PHINode>(Array->getBasePtr());
810
811 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
812 if (!S.contains(*BI) && *BI != PreEntryBB)
813 llvm_unreachable("Incoming edges from outside the scop should always "
814 "come from PreEntryBB");
815
816 int Idx = PHI->getBasicBlockIndex(PreEntryBB);
817 if (Idx < 0)
818 continue;
819
820 Value *ScalarValue = PHI->getIncomingValue(Idx);
821
822 Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
823 continue;
824 }
825
826 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
827
828 if (Inst && S.contains(Inst))
829 continue;
830
831 // PHI nodes that are not marked as such in their SAI object are either exit
832 // PHI nodes we model as common scalars but without initialization, or
833 // incoming phi nodes that need to be initialized. Check if the first is the
834 // case for Inst and do not create and initialize memory if so.
835 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
836 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
837 continue;
838
839 Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
840 }
841}
842
844 // The exit block of the __unoptimized__ region.
845 BasicBlock *ExitBB = S.getExitingBlock();
846 // The merge block __just after__ the region and the optimized region.
847 BasicBlock *MergeBB = S.getExit();
848
849 // The exit block of the __optimized__ region.
850 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
851 if (OptExitBB == ExitBB)
852 OptExitBB = *(++pred_begin(MergeBB));
853
854 Builder.SetInsertPoint(OptExitBB, OptExitBB->getTerminator()->getIterator());
855 for (const auto &EscapeMapping : EscapeMap) {
856 // Extract the escaping instruction and the escaping users as well as the
857 // alloca the instruction was demoted to.
858 Instruction *EscapeInst = EscapeMapping.first;
859 const auto &EscapeMappingValue = EscapeMapping.second;
860 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
861 auto *ScalarAddr = cast<AllocaInst>(&*EscapeMappingValue.first);
862
863 // Reload the demoted instruction in the optimized version of the SCoP.
864 Value *EscapeInstReload =
865 Builder.CreateLoad(ScalarAddr->getAllocatedType(), ScalarAddr,
866 EscapeInst->getName() + ".final_reload");
867 EscapeInstReload =
868 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
869
870 // Create the merge PHI that merges the optimized and unoptimized version.
871 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
872 EscapeInst->getName() + ".merge");
873 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
874
875 // Add the respective values to the merge PHI.
876 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
877 MergePHI->addIncoming(EscapeInst, ExitBB);
878
879 // The information of scalar evolution about the escaping instruction needs
880 // to be revoked so the new merged instruction will be used.
881 if (SE.isSCEVable(EscapeInst->getType()))
882 SE.forgetValue(EscapeInst);
883
884 // Replace all uses of the demoted instruction with the merge PHI.
885 for (Instruction *EUser : EscapeUsers)
886 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
887 }
888}
889
891 for (auto &Array : S.arrays()) {
892
893 if (Array->getNumberOfDimensions() != 0)
894 continue;
895
896 if (Array->isPHIKind())
897 continue;
898
899 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
900
901 if (!Inst)
902 continue;
903
904 // Scop invariant hoisting moves some of the base pointers out of the scop.
905 // We can ignore these, as the invariant load hoisting already registers the
906 // relevant outside users.
907 if (!S.contains(Inst))
908 continue;
909
911 }
912}
913
915 if (S.hasSingleExitEdge())
916 return;
917
918 auto *ExitBB = S.getExitingBlock();
919 auto *MergeBB = S.getExit();
920 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
921 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
922 if (OptExitBB == ExitBB)
923 OptExitBB = *(++pred_begin(MergeBB));
924
925 Builder.SetInsertPoint(OptExitBB, OptExitBB->getTerminator()->getIterator());
926
927 for (auto &SAI : S.arrays()) {
928 auto *Val = SAI->getBasePtr();
929
930 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
931 // the original PHI's value or the reloaded incoming values from the
932 // generated code. An llvm::Value is merged between the original code's
933 // value or the generated one.
934 if (!SAI->isExitPHIKind())
935 continue;
936
937 PHINode *PHI = dyn_cast<PHINode>(Val);
938 if (!PHI)
939 continue;
940
941 if (PHI->getParent() != AfterMergeBB)
942 continue;
943
944 std::string Name = PHI->getName().str();
945 Value *ScalarAddr = getOrCreateAlloca(SAI);
946 Value *Reload = Builder.CreateLoad(SAI->getElementType(), ScalarAddr,
947 Name + ".ph.final_reload");
948 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
949 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
950 assert((!isa<Instruction>(OriginalValue) ||
951 cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
952 "Original value must no be one we just generated.");
953 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
954 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
955 MergePHI->addIncoming(Reload, OptExitBB);
956 MergePHI->addIncoming(OriginalValue, ExitBB);
957 int Idx = PHI->getBasicBlockIndex(MergeBB);
958 PHI->setIncomingValue(Idx, MergePHI);
959 }
960}
961
963 for (auto &Stmt : S)
964 if (Stmt.isCopyStmt())
965 continue;
966 else if (Stmt.isBlockStmt())
967 for (auto &Inst : *Stmt.getBasicBlock())
968 SE.forgetValue(&Inst);
969 else if (Stmt.isRegionStmt())
970 for (auto *BB : Stmt.getRegion()->blocks())
971 for (auto &Inst : *BB)
972 SE.forgetValue(&Inst);
973 else
974 llvm_unreachable("Unexpected statement type found");
975
976 // Invalidate SCEV of loops surrounding the EscapeUsers.
977 for (const auto &EscapeMapping : EscapeMap) {
978 const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
979 for (Instruction *EUser : EscapeUsers) {
980 if (Loop *L = LI.getLoopFor(EUser->getParent()))
981 while (L) {
982 SE.forgetLoop(L);
983 L = L->getParentLoop();
984 }
985 }
986 }
987}
988
996
997BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
998 BasicBlock *BBCopy) {
999
1000 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1001 BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1002
1003 if (BBCopyIDom)
1004 GenDT->changeImmediateDominator(BBCopy, BBCopyIDom);
1005
1006 return StartBlockMap.lookup(BBIDom);
1007}
1008
1009// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1010// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1011// does not work in cases where the exit block has edges from outside the
1012// region. In that case the llvm::Value would never be usable in in the exit
1013// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1014// for the subregion's exiting edges only. We need to determine whether an
1015// llvm::Value is usable in there. We do this by checking whether it dominates
1016// all exiting blocks individually.
1017static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1018 BasicBlock *BB) {
1019 for (auto ExitingBB : predecessors(R->getExit())) {
1020 // Check for non-subregion incoming edges.
1021 if (!R->contains(ExitingBB))
1022 continue;
1023
1024 if (!DT.dominates(BB, ExitingBB))
1025 return false;
1026 }
1027
1028 return true;
1029}
1030
1031// Find the direct dominator of the subregion's exit block if the subregion was
1032// simplified.
1033static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1034 BasicBlock *Common = nullptr;
1035 for (auto ExitingBB : predecessors(R->getExit())) {
1036 // Check for non-subregion incoming edges.
1037 if (!R->contains(ExitingBB))
1038 continue;
1039
1040 // First exiting edge.
1041 if (!Common) {
1042 Common = ExitingBB;
1043 continue;
1044 }
1045
1046 Common = DT.findNearestCommonDominator(Common, ExitingBB);
1047 }
1048
1049 assert(Common && R->contains(Common));
1050 return Common;
1051}
1052
1054 __isl_keep isl_id_to_ast_expr *IdToAstExp) {
1055 assert(Stmt.isRegionStmt() &&
1056 "Only region statements can be copied by the region generator");
1057
1058 // Forget all old mappings.
1059 StartBlockMap.clear();
1060 EndBlockMap.clear();
1061 RegionMaps.clear();
1062 IncompletePHINodeMap.clear();
1063
1064 // Collection of all values related to this subregion.
1065 ValueMapT ValueMap;
1066
1067 // The region represented by the statement.
1068 Region *R = Stmt.getRegion();
1069
1070 // Create a dedicated entry for the region where we can reload all demoted
1071 // inputs.
1072 BasicBlock *EntryBB = R->getEntry();
1073 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1074 Builder.GetInsertPoint(), GenDT, GenLI);
1075 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1076 Builder.SetInsertPoint(EntryBBCopy, EntryBBCopy->begin());
1077
1078 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1079 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1080 generateBeginStmtTrace(Stmt, LTS, EntryBBMap);
1081
1082 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1083 if (!R->contains(*PI)) {
1084 StartBlockMap[*PI] = EntryBBCopy;
1085 EndBlockMap[*PI] = EntryBBCopy;
1086 }
1087
1088 // Iterate over all blocks in the region in a breadth-first search.
1089 std::deque<BasicBlock *> Blocks;
1090 SmallSetVector<BasicBlock *, 8> SeenBlocks;
1091 Blocks.push_back(EntryBB);
1092 SeenBlocks.insert(EntryBB);
1093
1094 while (!Blocks.empty()) {
1095 BasicBlock *BB = Blocks.front();
1096 Blocks.pop_front();
1097
1098 // First split the block and update dominance information.
1099 BasicBlock *BBCopy = splitBB(BB);
1100 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1101
1102 // Get the mapping for this block and initialize it with either the scalar
1103 // loads from the generated entering block (which dominates all blocks of
1104 // this subregion) or the maps of the immediate dominator, if part of the
1105 // subregion. The latter necessarily includes the former.
1106 ValueMapT *InitBBMap;
1107 if (BBCopyIDom) {
1108 assert(RegionMaps.count(BBCopyIDom));
1109 InitBBMap = &RegionMaps[BBCopyIDom];
1110 } else
1111 InitBBMap = &EntryBBMap;
1112 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1113 ValueMapT &RegionMap = Inserted.first->second;
1114
1115 // Copy the block with the BlockGenerator.
1116 Builder.SetInsertPoint(BBCopy, BBCopy->begin());
1117 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1118
1119 // In order to remap PHI nodes we store also basic block mappings.
1120 StartBlockMap[BB] = BBCopy;
1121 EndBlockMap[BB] = Builder.GetInsertBlock();
1122
1123 // Add values to incomplete PHI nodes waiting for this block to be copied.
1124 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1125 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1126 IncompletePHINodeMap[BB].clear();
1127
1128 // And continue with new successors inside the region.
1129 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1130 if (R->contains(*SI) && SeenBlocks.insert(*SI))
1131 Blocks.push_back(*SI);
1132
1133 // Remember value in case it is visible after this subregion.
1134 if (isDominatingSubregionExit(DT, R, BB))
1135 ValueMap.insert_range(RegionMap);
1136 }
1137
1138 // Now create a new dedicated region exit block and add it to the region map.
1139 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1140 Builder.GetInsertPoint(), GenDT, GenLI);
1141 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1142 StartBlockMap[R->getExit()] = ExitBBCopy;
1143 EndBlockMap[R->getExit()] = ExitBBCopy;
1144
1145 BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1146 assert(ExitDomBBCopy &&
1147 "Common exit dominator must be within region; at least the entry node "
1148 "must match");
1149 GenDT->changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1150
1151 // As the block generator doesn't handle control flow we need to add the
1152 // region control flow by hand after all blocks have been copied.
1153 for (BasicBlock *BB : SeenBlocks) {
1154
1155 BasicBlock *BBCopyStart = StartBlockMap[BB];
1156 BasicBlock *BBCopyEnd = EndBlockMap[BB];
1157 Instruction *TI = BB->getTerminator();
1158 if (isa<UnreachableInst>(TI)) {
1159 while (!BBCopyEnd->empty())
1160 BBCopyEnd->begin()->eraseFromParent();
1161 new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1162 continue;
1163 }
1164
1165 Instruction *BICopy = BBCopyEnd->getTerminator();
1166
1167 ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1168 RegionMap.insert_range(StartBlockMap);
1169
1170 Builder.SetInsertPoint(BBCopyEnd, BICopy->getIterator());
1171 copyInstScalar(Stmt, TI, RegionMap, LTS);
1172 BICopy->eraseFromParent();
1173 }
1174
1175 // Add counting PHI nodes to all loops in the region that can be used as
1176 // replacement for SCEVs referring to the old loop.
1177 for (BasicBlock *BB : SeenBlocks) {
1178 Loop *L = LI.getLoopFor(BB);
1179 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1180 continue;
1181
1182 BasicBlock *BBCopy = StartBlockMap[BB];
1183 Value *NullVal = Builder.getInt32(0);
1184 PHINode *LoopPHI =
1185 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1186 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1187 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1188 LoopPHI->insertBefore(BBCopy->begin());
1189 LoopPHIInc->insertBefore(BBCopy->getTerminator()->getIterator());
1190
1191 for (auto *PredBB : predecessors(BB)) {
1192 if (!R->contains(PredBB))
1193 continue;
1194 if (L->contains(PredBB))
1195 LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1196 else
1197 LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1198 }
1199
1200 for (auto *PredBBCopy : predecessors(BBCopy))
1201 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1202 LoopPHI->addIncoming(NullVal, PredBBCopy);
1203
1204 LTS[L] = SE.getUnknown(LoopPHI);
1205 }
1206
1207 // Continue generating code in the exit block.
1208 Builder.SetInsertPoint(ExitBBCopy, ExitBBCopy->getFirstInsertionPt());
1209
1210 // Write values visible to other statements.
1211 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1212 StartBlockMap.clear();
1213 EndBlockMap.clear();
1214 RegionMaps.clear();
1215 IncompletePHINodeMap.clear();
1216}
1217
1219 ValueMapT &BBMap, Loop *L) {
1220 ScopStmt *Stmt = MA->getStatement();
1221 Region *SubR = Stmt->getRegion();
1222 auto Incoming = MA->getIncoming();
1223
1224 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1225 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1226 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1227
1228 // This can happen if the subregion is simplified after the ScopStmts
1229 // have been created; simplification happens as part of CodeGeneration.
1230 if (OrigPHI->getParent() != SubR->getExit()) {
1231 BasicBlock *FormerExit = SubR->getExitingBlock();
1232 if (FormerExit)
1233 NewSubregionExit = StartBlockMap.lookup(FormerExit);
1234 }
1235
1236 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1237 "polly." + OrigPHI->getName(),
1238 NewSubregionExit->getFirstNonPHIIt());
1239
1240 // Add the incoming values to the PHI.
1241 for (auto &Pair : Incoming) {
1242 BasicBlock *OrigIncomingBlock = Pair.first;
1243 BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1244 BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1245 Builder.SetInsertPoint(NewIncomingBlockEnd,
1246 NewIncomingBlockEnd->getTerminator()->getIterator());
1247 assert(RegionMaps.count(NewIncomingBlockStart));
1248 assert(RegionMaps.count(NewIncomingBlockEnd));
1249 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1250
1251 Value *OrigIncomingValue = Pair.second;
1252 Value *NewIncomingValue =
1253 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1254 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1255 }
1256
1257 return NewPHI;
1258}
1259
1261 ValueMapT &BBMap) {
1262 ScopStmt *Stmt = MA->getStatement();
1263
1264 // TODO: Add some test cases that ensure this is really the right choice.
1265 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1266
1267 if (MA->isAnyPHIKind()) {
1268 auto Incoming = MA->getIncoming();
1269 assert(!Incoming.empty() &&
1270 "PHI WRITEs must have originate from at least one incoming block");
1271
1272 // If there is only one incoming value, we do not need to create a PHI.
1273 if (Incoming.size() == 1) {
1274 Value *OldVal = Incoming[0].second;
1275 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1276 }
1277
1278 return buildExitPHI(MA, LTS, BBMap, L);
1279 }
1280
1281 // MemoryKind::Value accesses leaving the subregion must dominate the exit
1282 // block; just pass the copied value.
1283 Value *OldVal = MA->getAccessValue();
1284 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1285}
1286
1288 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1289 __isl_keep isl_id_to_ast_expr *NewAccesses) {
1290 assert(Stmt.getRegion() &&
1291 "Block statements need to use the generateScalarStores() "
1292 "function in the BlockGenerator");
1293
1294 // Get the exit scalar values before generating the writes.
1295 // This is necessary because RegionGenerator::getExitScalar may insert
1296 // PHINodes that depend on the region's exiting blocks. But
1297 // BlockGenerator::generateConditionalExecution may insert a new basic block
1298 // such that the current basic block is not a direct successor of the exiting
1299 // blocks anymore. Hence, build the PHINodes while the current block is still
1300 // the direct successor.
1301 SmallDenseMap<MemoryAccess *, Value *> NewExitScalars;
1302 for (MemoryAccess *MA : Stmt) {
1303 if (MA->isOriginalArrayKind() || MA->isRead())
1304 continue;
1305
1306 Value *NewVal = getExitScalar(MA, LTS, BBMap);
1307 NewExitScalars[MA] = NewVal;
1308 }
1309
1310 for (MemoryAccess *MA : Stmt) {
1311 if (MA->isOriginalArrayKind() || MA->isRead())
1312 continue;
1313
1314 isl::set AccDom = MA->getAccessRelation().domain();
1315 std::string Subject = MA->getId().get_name();
1317 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1318 Value *NewVal = NewExitScalars.lookup(MA);
1319 assert(NewVal && "The exit scalar must be determined before");
1320 Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1321 BBMap, NewAccesses);
1322 assert((!isa<Instruction>(NewVal) ||
1323 GenDT->dominates(cast<Instruction>(NewVal)->getParent(),
1324 Builder.GetInsertBlock())) &&
1325 "Domination violation");
1326 assert((!isa<Instruction>(Address) ||
1327 GenDT->dominates(cast<Instruction>(Address)->getParent(),
1328 Builder.GetInsertBlock())) &&
1329 "Domination violation");
1330 Builder.CreateStore(NewVal, Address);
1331 });
1332 }
1333}
1334
1336 PHINode *PHICopy, BasicBlock *IncomingBB,
1337 LoopToScevMapT &LTS) {
1338 // If the incoming block was not yet copied mark this PHI as incomplete.
1339 // Once the block will be copied the incoming value will be added.
1340 BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1341 BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1342 if (!BBCopyStart) {
1343 assert(!BBCopyEnd);
1344 assert(Stmt.represents(IncomingBB) &&
1345 "Bad incoming block for PHI in non-affine region");
1346 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1347 return;
1348 }
1349
1350 assert(RegionMaps.count(BBCopyStart) &&
1351 "Incoming PHI block did not have a BBMap");
1352 ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1353
1354 Value *OpCopy = nullptr;
1355
1356 if (Stmt.represents(IncomingBB)) {
1357 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1358
1359 // If the current insert block is different from the PHIs incoming block
1360 // change it, otherwise do not.
1361 auto IP = Builder.GetInsertPoint();
1362 if (IP->getParent() != BBCopyEnd)
1363 Builder.SetInsertPoint(BBCopyEnd,
1364 BBCopyEnd->getTerminator()->getIterator());
1365 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1366 if (IP->getParent() != BBCopyEnd)
1367 Builder.SetInsertPoint(IP);
1368 } else {
1369 // All edges from outside the non-affine region become a single edge
1370 // in the new copy of the non-affine region. Make sure to only add the
1371 // corresponding edge the first time we encounter a basic block from
1372 // outside the non-affine region.
1373 if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1374 return;
1375
1376 // Get the reloaded value.
1377 OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1378 }
1379
1380 assert(OpCopy && "Incoming PHI value was not copied properly");
1381 PHICopy->addIncoming(OpCopy, BBCopyEnd);
1382}
1383
1385 ValueMapT &BBMap,
1386 LoopToScevMapT &LTS) {
1387 unsigned NumIncoming = PHI->getNumIncomingValues();
1388 PHINode *PHICopy =
1389 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1390 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHIIt());
1391 BBMap[PHI] = PHICopy;
1392
1393 for (BasicBlock *IncomingBB : PHI->blocks())
1394 addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1395}
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:426
const ScopArrayInfo * getLatestScopArrayInfo() const
Get the ScopArrayInfo object for the base address, or the one set by setNewAccessRelation().
Definition ScopInfo.cpp:557
bool isAnyPHIKind() const
Old name of isOriginalAnyPHIKind().
Definition ScopInfo.h:1023
bool isLatestArrayKind() const
Whether storage memory is either an custom .s2a/.phiops alloca (false) or an existing pointer into an...
Definition ScopInfo.h:945
Instruction * getAccessInstruction() const
Return the access instruction of this memory access.
Definition ScopInfo.h:880
isl::id getId() const
Get identifier for the memory access.
Definition ScopInfo.cpp:914
ArrayRef< std::pair< BasicBlock *, Value * > > getIncoming() const
Return the list of possible PHI/ExitPHI values.
Definition ScopInfo.h:743
ScopStmt * getStatement() const
Get the statement that contains this memory access.
Definition ScopInfo.h:1026
isl::map getAccessRelation() const
Old name of getLatestAccessRelation().
Definition ScopInfo.h:790
Value * getAccessValue() const
Return the access value of this memory access.
Definition ScopInfo.h:862
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:214
Statement of the Scop.
Definition ScopInfo.h:1135
MemoryAccess & getArrayAccessFor(const Instruction *Inst) const
Return the only array access for Inst.
Definition ScopInfo.h:1429
Scop * getParent()
Definition ScopInfo.h:1523
BasicBlock * getEntryBlock() const
Return a BasicBlock from this statement.
const std::vector< Instruction * > & getInstructions() const
Definition ScopInfo.h:1526
bool isBlockStmt() const
Return true if this statement represents a single basic block.
Definition ScopInfo.h:1316
Region * getRegion() const
Get the region represented by this ScopStmt (if any).
Definition ScopInfo.h:1325
bool represents(BasicBlock *BB) const
Return whether this statement represents BB.
Definition ScopInfo.h:1346
iterator_range< std::vector< Instruction * >::const_iterator > insts() const
The range of instructions in this statement.
Definition ScopInfo.h:1545
BasicBlock * getBasicBlock() const
Get the BasicBlock represented by this ScopStmt (if any).
Definition ScopInfo.h:1313
const char * getBaseName() const
isl::ast_build getAstBuild() const
Get the isl AST build.
Definition ScopInfo.h:1560
MemoryAccess * getArrayAccessOrNULLFor(const Instruction *Inst) const
Return the only array access for Inst, if existing.
Definition ScopInfo.h:1406
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1328
isl::set getDomain() const
Get the iteration domain of this ScopStmt.
Static Control Part.
Definition ScopInfo.h:1625
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:110
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:149
@ PHI
MemoryKind::PHI: Models PHI nodes within the SCoP.
Definition ScopInfo.h:186
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")