1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements stmt-related attribute processing.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Sema/DelayedDiagnostic.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/LoopHint.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "llvm/ADT/StringExtras.h"
22 
23 using namespace clang;
24 using namespace sema;
25 
26 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const AttributeList &A,
27                                    SourceRange Range) {
28   FallThroughAttr Attr(A.getRange(), S.Context,
29                        A.getAttributeSpellingListIndex());
30   if (!isa<NullStmt>(St)) {
31     S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target)
32         << Attr.getSpelling() << St->getLocStart();
33     if (isa<SwitchCase>(St)) {
34       SourceLocation L = S.getLocForEndOfToken(Range.getEnd());
35       S.Diag(L, diag::note_fallthrough_insert_semi_fixit)
36           << FixItHint::CreateInsertion(L, ";");
37     }
38     return nullptr;
39   }
40   auto *FnScope = S.getCurFunction();
41   if (FnScope->SwitchStack.empty()) {
42     S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch);
43     return nullptr;
44   }
45 
46   // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
47   // about using it as an extension.
48   if (!S.getLangOpts().CPlusPlus1z && A.isCXX11Attribute() &&
49       !A.getScopeName())
50     S.Diag(A.getLoc(), diag::ext_cxx1z_attr) << A.getName();
51 
52   FnScope->setHasFallthroughStmt();
53   return ::new (S.Context) auto(Attr);
54 }
55 
56 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const AttributeList &A,
57                                 SourceRange) {
58   IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0);
59   IdentifierLoc *OptionLoc = A.getArgAsIdent(1);
60   IdentifierLoc *StateLoc = A.getArgAsIdent(2);
61   Expr *ValueExpr = A.getArgAsExpr(3);
62 
63   bool PragmaUnroll = PragmaNameLoc->Ident->getName() == "unroll";
64   bool PragmaNoUnroll = PragmaNameLoc->Ident->getName() == "nounroll";
65   if (St->getStmtClass() != Stmt::DoStmtClass &&
66       St->getStmtClass() != Stmt::ForStmtClass &&
67       St->getStmtClass() != Stmt::CXXForRangeStmtClass &&
68       St->getStmtClass() != Stmt::WhileStmtClass) {
69     const char *Pragma =
70         llvm::StringSwitch<const char *>(PragmaNameLoc->Ident->getName())
71             .Case("unroll", "#pragma unroll")
72             .Case("nounroll", "#pragma nounroll")
73             .Default("#pragma clang loop");
74     S.Diag(St->getLocStart(), diag::err_pragma_loop_precedes_nonloop) << Pragma;
75     return nullptr;
76   }
77 
78   LoopHintAttr::Spelling Spelling;
79   LoopHintAttr::OptionType Option;
80   LoopHintAttr::LoopHintState State;
81   if (PragmaNoUnroll) {
82     // #pragma nounroll
83     Spelling = LoopHintAttr::Pragma_nounroll;
84     Option = LoopHintAttr::Unroll;
85     State = LoopHintAttr::Disable;
86   } else if (PragmaUnroll) {
87     Spelling = LoopHintAttr::Pragma_unroll;
88     if (ValueExpr) {
89       // #pragma unroll N
90       Option = LoopHintAttr::UnrollCount;
91       State = LoopHintAttr::Numeric;
92     } else {
93       // #pragma unroll
94       Option = LoopHintAttr::Unroll;
95       State = LoopHintAttr::Enable;
96     }
97   } else {
98     // #pragma clang loop ...
99     Spelling = LoopHintAttr::Pragma_clang_loop;
100     assert(OptionLoc && OptionLoc->Ident &&
101            "Attribute must have valid option info.");
102     Option = llvm::StringSwitch<LoopHintAttr::OptionType>(
103                  OptionLoc->Ident->getName())
104                  .Case("vectorize", LoopHintAttr::Vectorize)
105                  .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
106                  .Case("interleave", LoopHintAttr::Interleave)
107                  .Case("interleave_count", LoopHintAttr::InterleaveCount)
108                  .Case("unroll", LoopHintAttr::Unroll)
109                  .Case("unroll_count", LoopHintAttr::UnrollCount)
110                  .Default(LoopHintAttr::Vectorize);
111     if (Option == LoopHintAttr::VectorizeWidth ||
112         Option == LoopHintAttr::InterleaveCount ||
113         Option == LoopHintAttr::UnrollCount) {
114       assert(ValueExpr && "Attribute must have a valid value expression.");
115       if (S.CheckLoopHintExpr(ValueExpr, St->getLocStart()))
116         return nullptr;
117       State = LoopHintAttr::Numeric;
118     } else if (Option == LoopHintAttr::Vectorize ||
119                Option == LoopHintAttr::Interleave ||
120                Option == LoopHintAttr::Unroll) {
121       assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument");
122       if (StateLoc->Ident->isStr("disable"))
123         State = LoopHintAttr::Disable;
124       else if (StateLoc->Ident->isStr("assume_safety"))
125         State = LoopHintAttr::AssumeSafety;
126       else if (StateLoc->Ident->isStr("full"))
127         State = LoopHintAttr::Full;
128       else if (StateLoc->Ident->isStr("enable"))
129         State = LoopHintAttr::Enable;
130       else
131         llvm_unreachable("bad loop hint argument");
132     } else
133       llvm_unreachable("bad loop hint");
134   }
135 
136   return LoopHintAttr::CreateImplicit(S.Context, Spelling, Option, State,
137                                       ValueExpr, A.getRange());
138 }
139 
140 static void
141 CheckForIncompatibleAttributes(Sema &S,
142                                const SmallVectorImpl<const Attr *> &Attrs) {
143   // There are 3 categories of loop hints attributes: vectorize, interleave,
144   // and unroll. Each comes in two variants: a state form and a numeric form.
145   // The state form selectively defaults/enables/disables the transformation
146   // for the loop (for unroll, default indicates full unrolling rather than
147   // enabling the transformation).  The numeric form form provides an integer
148   // hint (for example, unroll count) to the transformer. The following array
149   // accumulates the hints encountered while iterating through the attributes
150   // to check for compatibility.
151   struct {
152     const LoopHintAttr *StateAttr;
153     const LoopHintAttr *NumericAttr;
154   } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}};
155 
156   for (const auto *I : Attrs) {
157     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);
158 
159     // Skip non loop hint attributes
160     if (!LH)
161       continue;
162 
163     LoopHintAttr::OptionType Option = LH->getOption();
164     enum { Vectorize, Interleave, Unroll } Category;
165     switch (Option) {
166     case LoopHintAttr::Vectorize:
167     case LoopHintAttr::VectorizeWidth:
168       Category = Vectorize;
169       break;
170     case LoopHintAttr::Interleave:
171     case LoopHintAttr::InterleaveCount:
172       Category = Interleave;
173       break;
174     case LoopHintAttr::Unroll:
175     case LoopHintAttr::UnrollCount:
176       Category = Unroll;
177       break;
178     };
179 
180     auto &CategoryState = HintAttrs[Category];
181     const LoopHintAttr *PrevAttr;
182     if (Option == LoopHintAttr::Vectorize ||
183         Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll) {
184       // Enable|Disable|AssumeSafety hint.  For example, vectorize(enable).
185       PrevAttr = CategoryState.StateAttr;
186       CategoryState.StateAttr = LH;
187     } else {
188       // Numeric hint.  For example, vectorize_width(8).
189       PrevAttr = CategoryState.NumericAttr;
190       CategoryState.NumericAttr = LH;
191     }
192 
193     PrintingPolicy Policy(S.Context.getLangOpts());
194     SourceLocation OptionLoc = LH->getRange().getBegin();
195     if (PrevAttr)
196       // Cannot specify same type of attribute twice.
197       S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
198           << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy)
199           << LH->getDiagnosticName(Policy);
200 
201     if (CategoryState.StateAttr && CategoryState.NumericAttr &&
202         (Category == Unroll ||
203          CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) {
204       // Disable hints are not compatible with numeric hints of the same
205       // category.  As a special case, numeric unroll hints are also not
206       // compatible with enable or full form of the unroll pragma because these
207       // directives indicate full unrolling.
208       S.Diag(OptionLoc, diag::err_pragma_loop_compatibility)
209           << /*Duplicate=*/false
210           << CategoryState.StateAttr->getDiagnosticName(Policy)
211           << CategoryState.NumericAttr->getDiagnosticName(Policy);
212     }
213   }
214 }
215 
216 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const AttributeList &A,
217                                     SourceRange Range) {
218   // OpenCL v2.0 s6.11.5 - opencl_unroll_hint can have 0 arguments (compiler
219   // determines unrolling factor) or 1 argument (the unroll factor provided
220   // by the user).
221 
222   if (S.getLangOpts().OpenCLVersion < 200) {
223     S.Diag(A.getLoc(), diag::err_attribute_requires_opencl_version)
224         << A.getName() << "2.0";
225     return nullptr;
226   }
227 
228   unsigned NumArgs = A.getNumArgs();
229 
230   if (NumArgs > 1) {
231     S.Diag(A.getLoc(), diag::err_attribute_too_many_arguments) << A.getName()
232                                                                << 1;
233     return nullptr;
234   }
235 
236   unsigned UnrollFactor = 0;
237 
238   if (NumArgs == 1) {
239     Expr *E = A.getArgAsExpr(0);
240     llvm::APSInt ArgVal(32);
241 
242     if (!E->isIntegerConstantExpr(ArgVal, S.Context)) {
243       S.Diag(A.getLoc(), diag::err_attribute_argument_type)
244           << A.getName() << AANT_ArgumentIntegerConstant << E->getSourceRange();
245       return nullptr;
246     }
247 
248     int Val = ArgVal.getSExtValue();
249 
250     if (Val <= 0) {
251       S.Diag(A.getRange().getBegin(),
252              diag::err_attribute_requires_positive_integer)
253           << A.getName();
254       return nullptr;
255     }
256     UnrollFactor = Val;
257   }
258 
259   return OpenCLUnrollHintAttr::CreateImplicit(S.Context, UnrollFactor);
260 }
261 
262 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const AttributeList &A,
263                                   SourceRange Range) {
264   switch (A.getKind()) {
265   case AttributeList::UnknownAttribute:
266     S.Diag(A.getLoc(), A.isDeclspecAttribute() ?
267            diag::warn_unhandled_ms_attribute_ignored :
268            diag::warn_unknown_attribute_ignored) << A.getName();
269     return nullptr;
270   case AttributeList::AT_FallThrough:
271     return handleFallThroughAttr(S, St, A, Range);
272   case AttributeList::AT_LoopHint:
273     return handleLoopHintAttr(S, St, A, Range);
274   case AttributeList::AT_OpenCLUnrollHint:
275     return handleOpenCLUnrollHint(S, St, A, Range);
276   default:
277     // if we're here, then we parsed a known attribute, but didn't recognize
278     // it as a statement attribute => it is declaration attribute
279     S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt)
280         << A.getName() << St->getLocStart();
281     return nullptr;
282   }
283 }
284 
285 StmtResult Sema::ProcessStmtAttributes(Stmt *S, AttributeList *AttrList,
286                                        SourceRange Range) {
287   SmallVector<const Attr*, 8> Attrs;
288   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
289     if (Attr *a = ProcessStmtAttribute(*this, S, *l, Range))
290       Attrs.push_back(a);
291   }
292 
293   CheckForIncompatibleAttributes(*this, Attrs);
294 
295   if (Attrs.empty())
296     return S;
297 
298   return ActOnAttributedStmt(Range.getBegin(), Attrs, S);
299 }
300