Adding a new #pragma for the vectorize and interleave optimization hints.
authorAaron Ballman <aaron@aaronballman.com>
Fri, 6 Jun 2014 12:40:24 +0000 (12:40 +0000)
committerAaron Ballman <aaron@aaronballman.com>
Fri, 6 Jun 2014 12:40:24 +0000 (12:40 +0000)
Patch thanks to Tyler Nowicki!

llvm-svn: 210330

15 files changed:
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/LoopHint.h [new file with mode: 0644]
clang/lib/AST/StmtPrinter.cpp
clang/lib/CodeGen/CGStmt.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/lib/Parse/ParsePragma.cpp
clang/lib/Parse/ParseStmt.cpp
clang/lib/Sema/SemaStmtAttr.cpp
clang/test/CodeGen/pragma-loop.cpp [new file with mode: 0644]
clang/test/PCH/pragma-loop.cpp [new file with mode: 0644]
clang/test/Parser/pragma-loop.cpp [new file with mode: 0644]

index 11a30b9..3556ea4 100644 (file)
@@ -1757,6 +1757,53 @@ def MSVtorDisp : InheritableAttr {
   let Documentation = [Undocumented];
 }
 
-def Unaligned : IgnoredAttr {
-  let Spellings = [Keyword<"__unaligned">];
-}
+def Unaligned : IgnoredAttr {\r
+  let Spellings = [Keyword<"__unaligned">];\r
+}\r
+\r
+def LoopHint : Attr {\r
+  /// vectorize: vectorizes loop operations if 'value != 0'.\r
+  /// vectorize_width: vectorize loop operations with width 'value'.\r
+  /// interleave: interleave multiple loop iterations if 'value != 0'.\r
+  /// interleave_count: interleaves 'value' loop interations.\r
+\r
+  /// FIXME: Add Pragma spelling to tablegen and\r
+  /// use it here.\r
+  let Spellings = [Keyword<"loop">];\r
+\r
+  /// State of the loop optimization specified by the spelling.\r
+  let Args = [EnumArgument<"Option", "OptionType",\r
+                          ["vectorize", "vectorize_width", "interleave", "interleave_count"],\r
+                          ["Vectorize", "VectorizeWidth", "Interleave", "InterleaveCount"]>,\r
+              DefaultIntArgument<"Value", 1>];\r
+\r
+  let AdditionalMembers = [{\r
+  static StringRef getOptionName(int Option) {\r
+    switch(Option) {\r
+    case Vectorize: return "vectorize";\r
+    case VectorizeWidth: return "vectorize_width";\r
+    case Interleave: return "interleave";\r
+    case InterleaveCount: return "interleave_count";\r
+    }\r
+    llvm_unreachable("Unhandled LoopHint option.");\r
+  }\r
+\r
+  static StringRef getValueName(int Value) {\r
+    if (Value)\r
+      return "enable";\r
+    return "disable";\r
+  }\r
+\r
+  // FIXME: Modify pretty printer to print this pragma.\r
+  void print(raw_ostream &OS, const PrintingPolicy &Policy) const {\r
+    OS << "#pragma clang loop " << getOptionName(option) << "(";\r
+    if (option == VectorizeWidth || option == InterleaveCount)\r
+      OS << value;\r
+    else\r
+      OS << getValueName(value);\r
+    OS << ")\n";\r
+  }\r
+  }];\r
+\r
+  let Documentation = [Undocumented];\r
+}\r
index 6a01dfc..2ab5021 100644 (file)
@@ -889,12 +889,16 @@ def err_omp_unexpected_directive : Error<
 def err_omp_expected_punc : Error<
   "expected ',' or ')' in '%0' clause">;
 def err_omp_unexpected_clause : Error<
-  "unexpected OpenMP clause '%0' in directive '#pragma omp %1'">;
-def err_omp_more_one_clause : Error<
-  "directive '#pragma omp %0' cannot contain more than one '%1' clause">;
-} // end of Parse Issue category.
-
-let CategoryName = "Modules Issue" in {
+  "unexpected OpenMP clause '%0' in directive '#pragma omp %1'">;\r
+def err_omp_more_one_clause : Error<\r
+  "directive '#pragma omp %0' cannot contain more than one '%1' clause">;\r
+\r
+// Pragma loop support.\r
+def err_pragma_loop_invalid_option : Error<\r
+  "%select{invalid|missing}0 option%select{ %1|}0; expected vectorize, vectorize_width, interleave, or interleave_count">;\r
+} // end of Parse Issue category.\r
+\r
+let CategoryName = "Modules Issue" in {\r
 def err_module_expected_ident : Error<
   "expected a module name after module import">;
 def err_module_expected_semi : Error<
index 41c2100..f49ff18 100644 (file)
@@ -539,12 +539,21 @@ def err_pragma_push_visibility_mismatch : Error<
 def note_surrounding_namespace_ends_here : Note<
   "surrounding namespace with visibility attribute ends here">;
 def err_pragma_pop_visibility_mismatch : Error<
-  "#pragma visibility pop with no matching #pragma visibility push">;
-def note_surrounding_namespace_starts_here : Note<
-  "surrounding namespace with visibility attribute starts here">;
-
-/// Objective-C parser diagnostics
-def err_duplicate_class_def : Error<
+  "#pragma visibility pop with no matching #pragma visibility push">;\r
+def note_surrounding_namespace_starts_here : Note<\r
+  "surrounding namespace with visibility attribute starts here">;\r
+def err_pragma_loop_invalid_value : Error<\r
+  "%select{invalid|missing}0 value%select{ %1|}0; expected a positive integer value">;\r
+def err_pragma_loop_invalid_keyword : Error<\r
+  "%select{invalid|missing}0 keyword%select{ %1|}0; expected 'enable' or 'disable'">;\r
+def err_pragma_loop_compatibility : Error<\r
+  "%select{incompatible|duplicate}0 directives '%1(%2)' and '%3(%4)'">;\r
+def err_pragma_loop_precedes_nonloop : Error<\r
+  "expected a for, while, or do-while loop to follow the '#pragma clang loop' "\r
+  "directive">;\r
+\r
+/// Objective-C parser diagnostics\r
+def err_duplicate_class_def : Error<\r
   "duplicate interface definition for class %0">;
 def err_undef_superclass : Error<
   "cannot find interface declaration for %0, superclass of %1">;
index 845a8b0..5d08833 100644 (file)
@@ -701,6 +701,11 @@ ANNOTATION(pragma_opencl_extension)
 ANNOTATION(pragma_openmp)
 ANNOTATION(pragma_openmp_end)
 
+// Annotations for loop pragma directives #pragma clang loop ...
+// The lexer produces these so that they only take effect when the parser
+// handles #pragma loop ... directives.
+ANNOTATION(pragma_loop_hint)
+
 // Annotations for module import translated from #include etc.
 ANNOTATION(module_include)
 ANNOTATION(module_begin)
index c2aa1e6..049a462 100644 (file)
@@ -20,6 +20,7 @@
 #include "clang/Lex/CodeCompletionHandler.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Sema/DeclSpec.h"
+#include "clang/Sema/LoopHint.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Compiler.h"
@@ -161,6 +162,7 @@ class Parser : public CodeCompletionHandler {
   std::unique_ptr<PragmaHandler> MSCodeSeg;
   std::unique_ptr<PragmaHandler> MSSection;
   std::unique_ptr<PragmaHandler> OptimizeHandler;
+  std::unique_ptr<PragmaHandler> LoopHintHandler;
 
   std::unique_ptr<CommentHandler> CommentSemaHandler;
 
@@ -519,6 +521,10 @@ private:
   /// #pragma clang __debug captured
   StmtResult HandlePragmaCaptured();
 
+  /// \brief Handle the annotation token produced for
+  /// #pragma vectorize...
+  LoopHint HandlePragmaLoopHint();
+
   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
   /// returns the token after Tok, etc.
@@ -1601,6 +1607,9 @@ private:
   StmtResult ParseReturnStatement();
   StmtResult ParseAsmStatement(bool &msAsm);
   StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
+  StmtResult ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
+                                 SourceLocation *TrailingElseLoc,
+                                 ParsedAttributesWithRange &Attrs);
 
   /// \brief Describes the behavior that should be taken for an __if_exists
   /// block.
diff --git a/clang/include/clang/Sema/LoopHint.h b/clang/include/clang/Sema/LoopHint.h
new file mode 100644 (file)
index 0000000..ad9b07d
--- /dev/null
@@ -0,0 +1,31 @@
+//===--- LoopHint.h - Types for LoopHint ------------------------*- C++ -*-===//\r
+//\r
+//                     The LLVM Compiler Infrastructure\r
+//\r
+// This file is distributed under the University of Illinois Open Source\r
+// License. See LICENSE.TXT for details.\r
+//\r
+//===----------------------------------------------------------------------===//\r
+\r
+#ifndef LLVM_CLANG_SEMA_LOOPHINT_H\r
+#define LLVM_CLANG_SEMA_LOOPHINT_H\r
+\r
+#include "clang/Basic/IdentifierTable.h"\r
+#include "clang/Basic/SourceLocation.h"\r
+#include "clang/Sema/AttributeList.h"\r
+#include "clang/Sema/Ownership.h"\r
+\r
+namespace clang {\r
+\r
+/// \brief Loop hint specified by a pragma loop directive.\r
+struct LoopHint {\r
+  SourceRange Range;\r
+  Expr *ValueExpr;\r
+  IdentifierLoc *LoopLoc;\r
+  IdentifierLoc *ValueLoc;\r
+  IdentifierLoc *OptionLoc;\r
+};\r
+\r
+} // end namespace clang\r
+\r
+#endif // LLVM_CLANG_SEMA_LOOPHINT_H\r
index 297de5e..1daab32 100644 (file)
@@ -168,8 +168,22 @@ void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
 }
 
 void StmtPrinter::VisitAttributedStmt(AttributedStmt *Node) {
-  for (const auto *Attr : Node->getAttrs())
-    Attr->printPretty(OS, Policy);
+  std::string raw_attr_os;
+  llvm::raw_string_ostream AttrOS(raw_attr_os);
+  for (const auto *Attr : Node->getAttrs()) {
+    // FIXME: This hack will be removed when printPretty
+    // has been modified to print pretty pragmas
+    if (const LoopHintAttr *LHA = dyn_cast<LoopHintAttr>(Attr)) {
+      LHA->print(OS, Policy);
+    } else
+      Attr->printPretty(AttrOS, Policy);
+  }
+
+  // Print attributes after pragmas.
+  StringRef AttrStr = AttrOS.str();
+  if (!AttrStr.empty())
+    OS << AttrStr;
+
   PrintStmt(Node->getSubStmt(), 0);
 }
 
index 534c16d..cca1624 100644 (file)
@@ -18,6 +18,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Sema/LoopHint.h"
 #include "clang/Sema/SemaDiagnostic.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/IR/CallSite.h"
@@ -398,7 +399,23 @@ void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
 }
 
 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
-  EmitStmt(S.getSubStmt());
+  const Stmt *SubStmt = S.getSubStmt();
+  switch (SubStmt->getStmtClass()) {
+  case Stmt::DoStmtClass:
+    EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
+    break;
+  case Stmt::ForStmtClass:
+    EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
+    break;
+  case Stmt::WhileStmtClass:
+    EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
+    break;
+  case Stmt::CXXForRangeStmtClass:
+    EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
+    break;
+  default:
+    EmitStmt(SubStmt);
+  }
 }
 
 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
@@ -504,7 +521,78 @@ void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
   EmitBlock(ContBlock, true);
 }
 
-void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
+void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
+                                      llvm::BranchInst *CondBr,
+                                      const ArrayRef<const Attr *> &Attrs) {
+  // Return if there are no hints.
+  if (Attrs.empty())
+    return;
+
+  // Add vectorize hints to the metadata on the conditional branch.
+  SmallVector<llvm::Value *, 2> Metadata(1);
+  for (const auto *Attr : Attrs) {
+    const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
+
+    // Skip non loop hint attributes
+    if (!LH)
+      continue;
+
+    LoopHintAttr::OptionType Option = LH->getOption();
+    int ValueInt = LH->getValue();
+
+    const char *MetadataName;
+    switch (Option) {
+    case LoopHintAttr::Vectorize:
+    case LoopHintAttr::VectorizeWidth:
+      MetadataName = "llvm.vectorizer.width";
+      break;
+    case LoopHintAttr::Interleave:
+    case LoopHintAttr::InterleaveCount:
+      MetadataName = "llvm.vectorizer.unroll";
+      break;
+    }
+
+    llvm::Value *Value;
+    llvm::MDString *Name;
+    switch (Option) {
+    case LoopHintAttr::Vectorize:
+    case LoopHintAttr::Interleave:
+      if (ValueInt == 1) {
+        // FIXME: In the future I will modifiy the behavior of the metadata
+        // so we can enable/disable vectorization and interleaving separately.
+        Name = llvm::MDString::get(Context, "llvm.vectorizer.enable");
+        Value = Builder.getTrue();
+        break;
+      }
+      // Vectorization/interleaving is disabled, set width/count to 1.
+      ValueInt = 1;
+      // Fallthrough.
+    case LoopHintAttr::VectorizeWidth:
+    case LoopHintAttr::InterleaveCount:
+      Name = llvm::MDString::get(Context, MetadataName);
+      Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
+      break;
+    }
+
+    SmallVector<llvm::Value *, 2> OpValues;
+    OpValues.push_back(Name);
+    OpValues.push_back(Value);
+
+    // Set or overwrite metadata indicated by Name.
+    Metadata.push_back(llvm::MDNode::get(Context, OpValues));
+  }
+
+  if (!Metadata.empty()) {
+    // Add llvm.loop MDNode to CondBr.
+    llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
+    LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
+
+    CondBr->setMetadata("llvm.loop", LoopID);
+  }
+}
+
+void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
+                                    const ArrayRef<const Attr *> &WhileAttrs) {
   RegionCounter Cnt = getPGORegionCounter(&S);
 
   // Emit the header for the loop, which will also become
@@ -551,13 +639,17 @@ void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
     if (ConditionScope.requiresCleanups())
       ExitBlock = createBasicBlock("while.exit");
-    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock,
-                         PGO.createLoopWeights(S.getCond(), Cnt));
+    llvm::BranchInst *CondBr =
+        Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock,
+                             PGO.createLoopWeights(S.getCond(), Cnt));
 
     if (ExitBlock != LoopExit.getBlock()) {
       EmitBlock(ExitBlock);
       EmitBranchThroughCleanup(LoopExit);
     }
+
+    // Attach metadata to loop body conditional branch.
+    EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
   }
 
   // Emit the loop body.  We have to emit this in a cleanup scope
@@ -588,7 +680,8 @@ void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
     SimplifyForwardingBlocks(LoopHeader.getBlock());
 }
 
-void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
+void CodeGenFunction::EmitDoStmt(const DoStmt &S,
+                                 const ArrayRef<const Attr *> &DoAttrs) {
   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
 
@@ -628,9 +721,14 @@ void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
       EmitBoolCondBranch = false;
 
   // As long as the condition is true, iterate the loop.
-  if (EmitBoolCondBranch)
-    Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
-                         PGO.createLoopWeights(S.getCond(), Cnt));
+  if (EmitBoolCondBranch) {
+    llvm::BranchInst *CondBr =
+        Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
+                             PGO.createLoopWeights(S.getCond(), Cnt));
+
+    // Attach metadata to loop body conditional branch.
+    EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
+  }
 
   LoopStack.pop();
 
@@ -643,7 +741,8 @@ void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
     SimplifyForwardingBlocks(LoopCond.getBlock());
 }
 
-void CodeGenFunction::EmitForStmt(const ForStmt &S) {
+void CodeGenFunction::EmitForStmt(const ForStmt &S,
+                                  const ArrayRef<const Attr *> &ForAttrs) {
   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
 
   RunCleanupsScope ForScope(*this);
@@ -699,8 +798,12 @@ void CodeGenFunction::EmitForStmt(const ForStmt &S) {
     // C99 6.8.5p2/p4: The first substatement is executed if the expression
     // compares unequal to 0.  The condition must be a scalar type.
     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
-    Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
-                         PGO.createLoopWeights(S.getCond(), Cnt));
+    llvm::BranchInst *CondBr =
+        Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
+                             PGO.createLoopWeights(S.getCond(), Cnt));
+
+    // Attach metadata to loop body conditional branch.
+    EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
 
     if (ExitBlock != LoopExit.getBlock()) {
       EmitBlock(ExitBlock);
@@ -743,7 +846,9 @@ void CodeGenFunction::EmitForStmt(const ForStmt &S) {
   EmitBlock(LoopExit.getBlock(), true);
 }
 
-void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
+void
+CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
+                                     const ArrayRef<const Attr *> &ForAttrs) {
   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
 
   RunCleanupsScope ForScope(*this);
@@ -778,8 +883,11 @@ void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
   // The body is executed if the expression, contextually converted
   // to bool, is true.
   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
-  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
-                       PGO.createLoopWeights(S.getCond(), Cnt));
+  llvm::BranchInst *CondBr = Builder.CreateCondBr(
+      BoolCondVal, ForBody, ExitBlock, PGO.createLoopWeights(S.getCond(), Cnt));
+
+  // Attach metadata to loop body conditional branch.
+  EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
 
   if (ExitBlock != LoopExit.getBlock()) {
     EmitBlock(ExitBlock);
index b6c58e0..570e1a8 100644 (file)
@@ -1860,9 +1860,14 @@ public:
   void EmitGotoStmt(const GotoStmt &S);
   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
   void EmitIfStmt(const IfStmt &S);
-  void EmitWhileStmt(const WhileStmt &S);
-  void EmitDoStmt(const DoStmt &S);
-  void EmitForStmt(const ForStmt &S);
+
+  void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr,
+                       const ArrayRef<const Attr *> &Attrs);
+  void EmitWhileStmt(const WhileStmt &S,
+                     const ArrayRef<const Attr *> &Attrs = None);
+  void EmitDoStmt(const DoStmt &S, const ArrayRef<const Attr *> &Attrs = None);
+  void EmitForStmt(const ForStmt &S,
+                   const ArrayRef<const Attr *> &Attrs = None);
   void EmitReturnStmt(const ReturnStmt &S);
   void EmitDeclStmt(const DeclStmt &S);
   void EmitBreakStmt(const BreakStmt &S);
@@ -1886,7 +1891,8 @@ public:
 
   void EmitCXXTryStmt(const CXXTryStmt &S);
   void EmitSEHTryStmt(const SEHTryStmt &S);
-  void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
+  void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
+                           const ArrayRef<const Attr *> &Attrs = None);
 
   llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
   llvm::Function *GenerateCapturedStmtFunction(const CapturedDecl *CD,
index 787d3f0..427a44d 100644 (file)
 //===----------------------------------------------------------------------===//
 
 #include "RAIIObjectsForParser.h"
-#include "clang/Lex/Preprocessor.h"
-#include "clang/Parse/ParseDiagnostic.h"
-#include "clang/Parse/Parser.h"
-#include "clang/Sema/Scope.h"
-#include "llvm/ADT/StringSwitch.h"
-using namespace clang;
+#include "clang/Lex/Preprocessor.h"\r
+#include "clang/Parse/ParseDiagnostic.h"\r
+#include "clang/Parse/Parser.h"\r
+#include "clang/Sema/LoopHint.h"\r
+#include "clang/Sema/Scope.h"\r
+#include "llvm/ADT/StringSwitch.h"\r
+using namespace clang;\r
 
 namespace {
 
@@ -138,12 +139,18 @@ struct PragmaOptimizeHandler : public PragmaHandler {
   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
                     Token &FirstToken) override;
 private:
-  Sema &Actions;
-};
-
-}  // end namespace
-
-void Parser::initializePragmaHandlers() {
+  Sema &Actions;\r
+};\r
+\r
+struct PragmaLoopHintHandler : public PragmaHandler {\r
+  PragmaLoopHintHandler() : PragmaHandler("loop") {}\r
+  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,\r
+                    Token &FirstToken) override;\r
+};\r
+\r
+}  // end namespace\r
+\r
+void Parser::initializePragmaHandlers() {\r
   AlignHandler.reset(new PragmaAlignHandler());
   PP.AddPragmaHandler(AlignHandler.get());
 
@@ -205,12 +212,15 @@ void Parser::initializePragmaHandlers() {
     MSSection.reset(new PragmaMSPragma("section"));
     PP.AddPragmaHandler(MSSection.get());
   }
-
-  OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));
-  PP.AddPragmaHandler("clang", OptimizeHandler.get());
-}
-
-void Parser::resetPragmaHandlers() {
+\r
+  OptimizeHandler.reset(new PragmaOptimizeHandler(Actions));\r
+  PP.AddPragmaHandler("clang", OptimizeHandler.get());\r
+\r
+  LoopHintHandler.reset(new PragmaLoopHintHandler());\r
+  PP.AddPragmaHandler("clang", LoopHintHandler.get());\r
+}\r
+\r
+void Parser::resetPragmaHandlers() {\r
   // Remove the pragma handlers we installed.
   PP.RemovePragmaHandler(AlignHandler.get());
   AlignHandler.reset();
@@ -262,12 +272,15 @@ void Parser::resetPragmaHandlers() {
 
   PP.RemovePragmaHandler("STDC", FPContractHandler.get());
   FPContractHandler.reset();
-
-  PP.RemovePragmaHandler("clang", OptimizeHandler.get());
-  OptimizeHandler.reset();
-}
-
-/// \brief Handle the annotation token produced for #pragma unused(...)
+\r
+  PP.RemovePragmaHandler("clang", OptimizeHandler.get());\r
+  OptimizeHandler.reset();\r
+\r
+  PP.RemovePragmaHandler("clang", LoopHintHandler.get());\r
+  LoopHintHandler.reset();\r
+}\r
+\r
+/// \brief Handle the annotation token produced for #pragma unused(...)\r
 ///
 /// Each annot_pragma_unused is followed by the argument token so e.g.
 /// "#pragma unused(x,y)" becomes:
@@ -583,12 +596,46 @@ unsigned Parser::HandlePragmaMSSegment(llvm::StringRef PragmaName,
 unsigned Parser::HandlePragmaMSInitSeg(llvm::StringRef PragmaName,
                                        SourceLocation PragmaLocation) {
   return PP.getDiagnostics().getCustomDiagID(
-      DiagnosticsEngine::Error, "'#pragma %0' not implemented.");
-}
-
-// #pragma GCC visibility comes in two variants:
-//   'push' '(' [visibility] ')'
-//   'pop'
+      DiagnosticsEngine::Error, "'#pragma %0' not implemented.");\r
+}\r
+\r
+struct PragmaLoopHintInfo {\r
+  Token Loop;\r
+  Token Value;\r
+  Token Option;\r
+};\r
+\r
+LoopHint Parser::HandlePragmaLoopHint() {\r
+  assert(Tok.is(tok::annot_pragma_loop_hint));\r
+  PragmaLoopHintInfo *Info =\r
+      static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());\r
+\r
+  LoopHint Hint;\r
+  Hint.LoopLoc =\r
+      IdentifierLoc::create(Actions.Context, Info->Loop.getLocation(),\r
+                            Info->Loop.getIdentifierInfo());\r
+  Hint.OptionLoc =\r
+      IdentifierLoc::create(Actions.Context, Info->Option.getLocation(),\r
+                            Info->Option.getIdentifierInfo());\r
+  Hint.ValueLoc =\r
+      IdentifierLoc::create(Actions.Context, Info->Value.getLocation(),\r
+                            Info->Value.getIdentifierInfo());\r
+  Hint.Range =\r
+      SourceRange(Info->Option.getLocation(), Info->Value.getLocation());\r
+\r
+  // FIXME: We should support template parameters for the loop hint value.\r
+  // See bug report #19610\r
+  if (Info->Value.is(tok::numeric_constant))\r
+    Hint.ValueExpr = Actions.ActOnNumericConstant(Info->Value).get();\r
+  else\r
+    Hint.ValueExpr = nullptr;\r
+\r
+  return Hint;\r
+}\r
+\r
+// #pragma GCC visibility comes in two variants:\r
+//   'push' '(' [visibility] ')'\r
+//   'pop'\r
 void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, 
                                               PragmaIntroducerKind Introducer,
                                               Token &VisTok) {
@@ -1581,6 +1628,113 @@ void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
       << PP.getSpelling(Tok);
     return;
   }
-
-  Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
-}
+\r
+  Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());\r
+}\r
+\r
+/// \brief Handle the \#pragma clang loop directive.\r
+///  #pragma clang 'loop' loop-hints\r
+///\r
+///  loop-hints:\r
+///    loop-hint loop-hints[opt]\r
+///\r
+///  loop-hint:\r
+///    'vectorize' '(' loop-hint-keyword ')'\r
+///    'interleave' '(' loop-hint-keyword ')'\r
+///    'vectorize_width' '(' loop-hint-value ')'\r
+///    'interleave_count' '(' loop-hint-value ')'\r
+///\r
+///  loop-hint-keyword:\r
+///    'enable'\r
+///    'disable'\r
+///\r
+///  loop-hint-value:\r
+///    constant-expression\r
+///\r
+/// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to\r
+/// try vectorizing the instructions of the loop it precedes. Specifying\r
+/// interleave(enable) or interleave_count(_value_) instructs llvm to try\r
+/// interleaving multiple iterations of the loop it precedes. The width of the\r
+/// vector instructions is specified by vectorize_width() and the number of\r
+/// interleaved loop iterations is specified by interleave_count(). Specifying a\r
+/// value of 1 effectively disables vectorization/interleaving, even if it is\r
+/// possible and profitable, and 0 is invalid. The loop vectorizer currently\r
+/// only works on inner loops.\r
+///\r
+void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,\r
+                                         PragmaIntroducerKind Introducer,\r
+                                         Token &Tok) {\r
+  Token Loop = Tok;\r
+  SmallVector<Token, 1> TokenList;\r
+\r
+  // Lex the optimization option and verify it is an identifier.\r
+  PP.Lex(Tok);\r
+  if (Tok.isNot(tok::identifier)) {\r
+    PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)\r
+        << /*MissingOption=*/true << "";\r
+    return;\r
+  }\r
+\r
+  while (Tok.is(tok::identifier)) {\r
+    Token Option = Tok;\r
+    IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();\r
+\r
+    if (!OptionInfo->isStr("vectorize") && !OptionInfo->isStr("interleave") &&\r
+        !OptionInfo->isStr("vectorize_width") &&\r
+        !OptionInfo->isStr("interleave_count")) {\r
+      PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)\r
+          << /*MissingOption=*/false << OptionInfo;\r
+      return;\r
+    }\r
+\r
+    // Read '('\r
+    PP.Lex(Tok);\r
+    if (Tok.isNot(tok::l_paren)) {\r
+      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;\r
+      return;\r
+    }\r
+\r
+    // FIXME: All tokens between '(' and ')' should be stored and parsed as a\r
+    // constant expression.\r
+    PP.Lex(Tok);\r
+    Token Value;\r
+    if (Tok.is(tok::identifier) || Tok.is(tok::numeric_constant))\r
+      Value = Tok;\r
+\r
+    // Read ')'\r
+    PP.Lex(Tok);\r
+    if (Tok.isNot(tok::r_paren)) {\r
+      PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;\r
+      return;\r
+    }\r
+\r
+    // Get next optimization option.\r
+    PP.Lex(Tok);\r
+\r
+    auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;\r
+    Info->Loop = Loop;\r
+    Info->Option = Option;\r
+    Info->Value = Value;\r
+\r
+    // Generate the vectorization hint token.\r
+    Token LoopHintTok;\r
+    LoopHintTok.startToken();\r
+    LoopHintTok.setKind(tok::annot_pragma_loop_hint);\r
+    LoopHintTok.setLocation(Loop.getLocation());\r
+    LoopHintTok.setAnnotationValue(static_cast<void *>(Info));\r
+    TokenList.push_back(LoopHintTok);\r
+  }\r
+\r
+  if (Tok.isNot(tok::eod)) {\r
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)\r
+        << "clang loop";\r
+    return;\r
+  }\r
+\r
+  Token *TokenArray = new Token[TokenList.size()];\r
+  std::copy(TokenList.begin(), TokenList.end(), TokenArray);\r
+\r
+  PP.EnterTokenStream(TokenArray, TokenList.size(),\r
+                      /*DisableMacroExpansion=*/false,\r
+                      /*OwnsTokens=*/true);\r
+}\r
index 1ee7c96..210963e 100644 (file)
 #include "clang/Parse/Parser.h"
 #include "RAIIObjectsForParser.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/Basic/Attributes.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/DeclSpec.h"
+#include "clang/Sema/LoopHint.h"
 #include "clang/Sema/PrettyDeclStackTrace.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/TypoCorrection.h"
@@ -357,6 +359,10 @@ Retry:
     ProhibitAttributes(Attrs);
     HandlePragmaMSPragma();
     return StmtEmpty();
+
+  case tok::annot_pragma_loop_hint:
+    ProhibitAttributes(Attrs);
+    return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs);
   }
 
   // If we reached this code, the statement must end in a semicolon.
@@ -1759,6 +1765,37 @@ StmtResult Parser::ParseReturnStatement() {
   return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
 }
 
+StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement,
+                                       SourceLocation *TrailingElseLoc,
+                                       ParsedAttributesWithRange &Attrs) {
+  // Create temporary attribute list.
+  ParsedAttributesWithRange TempAttrs(AttrFactory);
+
+  // Get vectorize hints and consume annotated token.
+  while (Tok.is(tok::annot_pragma_loop_hint)) {
+    LoopHint Hint = HandlePragmaLoopHint();
+    ConsumeToken();
+
+    if (!Hint.LoopLoc || !Hint.OptionLoc || !Hint.ValueLoc)
+      continue;
+
+    ArgsUnion ArgHints[] = {Hint.OptionLoc, Hint.ValueLoc,
+                            ArgsUnion(Hint.ValueExpr)};
+    // FIXME: Replace AS_Keyword with Pragma spelling AS_Pragma.
+    TempAttrs.addNew(Hint.LoopLoc->Ident, Hint.Range, 0, Hint.LoopLoc->Loc,
+                     ArgHints, 3, AttributeList::AS_Keyword);
+  }
+
+  // Get the next statement.
+  MaybeParseCXX11Attributes(Attrs);
+
+  StmtResult S = ParseStatementOrDeclarationAfterAttributes(
+      Stmts, OnlyStatement, TrailingElseLoc, Attrs);
+
+  Attrs.takeAllFrom(TempAttrs);
+  return S;
+}
+
 namespace {
   class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
     Parser &TheParser;
index 3bc620b..4e3999b 100644 (file)
 
 #include "clang/Sema/SemaInternal.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/Basic/SourceManager.h"
-#include "clang/Sema/DelayedDiagnostic.h"
-#include "clang/Sema/Lookup.h"
-#include "clang/Sema/ScopeInfo.h"
-#include "llvm/ADT/StringExtras.h"
-
+#include "clang/Basic/SourceManager.h"\r
+#include "clang/Sema/DelayedDiagnostic.h"\r
+#include "clang/Sema/Lookup.h"\r
+#include "clang/Sema/LoopHint.h"\r
+#include "clang/Sema/ScopeInfo.h"\r
+#include "llvm/ADT/StringExtras.h"\r
+\r
 using namespace clang;
 using namespace sema;
 
@@ -39,23 +40,175 @@ static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const AttributeList &A,
     return nullptr;
   }
   return ::new (S.Context) FallThroughAttr(A.getRange(), S.Context,
-                                           A.getAttributeSpellingListIndex());
-}
-
-
-static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const AttributeList &A,
-                                  SourceRange Range) {
-  switch (A.getKind()) {
+                                           A.getAttributeSpellingListIndex());\r
+}\r
+\r
+static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const AttributeList &A,\r
+                                SourceRange) {\r
+  if (St->getStmtClass() != Stmt::DoStmtClass &&\r
+      St->getStmtClass() != Stmt::ForStmtClass &&\r
+      St->getStmtClass() != Stmt::CXXForRangeStmtClass &&\r
+      St->getStmtClass() != Stmt::WhileStmtClass) {\r
+    S.Diag(St->getLocStart(), diag::err_pragma_loop_precedes_nonloop);\r
+    return nullptr;\r
+  }\r
+\r
+  IdentifierLoc *OptionLoc = A.getArgAsIdent(0);\r
+  IdentifierInfo *OptionInfo = OptionLoc->Ident;\r
+  IdentifierLoc *ValueLoc = A.getArgAsIdent(1);\r
+  IdentifierInfo *ValueInfo = ValueLoc->Ident;\r
+  Expr *ValueExpr = A.getArgAsExpr(2);\r
+\r
+  assert(OptionInfo && "Attribute must have valid option info.");\r
+\r
+  LoopHintAttr::OptionType Option =\r
+      llvm::StringSwitch<LoopHintAttr::OptionType>(OptionInfo->getNameStart())\r
+          .Case("vectorize", LoopHintAttr::Vectorize)\r
+          .Case("vectorize_width", LoopHintAttr::VectorizeWidth)\r
+          .Case("interleave", LoopHintAttr::Interleave)\r
+          .Case("interleave_count", LoopHintAttr::InterleaveCount)\r
+          .Default(LoopHintAttr::Vectorize);\r
+\r
+  int ValueInt;\r
+  if (Option == LoopHintAttr::Vectorize || Option == LoopHintAttr::Interleave) {\r
+    if (!ValueInfo) {\r
+      S.Diag(ValueLoc->Loc, diag::err_pragma_loop_invalid_keyword)\r
+          << /*MissingKeyword=*/true << "";\r
+      return nullptr;\r
+    }\r
+\r
+    if (ValueInfo->isStr("disable"))\r
+      ValueInt = 0;\r
+    else if (ValueInfo->isStr("enable"))\r
+      ValueInt = 1;\r
+    else {\r
+      S.Diag(ValueLoc->Loc, diag::err_pragma_loop_invalid_keyword)\r
+          << /*MissingKeyword=*/false << ValueInfo;\r
+      return nullptr;\r
+    }\r
+  } else if (Option == LoopHintAttr::VectorizeWidth ||\r
+             Option == LoopHintAttr::InterleaveCount) {\r
+    // FIXME: We should support template parameters for the loop hint value.\r
+    // See bug report #19610.\r
+    llvm::APSInt ValueAPS;\r
+    if (!ValueExpr || !ValueExpr->isIntegerConstantExpr(ValueAPS, S.Context)) {\r
+      S.Diag(ValueLoc->Loc, diag::err_pragma_loop_invalid_value)\r
+          << /*MissingValue=*/true << "";\r
+      return nullptr;\r
+    }\r
+\r
+    if ((ValueInt = ValueAPS.getSExtValue()) < 1) {\r
+      S.Diag(ValueLoc->Loc, diag::err_pragma_loop_invalid_value)\r
+          << /*MissingValue=*/false << ValueInt;\r
+      return nullptr;\r
+    }\r
+  }\r
+\r
+  return LoopHintAttr::CreateImplicit(S.Context, Option, ValueInt,\r
+                                      A.getRange());\r
+}\r
+\r
+static void\r
+CheckForIncompatibleAttributes(Sema &S, SmallVectorImpl<const Attr *> &Attrs) {\r
+  int PrevOptionValue[4] = {-1, -1, -1, -1};\r
+  int OptionId[4] = {LoopHintAttr::Vectorize, LoopHintAttr::VectorizeWidth,\r
+                     LoopHintAttr::Interleave, LoopHintAttr::InterleaveCount};\r
+\r
+  for (const auto *I : Attrs) {\r
+    const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I);\r
+\r
+    // Skip non loop hint attributes\r
+    if (!LH)\r
+      continue;\r
+\r
+    int State, Value;\r
+    int Option = LH->getOption();\r
+    int ValueInt = LH->getValue();\r
+\r
+    switch (Option) {\r
+    case LoopHintAttr::Vectorize:\r
+    case LoopHintAttr::VectorizeWidth:\r
+      State = 0;\r
+      Value = 1;\r
+      break;\r
+    case LoopHintAttr::Interleave:\r
+    case LoopHintAttr::InterleaveCount:\r
+      State = 2;\r
+      Value = 3;\r
+      break;\r
+    }\r
+\r
+    SourceLocation ValueLoc = LH->getRange().getEnd();\r
+\r
+    // Compatibility testing is split into two cases.\r
+    // 1. if the current loop hint sets state (enable/disable) - check against\r
+    // previous state and value.\r
+    // 2. if the current loop hint sets a value - check against previous state\r
+    // and value.\r
+\r
+    if (Option == State) {\r
+      if (PrevOptionValue[State] != -1) {\r
+        // Cannot specify state twice.\r
+        int PrevValue = PrevOptionValue[State];\r
+        S.Diag(ValueLoc, diag::err_pragma_loop_compatibility)\r
+            << /*Duplicate=*/true << LoopHintAttr::getOptionName(Option)\r
+            << LoopHintAttr::getValueName(PrevValue)\r
+            << LoopHintAttr::getOptionName(Option)\r
+            << LoopHintAttr::getValueName(Value);\r
+      }\r
+\r
+      if (PrevOptionValue[Value] != -1) {\r
+        // Compare state with previous width/count.\r
+        int PrevOption = OptionId[Value];\r
+        int PrevValueInt = PrevOptionValue[Value];\r
+        if ((ValueInt == 0 && PrevValueInt > 1) ||\r
+            (ValueInt == 1 && PrevValueInt <= 1))\r
+          S.Diag(ValueLoc, diag::err_pragma_loop_compatibility)\r
+              << /*Duplicate=*/false << LoopHintAttr::getOptionName(PrevOption)\r
+              << PrevValueInt << LoopHintAttr::getOptionName(Option)\r
+              << LoopHintAttr::getValueName(ValueInt);\r
+      }\r
+    } else {\r
+      if (PrevOptionValue[State] != -1) {\r
+        // Compare width/count value with previous state.\r
+        int PrevOption = OptionId[State];\r
+        int PrevValueInt = PrevOptionValue[State];\r
+        if ((ValueInt > 1 && PrevValueInt == 0) ||\r
+            (ValueInt <= 1 && PrevValueInt == 1))\r
+          S.Diag(ValueLoc, diag::err_pragma_loop_compatibility)\r
+              << /*Duplicate=*/false << LoopHintAttr::getOptionName(PrevOption)\r
+              << LoopHintAttr::getValueName(PrevValueInt)\r
+              << LoopHintAttr::getOptionName(Option) << ValueInt;\r
+      }\r
+\r
+      if (PrevOptionValue[Value] != -1) {\r
+        // Cannot specify a width/count twice.\r
+        int PrevValueInt = PrevOptionValue[Value];\r
+        S.Diag(ValueLoc, diag::err_pragma_loop_compatibility)\r
+            << /*Duplicate=*/true << LoopHintAttr::getOptionName(Option)\r
+            << PrevValueInt << LoopHintAttr::getOptionName(Option) << ValueInt;\r
+      }\r
+    }\r
+\r
+    PrevOptionValue[Option] = ValueInt;\r
+  }\r
+}\r
+\r
+static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const AttributeList &A,\r
+                                  SourceRange Range) {\r
+  switch (A.getKind()) {\r
   case AttributeList::UnknownAttribute:
     S.Diag(A.getLoc(), A.isDeclspecAttribute() ?
            diag::warn_unhandled_ms_attribute_ignored :
            diag::warn_unknown_attribute_ignored) << A.getName();
-    return nullptr;
-  case AttributeList::AT_FallThrough:
-    return handleFallThroughAttr(S, St, A, Range);
-  default:
-    // if we're here, then we parsed a known attribute, but didn't recognize
-    // it as a statement attribute => it is declaration attribute
+    return nullptr;\r
+  case AttributeList::AT_FallThrough:\r
+    return handleFallThroughAttr(S, St, A, Range);\r
+  case AttributeList::AT_LoopHint:\r
+    return handleLoopHintAttr(S, St, A, Range);\r
+  default:\r
+    // if we're here, then we parsed a known attribute, but didn't recognize\r
+    // it as a statement attribute => it is declaration attribute\r
     S.Diag(A.getRange().getBegin(), diag::err_attribute_invalid_on_stmt)
         << A.getName() << St->getLocStart();
     return nullptr;
@@ -67,11 +220,13 @@ StmtResult Sema::ProcessStmtAttributes(Stmt *S, AttributeList *AttrList,
   SmallVector<const Attr*, 8> Attrs;
   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
     if (Attr *a = ProcessStmtAttribute(*this, S, *l, Range))
-      Attrs.push_back(a);
-  }
-
-  if (Attrs.empty())
-    return S;
-
+      Attrs.push_back(a);\r
+  }\r
+\r
+  CheckForIncompatibleAttributes(*this, Attrs);\r
+\r
+  if (Attrs.empty())\r
+    return S;\r
+\r
   return ActOnAttributedStmt(Range.getBegin(), Attrs, S);
 }
diff --git a/clang/test/CodeGen/pragma-loop.cpp b/clang/test/CodeGen/pragma-loop.cpp
new file mode 100644 (file)
index 0000000..b00b0c0
--- /dev/null
@@ -0,0 +1,120 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s | FileCheck %s\r
+\r
+// Verify while loop is recognized after sequence of pragma clang loop directives.\r
+void while_test(int *List, int Length) {\r
+  // CHECK: define {{.*}} @_Z10while_test\r
+  int i = 0;\r
+\r
+#pragma clang loop vectorize(enable)\r
+#pragma clang loop interleave_count(4)\r
+#pragma clang loop vectorize_width(4)\r
+  while (i < Length) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_1:.*]]\r
+    List[i] = i * 2;\r
+    i++;\r
+  }\r
+}\r
+\r
+// Verify do loop is recognized after multi-option pragma clang loop directive.\r
+void do_test(int *List, int Length) {\r
+  int i = 0;\r
+\r
+#pragma clang loop vectorize_width(8) interleave_count(4)\r
+  do {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_2:.*]]\r
+    List[i] = i * 2;\r
+    i++;\r
+  } while (i < Length);\r
+}\r
+\r
+// Verify for loop is recognized after sequence of pragma clang loop directives.\r
+void for_test(int *List, int Length) {\r
+#pragma clang loop interleave(enable)\r
+#pragma clang loop interleave_count(4)\r
+  for (int i = 0; i < Length; i++) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_3:.*]]\r
+    List[i] = i * 2;\r
+  }\r
+}\r
+\r
+// Verify c++11 for range loop is recognized after\r
+// sequence of pragma clang loop directives.\r
+void for_range_test() {\r
+  double List[100];\r
+\r
+#pragma clang loop vectorize_width(2) interleave_count(2)\r
+  for (int i : List) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_4:.*]]\r
+    List[i] = i;\r
+  }\r
+}\r
+\r
+// Verify disable pragma clang loop directive generates correct metadata\r
+void disable_test(int *List, int Length) {\r
+#pragma clang loop vectorize(disable)\r
+  for (int i = 0; i < Length; i++) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_5:.*]]\r
+    List[i] = i * 2;\r
+  }\r
+}\r
+\r
+#define VECWIDTH 2\r
+#define INTCOUNT 2\r
+\r
+// Verify defines are correctly resolved in pragma clang loop directive\r
+void for_define_test(int *List, int Length, int Value) {\r
+#pragma clang loop vectorize_width(VECWIDTH) interleave_count(INTCOUNT)\r
+  for (int i = 0; i < Length; i++) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_6:.*]]\r
+    List[i] = i * Value;\r
+  }\r
+}\r
+\r
+// Verify metadata is generated when template is used.\r
+template <typename A>\r
+void for_template_test(A *List, int Length, A Value) {\r
+\r
+#pragma clang loop vectorize_width(8) interleave_count(8)\r
+  for (int i = 0; i < Length; i++) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_7:.*]]\r
+    List[i] = i * Value;\r
+  }\r
+}\r
+\r
+// Verify define is resolved correctly when template is used.\r
+template <typename A>\r
+void for_template_define_test(A *List, int Length, A Value) {\r
+#pragma clang loop vectorize_width(VECWIDTH) interleave_count(INTCOUNT)\r
+  for (int i = 0; i < Length; i++) {\r
+    // CHECK: br i1 {{.*}}, label {{.*}}, label {{.*}}, !llvm.loop ![[LOOP_8:.*]]\r
+    List[i] = i * Value;\r
+  }\r
+}\r
+\r
+#undef VECWIDTH\r
+#undef INTCOUNT\r
+\r
+// Use templates defined above. Test verifies metadata is generated correctly.\r
+void template_test(double *List, int Length) {\r
+  double Value = 10;\r
+\r
+  for_template_test<double>(List, Length, Value);\r
+  for_template_define_test<double>(List, Length, Value);\r
+}\r
+\r
+// CHECK: ![[LOOP_1]] = metadata !{metadata ![[LOOP_1]], metadata ![[WIDTH_4:.*]], metadata ![[UNROLL_4:.*]], metadata ![[ENABLE_1:.*]]}\r
+// CHECK: ![[WIDTH_4]] = metadata !{metadata !"llvm.vectorizer.width", i32 4}\r
+// CHECK: ![[UNROLL_4]] = metadata !{metadata !"llvm.vectorizer.unroll", i32 4}\r
+// CHECK: ![[ENABLE_1]] = metadata !{metadata !"llvm.vectorizer.enable", i1 true}\r
+// CHECK: ![[LOOP_2]] = metadata !{metadata ![[LOOP_2:.*]], metadata ![[UNROLL_4:.*]], metadata ![[WIDTH_8:.*]]}\r
+// CHECK: ![[WIDTH_8]] = metadata !{metadata !"llvm.vectorizer.width", i32 8}\r
+// CHECK: ![[LOOP_3]] = metadata !{metadata ![[LOOP_3]], metadata ![[UNROLL_4:.*]], metadata ![[ENABLE_1:.*]]}\r
+// CHECK: ![[LOOP_4]] = metadata !{metadata ![[LOOP_4]], metadata ![[UNROLL_2:.*]], metadata ![[WIDTH_2:.*]]}\r
+// CHECK: ![[UNROLL_2]] = metadata !{metadata !"llvm.vectorizer.unroll", i32 2}\r
+// CHECK: ![[WIDTH_2]] = metadata !{metadata !"llvm.vectorizer.width", i32 2}\r
+// CHECK: ![[LOOP_5]] = metadata !{metadata ![[LOOP_5]], metadata ![[WIDTH_1:.*]]}\r
+// CHECK: ![[WIDTH_1]] = metadata !{metadata !"llvm.vectorizer.width", i32 1}\r
+// CHECK: ![[LOOP_6]] = metadata !{metadata ![[LOOP_6]], metadata ![[UNROLL_2:.*]], metadata ![[WIDTH_2:.*]]}\r
+// CHECK: ![[LOOP_7]] = metadata !{metadata ![[LOOP_7]], metadata ![[UNROLL_8:.*]], metadata ![[WIDTH_8:.*]]}\r
+// CHECK: ![[UNROLL_8]] = metadata !{metadata !"llvm.vectorizer.unroll", i32 8}\r
+// CHECK: ![[LOOP_8]] = metadata !{metadata ![[LOOP_8]], metadata ![[UNROLL_2:.*]], metadata ![[WIDTH_2:.*]]}\r
diff --git a/clang/test/PCH/pragma-loop.cpp b/clang/test/PCH/pragma-loop.cpp
new file mode 100644 (file)
index 0000000..41bbf72
--- /dev/null
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -emit-pch -o %t.a %s\r
+// RUN: %clang_cc1 -include-pch %t.a %s -ast-print -o - | FileCheck %s\r
+\r
+// FIXME: A bug in ParsedAttributes causes the order of the attributes to be\r
+// reversed. The checks are consequently in the reverse order below.\r
+\r
+// CHECK: #pragma clang loop interleave_count(8)\r
+// CHECK: #pragma clang loop vectorize_width(4)\r
+// CHECK: #pragma clang loop interleave(disable)\r
+// CHECK: #pragma clang loop vectorize(enable)\r
+// CHECK: #pragma clang loop interleave(enable)\r
+// CHECK: #pragma clang loop vectorize(disable)\r
+\r
+#ifndef HEADER\r
+#define HEADER\r
+\r
+class pragma_test {\r
+public:\r
+  inline void run1(int *List, int Length) {\r
+    int i = 0;\r
+#pragma clang loop vectorize_width(4)\r
+#pragma clang loop interleave_count(8)\r
+    while (i < Length) {\r
+      List[i] = i;\r
+      i++;\r
+    }\r
+  }\r
+\r
+  inline void run2(int *List, int Length) {\r
+    int i = 0;\r
+#pragma clang loop vectorize(enable)\r
+#pragma clang loop interleave(disable)\r
+    while (i - 1 < Length) {\r
+      List[i] = i;\r
+      i++;\r
+    }\r
+  }\r
+\r
+  inline void run3(int *List, int Length) {\r
+    int i = 0;\r
+#pragma clang loop vectorize(disable)\r
+#pragma clang loop interleave(enable)\r
+    while (i - 3 < Length) {\r
+      List[i] = i;\r
+      i++;\r
+    }\r
+  }\r
+};\r
+\r
+#else\r
+\r
+void test() {\r
+  int List[100];\r
+\r
+  pragma_test pt;\r
+\r
+  pt.run1(List, 100);\r
+  pt.run2(List, 100);\r
+  pt.run3(List, 100);\r
+}\r
+\r
+#endif\r
diff --git a/clang/test/Parser/pragma-loop.cpp b/clang/test/Parser/pragma-loop.cpp
new file mode 100644 (file)
index 0000000..e515eb4
--- /dev/null
@@ -0,0 +1,132 @@
+// RUN: %clang_cc1 -std=c++11 -verify %s\r
+\r
+// Note that this puts the expected lines before the directives to work around\r
+// limitations in the -verify mode.\r
+\r
+void test(int *List, int Length) {\r
+  int i = 0;\r
+\r
+#pragma clang loop vectorize(enable)\r
+#pragma clang loop interleave(enable)\r
+  while (i + 1 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop vectorize_width(4)\r
+#pragma clang loop interleave_count(8)\r
+  while (i < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop vectorize(disable)\r
+#pragma clang loop interleave(disable)\r
+  while (i - 1 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop vectorize_width(4) interleave_count(8)\r
+  while (i - 2 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop interleave_count(16)\r
+  while (i - 3 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+  int VList[Length];\r
+#pragma clang loop vectorize(disable) interleave(disable)\r
+  for (int j : VList) {\r
+    VList[j] = List[j];\r
+  }\r
+\r
+/* expected-error {{expected '('}} */ #pragma clang loop vectorize\r
+/* expected-error {{expected '('}} */ #pragma clang loop interleave\r
+\r
+/* expected-error {{expected ')'}} */ #pragma clang loop vectorize(enable\r
+/* expected-error {{expected ')'}} */ #pragma clang loop interleave(enable\r
+\r
+/* expected-error {{expected ')'}} */ #pragma clang loop vectorize_width(4\r
+/* expected-error {{expected ')'}} */ #pragma clang loop interleave_count(4\r
+\r
+/* expected-error {{missing option}} */ #pragma clang loop\r
+/* expected-error {{invalid option 'badkeyword'}} */ #pragma clang loop badkeyword\r
+/* expected-error {{invalid option 'badkeyword'}} */ #pragma clang loop badkeyword(enable)\r
+/* expected-error {{invalid option 'badkeyword'}} */ #pragma clang loop vectorize(enable) badkeyword(4)\r
+/* expected-warning {{extra tokens at end of '#pragma clang loop'}} */ #pragma clang loop vectorize(enable) ,\r
+\r
+  while (i-4 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{invalid value 0; expected a positive integer value}} */ #pragma clang loop vectorize_width(0)\r
+/* expected-error {{invalid value 0; expected a positive integer value}} */ #pragma clang loop interleave_count(0)\r
+  while (i-5 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{invalid value -1294967296; expected a positive integer value}} */ #pragma clang loop vectorize_width(3000000000)\r
+/* expected-error {{invalid value -1294967296; expected a positive integer value}} */ #pragma clang loop interleave_count(3000000000)\r
+  while (i-6 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{missing value; expected a positive integer value}} */ #pragma clang loop vectorize_width(badvalue)\r
+/* expected-error {{missing value; expected a positive integer value}} */ #pragma clang loop interleave_count(badvalue)\r
+  while (i-6 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{invalid keyword 'badidentifier'; expected 'enable' or 'disable'}} */ #pragma clang loop vectorize(badidentifier)\r
+/* expected-error {{invalid keyword 'badidentifier'; expected 'enable' or 'disable'}} */ #pragma clang loop interleave(badidentifier)\r
+  while (i-7 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop vectorize(enable)\r
+/* expected-error {{expected a for, while, or do-while loop to follow the '#pragma clang loop' directive}} */ int j = Length;\r
+  List[0] = List[1];\r
+\r
+  while (j-1 < Length) {\r
+    List[j] = j;\r
+  }\r
+\r
+// FIXME: A bug in ParsedAttributes causes the order of the attributes to be\r
+// processed in reverse. Consequently, the errors occur on the first of pragma\r
+// of the next three tests rather than the last, and the order of the kinds\r
+// is also reversed.\r
+\r
+/* expected-error {{incompatible directives 'vectorize(disable)' and 'vectorize_width(4)'}} */ #pragma clang loop vectorize_width(4)\r
+#pragma clang loop vectorize(disable)\r
+/* expected-error {{incompatible directives 'interleave(disable)' and 'interleave_count(4)'}} */ #pragma clang loop interleave_count(4)\r
+#pragma clang loop interleave(disable)\r
+  while (i-8 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{duplicate directives 'vectorize(disable)' and 'vectorize(enable)'}} */ #pragma clang loop vectorize(enable)\r
+#pragma clang loop vectorize(disable)\r
+/* expected-error {{duplicate directives 'interleave(disable)' and 'interleave(enable)'}} */ #pragma clang loop interleave(enable)\r
+#pragma clang loop interleave(disable)\r
+  while (i-9 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{incompatible directives 'vectorize_width(4)' and 'vectorize(disable)'}} */ #pragma clang loop vectorize(disable)\r
+#pragma clang loop vectorize_width(4)\r
+/* expected-error {{incompatible directives 'interleave_count(4)' and 'interleave(disable)'}} */ #pragma clang loop interleave(disable)\r
+#pragma clang loop interleave_count(4)\r
+  while (i-10 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+/* expected-error {{duplicate directives 'vectorize_width(4)' and 'vectorize_width(8)'}} */ #pragma clang loop vectorize_width(8)\r
+#pragma clang loop vectorize_width(4)\r
+/* expected-error {{duplicate directives 'interleave_count(4)' and 'interleave_count(8)'}} */ #pragma clang loop interleave_count(8)\r
+#pragma clang loop interleave_count(4)\r
+  while (i-11 < Length) {\r
+    List[i] = i;\r
+  }\r
+\r
+#pragma clang loop interleave(enable)\r
+/* expected-error {{expected statement}} */ }\r