SemaStmt.cpp revision 534986f2b21e6050bf00163cd6423fd92155a6ed
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//  This file implements semantic analysis for statements.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
142d88708cbe4e4ec5e04e4acb6bd7f5be68557379John McCall#include "clang/Sema/SemaInternal.h"
155f1e0942a32657b625702aa52f82430d0120f424John McCall#include "clang/Sema/Scope.h"
16781472fe99a120098c631b0cbe33c89f8cef5e70John McCall#include "clang/Sema/ScopeInfo.h"
17e737f5041a36d0befb39ffeed8d50ba15916d3daDouglas Gregor#include "clang/Sema/Initialization.h"
18ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith#include "clang/Sema/Lookup.h"
19f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner#include "clang/AST/ASTContext.h"
201cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall#include "clang/AST/CharUnits.h"
21c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2284fb9c0be621c9e4ca4e56f67dae2a0bb6e44821Douglas Gregor#include "clang/AST/ExprCXX.h"
23419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner#include "clang/AST/ExprObjC.h"
2416f0049415ec596504891259e2a83e19871c0d52Chris Lattner#include "clang/AST/StmtObjC.h"
2516f0049415ec596504891259e2a83e19871c0d52Chris Lattner#include "clang/AST/StmtCXX.h"
26209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall#include "clang/AST/TypeLoc.h"
2784fb9c0be621c9e4ca4e56f67dae2a0bb6e44821Douglas Gregor#include "clang/Lex/Preprocessor.h"
286fa9086043b0338d895a4cdb0ec8542530af90d7Anders Carlsson#include "clang/Basic/TargetInfo.h"
29ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner#include "llvm/ADT/ArrayRef.h"
30c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl#include "llvm/ADT/STLExtras.h"
31c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl#include "llvm/ADT/SmallVector.h"
325f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
33781472fe99a120098c631b0cbe33c89f8cef5e70John McCallusing namespace sema;
345f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
3560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
369ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Expr *E = expr.get();
37bebbe0d9b7568ce43a464286bee49429489ef483Douglas Gregor  if (!E) // FIXME: FullExprArg has no error state?
38bebbe0d9b7568ce43a464286bee49429489ef483Douglas Gregor    return StmtError();
39bebbe0d9b7568ce43a464286bee49429489ef483Douglas Gregor
40834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // void expression for its side effects.  Conversion to void allows any
42834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // operand, even incomplete types.
43a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl
44834a72ac74cf4ff07ba6215545dba3db578f8a07Chris Lattner  // Same thing in for stmt first clause (when expr) and third clause.
45a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl  return Owned(static_cast<Stmt*>(E));
465f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
475f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
49b7d98d35ea723624345f06e5895ddce2e0388ef0Argyrios KyrtzidisStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
50e2ca828119b8bff4a5c25c6db8ee4fec558451e7Argyrios Kyrtzidis                               bool HasLeadingEmptyMacro) {
51e2ca828119b8bff4a5c25c6db8ee4fec558451e7Argyrios Kyrtzidis  return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
54337e550218128e7d922c09bb354fbc71de90c568Chris LattnerStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55337e550218128e7d922c09bb354fbc71de90c568Chris Lattner                               SourceLocation EndLoc) {
5620401698e3bd93a24bb5d9e18e435895cefe5fd1Chris Lattner  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
58682bf92db408a6cbc3d37b5496a99b6ef85041ecChris Lattner  // If we have an invalid decl, just return an error.
5920401698e3bd93a24bb5d9e18e435895cefe5fd1Chris Lattner  if (DG.isNull()) return StmtError();
601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6124e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
625f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
64a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanianvoid Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
66dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
67a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian  // If we have an invalid decl, just return.
68a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian  if (DG.isNull() || !DG.isSingleDecl()) return;
69f85e193739c953358c865005855253af4f68a497John McCall  VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70f85e193739c953358c865005855253af4f68a497John McCall
71a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian  // suppress any potential 'unused variable' warning.
72f85e193739c953358c865005855253af4f68a497John McCall  var->setUsed();
73f85e193739c953358c865005855253af4f68a497John McCall
747acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // foreach variables are never actually initialized in the way that
757acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // the parser came up with.
767acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  var->setInit(0);
777acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
787acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // In ARC, we don't need to retain the iteration variable of a fast
797acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // enumeration loop.  Rather than actually trying to catch that
807acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  // during declaration processing, we remove the consequences here.
814e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().ObjCAutoRefCount) {
827acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    QualType type = var->getType();
837acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
847acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // Only do this if we inferred the lifetime.  Inferred lifetime
857acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // will show up as a local qualifier because explicit lifetime
867acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // should have shown up as an AttributedType instead.
877acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
887acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      // Add 'const' and mark the variable as pseudo-strong.
897acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      var->setType(type.withConst());
907acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      var->setARCPseudoStrong(true);
91f85e193739c953358c865005855253af4f68a497John McCall    }
92f85e193739c953358c865005855253af4f68a497John McCall  }
93a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian}
94a7cf23a72b0846fc5aacf3f38bb8c8f9e76784cfFariborz Jahanian
95ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
969d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth///
979d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth/// Adding a cast to void (or other expression wrappers) will prevent the
989d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth/// warning from firing.
99ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruthstatic bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
1009d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  SourceLocation Loc;
10150bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  bool IsNotEqual, CanAssign;
1029d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1039d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
1049d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
105ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth      return false;
1069d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1079d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    Loc = Op->getOperatorLoc();
10850bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    IsNotEqual = Op->getOpcode() == BO_NE;
10950bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
1109d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
1119d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    if (Op->getOperator() != OO_EqualEqual &&
1129d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth        Op->getOperator() != OO_ExclaimEqual)
113ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth      return false;
1149d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1159d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    Loc = Op->getOperatorLoc();
11650bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
11750bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
1189d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  } else {
1199d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    // Not a typo-prone comparison.
120ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return false;
1219d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  }
1229d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
1239d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  // Suppress warnings when the operator, suspicious as it may be, comes from
1249d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  // a macro expansion.
1259d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth  if (Loc.isMacroID())
126ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return false;
1279d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
128ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  S.Diag(Loc, diag::warn_unused_comparison)
1299d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth    << (unsigned)IsNotEqual << E->getSourceRange();
1309d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
13150bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  // If the LHS is a plausible entity to assign to, provide a fixit hint to
13250bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  // correct common typos.
13350bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  if (CanAssign) {
13450bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    if (IsNotEqual)
13550bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth      S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
13650bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth        << FixItHint::CreateReplacement(Loc, "|=");
13750bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth    else
13850bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth      S.Diag(Loc, diag::note_equality_comparison_to_assign)
13950bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth        << FixItHint::CreateReplacement(Loc, "=");
14050bf68fc9698742e36c311fc37e6e4b7de235c4bChandler Carruth  }
141ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth
142ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  return true;
1439d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth}
1449d8eb3b2a892697aed332f6c318a8554fc2623ceChandler Carruth
145636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlssonvoid Sema::DiagnoseUnusedExprResult(const Stmt *S) {
146d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
147d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis    return DiagnoseUnusedExprResult(Label->getSubStmt());
148d2827af6f96d441d72315dbe6d8505c3be0f2aa6Argyrios Kyrtzidis
149754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  const Expr *E = dyn_cast_or_null<Expr>(S);
150636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  if (!E)
151636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    return;
152636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson
153636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  SourceLocation Loc;
154636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson  SourceRange R1, R2;
155d87a0cd2b3e1c9e9f01212875f4cbe5b7bb7ab57Matt Beaumont-Gay  if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
156d87a0cd2b3e1c9e9f01212875f4cbe5b7bb7ab57Matt Beaumont-Gay      !E->isUnusedResultAWarning(Loc, R1, R2, Context))
157636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    return;
1581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
159419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // Okay, we have an unused result.  Depending on what the base expression is,
160419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // we might want to make a more specific diagnostic.  Check for one of these
161419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  // cases now.
162419cfb318cd69b6c717019288d5a3822be18d8f9Chris Lattner  unsigned DiagID = diag::warn_unused_expr;
1634765fa05b5652fcc4356371c2f481d0ea9a1b007John McCall  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
1644dffad64c5c7106dc5ac506be94944299c8f7bc3Douglas Gregor    E = Temps->getSubExpr();
16534d49471e0b6386aefdc0f6bd15e4a4876ce5db1Chandler Carruth  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
16634d49471e0b6386aefdc0f6bd15e4a4876ce5db1Chandler Carruth    E = TempExpr->getSubExpr();
16712f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall
168ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth  if (DiagnoseUnusedComparison(*this, E))
169ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth    return;
170ec8058f64bbcd79bd47748f4cf8628123dd3bae6Chandler Carruth
171f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall  E = E->IgnoreParenImpCasts();
172bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1730faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall    if (E->getType()->isVoidType())
1740faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall      return;
1750faede6f31b07bcec7b776f2b420c3ea9bb3e58cJohn McCall
176bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner    // If the callee has attribute pure, const, or warn_unused_result, warn with
177bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner    // a more specific message to make it clear what is happening.
178d20254f2875d0004c57ee766f258dbcee29f4841Nuno Lopes    if (const Decl *FD = CE->getCalleeDecl()) {
179bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<WarnUnusedResultAttr>()) {
18042d7b2d25b6f90dc397886d05502b10ab5a8b51bMatt Beaumont-Gay        Diag(Loc, diag::warn_unused_result) << R1 << R2;
181bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
182bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
183bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<PureAttr>()) {
184bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
185bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
186bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
187bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      if (FD->getAttr<ConstAttr>()) {
188bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
189bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner        return;
190bc8d42c6f1565c0b2f93ad524edebfd7a4e6cac6Chris Lattner      }
191dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    }
19212f78a6741a4cb3d904340f8d3d2714568b50e7aJohn McCall  } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
1934e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
194f85e193739c953358c865005855253af4f68a497John McCall      Diag(Loc, diag::err_arc_unused_init_message) << R1;
195f85e193739c953358c865005855253af4f68a497John McCall      return;
196f85e193739c953358c865005855253af4f68a497John McCall    }
197f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    const ObjCMethodDecl *MD = ME->getMethodDecl();
198f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
19942d7b2d25b6f90dc397886d05502b10ab5a8b51bMatt Beaumont-Gay      Diag(Loc, diag::warn_unused_result) << R1 << R2;
200f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian      return;
201f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian    }
202ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
203ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    const Expr *Source = POE->getSyntacticForm();
204ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    if (isa<ObjCSubscriptRefExpr>(Source))
205ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek      DiagID = diag::warn_unused_container_subscript_expr;
206ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek    else
207ebcb57a8d298862c65043e88b2429591ab3c58d3Ted Kremenek      DiagID = diag::warn_unused_property_expr;
208d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor  } else if (const CXXFunctionalCastExpr *FC
209d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
210d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
211d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
212d6e44a3c4193bd422bfa78c8086fb16bb2168e34Douglas Gregor      return;
213f031774aa2638b4d3f487e7e44180c1f89b867efFariborz Jahanian  }
214209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  // Diagnose "(void*) blah" as a typo for "(void) blah".
215209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
216209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
217209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    QualType T = TI->getType();
218209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
219209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    // We really do want to use the non-canonical type here.
220209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    if (T == Context.VoidPtrTy) {
221209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
222209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
223209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall      Diag(Loc, diag::warn_unused_voidptr)
224209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall        << FixItHint::CreateRemoval(TL.getStarLoc());
225209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall      return;
226209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall    }
227209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall  }
228209acbd6d0c1b4444eb8c1682717753e1cbe38deJohn McCall
229351ba91eaa6d30e523587b2d7ed676a5172c6e56Ted Kremenek  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
230636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson}
231636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson
232625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkovoid Sema::ActOnStartOfCompoundStmt() {
233625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  PushCompoundScope();
234625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
235625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
236625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkovoid Sema::ActOnFinishOfCompoundStmt() {
237625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  PopCompoundScope();
238625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
239625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
240625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenkosema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
241625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  return getCurFunction()->CompoundScopes.back();
242625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko}
243625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
24460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2451b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
246a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl                        MultiStmtArg elts, bool isStmtExpr) {
247a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl  unsigned NumElts = elts.size();
248a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
249c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  // If we're in C89 mode, check that we don't have any decls after stmts.  If
250c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  // so, emit an extension diagnostic.
2514e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
252c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // Note that __extension__ can be around a decl.
253c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    unsigned i = 0;
254c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // Skip over all declarations.
255c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
256c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      /*empty*/;
257c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner
258c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    // We found the end of the list or a statement.  Scan for another declstmt.
259c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
260c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      /*empty*/;
2611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
262c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    if (i != NumElts) {
2634afa39deaa245592977136d367251ee2c173dd8dDouglas Gregor      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
264c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner      Diag(D->getLocation(), diag::ext_mixed_decls_code);
265c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner    }
266c30ebfbf23d6a471146e3c68c2cf7f170b7e55dcChris Lattner  }
26798414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  // Warn about unused expressions in statements.
26898414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  for (unsigned i = 0; i != NumElts; ++i) {
269636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    // Ignore statements that are last in a statement expression.
270636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    if (isStmtExpr && i == NumElts - 1)
27198414c1b7d1944a57156d52e29bd41c005de09acChris Lattner      continue;
2721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
273636463e4c43be15e2f0fd0b8a08667f3066d8af7Anders Carlsson    DiagnoseUnusedExprResult(Elts[i]);
27498414c1b7d1944a57156d52e29bd41c005de09acChris Lattner  }
275a60528cdac7deee3991c2b48af4df4f315e49e9dSebastian Redl
276625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // Check for suspicious empty body (null statement) in `for' and `while'
277625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // statements.  Don't do anything for template instantiations, this just adds
278625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  // noise.
279625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (NumElts != 0 && !CurrentInstantiationScope &&
280625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko      getCurCompoundScope().HasEmptyLoopBodies) {
281625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    for (unsigned i = 0; i != NumElts - 1; ++i)
282625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
283625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  }
284625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
2858189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
2865f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
2875f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
28860d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2899ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
2909ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                    SourceLocation DotDotDotLoc, Expr *RHSVal,
29124e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner                    SourceLocation ColonLoc) {
2929ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  assert((LHSVal != 0) && "missing expression in case statement");
293117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
2948ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith  if (getCurFunction()->SwitchStack.empty()) {
2958ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    Diag(CaseLoc, diag::err_case_not_in_switch);
29624e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner    return StmtError();
2978ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith  }
2985f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
2994e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().CPlusPlus0x) {
3008ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // C99 6.8.4.2p3: The expression shall be an integer constant.
3018ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // However, GCC allows any evaluatable integer expression.
302282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
303282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
304282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      if (!LHSVal)
305282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith        return StmtError();
306282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    }
307117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
3088ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    // GCC extension: The expression shall be an integer constant.
309117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
310282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith    if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
311282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
312282e7e66748cc6dd14d6f7f2cb52e5373c531e61Richard Smith      // Recover from an error by just forgetting about it.
3138ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith    }
3148a87e57beb96212ee61dc08a5f691cd7f7710703Chris Lattner  }
3155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
316dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
317dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                        ColonLoc);
318781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
319117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl  return Owned(CS);
3205f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
3215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
32224e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner/// ActOnCaseStmtBody - This installs a statement as the body of a case.
3239ae2f076ca5ab1feb3ba95629099ec2319833701John McCallvoid Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
3245440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth  DiagnoseUnusedExprResult(SubStmt);
3255440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth
32624e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
32724e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner  CS->setSubStmt(SubStmt);
32824e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner}
32924e1e707b4c362f18e371e2bbf054a8345b57bfaChris Lattner
33060d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
3311eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpSema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
3329ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                       Stmt *SubStmt, Scope *CurScope) {
3335440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth  DiagnoseUnusedExprResult(SubStmt);
3345440bfaff6aec058b60bc6da75bb4f13b7a76491Chandler Carruth
335781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  if (getCurFunction()->SwitchStack.empty()) {
3360fa152e72bb71c4aa184d0edd91caa9cbebbf70eChris Lattner    Diag(DefaultLoc, diag::err_default_not_in_switch);
337117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl    return Owned(SubStmt);
3380fa152e72bb71c4aa184d0edd91caa9cbebbf70eChris Lattner  }
339117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl
340dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
341781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
342117054a99f4994e4ec8a1fc904b554e1f2dc9b29Sebastian Redl  return Owned(DS);
3435f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
3445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
34560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
34657ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerSema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
34757ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                     SourceLocation ColonLoc, Stmt *SubStmt) {
348ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  // If the label was multiply defined, reject it now.
349ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  if (TheDecl->getStmt()) {
350ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
351ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner    Diag(TheDecl->getLocation(), diag::note_previous_definition);
352de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl    return Owned(SubStmt);
3535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
354de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
355ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  // Otherwise, things are good.  Fill in the declaration and return it.
356ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
357ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  TheDecl->setStmt(LS);
358203548ba4b72e7e59320d352afc1eb0b5ab131deAbramo Bagnara  if (!TheDecl->isGnuLocal())
359203548ba4b72e7e59320d352afc1eb0b5ab131deAbramo Bagnara    TheDecl->setLocation(IdentLoc);
360ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  return Owned(LS);
3615f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
3625f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
363534986f2b21e6050bf00163cd6423fd92155a6edRichard SmithStmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
364534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith                                     const AttrVec &Attrs,
365534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith                                     Stmt *SubStmt) {
366534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  // Fill in the declaration and return it. Variable length will require to
367534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  // change this to AttributedStmt::Create(Context, ....);
368534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  // and probably using ArrayRef
369534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt);
370534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith  return Owned(LS);
371534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith}
372534986f2b21e6050bf00163cd6423fd92155a6edRichard Smith
37360d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
374d226f65006733ed7f709c3174f22ce33391cb58fJohn McCallSema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
37544aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                  Stmt *thenStmt, SourceLocation ElseLoc,
37644aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                  Stmt *elseStmt) {
37760d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult(CondVal.release());
3781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3798cfe5a784133d90bf329fd20801824a6f71bb8caDouglas Gregor  VarDecl *ConditionVar = 0;
380d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
381d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
382586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
38399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (CondResult.isInvalid())
38499e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
3858cfe5a784133d90bf329fd20801824a6f71bb8caDouglas Gregor  }
38699e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  Expr *ConditionExpr = CondResult.takeAs<Expr>();
38799e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  if (!ConditionExpr)
38899e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    return StmtError();
389dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
390754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(thenStmt);
3915f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
3929ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!elseStmt) {
393625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
394625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                          diag::warn_empty_if_body);
3952d85f8ba62fd6fdcf0ae303d77112b413d412caeAnders Carlsson  }
3962d85f8ba62fd6fdcf0ae303d77112b413d412caeAnders Carlsson
397754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(elseStmt);
3981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
399dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
40044aa1f397855f130e88e62ffc1029f7f83bb5d2eArgyrios Kyrtzidis                                    thenStmt, ElseLoc, elseStmt));
4015f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4025f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
403f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
404f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// the specified width and sign.  If an overflow occurs, detect it and emit
405f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner/// the specified diagnostic.
406f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattnervoid Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
407f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                              unsigned NewWidth, bool NewSign,
4081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              SourceLocation Loc,
409f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                              unsigned DiagID) {
410f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Perform a conversion to the promoted condition type if needed.
411f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  if (NewWidth > Val.getBitWidth()) {
412f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // If this is an extension, just do it.
4139f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.extend(NewWidth);
414f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    Val.setIsSigned(NewSign);
415f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor
416f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // If the input was signed and negative and the output is
417f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // unsigned, don't bother to warn: this is implementation-defined
418f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // behavior.
419f9f627dbbc62fbf51b906c24c783b4249dc7e9bbDouglas Gregor    // FIXME: Introduce a second, default-ignored warning for this case?
420f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  } else if (NewWidth < Val.getBitWidth()) {
421f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // If this is a truncation, check for overflow.
422f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    llvm::APSInt ConvVal(Val);
4239f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    ConvVal = ConvVal.trunc(NewWidth);
424b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    ConvVal.setIsSigned(NewSign);
4259f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    ConvVal = ConvVal.extend(Val.getBitWidth());
426b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    ConvVal.setIsSigned(Val.isSigned());
427f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    if (ConvVal != Val)
428d3a94e24ddf3fb90de76b17bd176d9ed61e66f2cChris Lattner      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
4291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
430f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // Regardless of whether a diagnostic was emitted, really do the
431f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // truncation.
4329f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.trunc(NewWidth);
433b2137ae3f1bd0aadb0552189af2824a324ffaa69Chris Lattner    Val.setIsSigned(NewSign);
434f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  } else if (NewSign != Val.isSigned()) {
435f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // Convert the sign to match the sign of the condition.  This can cause
436f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    // overflow as well: unsigned(INTMIN)
437dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    // We don't diagnose this overflow, because it is implementation-defined
4382853eac24e2e70a74d7da817653b0528b976039fDouglas Gregor    // behavior.
4392853eac24e2e70a74d7da817653b0528b976039fDouglas Gregor    // FIXME: Introduce a second, default-ignored warning for this case?
440f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    llvm::APSInt OldVal(Val);
441f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    Val.setIsSigned(NewSign);
442f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  }
443f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner}
444f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner
4450471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattnernamespace {
4460471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  struct CaseCompareFunctor {
4470471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
4480471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner                    const llvm::APSInt &RHS) {
4490471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      return LHS.first < RHS;
4500471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    }
4510e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
4520e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
4530e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner      return LHS.first < RHS.first;
4540e85a2761ace912c66663d779dd230f88cf77fe0Chris Lattner    }
4550471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    bool operator()(const llvm::APSInt &LHS,
4560471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
4570471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      return LHS < RHS.first;
4580471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner    }
4590471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  };
4600471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner}
4610471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner
462764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner/// CmpCaseVals - Comparison predicate for sorting case values.
463764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner///
464764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattnerstatic bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
465764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
466764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  if (lhs.first < rhs.first)
467764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner    return true;
468764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner
469764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  if (lhs.first == rhs.first &&
470764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner      lhs.second->getCaseLoc().getRawEncoding()
471764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner       < rhs.second->getCaseLoc().getRawEncoding())
472764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner    return true;
473764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner  return false;
474764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner}
475764a7ce5217f9569e100a3445f47496ee82daf86Chris Lattner
476ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor/// CmpEnumVals - Comparison predicate for sorting enumeration values.
477ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor///
478ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregorstatic bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
479ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
480ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor{
481ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  return lhs.first < rhs.first;
482ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor}
483ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
484ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor/// EqEnumVals - Comparison preficate for uniqing enumeration values.
485ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor///
486ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregorstatic bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
487ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
488ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor{
489ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  return lhs.first == rhs.first;
490ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor}
491ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
4925f04881eb025f61396d0555d8173730fe2759e0aChris Lattner/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
4935f04881eb025f61396d0555d8173730fe2759e0aChris Lattner/// potentially integral-promoted expression @p expr.
494a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCallstatic QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
495a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
496a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    expr = cleanups->getSubExpr();
497a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
498a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    if (impcast->getCastKind() != CK_IntegralCast) break;
499a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall    expr = impcast->getSubExpr();
5005f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  }
5015f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  return expr->getType();
5025f04881eb025f61396d0555d8173730fe2759e0aChris Lattner}
5035f04881eb025f61396d0555d8173730fe2759e0aChris Lattner
50460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
505dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
506d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                             Decl *CondVar) {
50760d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult;
5089ae2f076ca5ab1feb3ba95629099ec2319833701John McCall
509586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  VarDecl *ConditionVar = 0;
510d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
511d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
5129ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
5139ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    if (CondResult.isInvalid())
514586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor      return StmtError();
515dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5169ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    Cond = CondResult.release();
517586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  }
518dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5199ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!Cond)
520586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    return StmtError();
521dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5229ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  CondResult
523ceccab908bd7824751b1def127272ec04dd4732bEli Friedman    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
524c30614b7e2bad089f2509499379de509f33162d6Douglas Gregor                          PDiag(diag::err_typecheck_statement_requires_integer),
525c30614b7e2bad089f2509499379de509f33162d6Douglas Gregor                                   PDiag(diag::err_switch_incomplete_class_type)
5269ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                     << Cond->getSourceRange(),
527c30614b7e2bad089f2509499379de509f33162d6Douglas Gregor                                   PDiag(diag::err_switch_explicit_conversion),
528c30614b7e2bad089f2509499379de509f33162d6Douglas Gregor                                         PDiag(diag::note_switch_conversion),
529c30614b7e2bad089f2509499379de509f33162d6Douglas Gregor                                   PDiag(diag::err_switch_multiple_conversions),
5306bc574daab3d3571d888cc4a21df67f2e2a14792Douglas Gregor                                         PDiag(diag::note_switch_conversion),
531f39aec17b89f8f0dd78e78c50ad2fa08f12272e3Richard Smith                                         PDiag(0),
532f39aec17b89f8f0dd78e78c50ad2fa08f12272e3Richard Smith                                         /*AllowScopedEnumerations*/ true);
5339ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (CondResult.isInvalid()) return StmtError();
5349ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Cond = CondResult.take();
535dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
536a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
537a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  CondResult = UsualUnaryConversions(Cond);
538a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (CondResult.isInvalid()) return StmtError();
539a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  Cond = CondResult.take();
540a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall
541d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (!CondVar) {
542b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall    CheckImplicitConversions(Cond, SwitchLoc);
5434765fa05b5652fcc4356371c2f481d0ea9a1b007John McCall    CondResult = MaybeCreateExprWithCleanups(Cond);
5449ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    if (CondResult.isInvalid())
545586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor      return StmtError();
5469ae2f076ca5ab1feb3ba95629099ec2319833701John McCall    Cond = CondResult.take();
547586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  }
548b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
549781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchIntoScope();
550dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
5519ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
552781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.push_back(SS);
553586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor  return Owned(SS);
5547e52de4b45286d057b367bb1f9283a1e32d79252Chris Lattner}
5557e52de4b45286d057b367bb1f9283a1e32d79252Chris Lattner
55628164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greifstatic void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
55728164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  if (Val.getBitWidth() < BitWidth)
5589f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.extend(BitWidth);
55928164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  else if (Val.getBitWidth() > BitWidth)
5609f71a8f4c7a182a5236da9e747d57cc1d1bd24c2Jay Foad    Val = Val.trunc(BitWidth);
56128164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif  Val.setIsSigned(IsSigned);
56228164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif}
56328164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif
56460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
5659ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
5669ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                            Stmt *BodyStmt) {
5679ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  SwitchStmt *SS = cast<SwitchStmt>(Switch);
568781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  assert(SS == getCurFunction()->SwitchStack.back() &&
569781472fe99a120098c631b0cbe33c89f8cef5e70John McCall         "switch stack missing push/pop!");
570de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
5719dcbfa450d751bd68fc4af8b75da381d4f6984b9Steve Naroff  SS->setBody(BodyStmt, SwitchLoc);
572781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->SwitchStack.pop_back();
573c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson
574f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  Expr *CondExpr = SS->getCond();
575a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  if (!CondExpr) return StmtError();
576de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
577a0d3ca1ea5578bc736bb71bcec50ab41fefc87b9Douglas Gregor  QualType CondType = CondExpr->getType();
578a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall
579a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  Expr *CondExprBeforePromotion = CondExpr;
580a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall  QualType CondTypeBeforePromotion =
581a8e0cd8cdecc7e0ba1792e46773b884c6eed4829John McCall      GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
58284fb9c0be621c9e4ca4e56f67dae2a0bb6e44821Douglas Gregor
5835f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // C++ 6.4.2.p2:
5845f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // Integral promotions are performed (on the switch condition).
5855f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  //
5865f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // A case value unrepresentable by the original switch condition
5875f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // type (before the promotion) doesn't make sense, even when it can
5885f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // be represented by the promoted type.  Therefore we need to find
5895f04881eb025f61396d0555d8173730fe2759e0aChris Lattner  // the pre-promotion type of the switch condition.
59012356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan  if (!CondExpr->isTypeDependent()) {
591acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    // We have already converted the expression to an integral or enumeration
592dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    // type, when we started the switch statement. If we don't have an
593acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    // appropriate type now, just return an error.
594acb0bd85d30ecacbe872ca9d9cfac5d7b6038a43Douglas Gregor    if (!CondType->isIntegralOrEnumerationType())
59512356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      return StmtError();
59612356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan
5972b334bb3126a67895813e49e6228dad4aec0b4d6Chris Lattner    if (CondExpr->isKnownToHaveBooleanValue()) {
59812356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      // switch(bool_expr) {...} is often a programmer error, e.g.
59912356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
60012356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      // One can always use an if statement instead of switch(bool_expr).
60112356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan      Diag(SwitchLoc, diag::warn_bool_switch_condition)
60212356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan          << CondExpr->getSourceRange();
60312356b119032edd64e9c32f9f01920d12c2acc57Edward O'Callaghan    }
604c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson  }
605de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
606f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Get the bitwidth of the switched-on value before promotions.  We must
607f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // convert the integer case values to this width before comparison.
6081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  bool HasDependentValue
609dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
6101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned CondWidth
6111d6ab7af99a1fc059a6aa5da083640c1d94b07f7Chris Lattner    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
612575a1c9dc8dc5b4977194993e289f9eda7295c39Douglas Gregor  bool CondIsSigned
613575a1c9dc8dc5b4977194993e289f9eda7295c39Douglas Gregor    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
615f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Accumulate all of the case values in a vector so that we can sort them
616f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // and detect duplicates.  This vector contains the APInt for the case after
617f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // it has been converted to the condition type.
6185f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
6190471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner  CaseValsTy CaseVals;
6201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
621f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
622ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
623ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor  CaseRangesTy CaseRanges;
6241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
625f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  DefaultStmt *TheDefaultStmt = 0;
6261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
627b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  bool CaseListIsErroneous = false;
6281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
629dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
630c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson       SC = SC->getNextSwitchCase()) {
6311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
632c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
633f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      if (TheDefaultStmt) {
634f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
6355f4a6829dc58cab2f76e2b98492859aa3b91e3f2Chris Lattner        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
636de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
637f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        // FIXME: Remove the default statement from the switch block so that
638390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // we'll return a valid AST.  This requires recursing down the AST and
639390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // finding it, not something we are set up to do right now.  For now,
640390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump        // just lop the entire switch stmt out of the AST.
641b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner        CaseListIsErroneous = true;
642c1fcb7762673be706b0a40477d5e93411e918f93Anders Carlsson      }
643f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      TheDefaultStmt = DS;
6441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
645f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    } else {
646f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      CaseStmt *CS = cast<CaseStmt>(SC);
6471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6481e0a39012467b4f409142c32148036a9ee05e1d7Chris Lattner      Expr *Lo = CS->getLHS();
649dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
650dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
651dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        HasDependentValue = true;
652dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        break;
653dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      }
6541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6558ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      llvm::APSInt LoVal;
6561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6574e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus0x) {
6588ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // C++11 [stmt.switch]p2: the constant-expression shall be a converted
6598ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // constant expression of the promoted type of the switch condition.
6608ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        ExprResult ConvLo =
6618ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
6628ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        if (ConvLo.isInvalid()) {
6638ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          CaseListIsErroneous = true;
6648ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          continue;
6658ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        }
6668ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = ConvLo.take();
6678ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      } else {
6688ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // We already verified that the expression has a i-c-e value (C99
6698ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // 6.8.4.2p3) - get that value now.
6708ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        LoVal = Lo->EvaluateKnownConstInt(Context);
6718ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
6728ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // If the LHS is not the same type as the condition, insert an implicit
6738ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        // cast.
6748ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = DefaultLvalueConversion(Lo).take();
6758ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
6768ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      }
6778ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
6788ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // Convert the value to the same width/sign as the condition had prior to
6798ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // integral promotions.
6808ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      //
6818ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // FIXME: This causes us to reject valid code:
6828ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      //   switch ((char)c) { case 256: case 0: return 0; }
6838ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith      // Here we claim there is a duplicated condition value, but there is not.
684f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
68528164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                                         Lo->getLocStart(),
686f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner                                         diag::warn_case_value_overflow);
6876c36be5b383875b490684bcf439d6d427298c1afChris Lattner
6881e0a39012467b4f409142c32148036a9ee05e1d7Chris Lattner      CS->setLHS(Lo);
6891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
690b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
691dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      if (CS->getRHS()) {
6921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        if (CS->getRHS()->isTypeDependent() ||
693dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            CS->getRHS()->isValueDependent()) {
694dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          HasDependentValue = true;
695dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          break;
696dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
697f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner        CaseRanges.push_back(std::make_pair(LoVal, CS));
6981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      } else
699b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner        CaseVals.push_back(std::make_pair(LoVal, CS));
700f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner    }
701f4021e7d5228a2be5a380269dffa0331a6c78b95Chris Lattner  }
702b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner
703dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor  if (!HasDependentValue) {
7040fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // If we don't have a default statement, check whether the
7050fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // condition is constant.
7060fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    llvm::APSInt ConstantCondValue;
7070fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    bool HasConstantCond = false;
7080fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    if (!HasDependentValue && !TheDefaultStmt) {
70951f4708c00110940ca3f337961915f2ca1668375Richard Smith      HasConstantCond
71080d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith        = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
71180d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith                                                 Expr::SE_AllowSideEffects);
71280d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith      assert(!HasConstantCond ||
71380d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith             (ConstantCondValue.getBitWidth() == CondWidth &&
71480d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith              ConstantCondValue.isSigned() == CondIsSigned));
7150fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    }
71680d4b55db94db2172a04617d1a80feca6bbcea5cRichard Smith    bool ShouldCheckConstantCond = HasConstantCond;
7170fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
718dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // Sort all the scalar case values so we can easily detect duplicates.
719dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
720dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
721dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    if (!CaseVals.empty()) {
7220fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
7230fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (ShouldCheckConstantCond &&
7240fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            CaseVals[i].first == ConstantCondValue)
7250fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          ShouldCheckConstantCond = false;
7260fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
7270fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
728dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          // If we have a duplicate, report it.
7291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Diag(CaseVals[i].second->getLHS()->getLocStart(),
7300fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
7310fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
732dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor               diag::note_duplicate_case_prev);
733390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // FIXME: We really want to remove the bogus case stmt from the
734390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // substmt, but we have no way to do this right now.
735dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseListIsErroneous = true;
736dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
7376efc4d3659632ddcea4a58cb62e9ee54ca4a373eChris Lattner      }
738b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner    }
7391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
740dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // Detect duplicate case ranges, which usually don't exist at all in
741dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    // the first place.
742dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor    if (!CaseRanges.empty()) {
743dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Sort all the case ranges by their low value so we can easily detect
744dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // overlaps between ranges.
745dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
7461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
747dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Scan the ranges, computing the high values and removing empty ranges.
748dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      std::vector<llvm::APSInt> HiVals;
749dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
7500fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        llvm::APSInt &LoVal = CaseRanges[i].first;
751dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *CR = CaseRanges[i].second;
752dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        Expr *Hi = CR->getRHS();
7538ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        llvm::APSInt HiVal;
7548ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
7554e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        if (getLangOpts().CPlusPlus0x) {
7568ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // C++11 [stmt.switch]p2: the constant-expression shall be a converted
7578ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // constant expression of the promoted type of the switch condition.
7588ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          ExprResult ConvHi =
7598ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            CheckConvertedConstantExpression(Hi, CondType, HiVal,
7608ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith                                             CCEK_CaseValue);
7618ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          if (ConvHi.isInvalid()) {
7628ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            CaseListIsErroneous = true;
7638ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith            continue;
7648ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          }
7658ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = ConvHi.take();
7668ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        } else {
7678ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          HiVal = Hi->EvaluateKnownConstInt(Context);
7688ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith
7698ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // If the RHS is not the same type as the condition, insert an
7708ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          // implicit cast.
7718ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = DefaultLvalueConversion(Hi).take();
7728ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith          Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
7738ef7b203332b0c8d65876a1f5e6d1db4e6f40e4bRichard Smith        }
7741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
775dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Convert the value to the same width/sign as the condition.
776dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
77728164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                                           Hi->getLocStart(),
778dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                           diag::warn_case_value_overflow);
7791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
780dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CR->setRHS(Hi);
7811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
782dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // If the low value is bigger than the high value, the case is empty.
7830fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (LoVal > HiVal) {
784dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
785dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            << SourceRange(CR->getLHS()->getLocStart(),
78628164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif                           Hi->getLocEnd());
787dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseRanges.erase(CaseRanges.begin()+i);
788dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          --i, --e;
789dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          continue;
790dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
7910fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
7920fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        if (ShouldCheckConstantCond &&
7930fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            LoVal <= ConstantCondValue &&
7940fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall            ConstantCondValue <= HiVal)
7950fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall          ShouldCheckConstantCond = false;
7960fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
797dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        HiVals.push_back(HiVal);
7980471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      }
7991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
800dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // Rescan the ranges, looking for overlap with singleton values and other
801dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // ranges.  Since the range list is sorted, we only need to compare case
802dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      // ranges with their neighbors.
803dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
804dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt &CRLo = CaseRanges[i].first;
805dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt &CRHi = HiVals[i];
806dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *CR = CaseRanges[i].second;
8071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
808dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Check to see whether the case range overlaps with any
809dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // singleton cases.
810dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseStmt *OverlapStmt = 0;
811dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        llvm::APSInt OverlapVal(32);
8121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
813dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Find the smallest value >= the lower bound.  If I is in the
814dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // case range, then we have overlap.
815dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
816dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                                  CaseVals.end(), CRLo,
817dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor                                                  CaseCompareFunctor());
818dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (I != CaseVals.end() && I->first < CRHi) {
819dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = I->first;   // Found overlap with scalar.
820dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = I->second;
821dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
8221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
823dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Find the smallest value bigger than the upper bound.
824dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
825dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
826dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
827dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = (I-1)->second;
828dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
8291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
830dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // Check to see if this case stmt overlaps with the subsequent
831dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        // case range.
832dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (i && CRLo <= HiVals[i-1]) {
833dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapVal  = HiVals[i-1];       // Found overlap with range.
834dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          OverlapStmt = CaseRanges[i-1].second;
835dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
8361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
837dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        if (OverlapStmt) {
838dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          // If we have a duplicate, report it.
839dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
840dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor            << OverlapVal.toString(10);
8411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Diag(OverlapStmt->getLHS()->getLocStart(),
842dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor               diag::note_duplicate_case_prev);
843390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // FIXME: We really want to remove the bogus case stmt from the
844390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump          // substmt, but we have no way to do this right now.
845dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor          CaseListIsErroneous = true;
846dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor        }
8470471f5bc8191e39cdb61fabcaf1870e2af2d42e8Chris Lattner      }
848b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner    }
849ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
8500fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // Complain if we have a constant condition and we didn't find a match.
8510fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
8520fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // TODO: it would be nice if we printed enums as enums, chars as
8530fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // chars, etc.
8540fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
8550fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        << ConstantCondValue.toString(10)
8560fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        << CondExpr->getSourceRange();
8570fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    }
8580fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall
8590fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    // Check to see if switch is over an Enum and handles all of its
860559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // values.  We only issue a warning if there is not 'default:', but
861559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // we still do the analysis to preserve this information in the AST
862559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    // (which can be used by flow-based analyes).
8630fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall    //
864ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
865559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
866ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor    // If switch has default case, then ignore it.
867559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
868ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      const EnumDecl *ED = ET->getDecl();
8695f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
87058f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet        EnumValsTy;
871ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      EnumValsTy EnumVals;
872ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
8730fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // Gather all enum values, set their type and sort them,
8740fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      // allowing easier comparison with CaseVals.
8750fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
87628164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif           EDI != ED->enumerator_end(); ++EDI) {
87728164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif        llvm::APSInt Val = EDI->getInitVal();
87828164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif        AdjustAPSInt(Val, CondWidth, CondIsSigned);
87928164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif        EnumVals.push_back(std::make_pair(Val, *EDI));
880ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
881ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
8820fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall      EnumValsTy::iterator EIend =
8830fb97083cc0f8a82e404e22991ae80d2216e71d5John McCall        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
884559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
885559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      // See which case values aren't in enum.
8869366750a5a97c8aeae1df4898ea849b087865195David Blaikie      EnumValsTy::const_iterator EI = EnumVals.begin();
8879366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (CaseValsTy::const_iterator CI = CaseVals.begin();
8889366750a5a97c8aeae1df4898ea849b087865195David Blaikie           CI != CaseVals.end(); CI++) {
8899366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < CI->first)
8909366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
8919366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first > CI->first)
8929366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
89354faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
8949366750a5a97c8aeae1df4898ea849b087865195David Blaikie      }
8959366750a5a97c8aeae1df4898ea849b087865195David Blaikie      // See which of case ranges aren't in enum
8969366750a5a97c8aeae1df4898ea849b087865195David Blaikie      EI = EnumVals.begin();
8979366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
8989366750a5a97c8aeae1df4898ea849b087865195David Blaikie           RI != CaseRanges.end() && EI != EIend; RI++) {
8999366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < RI->first)
9009366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
9019366750a5a97c8aeae1df4898ea849b087865195David Blaikie
9029366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first != RI->first) {
9039366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
90454faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
90547bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        }
906e0ba9d1beeba01a96808c2fc61f9ca89acec313bTed Kremenek
9079366750a5a97c8aeae1df4898ea849b087865195David Blaikie        llvm::APSInt Hi =
9089366750a5a97c8aeae1df4898ea849b087865195David Blaikie          RI->second->getRHS()->EvaluateKnownConstInt(Context);
9099366750a5a97c8aeae1df4898ea849b087865195David Blaikie        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
9109366750a5a97c8aeae1df4898ea849b087865195David Blaikie        while (EI != EIend && EI->first < Hi)
9119366750a5a97c8aeae1df4898ea849b087865195David Blaikie          EI++;
9129366750a5a97c8aeae1df4898ea849b087865195David Blaikie        if (EI == EIend || EI->first != Hi)
9139366750a5a97c8aeae1df4898ea849b087865195David Blaikie          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
91454faba4f7f3f0e8f1376da1c459312596ad5486dFariborz Jahanian            << CondTypeBeforePromotion;
915ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
916dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
917559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      // Check which enum vals aren't in switch
918ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      CaseValsTy::const_iterator CI = CaseVals.begin();
919ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      CaseRangesTy::const_iterator RI = CaseRanges.begin();
920559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      bool hasCasesNotInSwitch = false;
921559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
9225f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      SmallVector<DeclarationName,8> UnhandledNames;
923dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
9249366750a5a97c8aeae1df4898ea849b087865195David Blaikie      for (EI = EnumVals.begin(); EI != EIend; EI++){
925ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        // Drop unneeded case values
926ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        llvm::APSInt CIVal;
927ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        while (CI != CaseVals.end() && CI->first < EI->first)
928ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          CI++;
929dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
930ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        if (CI != CaseVals.end() && CI->first == EI->first)
931ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          continue;
932ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
933559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek        // Drop unneeded case ranges
934ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        for (; RI != CaseRanges.end(); RI++) {
935a6b8b2c09610b8bc4330e948ece8b940c2386406Richard Smith          llvm::APSInt Hi =
936a6b8b2c09610b8bc4330e948ece8b940c2386406Richard Smith            RI->second->getRHS()->EvaluateKnownConstInt(Context);
93728164ab2ac1deea68cdb989f941728bf1860ce41Gabor Greif          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
938ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor          if (EI->first <= Hi)
939ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor            break;
940ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor        }
941ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor
942559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek        if (RI == CaseRanges.end() || EI->first < RI->first) {
94347bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek          hasCasesNotInSwitch = true;
94431ceb61172bca7ebc3fb90e9125864c7a29c55c0David Blaikie          UnhandledNames.push_back(EI->second->getDeclName());
94547bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        }
946ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor      }
947dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
948585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie      if (TheDefaultStmt && UnhandledNames.empty())
949585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
95031ceb61172bca7ebc3fb90e9125864c7a29c55c0David Blaikie
951ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      // Produce a nice diagnostic if multiple values aren't handled.
952ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      switch (UnhandledNames.size()) {
953ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 0: break;
954ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 1:
955585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
956585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
957ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0];
958ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
959ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 2:
960585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
961585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
962ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1];
963ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
964ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      case 3:
965585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
966585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
967ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
968ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
969ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      default:
970585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie        Diag(CondExpr->getExprLoc(), TheDefaultStmt
971585d7795c2dddaa510b3bb1b3b18633bfcfdf643David Blaikie          ? diag::warn_def_missing_cases : diag::warn_missing_cases)
972ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << (unsigned)UnhandledNames.size()
973ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
974ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner        break;
975ce78461303f45fecb3460d1c49c9b71f27ad19c3Chris Lattner      }
976559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek
977559fb554602bedb57dbbf3cc14ac8a38264b4547Ted Kremenek      if (!hasCasesNotInSwitch)
97847bb27f16882e4f5ababdd0cf6642bb904a9aaf8Ted Kremenek        SS->setAllEnumCasesCovered();
979ba915af51ced751c46e7c2b9c6f3b59d2e668825Douglas Gregor    }
980b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  }
981dbb26db1d426fb6caaaf1b4fa47b46d1947c12c9Douglas Gregor
982625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
983625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                        diag::warn_empty_switch_body);
984625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
985390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump  // FIXME: If the case list was broken is some way, we don't have a good system
986390b4cc8b45a05612349269ef08faab3e4688f06Mike Stump  // to patch it up.  Instead, just return the whole substmt as broken.
987b2ec9d6fede9cccc170a202de7bf7f523dea8be4Chris Lattner  if (CaseListIsErroneous)
988de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl    return StmtError();
989de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl
990de307473448fb3cebcb4c10090728300b53bca03Sebastian Redl  return Owned(SS);
9915f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
9925f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
99360d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
994dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
9959ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                     Decl *CondVar, Stmt *Body) {
99660d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult CondResult(Cond.release());
997dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
9985656e14d91405417182171a705ed3e3d2d6d7aa3Douglas Gregor  VarDecl *ConditionVar = 0;
999d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (CondVar) {
1000d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(CondVar);
1001586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
100299e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (CondResult.isInvalid())
100399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
10045656e14d91405417182171a705ed3e3d2d6d7aa3Douglas Gregor  }
10059ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Expr *ConditionExpr = CondResult.take();
100699e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  if (!ConditionExpr)
100799e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    return StmtError();
1008dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
10099ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  DiagnoseUnusedExprResult(Body);
10101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1011625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (isa<NullStmt>(Body))
1012625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    getCurCompoundScope().setHasEmptyLoopBodies();
1013625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
101443dec6bbde2d0a16c35978983761c8b7030c8e18Douglas Gregor  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
10159ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                       Body, WhileLoc));
10165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
10175f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
101860d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
10199ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1020989135901c750af61ef012b6b0a0368be415bc46Chris Lattner                  SourceLocation WhileLoc, SourceLocation CondLParen,
10219ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                  Expr *Cond, SourceLocation CondRParen) {
10229ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  assert(Cond && "ActOnDoStmt(): missing expression");
1023f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl
1024429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1025429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  if (CondResult.isInvalid() || CondResult.isInvalid())
10265a881bb09928b7ade891efc680088aaad276f8d6John McCall    return StmtError();
1027429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  Cond = CondResult.take();
10285f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1029b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall  CheckImplicitConversions(Cond, DoLoc);
1030429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley  CondResult = MaybeCreateExprWithCleanups(Cond);
10319ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (CondResult.isInvalid())
1032586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    return StmtError();
10339ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Cond = CondResult.take();
1034dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
10359ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  DiagnoseUnusedExprResult(Body);
1036754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson
10379ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
10385f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
10395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
104060d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1041f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian RedlSema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
10429ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                   Stmt *First, FullExprArg second, Decl *secondVar,
104399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor                   FullExprArg third,
10449ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                   SourceLocation RParenLoc, Stmt *Body) {
10454e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().CPlusPlus) {
10465921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1047f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1048f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // declare identifiers for objects having storage class 'auto' or
1049f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // 'register'.
10505921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
10515921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis           DI!=DE; ++DI) {
10525921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis        VarDecl *VD = dyn_cast<VarDecl>(*DI);
1053b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
10545921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis          VD = 0;
10555921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis        if (VD == 0)
10565921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
10575921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis        // FIXME: mark decl erroneous!
10585921093cf1c2e9a8bd1a22b6f612e551bae7476bArgyrios Kyrtzidis      }
1059ae3b701f59e78e058b83344be17206af3bf5d277Chris Lattner    }
10605f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
106199e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor
106260d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult SecondResult(second.release());
106399e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  VarDecl *ConditionVar = 0;
1064d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  if (secondVar) {
1065d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall    ConditionVar = cast<VarDecl>(secondVar);
1066586596fd7f7a336a2847b300c80614dcf39ab6d5Douglas Gregor    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
106799e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor    if (SecondResult.isInvalid())
106899e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor      return StmtError();
106999e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  }
1070dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
107199e9b4d172f6877e6ba5ebe75bb8238721f5e01cDouglas Gregor  Expr *Third  = third.release().takeAs<Expr>();
1072dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
10733af708ff19e4ae2bf9e40550548361b00e5916bfAnders Carlsson  DiagnoseUnusedExprResult(First);
10743af708ff19e4ae2bf9e40550548361b00e5916bfAnders Carlsson  DiagnoseUnusedExprResult(Third);
1075754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson  DiagnoseUnusedExprResult(Body);
1076754431107b61a0523df5271c2876a73dd5a051e9Anders Carlsson
1077625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  if (isa<NullStmt>(Body))
1078625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko    getCurCompoundScope().setHasEmptyLoopBodies();
1079625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
1080dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  return Owned(new (Context) ForStmt(Context, First,
1081dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                                     SecondResult.take(), ConditionVar,
1082dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                                     Third, Body, ForLoc, LParenLoc,
108343dec6bbde2d0a16c35978983761c8b7030c8e18Douglas Gregor                                     RParenLoc));
10845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
10855f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1086f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// In an Objective C collection iteration statement:
1087f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall///   for (x in y)
1088f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// x can be an arbitrary l-value expression.  Bind it up as a
1089f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall/// full-expression.
1090f6a1648197562e0b133440d612d9af297d0a86ccJohn McCallStmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
109129bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  // Reduce placeholder expressions here.  Note that this rejects the
109229bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  // use of pseudo-object l-values in this position.
109329bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  ExprResult result = CheckPlaceholderExpr(E);
109429bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  if (result.isInvalid()) return StmtError();
109529bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  E = result.take();
109629bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall
1097f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall  CheckImplicitConversions(E);
109829bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall
109929bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  result = MaybeCreateExprWithCleanups(E);
110029bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  if (result.isInvalid()) return StmtError();
110129bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall
110229bbd1a33edfd3c81c35d5076530c2867a05bddcJohn McCall  return Owned(static_cast<Stmt*>(result.take()));
1103f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall}
1104f6a1648197562e0b133440d612d9af297d0a86ccJohn McCall
1105990567cb60e8530ba01b41d4e056e32b44b95ec0John McCallExprResult
1106990567cb60e8530ba01b41d4e056e32b44b95ec0John McCallSema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1107990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  assert(collection);
1108990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1109990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Bail out early if we've got a type-dependent expression.
1110990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (collection->isTypeDependent()) return Owned(collection);
1111990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1112990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Perform normal l-value conversion.
1113990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1114990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (result.isInvalid())
1115990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    return ExprError();
1116990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  collection = result.take();
1117990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1118990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // The operand needs to have object-pointer type.
1119990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // TODO: should we do a contextual conversion?
1120990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  const ObjCObjectPointerType *pointerType =
1121990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    collection->getType()->getAs<ObjCObjectPointerType>();
1122990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  if (!pointerType)
1123990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    return Diag(forLoc, diag::err_collection_expr_type)
1124990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall             << collection->getType() << collection->getSourceRange();
1125990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1126990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Check that the operand provides
1127990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  //   - countByEnumeratingWithState:objects:count:
1128990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  const ObjCObjectType *objectType = pointerType->getObjectType();
1129990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  ObjCInterfaceDecl *iface = objectType->getInterface();
1130990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1131990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // If we have a forward-declared type, we can't do this check.
1132b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor  // Under ARC, it is an error not to have a forward-declared class.
1133b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor  if (iface &&
1134b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor      RequireCompleteType(forLoc, QualType(objectType, 0),
11354e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie                          getLangOpts().ObjCAutoRefCount
1136b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor                            ? PDiag(diag::err_arc_collection_forward)
1137b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor                                << collection->getSourceRange()
1138b3029960632ca8a3248e74770eda64d6c16f7246Douglas Gregor                          : PDiag(0))) {
1139990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // Otherwise, if we have any useful type information, check that
1140990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // the type declares the appropriate method.
1141990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  } else if (iface || !objectType->qual_empty()) {
1142990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    IdentifierInfo *selectorIdents[] = {
1143990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("countByEnumeratingWithState"),
1144990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("objects"),
1145990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      &Context.Idents.get("count")
1146990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    };
1147990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1148990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1149990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    ObjCMethodDecl *method = 0;
1150990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1151990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // If there's an interface, look in both the public and private APIs.
1152990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (iface) {
1153990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      method = iface->lookupInstanceMethod(selector);
1154990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1155990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    }
1156990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1157990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // Also check protocol qualifiers.
1158990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (!method)
1159990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      method = LookupMethodInQualifiedType(selector, pointerType,
1160990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall                                           /*instance*/ true);
1161990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1162990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // If we didn't find it anywhere, give up.
1163990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    if (!method) {
1164990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall      Diag(forLoc, diag::warn_collection_expr_type)
1165990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall        << collection->getType() << selector << collection->getSourceRange();
1166990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    }
1167990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1168990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall    // TODO: check for an incompatible signature?
1169990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  }
1170990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
1171990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  // Wrap up any cleanups in the expression.
1172990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall  return Owned(MaybeCreateExprWithCleanups(collection));
1173990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall}
1174990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
117560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1176f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian RedlSema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1177f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                                 SourceLocation LParenLoc,
11789ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                 Stmt *First, Expr *Second,
11799ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                 SourceLocation RParenLoc, Stmt *Body) {
118020552d2842245692b649e0d25380670922f954a2Fariborz Jahanian  if (First) {
118120552d2842245692b649e0d25380670922f954a2Fariborz Jahanian    QualType FirstType;
118220552d2842245692b649e0d25380670922f954a2Fariborz Jahanian    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
11837e24e82a70a2c681f4291a3397bcd1e1005f251aChris Lattner      if (!DS->isSingleDecl())
1184f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1185f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                         diag::err_toomany_element_decls));
1186f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl
1187f85e193739c953358c865005855253af4f68a497John McCall      VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1188f85e193739c953358c865005855253af4f68a497John McCall      FirstType = D->getType();
1189f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1190f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // declare identifiers for objects having storage class 'auto' or
1191f3a41af4d5c98a72a1d6720bbbfd658e57ef2541Chris Lattner      // 'register'.
1192f85e193739c953358c865005855253af4f68a497John McCall      if (!D->hasLocalStorage())
1193f85e193739c953358c865005855253af4f68a497John McCall        return StmtError(Diag(D->getLocation(),
1194f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                              diag::err_non_variable_decl_in_for));
11951fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson    } else {
1196c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor      Expr *FirstE = cast<Expr>(First);
11977eb0a9eb0cde8444b97f9c5b713d9be7a6f1e607John McCall      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1198f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl        return StmtError(Diag(First->getLocStart(),
1199f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl                   diag::err_selector_element_not_lvalue)
1200f05b1520d6f175acbfc3913489f4dfa842875ec4Sebastian Redl          << First->getSourceRange());
12011fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson
12021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      FirstType = static_cast<Expr*>(First)->getType();
12031fe379f0fa6fbc0a6057e8966253aea2957ca953Anders Carlsson    }
1204c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor    if (!FirstType->isDependentType() &&
1205c3203e7ee1464a096f341c2e2a83a10be2da000aDouglas Gregor        !FirstType->isObjCObjectPointerType() &&
1206a5e42a82ce055f29f3733f3a1f10da6cb9877deeFariborz Jahanian        !FirstType->isBlockPointerType())
1207dcd5ef12488e4c7ea844327835896ca86b609a97Chris Lattner        Diag(ForLoc, diag::err_selector_element_type)
1208d162584991885ab004a02573a73ce06422b921fcChris Lattner          << FirstType << First->getSourceRange();
12093ba5a0f90a03d5e13d02cbee9abd2a1ba01b18bcFariborz Jahanian  }
1210990567cb60e8530ba01b41d4e056e32b44b95ec0John McCall
12118189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
12128189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek                                                   ForLoc, RParenLoc));
12133ba5a0f90a03d5e13d02cbee9abd2a1ba01b18bcFariborz Jahanian}
12145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1215ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithnamespace {
1216ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1217ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithenum BeginEndFunction {
1218ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  BEF_begin,
1219ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  BEF_end
1220ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith};
1221ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1222ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Build a variable declaration for a for-range statement.
1223ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithstatic VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1224ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                     QualType Type, const char *Name) {
1225ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclContext *DC = SemaRef.CurContext;
1226ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1227ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1228ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1229ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                  TInfo, SC_Auto, SC_None);
1230b403d6d746239095a2c7bac958c924d92434e2b4Richard Smith  Decl->setImplicit();
1231ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return Decl;
1232ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1233ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1234ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Finish building a variable declaration for a for-range statement.
1235ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// \return true if an error occurs.
1236ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithstatic bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1237ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                  SourceLocation Loc, int diag) {
1238ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Deduce the type for the iterator variable now rather than leaving it to
1239ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1240ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  TypeSourceInfo *InitTSI = 0;
124162b7cfb73e202051e7ab0dad42ba213acd0dec7eSebastian Redl  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1242b832f6dea893f25b40500a04781286236281cb20Sebastian Redl      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1243b832f6dea893f25b40500a04781286236281cb20Sebastian Redl          Sema::DAR_Failed)
1244ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    SemaRef.Diag(Loc, diag) << Init->getType();
1245ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!InitTSI) {
1246ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Decl->setInvalidDecl();
1247ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return true;
1248ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1249ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  Decl->setTypeSourceInfo(InitTSI);
1250ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  Decl->setType(InitTSI->getType());
1251ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1252f85e193739c953358c865005855253af4f68a497John McCall  // In ARC, infer lifetime.
1253f85e193739c953358c865005855253af4f68a497John McCall  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1254f85e193739c953358c865005855253af4f68a497John McCall  // we're doing the equivalent of fast iteration.
12554e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1256f85e193739c953358c865005855253af4f68a497John McCall      SemaRef.inferObjCARCLifetime(Decl))
1257f85e193739c953358c865005855253af4f68a497John McCall    Decl->setInvalidDecl();
1258f85e193739c953358c865005855253af4f68a497John McCall
1259ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1260ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                               /*TypeMayContainAuto=*/false);
1261ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.FinalizeDeclaration(Decl);
1262b403d6d746239095a2c7bac958c924d92434e2b4Richard Smith  SemaRef.CurContext->addHiddenDecl(Decl);
1263ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return false;
1264ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1265ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1266ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Produce a note indicating which begin/end function was implicitly called
1267ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// by a C++0x for-range statement. This is often not obvious from the code,
1268ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// nor from the diagnostics produced when analysing the implicit expressions
1269ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// required in a for-range statement.
1270ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithvoid NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1271ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                  BeginEndFunction BEF) {
1272ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  CallExpr *CE = dyn_cast<CallExpr>(E);
1273ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!CE)
1274ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return;
1275ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1276ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!D)
1277ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return;
1278ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SourceLocation Loc = D->getLocation();
1279ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1280ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  std::string Description;
1281ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  bool IsTemplate = false;
1282ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1283ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Description = SemaRef.getTemplateArgumentBindingsText(
1284ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1285ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IsTemplate = true;
1286ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1287ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1288ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1289ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    << BEF << IsTemplate << Description << E->getType();
1290ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1291ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1292ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1293ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// given LookupResult is non-empty, it is assumed to describe a member which
1294ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// will be invoked. Otherwise, the function will be found via argument
1295ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// dependent lookup.
1296ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smithstatic ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1297ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            SourceLocation Loc,
1298ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            VarDecl *Decl,
1299ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            BeginEndFunction BEF,
1300ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            const DeclarationNameInfo &NameInfo,
1301ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            LookupResult &MemberLookup,
1302ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            Expr *Range) {
1303ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  ExprResult CallExpr;
1304ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!MemberLookup.empty()) {
1305ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult MemberRef =
1306ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1307ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                       /*IsPtr=*/false, CXXScopeSpec(),
1308e4b92761b43ced611c417ae478568610f1ad7b1eAbramo Bagnara                                       /*TemplateKWLoc=*/SourceLocation(),
1309e4b92761b43ced611c417ae478568610f1ad7b1eAbramo Bagnara                                       /*FirstQualifierInScope=*/0,
1310e4b92761b43ced611c417ae478568610f1ad7b1eAbramo Bagnara                                       MemberLookup,
1311ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                       /*TemplateArgs=*/0);
1312ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (MemberRef.isInvalid())
1313ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return ExprError();
1314ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1315ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                     Loc, 0);
1316ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (CallExpr.isInvalid())
1317ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return ExprError();
1318ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  } else {
1319ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    UnresolvedSet<0> FoundNames;
1320ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1321ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // std is an associated namespace.
1322ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    UnresolvedLookupExpr *Fn =
1323ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1324ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                   NestedNameSpecifierLoc(), NameInfo,
1325ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                   /*NeedsADL=*/true, /*Overloaded=*/false,
1326ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                   FoundNames.begin(), FoundNames.end(),
1327ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                   /*LookInStdNamespace=*/true);
1328ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
13293943b1c0215da2a4171dd6c696cb75d19e5a04a9Kaelyn Uhrain                                               0, /*AllowTypoCorrection=*/false);
1330ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (CallExpr.isInvalid()) {
1331ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1332ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        << Range->getType();
1333ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return ExprError();
1334ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1335ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1336ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1337ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                            diag::err_for_range_iter_deduction_failure)) {
1338ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1339ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return ExprError();
1340ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1341ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return CallExpr;
1342ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1343ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1344ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1345ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1346ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1347ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1348ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// C++0x [stmt.ranged]:
1349ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   A range-based for statement is equivalent to
1350ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1351ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   {
1352ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     auto && __range = range-init;
1353ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     for ( auto __begin = begin-expr,
1354ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           __end = end-expr;
1355ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           __begin != __end;
1356ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///           ++__begin ) {
1357ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///       for-range-declaration = *__begin;
1358ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///       statement
1359ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///     }
1360ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///   }
1361ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith///
1362ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// The body of the loop is not available yet, since it cannot be analysed until
1363ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// we have determined the type of the for-range-declaration.
1364ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult
1365ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithSema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1366ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
1367ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           SourceLocation RParenLoc) {
1368ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!First || !Range)
1369ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1370ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1371ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1372ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  assert(DS && "first part of for range not a decl stmt");
1373ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1374ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!DS->isSingleDecl()) {
1375ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1376ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1377ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1378ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (DS->getSingleDecl()->isInvalidDecl())
1379ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1380ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1381ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1382ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1383ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1384ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Build  auto && __range = range-init
1385ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  SourceLocation RangeLoc = Range->getLocStart();
1386ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1387ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           Context.getAutoRRefDeductType(),
1388ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           "__range");
1389ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1390ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                            diag::err_for_range_deduction_failure))
1391ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1392ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1393ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  // Claim the type doesn't contain auto: we've already done the checking.
1394ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclGroupPtrTy RangeGroup =
1395ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1396ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1397ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (RangeDecl.isInvalid())
1398ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1399ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1400ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1401ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1402ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                              RParenLoc);
1403ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1404ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1405ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1406ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult
1407ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithSema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1408ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1409ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           Expr *Inc, Stmt *LoopVarDecl,
1410ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           SourceLocation RParenLoc) {
1411ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  Scope *S = getCurScope();
1412ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1413ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1414ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1415ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  QualType RangeVarType = RangeVar->getType();
1416ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1417ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1418ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1419ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1420ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  StmtResult BeginEndDecl = BeginEnd;
1421ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1422ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1423ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1424ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    SourceLocation RangeLoc = RangeVar->getLocation();
1425ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1426e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1427e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
1428e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1429e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                                VK_LValue, ColonLoc);
1430e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRangeRef.isInvalid())
1431e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
1432e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
1433e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1434e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                              VK_LValue, ColonLoc);
1435e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (EndRangeRef.isInvalid())
1436ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1437ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1438ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType AutoType = Context.getAutoDeductType();
1439ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Expr *Range = RangeVar->getInit();
1440ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (!Range)
1441ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1442ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType RangeType = Range->getType();
1443ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1444ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (RequireCompleteType(RangeLoc, RangeType,
1445ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                            PDiag(diag::err_for_range_incomplete_type)))
1446ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1447ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1448ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build auto __begin = begin-expr, __end = end-expr.
1449ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1450ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             "__begin");
1451ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1452ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           "__end");
1453ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1454ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build begin-expr and end-expr and attach to __begin and __end variables.
1455ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult BeginExpr, EndExpr;
1456ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1457ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // - if _RangeT is an array type, begin-expr and end-expr are __range and
1458ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   __range + __bound, respectively, where __bound is the array bound. If
1459ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   _RangeT is an array of unknown size or an array of incomplete type,
1460ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      //   the program is ill-formed;
1461ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1462ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // begin-expr is __range.
1463e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      BeginExpr = BeginRangeRef;
1464e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1465ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                diag::err_for_range_iter_deduction_failure)) {
1466ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1467ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
1468ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
1469ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1470ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // Find the array bound.
1471ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      ExprResult BoundExpr;
1472ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1473ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
14741dd986dff9ddfbec687975700770bb377988e9edRichard Trieu                                                 Context.getPointerDiffType(),
14751dd986dff9ddfbec687975700770bb377988e9edRichard Trieu                                                 RangeLoc));
1476ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      else if (const VariableArrayType *VAT =
1477ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith               dyn_cast<VariableArrayType>(UnqAT))
1478ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        BoundExpr = VAT->getSizeExpr();
1479ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      else {
1480ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1481ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // UnqAT is not incomplete and Range is not type-dependent.
1482b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie        llvm_unreachable("Unexpected array type in for-range");
1483ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
1484ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1485ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      // end-expr is __range + __bound.
1486e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1487ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           BoundExpr.get());
1488ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (EndExpr.isInvalid())
1489ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
1490ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1491ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                diag::err_for_range_iter_deduction_failure)) {
1492ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1493ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
1494ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
1495ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    } else {
1496ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1497ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                        ColonLoc);
1498ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1499ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                      ColonLoc);
1500ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1501ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1502ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1503ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1504ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1505ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // - if _RangeT is a class type, the unqualified-ids begin and end are
1506ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   looked up in the scope of class _RangeT as if by class member access
1507ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   lookup (3.4.5), and if either (or both) finds at least one
1508ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   declaration, begin-expr and end-expr are __range.begin() and
1509ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   __range.end(), respectively;
1510ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        LookupQualifiedName(BeginMemberLookup, D);
1511ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        LookupQualifiedName(EndMemberLookup, D);
1512ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1513ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1514ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith          Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1515ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith            << RangeType << BeginMemberLookup.empty();
1516ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith          return StmtError();
1517ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        }
1518ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      } else {
1519ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        // - otherwise, begin-expr and end-expr are begin(__range) and
1520ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   end(__range), respectively, where begin and end are looked up with
1521ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   argument-dependent lookup (3.4.2). For the purposes of this name
1522ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        //   lookup, namespace std is an associated namespace.
1523ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      }
1524ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1525ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1526ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                            BEF_begin, BeginNameInfo,
1527e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                            BeginMemberLookup,
1528e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                            BeginRangeRef.get());
1529ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (BeginExpr.isInvalid())
1530ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
1531ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1532ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1533ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                          BEF_end, EndNameInfo,
1534e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                          EndMemberLookup, EndRangeRef.get());
1535ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (EndExpr.isInvalid())
1536ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        return StmtError();
1537ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1538ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1539ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1540ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1541ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (!Context.hasSameType(BeginType, EndType)) {
1542ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1543ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        << BeginType << EndType;
1544ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1545ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1546ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1547ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1548ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    Decl *BeginEndDecls[] = { BeginVar, EndVar };
1549ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Claim the type doesn't contain auto: we've already done the checking.
1550ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    DeclGroupPtrTy BeginEndGroup =
1551ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1552ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1553ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1554e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1555e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1556ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                           VK_LValue, ColonLoc);
1557e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
1558e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
1559e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
1560ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1561ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                         VK_LValue, ColonLoc);
1562e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (EndRef.isInvalid())
1563e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
1564ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1565ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check __begin != __end expression.
1566ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1567ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           BeginRef.get(), EndRef.get());
1568ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1569ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1570ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (NotEqExpr.isInvalid()) {
1571ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1572ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (!Context.hasSameType(BeginType, EndType))
1573ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1574ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1575ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1576ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1577ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check ++__begin expression.
1578e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1579e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                VK_LValue, ColonLoc);
1580e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
1581e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
1582e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
1583ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1584ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1585ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (IncrExpr.isInvalid()) {
1586ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1587ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1588ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1589ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1590ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Build and check *__begin  expression.
1591e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1592e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek                                VK_LValue, ColonLoc);
1593e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek    if (BeginRef.isInvalid())
1594e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek      return StmtError();
1595e50b01531afcb4afc40d27720afa09613ddcdfa2Ted Kremenek
1596ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1597ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (DerefExpr.isInvalid()) {
1598ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1599ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      return StmtError();
1600ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1601ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1602ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    // Attach  *__begin  as initializer for VD.
1603ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    if (!LoopVar->isInvalidDecl()) {
1604ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1605ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                           /*TypeMayContainAuto=*/true);
1606ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith      if (LoopVar->isInvalidDecl())
1607ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1608ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    }
1609cd6f36693ed40cef8c8639c04438d865187c1f73Richard Smith  } else {
1610cd6f36693ed40cef8c8639c04438d865187c1f73Richard Smith    // The range is implicitly used as a placeholder when it is dependent.
1611cd6f36693ed40cef8c8639c04438d865187c1f73Richard Smith    RangeVar->setUsed();
1612ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  }
1613ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1614ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return Owned(new (Context) CXXForRangeStmt(RangeDS,
1615ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
1616ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             NotEqExpr.take(), IncrExpr.take(),
1617ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             LoopVarDS, /*Body=*/0, ForLoc,
1618ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith                                             ColonLoc, RParenLoc));
1619ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1620ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1621ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1622ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1623ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// body cannot be performed until after the type of the range variable is
1624ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith/// determined.
1625ad762fcdc16b9e4705b12b09d92b8c026212b906Richard SmithStmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1626ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  if (!S || !B)
1627ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith    return StmtError();
1628ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
1629625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1630625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  ForStmt->setBody(B);
1631625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
1632625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1633625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko                        diag::warn_empty_range_based_for_body);
1634625bb569df0c34feec0d52c0ec5215f21ef2e054Dmitri Gribenko
1635ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith  return S;
1636ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith}
1637ad762fcdc16b9e4705b12b09d92b8c026212b906Richard Smith
163857ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerStmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
163957ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                               SourceLocation LabelLoc,
164057ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                               LabelDecl *TheDecl) {
164157ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner  getCurFunction()->setHasBranchIntoScope();
1642ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  TheDecl->setUsed();
1643ad8dcf4a9df0e24051dc31bf9e6f3cd138a34298Chris Lattner  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
16445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
16455f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
164660d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
1647ad56d684259f706b7c0ae5ad9c23adb4f2926817Chris LattnerSema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
16489ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                            Expr *E) {
1649bbf462314b1dc8e422b7c4dd4cac47e566aedf6dEli Friedman  // Convert operand to void*
16505f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  if (!E->isTypeDependent()) {
16515f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor    QualType ETy = E->getType();
16522877998bd8db2fac1c56430a4edcfa0ce138aff9Chandler Carruth    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1653429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    ExprResult ExprRes = Owned(E);
16545f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor    AssignConvertType ConvTy =
1655429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      CheckSingleAssignmentConstraints(DestTy, ExprRes);
1656429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    if (ExprRes.isInvalid())
1657429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      return StmtError();
1658429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    E = ExprRes.take();
16592877998bd8db2fac1c56430a4edcfa0ce138aff9Chandler Carruth    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
16605f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor      return StmtError();
1661d29975fd08713eb9d1777e60536addaa62df8995Eli Friedman    E = MaybeCreateExprWithCleanups(E);
16625f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  }
1663b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
1664781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasIndirectGoto();
1665b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
16665f1b9e689fa5c101512aef99225f2afea1673449Douglas Gregor  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
16675f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
16685f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
166960d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
16701b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
16715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  Scope *S = CurScope->getContinueParent();
16725f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (!S) {
16735f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
16744cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
16755f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
16764cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
16778189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) ContinueStmt(ContinueLoc));
16785f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
16795f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
168060d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
16811b273c403734d343d720acb28f04011807c8aa56Steve NaroffSema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
16825f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  Scope *S = CurScope->getBreakParent();
16835f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (!S) {
16845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
16854cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
16865f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
16874cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
16888189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) BreakStmt(BreakLoc));
16895f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
16905f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1691dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi/// \brief Determine whether the given expression is a candidate for
1692f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// copy elision in either a return statement or a throw expression.
16935077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
1694f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// \param ReturnType If we're determining the copy elision candidate for
1695f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// a return statement, this is the return type of the function. If we're
1696f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// determining the copy elision candidate for a throw expression, this will
1697f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// be a NULL type.
16985077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
1699f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// \param E The expression being returned from the function or block, or
1700f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor/// being thrown.
17015077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
17024926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// \param AllowFunctionParameter Whether we allow function parameters to
17034926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
17044926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// we re-use this logic to determine whether we should try to move as part of
17054926d832aa2f0af9d7c00633727d49e7967eb978Douglas Gregor/// a return or throw (which does allow function parameters).
17065077c3876beeaed32280af88244e8050078619a8Douglas Gregor///
17075077c3876beeaed32280af88244e8050078619a8Douglas Gregor/// \returns The NRVO candidate variable, if the return statement may use the
17085077c3876beeaed32280af88244e8050078619a8Douglas Gregor/// NRVO, or NULL if there is no such candidate.
1709f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregorconst VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1710f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor                                             Expr *E,
1711f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor                                             bool AllowFunctionParameter) {
1712f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  QualType ExprType = E->getType();
17133c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  // - in a return statement in a function with ...
17143c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  // ... a class return type ...
1715f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  if (!ReturnType.isNull()) {
1716f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    if (!ReturnType->isRecordType())
1717f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      return 0;
1718f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    // ... the same cv-unqualified type as the function return type ...
1719f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1720f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      return 0;
1721f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  }
1722dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1723dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // ... the expression is the name of a non-volatile automatic object
1724f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  // (other than a function or catch-clause parameter)) ...
1725f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
17263c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  if (!DR)
17275077c3876beeaed32280af88244e8050078619a8Douglas Gregor    return 0;
17283c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
17293c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor  if (!VD)
17305077c3876beeaed32280af88244e8050078619a8Douglas Gregor    return 0;
1731dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
17321cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...object (other than a function or catch-clause parameter)...
17331cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getKind() != Decl::Var &&
17341cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall      !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
17351cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall    return 0;
17361cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->isExceptionVariable()) return 0;
17371cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
17381cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...automatic...
17391cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (!VD->hasLocalStorage()) return 0;
17401cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
17411cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // ...non-volatile...
17421cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getType().isVolatileQualified()) return 0;
17431cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->getType()->isReferenceType()) return 0;
17441cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
17451cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // __block variables can't be allocated in a way that permits NRVO.
17461cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->hasAttr<BlocksAttr>()) return 0;
17471cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall
17481cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // Variables with higher required alignment than their type's ABI
17491cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  // alignment cannot use NRVO.
17501cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  if (VD->hasAttr<AlignedAttr>() &&
17511cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall      Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
17521cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall    return 0;
1753dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
17541cd76e8ca8f890a4defadcae3372c025ebe7607cJohn McCall  return VD;
17553c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor}
17563c9034cb7ff1d6c1e4ecd1b44c98f553df013c7cDouglas Gregor
175707f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor/// \brief Perform the initialization of a potentially-movable value, which
175807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor/// is the result of return value.
1759cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor///
1760cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// This routine implements C++0x [class.copy]p33, which attempts to treat
1761cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// returned lvalues as rvalues in certain cases (to prefer move construction),
1762cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor/// then falls back to treating them as lvalues if that failed.
1763dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiExprResult
176407f402cff25354c5f06f307f19b0c57c09d964bdDouglas GregorSema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
176507f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                      const VarDecl *NRVOCandidate,
176607f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                      QualType ResultType,
1767bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor                                      Expr *Value,
1768bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor                                      bool AllowNRVO) {
1769cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // C++0x [class.copy]p33:
1770dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   When the criteria for elision of a copy operation are met or would
1771dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   be met save for the fact that the source object is a function
1772dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  //   parameter, and the object to be copied is designated by an lvalue,
1773cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  //   overload resolution to select the constructor for the copy is first
1774cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  //   performed as if the object were designated by an rvalue.
1775cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  ExprResult Res = ExprError();
1776bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor  if (AllowNRVO &&
1777bca01b46850f867b2f4137f25c882022b58f8471Douglas Gregor      (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
1778dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
177907f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                              Value->getType(), CK_LValueToRValue,
178007f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                              Value, VK_XValue);
1781dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1782cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    Expr *InitExpr = &AsRvalue;
1783dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    InitializationKind Kind
178407f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor      = InitializationKind::CreateCopy(Value->getLocStart(),
178507f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                       Value->getLocStart());
178607f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
1787dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1788dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    //   [...] If overload resolution fails, or if the type of the first
1789cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    //   parameter of the selected constructor is not an rvalue reference
17900099530a2288df7c2140dd8992b7310b9f6930a9NAKAMURA Takumi    //   to the object's type (possibly cv-qualified), overload resolution
1791cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    //   is performed again, considering the object as an lvalue.
1792383616cd2e61131a534afd9364ef53f643e1f834Sebastian Redl    if (Seq) {
1793cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1794cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor           StepEnd = Seq.step_end();
1795cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor           Step != StepEnd; ++Step) {
1796383616cd2e61131a534afd9364ef53f643e1f834Sebastian Redl        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
1797cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor          continue;
1798dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1799dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi        CXXConstructorDecl *Constructor
1800cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        = cast<CXXConstructorDecl>(Step->Function.Function);
1801dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1802cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        const RValueReferenceType *RRefType
180307f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor          = Constructor->getParamDecl(0)->getType()
180407f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                                 ->getAs<RValueReferenceType>();
1805dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1806cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // If we don't meet the criteria, break out now.
1807dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi        if (!RRefType ||
180807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
180907f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                            Context.getTypeDeclType(Constructor->getParent())))
1810cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor          break;
1811dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1812cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // Promote "AsRvalue" to the heap, since we now need this
1813cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // expression node to persist.
181407f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor        Value = ImplicitCastExpr::Create(Context, Value->getType(),
1815dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                                         CK_LValueToRValue, Value, 0,
181607f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                         VK_XValue);
1817dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1818cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // Complete type-checking the initialization of the return type
1819cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor        // using the constructor we found.
182007f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
1821cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor      }
1822cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor    }
1823cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  }
1824dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1825cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1826dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // above, or overload resolution failed. Either way, we need to try
1827cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  // (again) now with the return value expression as written.
1828cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  if (Res.isInvalid())
182907f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
1830dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1831cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor  return Res;
1832cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor}
1833cc15f010672a13b38104a32e3cefc7adc07ffbf7Douglas Gregor
183484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
183584b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman/// for capturing scopes.
18364eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff///
183760d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
183884b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli FriedmanSema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
183984b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  // If this is the first return we've seen, infer the return type.
184084b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
184184b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  // rules which allows multiple return statements.
184284b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
184384b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  if (CurCap->HasImplicitReturnType) {
184484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    QualType ReturnT;
1845a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor    if (RetValExp && !isa<InitListExpr>(RetValExp)) {
1846429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1847429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      if (Result.isInvalid())
1848429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley        return StmtError();
1849429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      RetValExp = Result.take();
18506a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor
185184b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      if (!RetValExp->isTypeDependent())
185284b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman        ReturnT = RetValExp->getType();
185384b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      else
185484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman        ReturnT = Context.DependentTy;
1855a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor    } else {
1856a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor      if (RetValExp) {
1857a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
1858a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // initializer list, because it is not an expression (even
1859a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        // though we represent it as one). We still deduce 'void'.
1860a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor        Diag(ReturnLoc, diag::err_lambda_return_init_list)
1861a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor          << RetValExp->getSourceRange();
1862a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor      }
1863a0c2b21e0d84ad289781e08e14148da6b8b8b76dDouglas Gregor
186484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      ReturnT = Context.VoidTy;
186584b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    }
186684b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    // We require the return types to strictly match here.
186784b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    if (!CurCap->ReturnType.isNull() &&
186884b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman        !CurCap->ReturnType->isDependentType() &&
186984b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman        !ReturnT->isDependentType() &&
187084b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman        !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
187184b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
18724e88df72e690498aeba2dc3d5089388b27be66faDouglas Gregor          << ReturnT << CurCap->ReturnType
18730bcc3d87223d7796946bfa6dd6174af900d8eba4Douglas Gregor          << (getCurLambda() != 0);
187484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      return StmtError();
1875649657e7d6c150136cae5ab22e39b9794cff80ccFariborz Jahanian    }
187684b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    CurCap->ReturnType = ReturnT;
18774eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  }
187884b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  QualType FnRetType = CurCap->ReturnType;
187984b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  assert(!FnRetType.isNull());
18804cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
1881793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
188284b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
188384b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
188484b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman      return StmtError();
188584b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    }
1886793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  } else {
1887793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
1888793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
1889793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
1890793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor      return StmtError();
1891793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor    }
1892793cd1c4cdfaafc52e2c2ad9dae959befe4bb166Douglas Gregor  }
18936c92fa75e62937f9738696840efcb258560f4568Mike Stump
18944eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // Otherwise, verify that this result type matches the previous one.  We are
18954eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // pickier with blocks than for normal functions because we don't have GCC
18964eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff  // compatibility to worry about here.
1897d963c37eb912342c8325048749e449861cf0a6e3John McCall  const VarDecl *NRVOCandidate = 0;
18980a7efe1142d241678c91bf93ee6adb51289863a4John McCall  if (FnRetType->isDependentType()) {
18990a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // Delay processing for now.  TODO: there are lots of dependent
19000a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // types we can conclusively prove aren't void.
19010a7efe1142d241678c91bf93ee6adb51289863a4John McCall  } else if (FnRetType->isVoidType()) {
19025b38a0f98e4420dae1bd3e13959bc207c97a9e98Sebastian Redl    if (RetValExp && !isa<InitListExpr>(RetValExp) &&
19034e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        !(getLangOpts().CPlusPlus &&
19040a7efe1142d241678c91bf93ee6adb51289863a4John McCall          (RetValExp->isTypeDependent() ||
19050a7efe1142d241678c91bf93ee6adb51289863a4John McCall           RetValExp->getType()->isVoidType()))) {
19064e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      if (!getLangOpts().CPlusPlus &&
19074e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian          RetValExp->getType()->isVoidType())
19089354f6aaa70e1543d122644fee0c3f834324d2fcFariborz Jahanian        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
19094e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      else {
19104e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian        Diag(ReturnLoc, diag::err_return_block_has_expr);
19114e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian        RetValExp = 0;
19124e648e4770d85febaf15ad8b7bad458bd7338ae2Fariborz Jahanian      }
19134eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff    }
19145077c3876beeaed32280af88244e8050078619a8Douglas Gregor  } else if (!RetValExp) {
19150a7efe1142d241678c91bf93ee6adb51289863a4John McCall    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
19160a7efe1142d241678c91bf93ee6adb51289863a4John McCall  } else if (!RetValExp->isTypeDependent()) {
19170a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // we have a non-void block with an expression, continue checking
19180a7efe1142d241678c91bf93ee6adb51289863a4John McCall
19190a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
19200a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
19210a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // function return.
19220a7efe1142d241678c91bf93ee6adb51289863a4John McCall
19230a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // In C++ the return statement is handled via a copy initialization.
19240a7efe1142d241678c91bf93ee6adb51289863a4John McCall    // the C version of which boils down to CheckSingleAssignmentConstraints.
19250a7efe1142d241678c91bf93ee6adb51289863a4John McCall    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
19260a7efe1142d241678c91bf93ee6adb51289863a4John McCall    InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
19270a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                                   FnRetType,
19280586520acb2f368c874943353a222be7f00c3068Fariborz Jahanian                                                          NRVOCandidate != 0);
19290a7efe1142d241678c91bf93ee6adb51289863a4John McCall    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
19300a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                     FnRetType, RetValExp);
19310a7efe1142d241678c91bf93ee6adb51289863a4John McCall    if (Res.isInvalid()) {
19320a7efe1142d241678c91bf93ee6adb51289863a4John McCall      // FIXME: Cleanup temporaries here, anyway?
19330a7efe1142d241678c91bf93ee6adb51289863a4John McCall      return StmtError();
1934c6acbc58a7aef0a3382775424c80e9534b54b2edAnders Carlsson    }
19350a7efe1142d241678c91bf93ee6adb51289863a4John McCall    RetValExp = Res.take();
19360a7efe1142d241678c91bf93ee6adb51289863a4John McCall    CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1937d963c37eb912342c8325048749e449861cf0a6e3John McCall  }
1938dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
1939d963c37eb912342c8325048749e449861cf0a6e3John McCall  if (RetValExp) {
1940d963c37eb912342c8325048749e449861cf0a6e3John McCall    CheckImplicitConversions(RetValExp, ReturnLoc);
1941d963c37eb912342c8325048749e449861cf0a6e3John McCall    RetValExp = MaybeCreateExprWithCleanups(RetValExp);
194298eb8a7a702b95183ed015706b1f1c66f5cb27a4Mike Stump  }
19430a7efe1142d241678c91bf93ee6adb51289863a4John McCall  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
19440a7efe1142d241678c91bf93ee6adb51289863a4John McCall                                                NRVOCandidate);
19454cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
1946dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // If we need to check for the named return value optimization, save the
19475077c3876beeaed32280af88244e8050078619a8Douglas Gregor  // return statement in our scope for later processing.
19484e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
19495077c3876beeaed32280af88244e8050078619a8Douglas Gregor      !CurContext->isDependentContext())
19505077c3876beeaed32280af88244e8050078619a8Douglas Gregor    FunctionScopes.back()->Returns.push_back(Result);
1951dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
19525077c3876beeaed32280af88244e8050078619a8Douglas Gregor  return Owned(Result);
19534eb206bebcdab28ababe8df55c6185cec2cdc071Steve Naroff}
19545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
195560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
19569ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1957fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor  // Check for unexpanded parameter packs.
1958fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1959fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor    return StmtError();
1960fc92137eee708b632c00a9b0934ff87aeae234a5Douglas Gregor
196184b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman  if (isa<CapturingScopeInfo>(getCurFunction()))
196284b007fae6c0cd30fa07074d34fbe2bf61fa44f9Eli Friedman    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
19634cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
1964371f258e61e1365b951b17931a3c5ac1530fd1a0Chris Lattner  QualType FnRetType;
196538ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman  QualType RelatedRetType;
1966f7c41dab1a8de29b0991e853b8822bb0d1ddc01cMike Stump  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1967371f258e61e1365b951b17931a3c5ac1530fd1a0Chris Lattner    FnRetType = FD->getResultType();
196804a67a6aa3dfdc92d57f7f8d93ba397348c868a4John McCall    if (FD->hasAttr<NoReturnAttr>() ||
196904a67a6aa3dfdc92d57f7f8d93ba397348c868a4John McCall        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
19708662587fa75d3fb04f873e265841c9314c7f5523Chris Lattner      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
197179430e9983f5e67a378fc1f50cd6278f2cea8259Eli Friedman        << FD->getDeclName();
1972926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
197338ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman    FnRetType = MD->getResultType();
1974926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1975926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor      // In the implementation of a method with a related return type, the
1976926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor      // type used to type-check the validity of return statements within the
1977926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor      // method body is a pointer to the type of the class being implemented.
197838ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
197938ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
1980926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor    }
1981926df6cfabf3eaa4afc990c097fa4619b76a9b57Douglas Gregor  } else // If we don't have a function/method context, bail.
1982c97fb9a394ce2cc5e664fcb472e93553528378adSteve Naroff    return StmtError();
19831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19845077c3876beeaed32280af88244e8050078619a8Douglas Gregor  ReturnStmt *Result = 0;
19855cf216b7fa64b933b60743b0b26053e8e7aa87beChris Lattner  if (FnRetType->isVoidType()) {
19868d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky    if (RetValExp) {
198733deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      if (isa<InitListExpr>(RetValExp)) {
198833deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // We simply never allow init lists as the return value of void
198933deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // functions. This is compatible because this was never allowed before,
199033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // so there's no legacy code to deal with.
199133deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
199233deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        int FunctionKind = 0;
199333deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        if (isa<ObjCMethodDecl>(CurDecl))
199433deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 1;
199533deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        else if (isa<CXXConstructorDecl>(CurDecl))
199633deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 2;
199733deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        else if (isa<CXXDestructorDecl>(CurDecl))
199833deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          FunctionKind = 3;
199933deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl
200033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        Diag(ReturnLoc, diag::err_return_init_list)
200133deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          << CurDecl->getDeclName() << FunctionKind
200233deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl          << RetValExp->getSourceRange();
200333deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl
200433deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        // Drop the expression.
200533deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        RetValExp = 0;
200633deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      } else if (!RetValExp->isTypeDependent()) {
20078d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        // C99 6.8.6.4p1 (ext_ since GCC warns)
20088d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        unsigned D = diag::ext_return_has_expr;
20098d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        if (RetValExp->getType()->isVoidType())
20108d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          D = diag::ext_return_has_void_expr;
20118d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        else {
20128d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          ExprResult Result = Owned(RetValExp);
20138d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          Result = IgnoredValueConversions(Result.take());
20148d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          if (Result.isInvalid())
20158d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky            return StmtError();
20168d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          RetValExp = Result.take();
20178d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          RetValExp = ImpCastExprToType(RetValExp,
20188d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky                                        Context.VoidTy, CK_ToVoid).take();
20198d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        }
20204cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
20218d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        // return (some void expression); is legal in C++.
20228d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        if (D != diag::ext_return_has_void_expr ||
20234e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie            !getLangOpts().CPlusPlus) {
20248d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2025ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth
2026ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          int FunctionKind = 0;
2027ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          if (isa<ObjCMethodDecl>(CurDecl))
2028ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 1;
2029ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          else if (isa<CXXConstructorDecl>(CurDecl))
2030ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 2;
2031ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth          else if (isa<CXXDestructorDecl>(CurDecl))
2032ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            FunctionKind = 3;
2033ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth
20348d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky          Diag(ReturnLoc, D)
2035ca0d0d4a0d6ecd256d4bf8c1a0dc183a83119833Chandler Carruth            << CurDecl->getDeclName() << FunctionKind
20368d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky            << RetValExp->getSourceRange();
20378d7946151cd15c0e7c34250c122d59b2f5027999Nick Lewycky        }
2038e878eb035b343d7d819c092102364ec9849716aeChris Lattner      }
20391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
204033deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      if (RetValExp) {
204133deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        CheckImplicitConversions(RetValExp, ReturnLoc);
204233deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
204333deb35535aebe81bed0eaf5c14f3032276a086eSebastian Redl      }
20445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    }
2045dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
20465077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
20475077c3876beeaed32280af88244e8050078619a8Douglas Gregor  } else if (!RetValExp && !FnRetType->isDependentType()) {
20483c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
20493c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    // C99 6.8.6.4p1 (ext_ since GCC warns)
20504e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
20513c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner
20523c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    if (FunctionDecl *FD = getCurFunctionDecl())
205308631c5fa053867146b5ee8be658c229f6bf127cChris Lattner      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
20543c73c41cefcfe76f36b7bed72c9f1ec195490951Chris Lattner    else
205508631c5fa053867146b5ee8be658c229f6bf127cChris Lattner      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
20565077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc);
20575077c3876beeaed32280af88244e8050078619a8Douglas Gregor  } else {
20585077c3876beeaed32280af88244e8050078619a8Douglas Gregor    const VarDecl *NRVOCandidate = 0;
20595077c3876beeaed32280af88244e8050078619a8Douglas Gregor    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
20605077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // we have a non-void function with an expression, continue checking
20615077c3876beeaed32280af88244e8050078619a8Douglas Gregor
206238ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      if (!RelatedRetType.isNull()) {
206338ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        // If we have a related result type, perform an extra conversion here.
206438ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        // FIXME: The diagnostics here don't really describe what is happening.
206538ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        InitializedEntity Entity =
206638ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman            InitializedEntity::InitializeTemporary(RelatedRetType);
206738ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman
206838ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
206938ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman                                                   RetValExp);
207038ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        if (Res.isInvalid()) {
207138ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman          // FIXME: Cleanup temporaries here, anyway?
207238ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman          return StmtError();
207338ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        }
207438ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman        RetValExp = Res.takeAs<Expr>();
207538ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman      }
207638ac243e300798e8cd9fe05888cd97beabfb94e6Eli Friedman
20775077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
20785077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
20795077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // function return.
20805077c3876beeaed32280af88244e8050078619a8Douglas Gregor
2081856d3798af7c2f7251e4a295f3da7a09ce4c62abJohn McCall      // In C++ the return statement is handled via a copy initialization,
20825077c3876beeaed32280af88244e8050078619a8Douglas Gregor      // the C version of which boils down to CheckSingleAssignmentConstraints.
2083f5d8f466c3eebaffc51468812bdcbe7f0fe4891aDouglas Gregor      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2084dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
208507f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                                                     FnRetType,
208658f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                                                            NRVOCandidate != 0);
2087dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
208807f402cff25354c5f06f307f19b0c57c09d964bdDouglas Gregor                                                       FnRetType, RetValExp);
20895077c3876beeaed32280af88244e8050078619a8Douglas Gregor      if (Res.isInvalid()) {
20905077c3876beeaed32280af88244e8050078619a8Douglas Gregor        // FIXME: Cleanup temporaries here, anyway?
20915077c3876beeaed32280af88244e8050078619a8Douglas Gregor        return StmtError();
20925077c3876beeaed32280af88244e8050078619a8Douglas Gregor      }
20934cffe2fd5c23168bc08f0453c684cbd3f79471d3Sebastian Redl
20945077c3876beeaed32280af88244e8050078619a8Douglas Gregor      RetValExp = Res.takeAs<Expr>();
2095dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi      if (RetValExp)
20965077c3876beeaed32280af88244e8050078619a8Douglas Gregor        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
209766724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor    }
2098dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2099b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall    if (RetValExp) {
2100b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall      CheckImplicitConversions(RetValExp, ReturnLoc);
21014765fa05b5652fcc4356371c2f481d0ea9a1b007John McCall      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2102b4eb64d8426c0eaa58d398961e0e74ff85063d7cJohn McCall    }
21035077c3876beeaed32280af88244e8050078619a8Douglas Gregor    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2104898574e7496ba8fd76290079d3a9d06954992734Douglas Gregor  }
2105dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2106dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  // If we need to check for the named return value optimization, save the
21075077c3876beeaed32280af88244e8050078619a8Douglas Gregor  // return statement in our scope for later processing.
21084e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
21095077c3876beeaed32280af88244e8050078619a8Douglas Gregor      !CurContext->isDependentContext())
21105077c3876beeaed32280af88244e8050078619a8Douglas Gregor    FunctionScopes.back()->Returns.push_back(Result);
2111f85e193739c953358c865005855253af4f68a497John McCall
21125077c3876beeaed32280af88244e8050078619a8Douglas Gregor  return Owned(Result);
21135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
21145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
2115810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2116810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2117810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2118810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// provide a strong guidance to not use it.
2119810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner///
2120810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// This method checks to see if the argument is an acceptable l-value and
2121810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner/// returns false if it is a case we can handle.
2122810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattnerstatic bool CheckAsmLValue(const Expr *E, Sema &S) {
2123703e39486689d6660e75f6b6de0068db031a51c7Anders Carlsson  // Type dependent expressions will be checked during instantiation.
2124703e39486689d6660e75f6b6de0068db031a51c7Anders Carlsson  if (E->isTypeDependent())
2125703e39486689d6660e75f6b6de0068db031a51c7Anders Carlsson    return false;
2126dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
21277eb0a9eb0cde8444b97f9c5b713d9be7a6f1e607John McCall  if (E->isLValue())
2128810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner    return false;  // Cool, this is an lvalue.
2129810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner
2130810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2131810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  // are supposed to allow.
2132810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
21337eb0a9eb0cde8444b97f9c5b713d9be7a6f1e607John McCall  if (E != E2 && E2->isLValue()) {
21344e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (!S.getLangOpts().HeinousExtensions)
2135810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2136810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner        << E->getSourceRange();
2137810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner    else
2138810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2139810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner        << E->getSourceRange();
2140810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner    // Accept, even if we emitted an error diagnostic.
2141810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner    return false;
2142810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  }
2143810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner
2144810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  // None of the above, just randomly invalid non-lvalue.
2145810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner  return true;
2146810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner}
2147810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner
2148ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner/// isOperandMentioned - Return true if the specified operand # is mentioned
2149ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner/// anywhere in the decomposed asm string.
2150ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattnerstatic bool isOperandMentioned(unsigned OpNo,
21512d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                         ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
2152ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2153ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2154ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    if (!Piece.isOperand()) continue;
2155ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner
2156ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    // If this is a reference to the input and if the input was the smaller
2157ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    // one, then we have to reject this asm.
2158ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    if (Piece.getOperandNo() == OpNo)
2159ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      return true;
2160ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner  }
2161ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner
2162ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner  return false;
2163ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner}
2164810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner
2165ca57b4b7658a031b74cda5ac504311998be8e343Chris LattnerStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2166ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner                              bool IsVolatile, unsigned NumOutputs,
2167ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner                              unsigned NumInputs, IdentifierInfo **Names,
2168ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner                              MultiExprArg constraints, MultiExprArg exprs,
2169ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner                              Expr *asmString, MultiExprArg clobbers,
2170ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner                              SourceLocation RParenLoc, bool MSAsm) {
21713037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl  unsigned NumClobbers = clobbers.size();
21723037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl  StringLiteral **Constraints =
21733037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl    reinterpret_cast<StringLiteral**>(constraints.get());
21749ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Expr **Exprs = exprs.get();
21759ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  StringLiteral *AsmString = cast<StringLiteral>(asmString);
21763037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
21773037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
21785f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
21791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21801708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner  // The parser verifies that there is a string literal here.
21815cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  if (!AsmString->isAscii())
21823037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
21833037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      << AsmString->getSourceRange());
21843037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
21851708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner  for (unsigned i = 0; i != NumOutputs; i++) {
21861708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner    StringLiteral *Literal = Constraints[i];
21875cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    if (!Literal->isAscii())
21883037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
21893037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl        << Literal->getSourceRange());
21903037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
21915f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef OutputName;
2192ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson    if (Names[i])
2193ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson      OutputName = Names[i]->getName();
2194ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson
2195ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
2196bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    if (!Context.getTargetInfo().validateOutputConstraint(Info))
21973037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),
2198432c86969eced2ce658b3f3f2aa7407c8864f21bChris Lattner                            diag::err_asm_invalid_output_constraint)
2199432c86969eced2ce658b3f3f2aa7407c8864f21bChris Lattner                       << Info.getConstraintStr());
22003037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
2201d04c6e23f2e10eeb9936778d67f4a1c4a14cc4f6Anders Carlsson    // Check that the output exprs are valid lvalues.
220272056a237c536ee63285ab0850cb50f299281767Eli Friedman    Expr *OutputExpr = Exprs[i];
2203810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner    if (CheckAsmLValue(OutputExpr, *this)) {
220472056a237c536ee63285ab0850cb50f299281767Eli Friedman      return StmtError(Diag(OutputExpr->getLocStart(),
2205dcd5ef12488e4c7ea844327835896ca86b609a97Chris Lattner                  diag::err_asm_invalid_lvalue_in_output)
220672056a237c536ee63285ab0850cb50f299281767Eli Friedman        << OutputExpr->getSourceRange());
220704728b7ea928b029f165fc67d32ced40e6868b31Anders Carlsson    }
22081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
220944def070435a2b5d67f0534f7a3a85a7389d60f2Chris Lattner    OutputConstraintInfos.push_back(Info);
221004728b7ea928b029f165fc67d32ced40e6868b31Anders Carlsson  }
22113037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
22125f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2213806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner
221404728b7ea928b029f165fc67d32ced40e6868b31Anders Carlsson  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
22151708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner    StringLiteral *Literal = Constraints[i];
22165cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    if (!Literal->isAscii())
22173037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
22183037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl        << Literal->getSourceRange());
22193037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
22205f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef InputName;
2221ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson    if (Names[i])
2222ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson      InputName = Names[i]->getName();
2223ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson
2224ff93dbd887e40588ed55d135037bb9287488b285Anders Carlsson    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
2225bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
22262819fa85651526d59ade4fdc9da2cadd7b132973Chris Lattner                                                NumOutputs, Info)) {
22273037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),
2228432c86969eced2ce658b3f3f2aa7407c8864f21bChris Lattner                            diag::err_asm_invalid_input_constraint)
2229432c86969eced2ce658b3f3f2aa7407c8864f21bChris Lattner                       << Info.getConstraintStr());
2230d04c6e23f2e10eeb9936778d67f4a1c4a14cc4f6Anders Carlsson    }
22313037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
223272056a237c536ee63285ab0850cb50f299281767Eli Friedman    Expr *InputExpr = Exprs[i];
22333037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
2234d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson    // Only allow void types for memory constraints.
223544def070435a2b5d67f0534f7a3a85a7389d60f2Chris Lattner    if (Info.allowsMemory() && !Info.allowsRegister()) {
2236810f6d5d6223adaab0ccf0139f40de6484ad1bb5Chris Lattner      if (CheckAsmLValue(InputExpr, *this))
223772056a237c536ee63285ab0850cb50f299281767Eli Friedman        return StmtError(Diag(InputExpr->getLocStart(),
2238d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson                              diag::err_asm_invalid_lvalue_in_input)
2239432c86969eced2ce658b3f3f2aa7407c8864f21bChris Lattner                         << Info.getConstraintStr()
224072056a237c536ee63285ab0850cb50f299281767Eli Friedman                         << InputExpr->getSourceRange());
224104728b7ea928b029f165fc67d32ced40e6868b31Anders Carlsson    }
22423037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
224344def070435a2b5d67f0534f7a3a85a7389d60f2Chris Lattner    if (Info.allowsRegister()) {
2244d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson      if (InputExpr->getType()->isVoidType()) {
224572056a237c536ee63285ab0850cb50f299281767Eli Friedman        return StmtError(Diag(InputExpr->getLocStart(),
2246d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson                              diag::err_asm_invalid_type_in_input)
22471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          << InputExpr->getType() << Info.getConstraintStr()
224872056a237c536ee63285ab0850cb50f299281767Eli Friedman          << InputExpr->getSourceRange());
2249d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson      }
2250d9fca6e3950346ea503f92f27ed0f9d8edde9febAnders Carlsson    }
22511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2252429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2253429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    if (Result.isInvalid())
2254429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      return StmtError();
22551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2256429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    Exprs[i] = Result.take();
2257806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    InputConstraintInfos.push_back(Info);
225804728b7ea928b029f165fc67d32ced40e6868b31Anders Carlsson  }
22593037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
22606fa9086043b0338d895a4cdb0ec8542530af90d7Anders Carlsson  // Check that the clobbers are valid.
22611708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner  for (unsigned i = 0; i != NumClobbers; i++) {
22621708b963a014b48103e78131f960a13ee1aa6d0cChris Lattner    StringLiteral *Literal = Clobbers[i];
22635cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    if (!Literal->isAscii())
22643037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
22653037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl        << Literal->getSourceRange());
22663037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
22675f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Clobber = Literal->getString();
22683037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
2269bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    if (!Context.getTargetInfo().isValidClobber(Clobber))
22703037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl      return StmtError(Diag(Literal->getLocStart(),
22717765934ad7e157b5fcf925792a38e01b1edbcf8aDaniel Dunbar                  diag::err_asm_unknown_register_name) << Clobber);
22726fa9086043b0338d895a4cdb0ec8542530af90d7Anders Carlsson  }
22733037ed0a27dba62e522304183718efc149e8b6d9Sebastian Redl
2274fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  AsmStmt *NS =
2275dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2276dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi                          NumOutputs, NumInputs, Names, Constraints, Exprs,
2277966146e89141804ff6492739a2a6e6592ca671c7Anders Carlsson                          AsmString, NumClobbers, Clobbers, RParenLoc);
2278fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  // Validate the asm string, ensuring it makes sense given the operands we
2279fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  // have.
22805f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2281fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  unsigned DiagOffs;
2282fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
22832ff0f42a962fec5a6300b5986297b417db173e6aChris Lattner    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
22842ff0f42a962fec5a6300b5986297b417db173e6aChris Lattner           << AsmString->getSourceRange();
2285fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner    return StmtError();
2286fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  }
22871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2288806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner  // Validate tied input operands for type mismatches.
2289806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2290806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
22911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2292806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    // If this is a tied constraint, verify that the output and input have
2293806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    // either exactly the same type, or that they are int/ptr operands with the
2294806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    // same size (int/long, int*/long, are ok etc).
2295806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    if (!Info.hasTiedOperand()) continue;
22961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2297806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    unsigned TiedTo = Info.getTiedOperand();
2298935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    unsigned InputOpNo = i+NumOutputs;
2299f69fcaeb3843297757251a19f0a6f5bbffed7f32Chris Lattner    Expr *OutputExpr = Exprs[TiedTo];
2300935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    Expr *InputExpr = Exprs[InputOpNo];
2301f45b357c0d0df99e160a6320e279ef788dd91ba6Eli Friedman
2302f45b357c0d0df99e160a6320e279ef788dd91ba6Eli Friedman    if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2303f45b357c0d0df99e160a6320e279ef788dd91ba6Eli Friedman      continue;
2304f45b357c0d0df99e160a6320e279ef788dd91ba6Eli Friedman
23057adaa18ef3be65971cd41cc61dd739baeb02af10Chris Lattner    QualType InTy = InputExpr->getType();
23067adaa18ef3be65971cd41cc61dd739baeb02af10Chris Lattner    QualType OutTy = OutputExpr->getType();
23077adaa18ef3be65971cd41cc61dd739baeb02af10Chris Lattner    if (Context.hasSameType(InTy, OutTy))
2308806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner      continue;  // All types can be tied to themselves.
23091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2310aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // Decide if the input and output are in the same domain (integer/ptr or
2311aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // floating point.
2312aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    enum AsmDomain {
2313aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      AD_Int, AD_FP, AD_Other
2314aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    } InputDomain, OutputDomain;
2315dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2316aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    if (InTy->isIntegerType() || InTy->isPointerType())
2317aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      InputDomain = AD_Int;
23180c293ea13d452c1a47a05ada5a5ee9acc69c66ccDouglas Gregor    else if (InTy->isRealFloatingType())
2319aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      InputDomain = AD_FP;
2320aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    else
2321aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      InputDomain = AD_Other;
23223351f1145aa91ddd8022fcd3ca16c219db9e8277Chris Lattner
2323aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    if (OutTy->isIntegerType() || OutTy->isPointerType())
2324aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      OutputDomain = AD_Int;
23250c293ea13d452c1a47a05ada5a5ee9acc69c66ccDouglas Gregor    else if (OutTy->isRealFloatingType())
2326aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      OutputDomain = AD_FP;
2327aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    else
2328aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      OutputDomain = AD_Other;
2329dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2330aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // They are ok if they are the same size and in the same domain.  This
2331aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // allows tying things like:
2332aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    //   void* to int*
2333aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    //   void* to int            if they are the same size.
2334aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    //   double to long double   if they are the same size.
2335dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi    //
2336aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    uint64_t OutSize = Context.getTypeSize(OutTy);
2337aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    uint64_t InSize = Context.getTypeSize(InTy);
2338aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    if (OutSize == InSize && InputDomain == OutputDomain &&
2339aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner        InputDomain != AD_Other)
2340aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      continue;
2341dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
2342aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // If the smaller input/output operand is not mentioned in the asm string,
2343f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner    // then we can promote the smaller one to a larger input and the asm string
2344f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner    // won't notice.
2345aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    bool SmallerValueMentioned = false;
2346ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner
2347ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    // If this is a reference to the input and if the input was the smaller
2348ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    // one, then we have to reject this asm.
2349935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    if (isOperandMentioned(InputOpNo, Pieces)) {
2350ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      // This is a use in the asm string of the smaller operand.  Since we
2351ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      // codegen this by promoting to a wider value, the asm will get printed
2352ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      // "wrong".
2353f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner      SmallerValueMentioned |= InSize < OutSize;
2354ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner    }
2355f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner    if (isOperandMentioned(TiedTo, Pieces)) {
2356ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      // If this is a reference to the output, and if the output is the larger
2357ca57b4b7658a031b74cda5ac504311998be8e343Chris Lattner      // value, then it's ok because we'll promote the input to the larger type.
2358f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner      SmallerValueMentioned |= OutSize < InSize;
2359806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    }
23601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2361aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // If the smaller value wasn't mentioned in the asm string, and if the
2362aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // output was a register, just extend the shorter one to the size of the
2363aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    // larger one.
2364aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner    if (!SmallerValueMentioned && InputDomain != AD_Other &&
2365aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner        OutputConstraintInfos[TiedTo].allowsRegister())
2366aab64d0b7f41ed30b15ba9210ed859424cbc7455Chris Lattner      continue;
2367f0c4d28020fb13fdbf7d6fccfab1b7b6a118ad0eChris Lattner
2368935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    // Either both of the operands were mentioned or the smaller one was
2369935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    // mentioned.  One more special case that we'll allow: if the tied input is
2370935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    // integer, unmentioned, and is a constant, then we'll allow truncating it
2371935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    // down to the size of the destination.
2372935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2373935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner        !isOperandMentioned(InputOpNo, Pieces) &&
2374935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner        InputExpr->isEvaluatable(Context)) {
23754da89c87b2b6ca31f1015ec19aae65a02971ea9aJohn McCall      CastKind castKind =
23764da89c87b2b6ca31f1015ec19aae65a02971ea9aJohn McCall        (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
23774da89c87b2b6ca31f1015ec19aae65a02971ea9aJohn McCall      InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2378935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner      Exprs[InputOpNo] = InputExpr;
2379935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner      NS->setInputExpr(i, InputExpr);
2380935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner      continue;
2381935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner    }
2382935f0f01c1ed3c2052b797ac035d57a85b78adc4Chris Lattner
2383c1f3b28004a032f4cd13721d4d884c6dcec29c31Chris Lattner    Diag(InputExpr->getLocStart(),
2384806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner         diag::err_asm_tying_incompatible_types)
23857adaa18ef3be65971cd41cc61dd739baeb02af10Chris Lattner      << InTy << OutTy << OutputExpr->getSourceRange()
2386806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner      << InputExpr->getSourceRange();
2387806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner    return StmtError();
2388806503f8c839d7f5ebf3fbf7ee848c179be76dd2Chris Lattner  }
23891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2390fb5058ef67c054296c88db18ab1b3717845cb71dChris Lattner  return Owned(NS);
2391fe795956194141c91ae555985c9b930595bff43fChris Lattner}
23923b1191d7eaf2f4984564e01ab84b6713a9d80e70Fariborz Jahanian
239360d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2394431e90e887c21c0d0d56fc12a2d359df8d53ea66Sebastian RedlSema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2395d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                           SourceLocation RParen, Decl *Parm,
23969ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                           Stmt *Body) {
2397d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  VarDecl *Var = cast_or_null<VarDecl>(Parm);
2398160b5630aa781ac348303e1ae088d27016637778Douglas Gregor  if (Var && Var->isInvalidDecl())
2399160b5630aa781ac348303e1ae088d27016637778Douglas Gregor    return StmtError();
2400dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
24019ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
24023b1191d7eaf2f4984564e01ab84b6713a9d80e70Fariborz Jahanian}
24033b1191d7eaf2f4984564e01ab84b6713a9d80e70Fariborz Jahanian
240460d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
24059ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
24069ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2407161a9c5afaafb4d527b7efba9675a8b2cbbe32e0Fariborz Jahanian}
2408bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
240960d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2410dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
24119ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                         MultiStmtArg CatchStmts, Stmt *Finally) {
24124e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().ObjCExceptions)
2413da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2414da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson
2415781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchProtectedScope();
24168f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor  unsigned NumCatchStmts = CatchStmts.size();
24179ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
24189ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                     CatchStmts.release(),
24198f5e3dd32e443768d9dbbad7191e123e6733750cDouglas Gregor                                     NumCatchStmts,
24209ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                     Finally));
2421bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian}
2422bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
242360d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
24249ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                                  Expr *Throw) {
2425d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor  if (Throw) {
2426f2dd68fb37a62571a4985c8dd05310ac90d07ef0Fariborz Jahanian    Throw = MaybeCreateExprWithCleanups(Throw);
2427429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    ExprResult Result = DefaultLvalueConversion(Throw);
2428429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    if (Result.isInvalid())
2429429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley      return StmtError();
24305e3c67b4bd894a926282d24b4d0cbc0e123c9f4aJohn McCall
2431429bb276991ff2dbc7c5b438828b9b7737cb15ebJohn Wiegley    Throw = Result.take();
2432d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    QualType ThrowType = Throw->getType();
2433d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    // Make sure the expression type is an ObjC pointer or "void *".
2434d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    if (!ThrowType->isDependentType() &&
2435d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor        !ThrowType->isObjCObjectPointerType()) {
2436d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor      const PointerType *PT = ThrowType->getAs<PointerType>();
2437d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor      if (!PT || !PT->getPointeeType()->isVoidType())
2438d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2439d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor                         << Throw->getType() << Throw->getSourceRange());
2440d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor    }
2441d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor  }
2442dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi
24439ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2444d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor}
2445d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor
244660d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2447dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA TakumiSema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2448d1377b25a36adfe6604f78cbd3a23a07cf0f29e6Douglas Gregor                           Scope *CurScope) {
24494e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().ObjCExceptions)
2450da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2451da4b7cf09ebfd4e4098b516081fa9dae2f5c99e0Anders Carlsson
24529ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  if (!Throw) {
2453e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    // @throw without an expression designates a rethrow (which much occur
2454e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    // in the context of an @catch clause).
2455e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    Scope *AtCatchParent = CurScope;
2456e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2457e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff      AtCatchParent = AtCatchParent->getParent();
2458e21dd6ffef4585fa43cd3586ed971217d65bf56cSteve Naroff    if (!AtCatchParent)
24594ab2414f297fab1b290e77bfc3b049ccf45eda81Steve Naroff      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2460dfbb02a16ac8c764b5ba1742450513d6212d2f9fNAKAMURA Takumi  }
2461f2dd68fb37a62571a4985c8dd05310ac90d07ef0Fariborz Jahanian
24629ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return BuildObjCAtThrowStmt(AtLoc, Throw);
246339f8f159c488a900e5958d5aab3e467af9ec8a2bFariborz Jahanian}
2464bd49a647afd9cc534fef13cadf652d4e9c396e2bFariborz Jahanian
246507524039dce5c820f111a1b3f772b4261f004b4aJohn McCallExprResult
246607524039dce5c820f111a1b3f772b4261f004b4aJohn McCallSema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
246707524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  ExprResult result = DefaultLvalueConversion(operand);
246807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  if (result.isInvalid())
246907524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    return ExprError();
247007524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  operand = result.take();
24715e3c67b4bd894a926282d24b4d0cbc0e123c9f4aJohn McCall
2472a868a203a18571d091e5d226f5f100d4440f3d94Chris Lattner  // Make sure the expression type is an ObjC pointer or "void *".
247307524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  QualType type = operand->getType();
247407524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  if (!type->isDependentType() &&
247507524039dce5c820f111a1b3f772b4261f004b4aJohn McCall      !type->isObjCObjectPointerType()) {
247607524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    const PointerType *pointerType = type->getAs<PointerType>();
247707524039dce5c820f111a1b3f772b4261f004b4aJohn McCall    if (!pointerType || !pointerType->getPointeeType()->isVoidType())
247807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall      return Diag(atLoc, diag::error_objc_synchronized_expects_object)
247907524039dce5c820f111a1b3f772b4261f004b4aJohn McCall               << type << operand->getSourceRange();
2480a868a203a18571d091e5d226f5f100d4440f3d94Chris Lattner  }
24811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
248207524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  // The operand to @synchronized is a full-expression.
248307524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  return MaybeCreateExprWithCleanups(operand);
248407524039dce5c820f111a1b3f772b4261f004b4aJohn McCall}
248507524039dce5c820f111a1b3f772b4261f004b4aJohn McCall
248607524039dce5c820f111a1b3f772b4261f004b4aJohn McCallStmtResult
248707524039dce5c820f111a1b3f772b4261f004b4aJohn McCallSema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
248807524039dce5c820f111a1b3f772b4261f004b4aJohn McCall                                  Stmt *SyncBody) {
248907524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  // We can't jump into or indirect-jump out of a @synchronized block.
249007524039dce5c820f111a1b3f772b4261f004b4aJohn McCall  getCurFunction()->setHasBranchProtectedScope();
24919ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2492fa3ee8e6776634caf064ba5928ca7699d317a280Fariborz Jahanian}
24934b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl
24944b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
24954b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl/// and creates a proper catch handler from them.
249660d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
2497d226f65006733ed7f709c3174f22ce33391cb58fJohn McCallSema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
24989ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                         Stmt *HandlerBlock) {
24994b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl  // There's nothing to test that ActOnExceptionDecl didn't already test.
25008189cde56b4f6f938cd65f53c932fe1860d0204cTed Kremenek  return Owned(new (Context) CXXCatchStmt(CatchLoc,
2501d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall                                          cast_or_null<VarDecl>(ExDecl),
25029ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                          HandlerBlock));
25034b07b2968f87f3cd5a3d8c76145f1cbfd718d42dSebastian Redl}
25048351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
2505f85e193739c953358c865005855253af4f68a497John McCallStmtResult
2506f85e193739c953358c865005855253af4f68a497John McCallSema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2507f85e193739c953358c865005855253af4f68a497John McCall  getCurFunction()->setHasBranchProtectedScope();
2508f85e193739c953358c865005855253af4f68a497John McCall  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2509f85e193739c953358c865005855253af4f68a497John McCall}
2510f85e193739c953358c865005855253af4f68a497John McCall
25113c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohmannamespace {
25123c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman
2513c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redlclass TypeWithHandler {
2514c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  QualType t;
2515c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  CXXCatchStmt *stmt;
2516c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redlpublic:
2517c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2518c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  : t(type), stmt(statement) {}
2519c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
25200953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  // An arbitrary order is fine as long as it places identical
25210953e767ff7817f97b3ab20896b229891eeff45bJohn McCall  // types next to each other.
2522c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  bool operator<(const TypeWithHandler &y) const {
25230953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2524c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return true;
25250953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2526c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return false;
2527c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    else
2528c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2529c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
25301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2531c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  bool operator==(const TypeWithHandler& other) const {
25320953e767ff7817f97b3ab20896b229891eeff45bJohn McCall    return t == other.t;
2533c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
25341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2535c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  CXXCatchStmt *getCatchStmt() const { return stmt; }
2536c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  SourceLocation getTypeSpecStartLoc() const {
2537c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2538c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
2539c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl};
2540c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
25413c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman}
25423c46e8db99196179b30e7ac5c20c4efd5f3926d7Dan Gohman
25438351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
25448351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl/// handlers and creates a try statement from them.
254560d7b3a319d84d688752be3870615ac0f111fb16John McCallStmtResult
25469ae2f076ca5ab1feb3ba95629099ec2319833701John McCallSema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
25478351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl                       MultiStmtArg RawHandlers) {
2548729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson  // Don't report an error if 'try' is used in system headers.
25494e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!getLangOpts().CXXExceptions &&
2550729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson      !getSourceManager().isInSystemHeader(TryLoc))
2551729b853f4bfa83e53c638a06a9dccf83b4e1f720Anders Carlsson      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
25527f11d9cf5df1f8ce82af46eabc4ec5cec7d580b0Anders Carlsson
25538351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  unsigned NumHandlers = RawHandlers.size();
25548351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  assert(NumHandlers > 0 &&
25558351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl         "The parser shouldn't call this if there are no handlers.");
25569ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  Stmt **Handlers = RawHandlers.get();
25578351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
25585f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TypeWithHandler, 8> TypesWithHandlers;
25591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
25601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (unsigned i = 0; i < NumHandlers; ++i) {
25615f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
2562c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    if (!Handler->getExceptionDecl()) {
2563c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      if (i < NumHandlers - 1)
2564c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        return StmtError(Diag(Handler->getLocStart(),
2565c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl                              diag::err_early_catch_all));
25661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2567c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      continue;
2568c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    }
25691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2570c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    const QualType CaughtType = Handler->getCaughtType();
2571c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2572c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2573c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  }
2574c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl
2575c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  // Detect handlers for the same type as an earlier one.
2576c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl  if (NumHandlers > 1) {
2577c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
25781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2579c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    TypeWithHandler prev = TypesWithHandlers[0];
2580c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2581c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      TypeWithHandler curr = TypesWithHandlers[i];
25821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2583c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      if (curr == prev) {
2584c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        Diag(curr.getTypeSpecStartLoc(),
2585c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl             diag::warn_exception_caught_by_earlier_handler)
2586c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl          << curr.getCatchStmt()->getCaughtType().getAsString();
2587c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl        Diag(prev.getTypeSpecStartLoc(),
2588c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl             diag::note_previous_exception_handler)
2589c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl          << prev.getCatchStmt()->getCaughtType().getAsString();
2590c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      }
25911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2592c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl      prev = curr;
2593c447aba04527a71d254b151f79f444d1cbe83ce9Sebastian Redl    }
25948351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  }
25951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2596781472fe99a120098c631b0cbe33c89f8cef5e70John McCall  getCurFunction()->setHasBranchProtectedScope();
2597b60a77e453d32db0ab1914d28e175c2defc0eb65John McCall
25988351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // FIXME: We should detect handlers that cannot catch anything because an
25998351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // earlier handler catches a superclass. Need to find a method that is not
26008351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // quadratic for this.
26018351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // Neither of these are explicitly forbidden, but every compiler detects them
26028351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl  // and warns.
26038351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl
26049ae2f076ca5ab1feb3ba95629099ec2319833701John McCall  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2605a1a396df16c02b22983b5c9592022fd9237d4866Sam Weinig                                  Handlers, NumHandlers));
26068351da06ca3082dfd49dd8e3c1785a986920f57cSebastian Redl}
260728bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
260828bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
260928bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHTryBlock(bool IsCXXTry,
261028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       SourceLocation TryLoc,
261128bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       Stmt *TryBlock,
261228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                       Stmt *Handler) {
261328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(TryBlock && Handler);
261428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
261528bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  getCurFunction()->setHasBranchProtectedScope();
261628bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
261728bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
261828bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
261928bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
262028bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
262128bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHExceptBlock(SourceLocation Loc,
262228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                          Expr *FilterExpr,
262328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                          Stmt *Block) {
262428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(FilterExpr && Block);
262528bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
262628bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  if(!FilterExpr->getType()->isIntegerType()) {
262758f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet    return StmtError(Diag(FilterExpr->getExprLoc(),
262858f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                     diag::err_filter_expression_integral)
262958f14c012e5d739b09532bb12645dc161f88cfcfFrancois Pichet                     << FilterExpr->getType());
263028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  }
263128bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
263228bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
263328bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
263428bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley
263528bbe4b8acc338476fe0825769b41fb32b423c72John WiegleyStmtResult
263628bbe4b8acc338476fe0825769b41fb32b423c72John WiegleySema::ActOnSEHFinallyBlock(SourceLocation Loc,
263728bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley                           Stmt *Block) {
263828bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  assert(Block);
263928bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
264028bbe4b8acc338476fe0825769b41fb32b423c72John Wiegley}
2641ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
2642ba0513de93d2fab6db5ab30b6927209fcc883078Douglas GregorStmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2643ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            bool IsIfExists,
2644ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            NestedNameSpecifierLoc QualifierLoc,
2645ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            DeclarationNameInfo NameInfo,
2646ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            Stmt *Nested)
2647ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor{
2648ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2649ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                             QualifierLoc, NameInfo,
2650ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                             cast<CompoundStmt>(Nested));
2651ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor}
2652ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
2653ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor
2654ba0513de93d2fab6db5ab30b6927209fcc883078Douglas GregorStmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2655ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            bool IsIfExists,
2656ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            CXXScopeSpec &SS,
2657ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            UnqualifiedId &Name,
2658ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                            Stmt *Nested) {
2659ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2660ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    SS.getWithLocInContext(Context),
2661ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    GetNameFromUnqualifiedId(Name),
2662ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor                                    Nested);
2663ba0513de93d2fab6db5ab30b6927209fcc883078Douglas Gregor}
2664