1 
2 #include "polly/Support/SCEVValidator.h"
3 #include "polly/ScopInfo.h"
4 #include "llvm/Analysis/RegionInfo.h"
5 #include "llvm/Analysis/ScalarEvolution.h"
6 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
7 #include "llvm/Support/Debug.h"
8 #include <vector>
9 
10 using namespace llvm;
11 using namespace polly;
12 
13 #define DEBUG_TYPE "polly-scev-validator"
14 
15 namespace SCEVType {
16 /// @brief The type of a SCEV
17 ///
18 /// To check for the validity of a SCEV we assign to each SCEV a type. The
19 /// possible types are INT, PARAM, IV and INVALID. The order of the types is
20 /// important. The subexpressions of SCEV with a type X can only have a type
21 /// that is smaller or equal than X.
22 enum TYPE {
23   // An integer value.
24   INT,
25 
26   // An expression that is constant during the execution of the Scop,
27   // but that may depend on parameters unknown at compile time.
28   PARAM,
29 
30   // An expression that may change during the execution of the SCoP.
31   IV,
32 
33   // An invalid expression.
34   INVALID
35 };
36 }
37 
38 /// @brief The result the validator returns for a SCEV expression.
39 class ValidatorResult {
40   /// @brief The type of the expression
41   SCEVType::TYPE Type;
42 
43   /// @brief The set of Parameters in the expression.
44   std::vector<const SCEV *> Parameters;
45 
46 public:
47   /// @brief The copy constructor
48   ValidatorResult(const ValidatorResult &Source) {
49     Type = Source.Type;
50     Parameters = Source.Parameters;
51   }
52 
53   /// @brief Construct a result with a certain type and no parameters.
54   ValidatorResult(SCEVType::TYPE Type) : Type(Type) {
55     assert(Type != SCEVType::PARAM && "Did you forget to pass the parameter");
56   }
57 
58   /// @brief Construct a result with a certain type and a single parameter.
59   ValidatorResult(SCEVType::TYPE Type, const SCEV *Expr) : Type(Type) {
60     Parameters.push_back(Expr);
61   }
62 
63   /// @brief Get the type of the ValidatorResult.
64   SCEVType::TYPE getType() { return Type; }
65 
66   /// @brief Is the analyzed SCEV constant during the execution of the SCoP.
67   bool isConstant() { return Type == SCEVType::INT || Type == SCEVType::PARAM; }
68 
69   /// @brief Is the analyzed SCEV valid.
70   bool isValid() { return Type != SCEVType::INVALID; }
71 
72   /// @brief Is the analyzed SCEV of Type IV.
73   bool isIV() { return Type == SCEVType::IV; }
74 
75   /// @brief Is the analyzed SCEV of Type INT.
76   bool isINT() { return Type == SCEVType::INT; }
77 
78   /// @brief Is the analyzed SCEV of Type PARAM.
79   bool isPARAM() { return Type == SCEVType::PARAM; }
80 
81   /// @brief Get the parameters of this validator result.
82   std::vector<const SCEV *> getParameters() { return Parameters; }
83 
84   /// @brief Add the parameters of Source to this result.
85   void addParamsFrom(const ValidatorResult &Source) {
86     Parameters.insert(Parameters.end(), Source.Parameters.begin(),
87                       Source.Parameters.end());
88   }
89 
90   /// @brief Merge a result.
91   ///
92   /// This means to merge the parameters and to set the Type to the most
93   /// specific Type that matches both.
94   void merge(const ValidatorResult &ToMerge) {
95     Type = std::max(Type, ToMerge.Type);
96     addParamsFrom(ToMerge);
97   }
98 
99   void print(raw_ostream &OS) {
100     switch (Type) {
101     case SCEVType::INT:
102       OS << "SCEVType::INT";
103       break;
104     case SCEVType::PARAM:
105       OS << "SCEVType::PARAM";
106       break;
107     case SCEVType::IV:
108       OS << "SCEVType::IV";
109       break;
110     case SCEVType::INVALID:
111       OS << "SCEVType::INVALID";
112       break;
113     }
114   }
115 };
116 
117 raw_ostream &operator<<(raw_ostream &OS, class ValidatorResult &VR) {
118   VR.print(OS);
119   return OS;
120 }
121 
122 /// Check if a SCEV is valid in a SCoP.
123 struct SCEVValidator
124     : public SCEVVisitor<SCEVValidator, class ValidatorResult> {
125 private:
126   const Region *R;
127   Loop *Scope;
128   ScalarEvolution &SE;
129   const Value *BaseAddress;
130   InvariantLoadsSetTy *ILS;
131 
132 public:
133   SCEVValidator(const Region *R, Loop *Scope, ScalarEvolution &SE,
134                 const Value *BaseAddress, InvariantLoadsSetTy *ILS)
135       : R(R), Scope(Scope), SE(SE), BaseAddress(BaseAddress), ILS(ILS) {}
136 
137   class ValidatorResult visitConstant(const SCEVConstant *Constant) {
138     return ValidatorResult(SCEVType::INT);
139   }
140 
141   class ValidatorResult visitTruncateExpr(const SCEVTruncateExpr *Expr) {
142     ValidatorResult Op = visit(Expr->getOperand());
143 
144     switch (Op.getType()) {
145     case SCEVType::INT:
146     case SCEVType::PARAM:
147       // We currently do not represent a truncate expression as an affine
148       // expression. If it is constant during Scop execution, we treat it as a
149       // parameter.
150       return ValidatorResult(SCEVType::PARAM, Expr);
151     case SCEVType::IV:
152       DEBUG(dbgs() << "INVALID: Truncation of SCEVType::IV expression");
153       return ValidatorResult(SCEVType::INVALID);
154     case SCEVType::INVALID:
155       return Op;
156     }
157 
158     llvm_unreachable("Unknown SCEVType");
159   }
160 
161   class ValidatorResult visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
162     ValidatorResult Op = visit(Expr->getOperand());
163 
164     switch (Op.getType()) {
165     case SCEVType::INT:
166     case SCEVType::PARAM:
167       // We currently do not represent a truncate expression as an affine
168       // expression. If it is constant during Scop execution, we treat it as a
169       // parameter.
170       return ValidatorResult(SCEVType::PARAM, Expr);
171     case SCEVType::IV:
172       DEBUG(dbgs() << "INVALID: ZeroExtend of SCEVType::IV expression");
173       return ValidatorResult(SCEVType::INVALID);
174     case SCEVType::INVALID:
175       return Op;
176     }
177 
178     llvm_unreachable("Unknown SCEVType");
179   }
180 
181   class ValidatorResult visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
182     // We currently allow only signed SCEV expressions. In the case of a
183     // signed value, a sign extend is a noop.
184     //
185     // TODO: Reconsider this when we add support for unsigned values.
186     return visit(Expr->getOperand());
187   }
188 
189   class ValidatorResult visitAddExpr(const SCEVAddExpr *Expr) {
190     ValidatorResult Return(SCEVType::INT);
191 
192     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
193       ValidatorResult Op = visit(Expr->getOperand(i));
194       Return.merge(Op);
195 
196       // Early exit.
197       if (!Return.isValid())
198         break;
199     }
200 
201     // TODO: Check for NSW and NUW.
202     return Return;
203   }
204 
205   class ValidatorResult visitMulExpr(const SCEVMulExpr *Expr) {
206     ValidatorResult Return(SCEVType::INT);
207 
208     bool HasMultipleParams = false;
209 
210     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
211       ValidatorResult Op = visit(Expr->getOperand(i));
212 
213       if (Op.isINT())
214         continue;
215 
216       if (Op.isPARAM() && Return.isPARAM()) {
217         HasMultipleParams = true;
218         continue;
219       }
220 
221       if ((Op.isIV() || Op.isPARAM()) && !Return.isINT()) {
222         DEBUG(dbgs() << "INVALID: More than one non-int operand in MulExpr\n"
223                      << "\tExpr: " << *Expr << "\n"
224                      << "\tPrevious expression type: " << Return << "\n"
225                      << "\tNext operand (" << Op
226                      << "): " << *Expr->getOperand(i) << "\n");
227 
228         return ValidatorResult(SCEVType::INVALID);
229       }
230 
231       Return.merge(Op);
232     }
233 
234     if (HasMultipleParams && Return.isValid())
235       return ValidatorResult(SCEVType::PARAM, Expr);
236 
237     // TODO: Check for NSW and NUW.
238     return Return;
239   }
240 
241   class ValidatorResult visitUDivExpr(const SCEVUDivExpr *Expr) {
242     ValidatorResult LHS = visit(Expr->getLHS());
243     ValidatorResult RHS = visit(Expr->getRHS());
244 
245     // We currently do not represent an unsigned division as an affine
246     // expression. If the division is constant during Scop execution we treat it
247     // as a parameter, otherwise we bail out.
248     if (LHS.isConstant() && RHS.isConstant())
249       return ValidatorResult(SCEVType::PARAM, Expr);
250 
251     DEBUG(dbgs() << "INVALID: unsigned division of non-constant expressions");
252     return ValidatorResult(SCEVType::INVALID);
253   }
254 
255   class ValidatorResult visitAddRecExpr(const SCEVAddRecExpr *Expr) {
256     if (!Expr->isAffine()) {
257       DEBUG(dbgs() << "INVALID: AddRec is not affine");
258       return ValidatorResult(SCEVType::INVALID);
259     }
260 
261     ValidatorResult Start = visit(Expr->getStart());
262     ValidatorResult Recurrence = visit(Expr->getStepRecurrence(SE));
263 
264     if (!Start.isValid())
265       return Start;
266 
267     if (!Recurrence.isValid())
268       return Recurrence;
269 
270     auto *L = Expr->getLoop();
271     if (R->contains(L) && (!Scope || !L->contains(Scope))) {
272       DEBUG(dbgs() << "INVALID: AddRec out of a loop whose exit value is not "
273                       "synthesizable");
274       return ValidatorResult(SCEVType::INVALID);
275     }
276 
277     if (R->contains(L)) {
278       if (Recurrence.isINT()) {
279         ValidatorResult Result(SCEVType::IV);
280         Result.addParamsFrom(Start);
281         return Result;
282       }
283 
284       DEBUG(dbgs() << "INVALID: AddRec within scop has non-int"
285                       "recurrence part");
286       return ValidatorResult(SCEVType::INVALID);
287     }
288 
289     assert(Start.isConstant() && Recurrence.isConstant() &&
290            "Expected 'Start' and 'Recurrence' to be constant");
291 
292     // Directly generate ValidatorResult for Expr if 'start' is zero.
293     if (Expr->getStart()->isZero())
294       return ValidatorResult(SCEVType::PARAM, Expr);
295 
296     // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
297     // if 'start' is not zero.
298     const SCEV *ZeroStartExpr = SE.getAddRecExpr(
299         SE.getConstant(Expr->getStart()->getType(), 0),
300         Expr->getStepRecurrence(SE), Expr->getLoop(), Expr->getNoWrapFlags());
301 
302     ValidatorResult ZeroStartResult =
303         ValidatorResult(SCEVType::PARAM, ZeroStartExpr);
304     ZeroStartResult.addParamsFrom(Start);
305 
306     return ZeroStartResult;
307   }
308 
309   class ValidatorResult visitSMaxExpr(const SCEVSMaxExpr *Expr) {
310     ValidatorResult Return(SCEVType::INT);
311 
312     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
313       ValidatorResult Op = visit(Expr->getOperand(i));
314 
315       if (!Op.isValid())
316         return Op;
317 
318       Return.merge(Op);
319     }
320 
321     return Return;
322   }
323 
324   class ValidatorResult visitUMaxExpr(const SCEVUMaxExpr *Expr) {
325     // We do not support unsigned operations. If 'Expr' is constant during Scop
326     // execution we treat this as a parameter, otherwise we bail out.
327     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
328       ValidatorResult Op = visit(Expr->getOperand(i));
329 
330       if (!Op.isConstant()) {
331         DEBUG(dbgs() << "INVALID: UMaxExpr has a non-constant operand");
332         return ValidatorResult(SCEVType::INVALID);
333       }
334     }
335 
336     return ValidatorResult(SCEVType::PARAM, Expr);
337   }
338 
339   ValidatorResult visitGenericInst(Instruction *I, const SCEV *S) {
340     if (R->contains(I)) {
341       DEBUG(dbgs() << "INVALID: UnknownExpr references an instruction "
342                       "within the region\n");
343       return ValidatorResult(SCEVType::INVALID);
344     }
345 
346     return ValidatorResult(SCEVType::PARAM, S);
347   }
348 
349   ValidatorResult visitLoadInstruction(Instruction *I, const SCEV *S) {
350     if (R->contains(I) && ILS) {
351       ILS->insert(cast<LoadInst>(I));
352       return ValidatorResult(SCEVType::PARAM, S);
353     }
354 
355     return visitGenericInst(I, S);
356   }
357 
358   ValidatorResult visitSDivInstruction(Instruction *SDiv, const SCEV *S) {
359     assert(SDiv->getOpcode() == Instruction::SDiv &&
360            "Assumed SDiv instruction!");
361 
362     auto *Divisor = SDiv->getOperand(1);
363     auto *CI = dyn_cast<ConstantInt>(Divisor);
364     if (!CI)
365       return visitGenericInst(SDiv, S);
366 
367     auto *Dividend = SDiv->getOperand(0);
368     auto *DividendSCEV = SE.getSCEV(Dividend);
369     return visit(DividendSCEV);
370   }
371 
372   ValidatorResult visitSRemInstruction(Instruction *SRem, const SCEV *S) {
373     assert(SRem->getOpcode() == Instruction::SRem &&
374            "Assumed SRem instruction!");
375 
376     auto *Divisor = SRem->getOperand(1);
377     auto *CI = dyn_cast<ConstantInt>(Divisor);
378     if (!CI)
379       return visitGenericInst(SRem, S);
380 
381     auto *Dividend = SRem->getOperand(0);
382     auto *DividendSCEV = SE.getSCEV(Dividend);
383     return visit(DividendSCEV);
384   }
385 
386   ValidatorResult visitUnknown(const SCEVUnknown *Expr) {
387     Value *V = Expr->getValue();
388 
389     if (!Expr->getType()->isIntegerTy() && !Expr->getType()->isPointerTy()) {
390       DEBUG(dbgs() << "INVALID: UnknownExpr is not an integer or pointer");
391       return ValidatorResult(SCEVType::INVALID);
392     }
393 
394     if (isa<UndefValue>(V)) {
395       DEBUG(dbgs() << "INVALID: UnknownExpr references an undef value");
396       return ValidatorResult(SCEVType::INVALID);
397     }
398 
399     if (BaseAddress == V) {
400       DEBUG(dbgs() << "INVALID: UnknownExpr references BaseAddress\n");
401       return ValidatorResult(SCEVType::INVALID);
402     }
403 
404     if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
405       switch (I->getOpcode()) {
406       case Instruction::Load:
407         return visitLoadInstruction(I, Expr);
408       case Instruction::SDiv:
409         return visitSDivInstruction(I, Expr);
410       case Instruction::SRem:
411         return visitSRemInstruction(I, Expr);
412       default:
413         return visitGenericInst(I, Expr);
414       }
415     }
416 
417     return ValidatorResult(SCEVType::PARAM, Expr);
418   }
419 };
420 
421 /// @brief Check whether a SCEV refers to an SSA name defined inside a region.
422 class SCEVInRegionDependences {
423   const Region *R;
424   Loop *Scope;
425   bool AllowLoops;
426   bool HasInRegionDeps = false;
427 
428 public:
429   SCEVInRegionDependences(const Region *R, Loop *Scope, bool AllowLoops)
430       : R(R), Scope(Scope), AllowLoops(AllowLoops) {}
431 
432   bool follow(const SCEV *S) {
433     if (auto Unknown = dyn_cast<SCEVUnknown>(S)) {
434       Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
435 
436       // Return true when Inst is defined inside the region R.
437       if (Inst && R->contains(Inst)) {
438         HasInRegionDeps = true;
439         return false;
440       }
441     } else if (auto AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
442       if (!AllowLoops) {
443         if (!Scope) {
444           HasInRegionDeps = true;
445           return false;
446         }
447         auto *L = AddRec->getLoop();
448         if (R->contains(L) && !L->contains(Scope)) {
449           HasInRegionDeps = true;
450           return false;
451         }
452       }
453     }
454     return true;
455   }
456   bool isDone() { return false; }
457   bool hasDependences() { return HasInRegionDeps; }
458 };
459 
460 namespace polly {
461 /// Find all loops referenced in SCEVAddRecExprs.
462 class SCEVFindLoops {
463   SetVector<const Loop *> &Loops;
464 
465 public:
466   SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {}
467 
468   bool follow(const SCEV *S) {
469     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
470       Loops.insert(AddRec->getLoop());
471     return true;
472   }
473   bool isDone() { return false; }
474 };
475 
476 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) {
477   SCEVFindLoops FindLoops(Loops);
478   SCEVTraversal<SCEVFindLoops> ST(FindLoops);
479   ST.visitAll(Expr);
480 }
481 
482 /// Find all values referenced in SCEVUnknowns.
483 class SCEVFindValues {
484   ScalarEvolution &SE;
485   SetVector<Value *> &Values;
486 
487 public:
488   SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values)
489       : SE(SE), Values(Values) {}
490 
491   bool follow(const SCEV *S) {
492     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
493     if (!Unknown)
494       return true;
495 
496     Values.insert(Unknown->getValue());
497     Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
498     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
499                   Inst->getOpcode() != Instruction::SDiv))
500       return false;
501 
502     auto *Dividend = SE.getSCEV(Inst->getOperand(1));
503     if (!isa<SCEVConstant>(Dividend))
504       return false;
505 
506     auto *Divisor = SE.getSCEV(Inst->getOperand(0));
507     SCEVFindValues FindValues(SE, Values);
508     SCEVTraversal<SCEVFindValues> ST(FindValues);
509     ST.visitAll(Dividend);
510     ST.visitAll(Divisor);
511 
512     return false;
513   }
514   bool isDone() { return false; }
515 };
516 
517 void findValues(const SCEV *Expr, ScalarEvolution &SE,
518                 SetVector<Value *> &Values) {
519   SCEVFindValues FindValues(SE, Values);
520   SCEVTraversal<SCEVFindValues> ST(FindValues);
521   ST.visitAll(Expr);
522 }
523 
524 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R,
525                                llvm::Loop *Scope, bool AllowLoops) {
526   SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops);
527   SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps);
528   ST.visitAll(Expr);
529   return InRegionDeps.hasDependences();
530 }
531 
532 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr,
533                   ScalarEvolution &SE, const Value *BaseAddress,
534                   InvariantLoadsSetTy *ILS) {
535   if (isa<SCEVCouldNotCompute>(Expr))
536     return false;
537 
538   SCEVValidator Validator(R, Scope, SE, BaseAddress, ILS);
539   DEBUG({
540     dbgs() << "\n";
541     dbgs() << "Expr: " << *Expr << "\n";
542     dbgs() << "Region: " << R->getNameStr() << "\n";
543     dbgs() << " -> ";
544   });
545 
546   ValidatorResult Result = Validator.visit(Expr);
547 
548   DEBUG({
549     if (Result.isValid())
550       dbgs() << "VALID\n";
551     dbgs() << "\n";
552   });
553 
554   return Result.isValid();
555 }
556 
557 static bool isAffineParamExpr(Value *V, const Region *R, Loop *Scope,
558                               ScalarEvolution &SE,
559                               std::vector<const SCEV *> &Params) {
560   auto *E = SE.getSCEV(V);
561   if (isa<SCEVCouldNotCompute>(E))
562     return false;
563 
564   SCEVValidator Validator(R, Scope, SE, nullptr, nullptr);
565   ValidatorResult Result = Validator.visit(E);
566   if (!Result.isConstant())
567     return false;
568 
569   auto ResultParams = Result.getParameters();
570   Params.insert(Params.end(), ResultParams.begin(), ResultParams.end());
571 
572   return true;
573 }
574 
575 bool isAffineParamConstraint(Value *V, const Region *R, llvm::Loop *Scope,
576                              ScalarEvolution &SE,
577                              std::vector<const SCEV *> &Params, bool OrExpr) {
578   if (auto *ICmp = dyn_cast<ICmpInst>(V)) {
579     return isAffineParamConstraint(ICmp->getOperand(0), R, Scope, SE, Params,
580                                    true) &&
581            isAffineParamConstraint(ICmp->getOperand(1), R, Scope, SE, Params,
582                                    true);
583   } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) {
584     auto Opcode = BinOp->getOpcode();
585     if (Opcode == Instruction::And || Opcode == Instruction::Or)
586       return isAffineParamConstraint(BinOp->getOperand(0), R, Scope, SE, Params,
587                                      false) &&
588              isAffineParamConstraint(BinOp->getOperand(1), R, Scope, SE, Params,
589                                      false);
590     /* Fall through */
591   }
592 
593   if (!OrExpr)
594     return false;
595 
596   return isAffineParamExpr(V, R, Scope, SE, Params);
597 }
598 
599 std::vector<const SCEV *> getParamsInAffineExpr(const Region *R, Loop *Scope,
600                                                 const SCEV *Expr,
601                                                 ScalarEvolution &SE,
602                                                 const Value *BaseAddress) {
603   if (isa<SCEVCouldNotCompute>(Expr))
604     return std::vector<const SCEV *>();
605 
606   InvariantLoadsSetTy ILS;
607   SCEVValidator Validator(R, Scope, SE, BaseAddress, &ILS);
608   ValidatorResult Result = Validator.visit(Expr);
609   assert(Result.isValid() && "Requested parameters for an invalid SCEV!");
610 
611   return Result.getParameters();
612 }
613 
614 std::pair<const SCEVConstant *, const SCEV *>
615 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) {
616 
617   auto *LeftOver = SE.getConstant(S->getType(), 1);
618   auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1));
619 
620   if (auto *Constant = dyn_cast<SCEVConstant>(S))
621     return std::make_pair(Constant, LeftOver);
622 
623   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
624   if (AddRec) {
625     auto *StartExpr = AddRec->getStart();
626     if (StartExpr->isZero()) {
627       auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE);
628       auto *LeftOverAddRec =
629           SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(),
630                            AddRec->getNoWrapFlags());
631       return std::make_pair(StepPair.first, LeftOverAddRec);
632     }
633     return std::make_pair(ConstPart, S);
634   }
635 
636   auto *Mul = dyn_cast<SCEVMulExpr>(S);
637   if (!Mul)
638     return std::make_pair(ConstPart, S);
639 
640   for (auto *Op : Mul->operands())
641     if (isa<SCEVConstant>(Op))
642       ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op));
643     else
644       LeftOver = SE.getMulExpr(LeftOver, Op);
645 
646   return std::make_pair(ConstPart, LeftOver);
647 }
648 }
649