1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/Sema/ScopeInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 using namespace clang
;
33 StmtResult
Sema::ActOnExprStmt(FullExprArg expr
) {
35 if (!E
) // FIXME: FullExprArg has no error state?
38 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
39 // void expression for its side effects. Conversion to void allows any
40 // operand, even incomplete types.
42 // Same thing in for stmt first clause (when expr) and third clause.
43 return Owned(static_cast<Stmt
*>(E
));
47 StmtResult
Sema::ActOnNullStmt(SourceLocation SemiLoc
, bool LeadingEmptyMacro
) {
48 return Owned(new (Context
) NullStmt(SemiLoc
, LeadingEmptyMacro
));
51 StmtResult
Sema::ActOnDeclStmt(DeclGroupPtrTy dg
, SourceLocation StartLoc
,
52 SourceLocation EndLoc
) {
53 DeclGroupRef DG
= dg
.getAsVal
<DeclGroupRef
>();
55 // If we have an invalid decl, just return an error.
56 if (DG
.isNull()) return StmtError();
58 return Owned(new (Context
) DeclStmt(DG
, StartLoc
, EndLoc
));
61 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg
) {
62 DeclGroupRef DG
= dg
.getAsVal
<DeclGroupRef
>();
64 // If we have an invalid decl, just return.
65 if (DG
.isNull() || !DG
.isSingleDecl()) return;
66 // suppress any potential 'unused variable' warning.
67 DG
.getSingleDecl()->setUsed();
70 void Sema::DiagnoseUnusedExprResult(const Stmt
*S
) {
71 if (const LabelStmt
*Label
= dyn_cast_or_null
<LabelStmt
>(S
))
72 return DiagnoseUnusedExprResult(Label
->getSubStmt());
74 const Expr
*E
= dyn_cast_or_null
<Expr
>(S
);
78 if (E
->isBoundMemberFunction(Context
)) {
79 Diag(E
->getLocStart(), diag::err_invalid_use_of_bound_member_func
)
80 << E
->getSourceRange();
86 if (!E
->isUnusedResultAWarning(Loc
, R1
, R2
, Context
))
89 // Okay, we have an unused result. Depending on what the base expression is,
90 // we might want to make a more specific diagnostic. Check for one of these
92 unsigned DiagID
= diag::warn_unused_expr
;
93 if (const ExprWithCleanups
*Temps
= dyn_cast
<ExprWithCleanups
>(E
))
94 E
= Temps
->getSubExpr();
96 E
= E
->IgnoreParenImpCasts();
97 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
98 if (E
->getType()->isVoidType())
101 // If the callee has attribute pure, const, or warn_unused_result, warn with
102 // a more specific message to make it clear what is happening.
103 if (const Decl
*FD
= CE
->getCalleeDecl()) {
104 if (FD
->getAttr
<WarnUnusedResultAttr
>()) {
105 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "warn_unused_result";
108 if (FD
->getAttr
<PureAttr
>()) {
109 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "pure";
112 if (FD
->getAttr
<ConstAttr
>()) {
113 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "const";
117 } else if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(E
)) {
118 const ObjCMethodDecl
*MD
= ME
->getMethodDecl();
119 if (MD
&& MD
->getAttr
<WarnUnusedResultAttr
>()) {
120 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "warn_unused_result";
123 } else if (isa
<ObjCPropertyRefExpr
>(E
)) {
124 DiagID
= diag::warn_unused_property_expr
;
125 } else if (const CXXFunctionalCastExpr
*FC
126 = dyn_cast
<CXXFunctionalCastExpr
>(E
)) {
127 if (isa
<CXXConstructExpr
>(FC
->getSubExpr()) ||
128 isa
<CXXTemporaryObjectExpr
>(FC
->getSubExpr()))
131 // Diagnose "(void*) blah" as a typo for "(void) blah".
132 else if (const CStyleCastExpr
*CE
= dyn_cast
<CStyleCastExpr
>(E
)) {
133 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
134 QualType T
= TI
->getType();
136 // We really do want to use the non-canonical type here.
137 if (T
== Context
.VoidPtrTy
) {
138 PointerTypeLoc TL
= cast
<PointerTypeLoc
>(TI
->getTypeLoc());
140 Diag(Loc
, diag::warn_unused_voidptr
)
141 << FixItHint::CreateRemoval(TL
.getStarLoc());
146 DiagRuntimeBehavior(Loc
, PDiag(DiagID
) << R1
<< R2
);
150 Sema::ActOnCompoundStmt(SourceLocation L
, SourceLocation R
,
151 MultiStmtArg elts
, bool isStmtExpr
) {
152 unsigned NumElts
= elts
.size();
153 Stmt
**Elts
= reinterpret_cast<Stmt
**>(elts
.release());
154 // If we're in C89 mode, check that we don't have any decls after stmts. If
155 // so, emit an extension diagnostic.
156 if (!getLangOptions().C99
&& !getLangOptions().CPlusPlus
) {
157 // Note that __extension__ can be around a decl.
159 // Skip over all declarations.
160 for (; i
!= NumElts
&& isa
<DeclStmt
>(Elts
[i
]); ++i
)
163 // We found the end of the list or a statement. Scan for another declstmt.
164 for (; i
!= NumElts
&& !isa
<DeclStmt
>(Elts
[i
]); ++i
)
168 Decl
*D
= *cast
<DeclStmt
>(Elts
[i
])->decl_begin();
169 Diag(D
->getLocation(), diag::ext_mixed_decls_code
);
172 // Warn about unused expressions in statements.
173 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
174 // Ignore statements that are last in a statement expression.
175 if (isStmtExpr
&& i
== NumElts
- 1)
178 DiagnoseUnusedExprResult(Elts
[i
]);
181 return Owned(new (Context
) CompoundStmt(Context
, Elts
, NumElts
, L
, R
));
185 Sema::ActOnCaseStmt(SourceLocation CaseLoc
, Expr
*LHSVal
,
186 SourceLocation DotDotDotLoc
, Expr
*RHSVal
,
187 SourceLocation ColonLoc
) {
188 assert((LHSVal
!= 0) && "missing expression in case statement");
190 // C99 6.8.4.2p3: The expression shall be an integer constant.
191 // However, GCC allows any evaluatable integer expression.
192 if (!LHSVal
->isTypeDependent() && !LHSVal
->isValueDependent() &&
193 VerifyIntegerConstantExpression(LHSVal
))
196 // GCC extension: The expression shall be an integer constant.
198 if (RHSVal
&& !RHSVal
->isTypeDependent() && !RHSVal
->isValueDependent() &&
199 VerifyIntegerConstantExpression(RHSVal
)) {
200 RHSVal
= 0; // Recover by just forgetting about it.
203 if (getCurFunction()->SwitchStack
.empty()) {
204 Diag(CaseLoc
, diag::err_case_not_in_switch
);
208 CaseStmt
*CS
= new (Context
) CaseStmt(LHSVal
, RHSVal
, CaseLoc
, DotDotDotLoc
,
210 getCurFunction()->SwitchStack
.back()->addSwitchCase(CS
);
214 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
215 void Sema::ActOnCaseStmtBody(Stmt
*caseStmt
, Stmt
*SubStmt
) {
216 CaseStmt
*CS
= static_cast<CaseStmt
*>(caseStmt
);
217 CS
->setSubStmt(SubStmt
);
221 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc
, SourceLocation ColonLoc
,
222 Stmt
*SubStmt
, Scope
*CurScope
) {
223 if (getCurFunction()->SwitchStack
.empty()) {
224 Diag(DefaultLoc
, diag::err_default_not_in_switch
);
225 return Owned(SubStmt
);
228 DefaultStmt
*DS
= new (Context
) DefaultStmt(DefaultLoc
, ColonLoc
, SubStmt
);
229 getCurFunction()->SwitchStack
.back()->addSwitchCase(DS
);
234 Sema::ActOnLabelStmt(SourceLocation IdentLoc
, LabelDecl
*TheDecl
,
235 SourceLocation ColonLoc
, Stmt
*SubStmt
) {
237 // If the label was multiply defined, reject it now.
238 if (TheDecl
->getStmt()) {
239 Diag(IdentLoc
, diag::err_redefinition_of_label
) << TheDecl
->getDeclName();
240 Diag(TheDecl
->getLocation(), diag::note_previous_definition
);
241 return Owned(SubStmt
);
244 // Otherwise, things are good. Fill in the declaration and return it.
245 TheDecl
->setLocation(IdentLoc
);
247 LabelStmt
*LS
= new (Context
) LabelStmt(IdentLoc
, TheDecl
, SubStmt
);
248 TheDecl
->setStmt(LS
);
249 TheDecl
->setLocation(IdentLoc
);
254 Sema::ActOnIfStmt(SourceLocation IfLoc
, FullExprArg CondVal
, Decl
*CondVar
,
255 Stmt
*thenStmt
, SourceLocation ElseLoc
,
257 ExprResult
CondResult(CondVal
.release());
259 VarDecl
*ConditionVar
= 0;
261 ConditionVar
= cast
<VarDecl
>(CondVar
);
262 CondResult
= CheckConditionVariable(ConditionVar
, IfLoc
, true);
263 if (CondResult
.isInvalid())
266 Expr
*ConditionExpr
= CondResult
.takeAs
<Expr
>();
270 DiagnoseUnusedExprResult(thenStmt
);
272 // Warn if the if block has a null body without an else value.
273 // this helps prevent bugs due to typos, such as
278 if (NullStmt
* stmt
= dyn_cast
<NullStmt
>(thenStmt
))
279 // But do not warn if the body is a macro that expands to nothing, e.g:
285 if (!stmt
->hasLeadingEmptyMacro())
286 Diag(stmt
->getSemiLoc(), diag::warn_empty_if_body
);
289 DiagnoseUnusedExprResult(elseStmt
);
291 return Owned(new (Context
) IfStmt(Context
, IfLoc
, ConditionVar
, ConditionExpr
,
292 thenStmt
, ElseLoc
, elseStmt
));
295 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
296 /// the specified width and sign. If an overflow occurs, detect it and emit
297 /// the specified diagnostic.
298 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt
&Val
,
299 unsigned NewWidth
, bool NewSign
,
302 // Perform a conversion to the promoted condition type if needed.
303 if (NewWidth
> Val
.getBitWidth()) {
304 // If this is an extension, just do it.
305 Val
= Val
.extend(NewWidth
);
306 Val
.setIsSigned(NewSign
);
308 // If the input was signed and negative and the output is
309 // unsigned, don't bother to warn: this is implementation-defined
311 // FIXME: Introduce a second, default-ignored warning for this case?
312 } else if (NewWidth
< Val
.getBitWidth()) {
313 // If this is a truncation, check for overflow.
314 llvm::APSInt
ConvVal(Val
);
315 ConvVal
= ConvVal
.trunc(NewWidth
);
316 ConvVal
.setIsSigned(NewSign
);
317 ConvVal
= ConvVal
.extend(Val
.getBitWidth());
318 ConvVal
.setIsSigned(Val
.isSigned());
320 Diag(Loc
, DiagID
) << Val
.toString(10) << ConvVal
.toString(10);
322 // Regardless of whether a diagnostic was emitted, really do the
324 Val
= Val
.trunc(NewWidth
);
325 Val
.setIsSigned(NewSign
);
326 } else if (NewSign
!= Val
.isSigned()) {
327 // Convert the sign to match the sign of the condition. This can cause
328 // overflow as well: unsigned(INTMIN)
329 // We don't diagnose this overflow, because it is implementation-defined
331 // FIXME: Introduce a second, default-ignored warning for this case?
332 llvm::APSInt
OldVal(Val
);
333 Val
.setIsSigned(NewSign
);
338 struct CaseCompareFunctor
{
339 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
340 const llvm::APSInt
&RHS
) {
341 return LHS
.first
< RHS
;
343 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
344 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
345 return LHS
.first
< RHS
.first
;
347 bool operator()(const llvm::APSInt
&LHS
,
348 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
349 return LHS
< RHS
.first
;
354 /// CmpCaseVals - Comparison predicate for sorting case values.
356 static bool CmpCaseVals(const std::pair
<llvm::APSInt
, CaseStmt
*>& lhs
,
357 const std::pair
<llvm::APSInt
, CaseStmt
*>& rhs
) {
358 if (lhs
.first
< rhs
.first
)
361 if (lhs
.first
== rhs
.first
&&
362 lhs
.second
->getCaseLoc().getRawEncoding()
363 < rhs
.second
->getCaseLoc().getRawEncoding())
368 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
370 static bool CmpEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
371 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
373 return lhs
.first
< rhs
.first
;
376 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
378 static bool EqEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
379 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
381 return lhs
.first
== rhs
.first
;
384 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
385 /// potentially integral-promoted expression @p expr.
386 static QualType
GetTypeBeforeIntegralPromotion(const Expr
* expr
) {
387 if (const CastExpr
*ImplicitCast
= dyn_cast
<ImplicitCastExpr
>(expr
)) {
388 const Expr
*ExprBeforePromotion
= ImplicitCast
->getSubExpr();
389 QualType TypeBeforePromotion
= ExprBeforePromotion
->getType();
390 if (TypeBeforePromotion
->isIntegralOrEnumerationType()) {
391 return TypeBeforePromotion
;
394 return expr
->getType();
398 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc
, Expr
*Cond
,
400 ExprResult CondResult
;
402 VarDecl
*ConditionVar
= 0;
404 ConditionVar
= cast
<VarDecl
>(CondVar
);
405 CondResult
= CheckConditionVariable(ConditionVar
, SourceLocation(), false);
406 if (CondResult
.isInvalid())
409 Cond
= CondResult
.release();
416 = ConvertToIntegralOrEnumerationType(SwitchLoc
, Cond
,
417 PDiag(diag::err_typecheck_statement_requires_integer
),
418 PDiag(diag::err_switch_incomplete_class_type
)
419 << Cond
->getSourceRange(),
420 PDiag(diag::err_switch_explicit_conversion
),
421 PDiag(diag::note_switch_conversion
),
422 PDiag(diag::err_switch_multiple_conversions
),
423 PDiag(diag::note_switch_conversion
),
425 if (CondResult
.isInvalid()) return StmtError();
426 Cond
= CondResult
.take();
429 CheckImplicitConversions(Cond
, SwitchLoc
);
430 CondResult
= MaybeCreateExprWithCleanups(Cond
);
431 if (CondResult
.isInvalid())
433 Cond
= CondResult
.take();
436 getCurFunction()->setHasBranchIntoScope();
438 SwitchStmt
*SS
= new (Context
) SwitchStmt(Context
, ConditionVar
, Cond
);
439 getCurFunction()->SwitchStack
.push_back(SS
);
443 static void AdjustAPSInt(llvm::APSInt
&Val
, unsigned BitWidth
, bool IsSigned
) {
444 if (Val
.getBitWidth() < BitWidth
)
445 Val
= Val
.extend(BitWidth
);
446 else if (Val
.getBitWidth() > BitWidth
)
447 Val
= Val
.trunc(BitWidth
);
448 Val
.setIsSigned(IsSigned
);
452 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc
, Stmt
*Switch
,
454 SwitchStmt
*SS
= cast
<SwitchStmt
>(Switch
);
455 assert(SS
== getCurFunction()->SwitchStack
.back() &&
456 "switch stack missing push/pop!");
458 SS
->setBody(BodyStmt
, SwitchLoc
);
459 getCurFunction()->SwitchStack
.pop_back();
461 if (SS
->getCond() == 0)
464 Expr
*CondExpr
= SS
->getCond();
465 Expr
*CondExprBeforePromotion
= CondExpr
;
466 QualType CondTypeBeforePromotion
=
467 GetTypeBeforeIntegralPromotion(CondExpr
);
469 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
470 UsualUnaryConversions(CondExpr
);
471 QualType CondType
= CondExpr
->getType();
472 SS
->setCond(CondExpr
);
475 // Integral promotions are performed (on the switch condition).
477 // A case value unrepresentable by the original switch condition
478 // type (before the promotion) doesn't make sense, even when it can
479 // be represented by the promoted type. Therefore we need to find
480 // the pre-promotion type of the switch condition.
481 if (!CondExpr
->isTypeDependent()) {
482 // We have already converted the expression to an integral or enumeration
483 // type, when we started the switch statement. If we don't have an
484 // appropriate type now, just return an error.
485 if (!CondType
->isIntegralOrEnumerationType())
488 if (CondExpr
->isKnownToHaveBooleanValue()) {
489 // switch(bool_expr) {...} is often a programmer error, e.g.
490 // switch(n && mask) { ... } // Doh - should be "n & mask".
491 // One can always use an if statement instead of switch(bool_expr).
492 Diag(SwitchLoc
, diag::warn_bool_switch_condition
)
493 << CondExpr
->getSourceRange();
497 // Get the bitwidth of the switched-on value before promotions. We must
498 // convert the integer case values to this width before comparison.
499 bool HasDependentValue
500 = CondExpr
->isTypeDependent() || CondExpr
->isValueDependent();
502 = HasDependentValue
? 0
503 : static_cast<unsigned>(Context
.getTypeSize(CondTypeBeforePromotion
));
504 bool CondIsSigned
= CondTypeBeforePromotion
->isSignedIntegerType();
506 // Accumulate all of the case values in a vector so that we can sort them
507 // and detect duplicates. This vector contains the APInt for the case after
508 // it has been converted to the condition type.
509 typedef llvm::SmallVector
<std::pair
<llvm::APSInt
, CaseStmt
*>, 64> CaseValsTy
;
512 // Keep track of any GNU case ranges we see. The APSInt is the low value.
513 typedef std::vector
<std::pair
<llvm::APSInt
, CaseStmt
*> > CaseRangesTy
;
514 CaseRangesTy CaseRanges
;
516 DefaultStmt
*TheDefaultStmt
= 0;
518 bool CaseListIsErroneous
= false;
520 for (SwitchCase
*SC
= SS
->getSwitchCaseList(); SC
&& !HasDependentValue
;
521 SC
= SC
->getNextSwitchCase()) {
523 if (DefaultStmt
*DS
= dyn_cast
<DefaultStmt
>(SC
)) {
524 if (TheDefaultStmt
) {
525 Diag(DS
->getDefaultLoc(), diag::err_multiple_default_labels_defined
);
526 Diag(TheDefaultStmt
->getDefaultLoc(), diag::note_duplicate_case_prev
);
528 // FIXME: Remove the default statement from the switch block so that
529 // we'll return a valid AST. This requires recursing down the AST and
530 // finding it, not something we are set up to do right now. For now,
531 // just lop the entire switch stmt out of the AST.
532 CaseListIsErroneous
= true;
537 CaseStmt
*CS
= cast
<CaseStmt
>(SC
);
539 // We already verified that the expression has a i-c-e value (C99
540 // 6.8.4.2p3) - get that value now.
541 Expr
*Lo
= CS
->getLHS();
543 if (Lo
->isTypeDependent() || Lo
->isValueDependent()) {
544 HasDependentValue
= true;
548 llvm::APSInt LoVal
= Lo
->EvaluateAsInt(Context
);
550 // Convert the value to the same width/sign as the condition.
551 ConvertIntegerToTypeWarnOnOverflow(LoVal
, CondWidth
, CondIsSigned
,
553 diag::warn_case_value_overflow
);
555 // If the LHS is not the same type as the condition, insert an implicit
557 ImpCastExprToType(Lo
, CondType
, CK_IntegralCast
);
560 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
562 if (CS
->getRHS()->isTypeDependent() ||
563 CS
->getRHS()->isValueDependent()) {
564 HasDependentValue
= true;
567 CaseRanges
.push_back(std::make_pair(LoVal
, CS
));
569 CaseVals
.push_back(std::make_pair(LoVal
, CS
));
573 if (!HasDependentValue
) {
574 // If we don't have a default statement, check whether the
575 // condition is constant.
576 llvm::APSInt ConstantCondValue
;
577 bool HasConstantCond
= false;
578 bool ShouldCheckConstantCond
= false;
579 if (!HasDependentValue
&& !TheDefaultStmt
) {
580 Expr::EvalResult Result
;
581 HasConstantCond
= CondExprBeforePromotion
->Evaluate(Result
, Context
);
582 if (HasConstantCond
) {
583 assert(Result
.Val
.isInt() && "switch condition evaluated to non-int");
584 ConstantCondValue
= Result
.Val
.getInt();
585 ShouldCheckConstantCond
= true;
587 assert(ConstantCondValue
.getBitWidth() == CondWidth
&&
588 ConstantCondValue
.isSigned() == CondIsSigned
);
592 // Sort all the scalar case values so we can easily detect duplicates.
593 std::stable_sort(CaseVals
.begin(), CaseVals
.end(), CmpCaseVals
);
595 if (!CaseVals
.empty()) {
596 for (unsigned i
= 0, e
= CaseVals
.size(); i
!= e
; ++i
) {
597 if (ShouldCheckConstantCond
&&
598 CaseVals
[i
].first
== ConstantCondValue
)
599 ShouldCheckConstantCond
= false;
601 if (i
!= 0 && CaseVals
[i
].first
== CaseVals
[i
-1].first
) {
602 // If we have a duplicate, report it.
603 Diag(CaseVals
[i
].second
->getLHS()->getLocStart(),
604 diag::err_duplicate_case
) << CaseVals
[i
].first
.toString(10);
605 Diag(CaseVals
[i
-1].second
->getLHS()->getLocStart(),
606 diag::note_duplicate_case_prev
);
607 // FIXME: We really want to remove the bogus case stmt from the
608 // substmt, but we have no way to do this right now.
609 CaseListIsErroneous
= true;
614 // Detect duplicate case ranges, which usually don't exist at all in
616 if (!CaseRanges
.empty()) {
617 // Sort all the case ranges by their low value so we can easily detect
618 // overlaps between ranges.
619 std::stable_sort(CaseRanges
.begin(), CaseRanges
.end());
621 // Scan the ranges, computing the high values and removing empty ranges.
622 std::vector
<llvm::APSInt
> HiVals
;
623 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
624 llvm::APSInt
&LoVal
= CaseRanges
[i
].first
;
625 CaseStmt
*CR
= CaseRanges
[i
].second
;
626 Expr
*Hi
= CR
->getRHS();
627 llvm::APSInt HiVal
= Hi
->EvaluateAsInt(Context
);
629 // Convert the value to the same width/sign as the condition.
630 ConvertIntegerToTypeWarnOnOverflow(HiVal
, CondWidth
, CondIsSigned
,
632 diag::warn_case_value_overflow
);
634 // If the LHS is not the same type as the condition, insert an implicit
636 ImpCastExprToType(Hi
, CondType
, CK_IntegralCast
);
639 // If the low value is bigger than the high value, the case is empty.
641 Diag(CR
->getLHS()->getLocStart(), diag::warn_case_empty_range
)
642 << SourceRange(CR
->getLHS()->getLocStart(),
644 CaseRanges
.erase(CaseRanges
.begin()+i
);
649 if (ShouldCheckConstantCond
&&
650 LoVal
<= ConstantCondValue
&&
651 ConstantCondValue
<= HiVal
)
652 ShouldCheckConstantCond
= false;
654 HiVals
.push_back(HiVal
);
657 // Rescan the ranges, looking for overlap with singleton values and other
658 // ranges. Since the range list is sorted, we only need to compare case
659 // ranges with their neighbors.
660 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
661 llvm::APSInt
&CRLo
= CaseRanges
[i
].first
;
662 llvm::APSInt
&CRHi
= HiVals
[i
];
663 CaseStmt
*CR
= CaseRanges
[i
].second
;
665 // Check to see whether the case range overlaps with any
667 CaseStmt
*OverlapStmt
= 0;
668 llvm::APSInt
OverlapVal(32);
670 // Find the smallest value >= the lower bound. If I is in the
671 // case range, then we have overlap.
672 CaseValsTy::iterator I
= std::lower_bound(CaseVals
.begin(),
673 CaseVals
.end(), CRLo
,
674 CaseCompareFunctor());
675 if (I
!= CaseVals
.end() && I
->first
< CRHi
) {
676 OverlapVal
= I
->first
; // Found overlap with scalar.
677 OverlapStmt
= I
->second
;
680 // Find the smallest value bigger than the upper bound.
681 I
= std::upper_bound(I
, CaseVals
.end(), CRHi
, CaseCompareFunctor());
682 if (I
!= CaseVals
.begin() && (I
-1)->first
>= CRLo
) {
683 OverlapVal
= (I
-1)->first
; // Found overlap with scalar.
684 OverlapStmt
= (I
-1)->second
;
687 // Check to see if this case stmt overlaps with the subsequent
689 if (i
&& CRLo
<= HiVals
[i
-1]) {
690 OverlapVal
= HiVals
[i
-1]; // Found overlap with range.
691 OverlapStmt
= CaseRanges
[i
-1].second
;
695 // If we have a duplicate, report it.
696 Diag(CR
->getLHS()->getLocStart(), diag::err_duplicate_case
)
697 << OverlapVal
.toString(10);
698 Diag(OverlapStmt
->getLHS()->getLocStart(),
699 diag::note_duplicate_case_prev
);
700 // FIXME: We really want to remove the bogus case stmt from the
701 // substmt, but we have no way to do this right now.
702 CaseListIsErroneous
= true;
707 // Complain if we have a constant condition and we didn't find a match.
708 if (!CaseListIsErroneous
&& ShouldCheckConstantCond
) {
709 // TODO: it would be nice if we printed enums as enums, chars as
711 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case_for_condition
)
712 << ConstantCondValue
.toString(10)
713 << CondExpr
->getSourceRange();
716 // Check to see if switch is over an Enum and handles all of its
717 // values. We only issue a warning if there is not 'default:', but
718 // we still do the analysis to preserve this information in the AST
719 // (which can be used by flow-based analyes).
721 const EnumType
*ET
= CondTypeBeforePromotion
->getAs
<EnumType
>();
723 // If switch has default case, then ignore it.
724 if (!CaseListIsErroneous
&& !HasConstantCond
&& ET
) {
725 const EnumDecl
*ED
= ET
->getDecl();
726 typedef llvm::SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64> EnumValsTy
;
729 // Gather all enum values, set their type and sort them,
730 // allowing easier comparison with CaseVals.
731 for (EnumDecl::enumerator_iterator EDI
= ED
->enumerator_begin();
732 EDI
!= ED
->enumerator_end(); ++EDI
) {
733 llvm::APSInt Val
= EDI
->getInitVal();
734 AdjustAPSInt(Val
, CondWidth
, CondIsSigned
);
735 EnumVals
.push_back(std::make_pair(Val
, *EDI
));
737 std::stable_sort(EnumVals
.begin(), EnumVals
.end(), CmpEnumVals
);
738 EnumValsTy::iterator EIend
=
739 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
741 // See which case values aren't in enum.
742 // TODO: we might want to check whether case values are out of the
743 // enum even if we don't want to check whether all cases are handled.
744 if (!TheDefaultStmt
) {
745 EnumValsTy::const_iterator EI
= EnumVals
.begin();
746 for (CaseValsTy::const_iterator CI
= CaseVals
.begin();
747 CI
!= CaseVals
.end(); CI
++) {
748 while (EI
!= EIend
&& EI
->first
< CI
->first
)
750 if (EI
== EIend
|| EI
->first
> CI
->first
)
751 Diag(CI
->second
->getLHS()->getExprLoc(), diag::warn_not_in_enum
)
752 << ED
->getDeclName();
754 // See which of case ranges aren't in enum
755 EI
= EnumVals
.begin();
756 for (CaseRangesTy::const_iterator RI
= CaseRanges
.begin();
757 RI
!= CaseRanges
.end() && EI
!= EIend
; RI
++) {
758 while (EI
!= EIend
&& EI
->first
< RI
->first
)
761 if (EI
== EIend
|| EI
->first
!= RI
->first
) {
762 Diag(RI
->second
->getLHS()->getExprLoc(), diag::warn_not_in_enum
)
763 << ED
->getDeclName();
766 llvm::APSInt Hi
= RI
->second
->getRHS()->EvaluateAsInt(Context
);
767 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
768 while (EI
!= EIend
&& EI
->first
< Hi
)
770 if (EI
== EIend
|| EI
->first
!= Hi
)
771 Diag(RI
->second
->getRHS()->getExprLoc(), diag::warn_not_in_enum
)
772 << ED
->getDeclName();
776 // Check which enum vals aren't in switch
777 CaseValsTy::const_iterator CI
= CaseVals
.begin();
778 CaseRangesTy::const_iterator RI
= CaseRanges
.begin();
779 bool hasCasesNotInSwitch
= false;
781 llvm::SmallVector
<DeclarationName
,8> UnhandledNames
;
783 for (EnumValsTy::const_iterator EI
= EnumVals
.begin(); EI
!= EIend
; EI
++){
784 // Drop unneeded case values
786 while (CI
!= CaseVals
.end() && CI
->first
< EI
->first
)
789 if (CI
!= CaseVals
.end() && CI
->first
== EI
->first
)
792 // Drop unneeded case ranges
793 for (; RI
!= CaseRanges
.end(); RI
++) {
794 llvm::APSInt Hi
= RI
->second
->getRHS()->EvaluateAsInt(Context
);
795 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
800 if (RI
== CaseRanges
.end() || EI
->first
< RI
->first
) {
801 hasCasesNotInSwitch
= true;
803 UnhandledNames
.push_back(EI
->second
->getDeclName());
807 // Produce a nice diagnostic if multiple values aren't handled.
808 switch (UnhandledNames
.size()) {
811 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case1
)
812 << UnhandledNames
[0];
815 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case2
)
816 << UnhandledNames
[0] << UnhandledNames
[1];
819 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case3
)
820 << UnhandledNames
[0] << UnhandledNames
[1] << UnhandledNames
[2];
823 Diag(CondExpr
->getExprLoc(), diag::warn_missing_cases
)
824 << (unsigned)UnhandledNames
.size()
825 << UnhandledNames
[0] << UnhandledNames
[1] << UnhandledNames
[2];
829 if (!hasCasesNotInSwitch
)
830 SS
->setAllEnumCasesCovered();
834 // FIXME: If the case list was broken is some way, we don't have a good system
835 // to patch it up. Instead, just return the whole substmt as broken.
836 if (CaseListIsErroneous
)
843 Sema::ActOnWhileStmt(SourceLocation WhileLoc
, FullExprArg Cond
,
844 Decl
*CondVar
, Stmt
*Body
) {
845 ExprResult
CondResult(Cond
.release());
847 VarDecl
*ConditionVar
= 0;
849 ConditionVar
= cast
<VarDecl
>(CondVar
);
850 CondResult
= CheckConditionVariable(ConditionVar
, WhileLoc
, true);
851 if (CondResult
.isInvalid())
854 Expr
*ConditionExpr
= CondResult
.take();
858 DiagnoseUnusedExprResult(Body
);
860 return Owned(new (Context
) WhileStmt(Context
, ConditionVar
, ConditionExpr
,
865 Sema::ActOnDoStmt(SourceLocation DoLoc
, Stmt
*Body
,
866 SourceLocation WhileLoc
, SourceLocation CondLParen
,
867 Expr
*Cond
, SourceLocation CondRParen
) {
868 assert(Cond
&& "ActOnDoStmt(): missing expression");
870 if (CheckBooleanCondition(Cond
, DoLoc
))
873 CheckImplicitConversions(Cond
, DoLoc
);
874 ExprResult CondResult
= MaybeCreateExprWithCleanups(Cond
);
875 if (CondResult
.isInvalid())
877 Cond
= CondResult
.take();
879 DiagnoseUnusedExprResult(Body
);
881 return Owned(new (Context
) DoStmt(Body
, Cond
, DoLoc
, WhileLoc
, CondRParen
));
885 Sema::ActOnForStmt(SourceLocation ForLoc
, SourceLocation LParenLoc
,
886 Stmt
*First
, FullExprArg second
, Decl
*secondVar
,
888 SourceLocation RParenLoc
, Stmt
*Body
) {
889 if (!getLangOptions().CPlusPlus
) {
890 if (DeclStmt
*DS
= dyn_cast_or_null
<DeclStmt
>(First
)) {
891 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
892 // declare identifiers for objects having storage class 'auto' or
894 for (DeclStmt::decl_iterator DI
=DS
->decl_begin(), DE
=DS
->decl_end();
896 VarDecl
*VD
= dyn_cast
<VarDecl
>(*DI
);
897 if (VD
&& VD
->isLocalVarDecl() && !VD
->hasLocalStorage())
900 Diag((*DI
)->getLocation(), diag::err_non_variable_decl_in_for
);
901 // FIXME: mark decl erroneous!
906 ExprResult
SecondResult(second
.release());
907 VarDecl
*ConditionVar
= 0;
909 ConditionVar
= cast
<VarDecl
>(secondVar
);
910 SecondResult
= CheckConditionVariable(ConditionVar
, ForLoc
, true);
911 if (SecondResult
.isInvalid())
915 Expr
*Third
= third
.release().takeAs
<Expr
>();
917 DiagnoseUnusedExprResult(First
);
918 DiagnoseUnusedExprResult(Third
);
919 DiagnoseUnusedExprResult(Body
);
921 return Owned(new (Context
) ForStmt(Context
, First
,
922 SecondResult
.take(), ConditionVar
,
923 Third
, Body
, ForLoc
, LParenLoc
,
927 /// In an Objective C collection iteration statement:
929 /// x can be an arbitrary l-value expression. Bind it up as a
931 StmtResult
Sema::ActOnForEachLValueExpr(Expr
*E
) {
932 CheckImplicitConversions(E
);
933 ExprResult Result
= MaybeCreateExprWithCleanups(E
);
934 if (Result
.isInvalid()) return StmtError();
935 return Owned(static_cast<Stmt
*>(Result
.get()));
939 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc
,
940 SourceLocation LParenLoc
,
941 Stmt
*First
, Expr
*Second
,
942 SourceLocation RParenLoc
, Stmt
*Body
) {
945 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
)) {
946 if (!DS
->isSingleDecl())
947 return StmtError(Diag((*DS
->decl_begin())->getLocation(),
948 diag::err_toomany_element_decls
));
950 Decl
*D
= DS
->getSingleDecl();
951 FirstType
= cast
<ValueDecl
>(D
)->getType();
952 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
953 // declare identifiers for objects having storage class 'auto' or
955 VarDecl
*VD
= cast
<VarDecl
>(D
);
956 if (VD
->isLocalVarDecl() && !VD
->hasLocalStorage())
957 return StmtError(Diag(VD
->getLocation(),
958 diag::err_non_variable_decl_in_for
));
960 Expr
*FirstE
= cast
<Expr
>(First
);
961 if (!FirstE
->isTypeDependent() && !FirstE
->isLValue())
962 return StmtError(Diag(First
->getLocStart(),
963 diag::err_selector_element_not_lvalue
)
964 << First
->getSourceRange());
966 FirstType
= static_cast<Expr
*>(First
)->getType();
968 if (!FirstType
->isDependentType() &&
969 !FirstType
->isObjCObjectPointerType() &&
970 !FirstType
->isBlockPointerType())
971 Diag(ForLoc
, diag::err_selector_element_type
)
972 << FirstType
<< First
->getSourceRange();
974 if (Second
&& !Second
->isTypeDependent()) {
975 DefaultFunctionArrayLvalueConversion(Second
);
976 QualType SecondType
= Second
->getType();
977 if (!SecondType
->isObjCObjectPointerType())
978 Diag(ForLoc
, diag::err_collection_expr_type
)
979 << SecondType
<< Second
->getSourceRange();
980 else if (const ObjCObjectPointerType
*OPT
=
981 SecondType
->getAsObjCInterfacePointerType()) {
982 llvm::SmallVector
<IdentifierInfo
*, 4> KeyIdents
;
983 IdentifierInfo
* selIdent
=
984 &Context
.Idents
.get("countByEnumeratingWithState");
985 KeyIdents
.push_back(selIdent
);
986 selIdent
= &Context
.Idents
.get("objects");
987 KeyIdents
.push_back(selIdent
);
988 selIdent
= &Context
.Idents
.get("count");
989 KeyIdents
.push_back(selIdent
);
990 Selector CSelector
= Context
.Selectors
.getSelector(3, &KeyIdents
[0]);
991 if (ObjCInterfaceDecl
*IDecl
= OPT
->getInterfaceDecl()) {
992 if (!IDecl
->isForwardDecl() &&
993 !IDecl
->lookupInstanceMethod(CSelector
)) {
994 // Must further look into private implementation methods.
995 if (!LookupPrivateInstanceMethod(CSelector
, IDecl
))
996 Diag(ForLoc
, diag::warn_collection_expr_type
)
997 << SecondType
<< CSelector
<< Second
->getSourceRange();
1002 return Owned(new (Context
) ObjCForCollectionStmt(First
, Second
, Body
,
1003 ForLoc
, RParenLoc
));
1006 StmtResult
Sema::ActOnGotoStmt(SourceLocation GotoLoc
,
1007 SourceLocation LabelLoc
,
1008 LabelDecl
*TheDecl
) {
1009 getCurFunction()->setHasBranchIntoScope();
1011 return Owned(new (Context
) GotoStmt(TheDecl
, GotoLoc
, LabelLoc
));
1015 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc
, SourceLocation StarLoc
,
1017 // Convert operand to void*
1018 if (!E
->isTypeDependent()) {
1019 QualType ETy
= E
->getType();
1020 QualType DestTy
= Context
.getPointerType(Context
.VoidTy
.withConst());
1021 AssignConvertType ConvTy
=
1022 CheckSingleAssignmentConstraints(DestTy
, E
);
1023 if (DiagnoseAssignmentResult(ConvTy
, StarLoc
, DestTy
, ETy
, E
, AA_Passing
))
1027 getCurFunction()->setHasIndirectGoto();
1029 return Owned(new (Context
) IndirectGotoStmt(GotoLoc
, StarLoc
, E
));
1033 Sema::ActOnContinueStmt(SourceLocation ContinueLoc
, Scope
*CurScope
) {
1034 Scope
*S
= CurScope
->getContinueParent();
1036 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1037 return StmtError(Diag(ContinueLoc
, diag::err_continue_not_in_loop
));
1040 return Owned(new (Context
) ContinueStmt(ContinueLoc
));
1044 Sema::ActOnBreakStmt(SourceLocation BreakLoc
, Scope
*CurScope
) {
1045 Scope
*S
= CurScope
->getBreakParent();
1047 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1048 return StmtError(Diag(BreakLoc
, diag::err_break_not_in_loop_or_switch
));
1051 return Owned(new (Context
) BreakStmt(BreakLoc
));
1054 /// \brief Determine whether the given expression is a candidate for
1055 /// copy elision in either a return statement or a throw expression.
1057 /// \param ReturnType If we're determining the copy elision candidate for
1058 /// a return statement, this is the return type of the function. If we're
1059 /// determining the copy elision candidate for a throw expression, this will
1062 /// \param E The expression being returned from the function or block, or
1065 /// \param AllowFunctionParameter
1067 /// \returns The NRVO candidate variable, if the return statement may use the
1068 /// NRVO, or NULL if there is no such candidate.
1069 const VarDecl
*Sema::getCopyElisionCandidate(QualType ReturnType
,
1071 bool AllowFunctionParameter
) {
1072 QualType ExprType
= E
->getType();
1073 // - in a return statement in a function with ...
1074 // ... a class return type ...
1075 if (!ReturnType
.isNull()) {
1076 if (!ReturnType
->isRecordType())
1078 // ... the same cv-unqualified type as the function return type ...
1079 if (!Context
.hasSameUnqualifiedType(ReturnType
, ExprType
))
1083 // ... the expression is the name of a non-volatile automatic object
1084 // (other than a function or catch-clause parameter)) ...
1085 const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens());
1088 const VarDecl
*VD
= dyn_cast
<VarDecl
>(DR
->getDecl());
1092 if (VD
->hasLocalStorage() && !VD
->isExceptionVariable() &&
1093 !VD
->getType()->isReferenceType() && !VD
->hasAttr
<BlocksAttr
>() &&
1094 !VD
->getType().isVolatileQualified() &&
1095 ((VD
->getKind() == Decl::Var
) ||
1096 (AllowFunctionParameter
&& VD
->getKind() == Decl::ParmVar
)))
1102 /// \brief Perform the initialization of a potentially-movable value, which
1103 /// is the result of return value.
1105 /// This routine implements C++0x [class.copy]p33, which attempts to treat
1106 /// returned lvalues as rvalues in certain cases (to prefer move construction),
1107 /// then falls back to treating them as lvalues if that failed.
1109 Sema::PerformMoveOrCopyInitialization(const InitializedEntity
&Entity
,
1110 const VarDecl
*NRVOCandidate
,
1111 QualType ResultType
,
1113 // C++0x [class.copy]p33:
1114 // When the criteria for elision of a copy operation are met or would
1115 // be met save for the fact that the source object is a function
1116 // parameter, and the object to be copied is designated by an lvalue,
1117 // overload resolution to select the constructor for the copy is first
1118 // performed as if the object were designated by an rvalue.
1119 ExprResult Res
= ExprError();
1120 if (NRVOCandidate
|| getCopyElisionCandidate(ResultType
, Value
, true)) {
1121 ImplicitCastExpr
AsRvalue(ImplicitCastExpr::OnStack
,
1122 Value
->getType(), CK_LValueToRValue
,
1125 Expr
*InitExpr
= &AsRvalue
;
1126 InitializationKind Kind
1127 = InitializationKind::CreateCopy(Value
->getLocStart(),
1128 Value
->getLocStart());
1129 InitializationSequence
Seq(*this, Entity
, Kind
, &InitExpr
, 1);
1131 // [...] If overload resolution fails, or if the type of the first
1132 // parameter of the selected constructor is not an rvalue reference
1133 // to the object's type (possibly cv-qualified), overload resolution
1134 // is performed again, considering the object as an lvalue.
1135 if (Seq
.getKind() != InitializationSequence::FailedSequence
) {
1136 for (InitializationSequence::step_iterator Step
= Seq
.step_begin(),
1137 StepEnd
= Seq
.step_end();
1138 Step
!= StepEnd
; ++Step
) {
1140 != InitializationSequence::SK_ConstructorInitialization
)
1143 CXXConstructorDecl
*Constructor
1144 = cast
<CXXConstructorDecl
>(Step
->Function
.Function
);
1146 const RValueReferenceType
*RRefType
1147 = Constructor
->getParamDecl(0)->getType()
1148 ->getAs
<RValueReferenceType
>();
1150 // If we don't meet the criteria, break out now.
1152 !Context
.hasSameUnqualifiedType(RRefType
->getPointeeType(),
1153 Context
.getTypeDeclType(Constructor
->getParent())))
1156 // Promote "AsRvalue" to the heap, since we now need this
1157 // expression node to persist.
1158 Value
= ImplicitCastExpr::Create(Context
, Value
->getType(),
1159 CK_LValueToRValue
, Value
, 0,
1162 // Complete type-checking the initialization of the return type
1163 // using the constructor we found.
1164 Res
= Seq
.Perform(*this, Entity
, Kind
, MultiExprArg(&Value
, 1));
1169 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1170 // above, or overload resolution failed. Either way, we need to try
1171 // (again) now with the return value expression as written.
1172 if (Res
.isInvalid())
1173 Res
= PerformCopyInitialization(Entity
, SourceLocation(), Value
);
1178 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1181 Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
) {
1182 // If this is the first return we've seen in the block, infer the type of
1183 // the block from it.
1184 BlockScopeInfo
*CurBlock
= getCurBlock();
1185 if (CurBlock
->ReturnType
.isNull()) {
1187 // Don't call UsualUnaryConversions(), since we don't want to do
1188 // integer promotions here.
1189 DefaultFunctionArrayLvalueConversion(RetValExp
);
1190 CurBlock
->ReturnType
= RetValExp
->getType();
1191 if (BlockDeclRefExpr
*CDRE
= dyn_cast
<BlockDeclRefExpr
>(RetValExp
)) {
1192 // We have to remove a 'const' added to copied-in variable which was
1193 // part of the implementation spec. and not the actual qualifier for
1195 if (CDRE
->isConstQualAdded())
1196 CurBlock
->ReturnType
.removeLocalConst(); // FIXME: local???
1199 CurBlock
->ReturnType
= Context
.VoidTy
;
1201 QualType FnRetType
= CurBlock
->ReturnType
;
1203 if (CurBlock
->FunctionType
->getAs
<FunctionType
>()->getNoReturnAttr()) {
1204 Diag(ReturnLoc
, diag::err_noreturn_block_has_return_expr
)
1205 << getCurFunctionOrMethodDecl()->getDeclName();
1209 // Otherwise, verify that this result type matches the previous one. We are
1210 // pickier with blocks than for normal functions because we don't have GCC
1211 // compatibility to worry about here.
1212 ReturnStmt
*Result
= 0;
1213 if (CurBlock
->ReturnType
->isVoidType()) {
1215 Diag(ReturnLoc
, diag::err_return_block_has_expr
);
1218 Result
= new (Context
) ReturnStmt(ReturnLoc
, RetValExp
, 0);
1219 } else if (!RetValExp
) {
1220 return StmtError(Diag(ReturnLoc
, diag::err_block_return_missing_expr
));
1222 const VarDecl
*NRVOCandidate
= 0;
1224 if (!FnRetType
->isDependentType() && !RetValExp
->isTypeDependent()) {
1225 // we have a non-void block with an expression, continue checking
1227 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1228 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1231 // In C++ the return statement is handled via a copy initialization.
1232 // the C version of which boils down to CheckSingleAssignmentConstraints.
1233 NRVOCandidate
= getCopyElisionCandidate(FnRetType
, RetValExp
, false);
1234 InitializedEntity Entity
= InitializedEntity::InitializeResult(ReturnLoc
,
1236 NRVOCandidate
!= 0);
1237 ExprResult Res
= PerformMoveOrCopyInitialization(Entity
, NRVOCandidate
,
1238 FnRetType
, RetValExp
);
1239 if (Res
.isInvalid()) {
1240 // FIXME: Cleanup temporaries here, anyway?
1245 CheckImplicitConversions(RetValExp
, ReturnLoc
);
1246 RetValExp
= MaybeCreateExprWithCleanups(RetValExp
);
1249 RetValExp
= Res
.takeAs
<Expr
>();
1251 CheckReturnStackAddr(RetValExp
, FnRetType
, ReturnLoc
);
1254 Result
= new (Context
) ReturnStmt(ReturnLoc
, RetValExp
, NRVOCandidate
);
1257 // If we need to check for the named return value optimization, save the
1258 // return statement in our scope for later processing.
1259 if (getLangOptions().CPlusPlus
&& FnRetType
->isRecordType() &&
1260 !CurContext
->isDependentContext())
1261 FunctionScopes
.back()->Returns
.push_back(Result
);
1263 return Owned(Result
);
1267 Sema::ActOnReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
) {
1269 return ActOnBlockReturnStmt(ReturnLoc
, RetValExp
);
1272 if (const FunctionDecl
*FD
= getCurFunctionDecl()) {
1273 FnRetType
= FD
->getResultType();
1274 if (FD
->hasAttr
<NoReturnAttr
>() ||
1275 FD
->getType()->getAs
<FunctionType
>()->getNoReturnAttr())
1276 Diag(ReturnLoc
, diag::warn_noreturn_function_has_return_expr
)
1277 << getCurFunctionOrMethodDecl()->getDeclName();
1278 } else if (ObjCMethodDecl
*MD
= getCurMethodDecl())
1279 FnRetType
= MD
->getResultType();
1280 else // If we don't have a function/method context, bail.
1283 ReturnStmt
*Result
= 0;
1284 if (FnRetType
->isVoidType()) {
1285 if (RetValExp
&& !RetValExp
->isTypeDependent()) {
1286 // C99 6.8.6.4p1 (ext_ since GCC warns)
1287 unsigned D
= diag::ext_return_has_expr
;
1288 if (RetValExp
->getType()->isVoidType())
1289 D
= diag::ext_return_has_void_expr
;
1291 IgnoredValueConversions(RetValExp
);
1292 ImpCastExprToType(RetValExp
, Context
.VoidTy
, CK_ToVoid
);
1295 // return (some void expression); is legal in C++.
1296 if (D
!= diag::ext_return_has_void_expr
||
1297 !getLangOptions().CPlusPlus
) {
1298 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
1300 << CurDecl
->getDeclName() << isa
<ObjCMethodDecl
>(CurDecl
)
1301 << RetValExp
->getSourceRange();
1304 CheckImplicitConversions(RetValExp
, ReturnLoc
);
1305 RetValExp
= MaybeCreateExprWithCleanups(RetValExp
);
1308 Result
= new (Context
) ReturnStmt(ReturnLoc
, RetValExp
, 0);
1309 } else if (!RetValExp
&& !FnRetType
->isDependentType()) {
1310 unsigned DiagID
= diag::warn_return_missing_expr
; // C90 6.6.6.4p4
1311 // C99 6.8.6.4p1 (ext_ since GCC warns)
1312 if (getLangOptions().C99
) DiagID
= diag::ext_return_missing_expr
;
1314 if (FunctionDecl
*FD
= getCurFunctionDecl())
1315 Diag(ReturnLoc
, DiagID
) << FD
->getIdentifier() << 0/*fn*/;
1317 Diag(ReturnLoc
, DiagID
) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1318 Result
= new (Context
) ReturnStmt(ReturnLoc
);
1320 const VarDecl
*NRVOCandidate
= 0;
1321 if (!FnRetType
->isDependentType() && !RetValExp
->isTypeDependent()) {
1322 // we have a non-void function with an expression, continue checking
1324 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1325 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1328 // In C++ the return statement is handled via a copy initialization.
1329 // the C version of which boils down to CheckSingleAssignmentConstraints.
1330 NRVOCandidate
= getCopyElisionCandidate(FnRetType
, RetValExp
, false);
1331 InitializedEntity Entity
= InitializedEntity::InitializeResult(ReturnLoc
,
1333 NRVOCandidate
!= 0);
1334 ExprResult Res
= PerformMoveOrCopyInitialization(Entity
, NRVOCandidate
,
1335 FnRetType
, RetValExp
);
1336 if (Res
.isInvalid()) {
1337 // FIXME: Cleanup temporaries here, anyway?
1341 RetValExp
= Res
.takeAs
<Expr
>();
1343 CheckReturnStackAddr(RetValExp
, FnRetType
, ReturnLoc
);
1347 CheckImplicitConversions(RetValExp
, ReturnLoc
);
1348 RetValExp
= MaybeCreateExprWithCleanups(RetValExp
);
1350 Result
= new (Context
) ReturnStmt(ReturnLoc
, RetValExp
, NRVOCandidate
);
1353 // If we need to check for the named return value optimization, save the
1354 // return statement in our scope for later processing.
1355 if (getLangOptions().CPlusPlus
&& FnRetType
->isRecordType() &&
1356 !CurContext
->isDependentContext())
1357 FunctionScopes
.back()->Returns
.push_back(Result
);
1359 return Owned(Result
);
1362 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1363 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
1364 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1365 /// provide a strong guidance to not use it.
1367 /// This method checks to see if the argument is an acceptable l-value and
1368 /// returns false if it is a case we can handle.
1369 static bool CheckAsmLValue(const Expr
*E
, Sema
&S
) {
1370 // Type dependent expressions will be checked during instantiation.
1371 if (E
->isTypeDependent())
1375 return false; // Cool, this is an lvalue.
1377 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1378 // are supposed to allow.
1379 const Expr
*E2
= E
->IgnoreParenNoopCasts(S
.Context
);
1380 if (E
!= E2
&& E2
->isLValue()) {
1381 if (!S
.getLangOptions().HeinousExtensions
)
1382 S
.Diag(E2
->getLocStart(), diag::err_invalid_asm_cast_lvalue
)
1383 << E
->getSourceRange();
1385 S
.Diag(E2
->getLocStart(), diag::warn_invalid_asm_cast_lvalue
)
1386 << E
->getSourceRange();
1387 // Accept, even if we emitted an error diagnostic.
1391 // None of the above, just randomly invalid non-lvalue.
1396 StmtResult
Sema::ActOnAsmStmt(SourceLocation AsmLoc
,
1399 unsigned NumOutputs
,
1401 IdentifierInfo
**Names
,
1402 MultiExprArg constraints
,
1405 MultiExprArg clobbers
,
1406 SourceLocation RParenLoc
,
1408 unsigned NumClobbers
= clobbers
.size();
1409 StringLiteral
**Constraints
=
1410 reinterpret_cast<StringLiteral
**>(constraints
.get());
1411 Expr
**Exprs
= exprs
.get();
1412 StringLiteral
*AsmString
= cast
<StringLiteral
>(asmString
);
1413 StringLiteral
**Clobbers
= reinterpret_cast<StringLiteral
**>(clobbers
.get());
1415 llvm::SmallVector
<TargetInfo::ConstraintInfo
, 4> OutputConstraintInfos
;
1417 // The parser verifies that there is a string literal here.
1418 if (AsmString
->isWide())
1419 return StmtError(Diag(AsmString
->getLocStart(),diag::err_asm_wide_character
)
1420 << AsmString
->getSourceRange());
1422 for (unsigned i
= 0; i
!= NumOutputs
; i
++) {
1423 StringLiteral
*Literal
= Constraints
[i
];
1424 if (Literal
->isWide())
1425 return StmtError(Diag(Literal
->getLocStart(),diag::err_asm_wide_character
)
1426 << Literal
->getSourceRange());
1428 llvm::StringRef OutputName
;
1430 OutputName
= Names
[i
]->getName();
1432 TargetInfo::ConstraintInfo
Info(Literal
->getString(), OutputName
);
1433 if (!Context
.Target
.validateOutputConstraint(Info
))
1434 return StmtError(Diag(Literal
->getLocStart(),
1435 diag::err_asm_invalid_output_constraint
)
1436 << Info
.getConstraintStr());
1438 // Check that the output exprs are valid lvalues.
1439 Expr
*OutputExpr
= Exprs
[i
];
1440 if (CheckAsmLValue(OutputExpr
, *this)) {
1441 return StmtError(Diag(OutputExpr
->getLocStart(),
1442 diag::err_asm_invalid_lvalue_in_output
)
1443 << OutputExpr
->getSourceRange());
1446 OutputConstraintInfos
.push_back(Info
);
1449 llvm::SmallVector
<TargetInfo::ConstraintInfo
, 4> InputConstraintInfos
;
1451 for (unsigned i
= NumOutputs
, e
= NumOutputs
+ NumInputs
; i
!= e
; i
++) {
1452 StringLiteral
*Literal
= Constraints
[i
];
1453 if (Literal
->isWide())
1454 return StmtError(Diag(Literal
->getLocStart(),diag::err_asm_wide_character
)
1455 << Literal
->getSourceRange());
1457 llvm::StringRef InputName
;
1459 InputName
= Names
[i
]->getName();
1461 TargetInfo::ConstraintInfo
Info(Literal
->getString(), InputName
);
1462 if (!Context
.Target
.validateInputConstraint(OutputConstraintInfos
.data(),
1463 NumOutputs
, Info
)) {
1464 return StmtError(Diag(Literal
->getLocStart(),
1465 diag::err_asm_invalid_input_constraint
)
1466 << Info
.getConstraintStr());
1469 Expr
*InputExpr
= Exprs
[i
];
1471 // Only allow void types for memory constraints.
1472 if (Info
.allowsMemory() && !Info
.allowsRegister()) {
1473 if (CheckAsmLValue(InputExpr
, *this))
1474 return StmtError(Diag(InputExpr
->getLocStart(),
1475 diag::err_asm_invalid_lvalue_in_input
)
1476 << Info
.getConstraintStr()
1477 << InputExpr
->getSourceRange());
1480 if (Info
.allowsRegister()) {
1481 if (InputExpr
->getType()->isVoidType()) {
1482 return StmtError(Diag(InputExpr
->getLocStart(),
1483 diag::err_asm_invalid_type_in_input
)
1484 << InputExpr
->getType() << Info
.getConstraintStr()
1485 << InputExpr
->getSourceRange());
1489 DefaultFunctionArrayLvalueConversion(Exprs
[i
]);
1491 InputConstraintInfos
.push_back(Info
);
1494 // Check that the clobbers are valid.
1495 for (unsigned i
= 0; i
!= NumClobbers
; i
++) {
1496 StringLiteral
*Literal
= Clobbers
[i
];
1497 if (Literal
->isWide())
1498 return StmtError(Diag(Literal
->getLocStart(),diag::err_asm_wide_character
)
1499 << Literal
->getSourceRange());
1501 llvm::StringRef Clobber
= Literal
->getString();
1503 if (!Context
.Target
.isValidGCCRegisterName(Clobber
))
1504 return StmtError(Diag(Literal
->getLocStart(),
1505 diag::err_asm_unknown_register_name
) << Clobber
);
1509 new (Context
) AsmStmt(Context
, AsmLoc
, IsSimple
, IsVolatile
, MSAsm
,
1510 NumOutputs
, NumInputs
, Names
, Constraints
, Exprs
,
1511 AsmString
, NumClobbers
, Clobbers
, RParenLoc
);
1512 // Validate the asm string, ensuring it makes sense given the operands we
1514 llvm::SmallVector
<AsmStmt::AsmStringPiece
, 8> Pieces
;
1516 if (unsigned DiagID
= NS
->AnalyzeAsmString(Pieces
, Context
, DiagOffs
)) {
1517 Diag(getLocationOfStringLiteralByte(AsmString
, DiagOffs
), DiagID
)
1518 << AsmString
->getSourceRange();
1522 // Validate tied input operands for type mismatches.
1523 for (unsigned i
= 0, e
= InputConstraintInfos
.size(); i
!= e
; ++i
) {
1524 TargetInfo::ConstraintInfo
&Info
= InputConstraintInfos
[i
];
1526 // If this is a tied constraint, verify that the output and input have
1527 // either exactly the same type, or that they are int/ptr operands with the
1528 // same size (int/long, int*/long, are ok etc).
1529 if (!Info
.hasTiedOperand()) continue;
1531 unsigned TiedTo
= Info
.getTiedOperand();
1532 Expr
*OutputExpr
= Exprs
[TiedTo
];
1533 Expr
*InputExpr
= Exprs
[i
+NumOutputs
];
1534 QualType InTy
= InputExpr
->getType();
1535 QualType OutTy
= OutputExpr
->getType();
1536 if (Context
.hasSameType(InTy
, OutTy
))
1537 continue; // All types can be tied to themselves.
1539 // Decide if the input and output are in the same domain (integer/ptr or
1542 AD_Int
, AD_FP
, AD_Other
1543 } InputDomain
, OutputDomain
;
1545 if (InTy
->isIntegerType() || InTy
->isPointerType())
1546 InputDomain
= AD_Int
;
1547 else if (InTy
->isRealFloatingType())
1548 InputDomain
= AD_FP
;
1550 InputDomain
= AD_Other
;
1552 if (OutTy
->isIntegerType() || OutTy
->isPointerType())
1553 OutputDomain
= AD_Int
;
1554 else if (OutTy
->isRealFloatingType())
1555 OutputDomain
= AD_FP
;
1557 OutputDomain
= AD_Other
;
1559 // They are ok if they are the same size and in the same domain. This
1560 // allows tying things like:
1562 // void* to int if they are the same size.
1563 // double to long double if they are the same size.
1565 uint64_t OutSize
= Context
.getTypeSize(OutTy
);
1566 uint64_t InSize
= Context
.getTypeSize(InTy
);
1567 if (OutSize
== InSize
&& InputDomain
== OutputDomain
&&
1568 InputDomain
!= AD_Other
)
1571 // If the smaller input/output operand is not mentioned in the asm string,
1572 // then we can promote it and the asm string won't notice. Check this
1574 bool SmallerValueMentioned
= false;
1575 for (unsigned p
= 0, e
= Pieces
.size(); p
!= e
; ++p
) {
1576 AsmStmt::AsmStringPiece
&Piece
= Pieces
[p
];
1577 if (!Piece
.isOperand()) continue;
1579 // If this is a reference to the input and if the input was the smaller
1580 // one, then we have to reject this asm.
1581 if (Piece
.getOperandNo() == i
+NumOutputs
) {
1582 if (InSize
< OutSize
) {
1583 SmallerValueMentioned
= true;
1588 // If this is a reference to the input and if the input was the smaller
1589 // one, then we have to reject this asm.
1590 if (Piece
.getOperandNo() == TiedTo
) {
1591 if (InSize
> OutSize
) {
1592 SmallerValueMentioned
= true;
1598 // If the smaller value wasn't mentioned in the asm string, and if the
1599 // output was a register, just extend the shorter one to the size of the
1601 if (!SmallerValueMentioned
&& InputDomain
!= AD_Other
&&
1602 OutputConstraintInfos
[TiedTo
].allowsRegister())
1605 Diag(InputExpr
->getLocStart(),
1606 diag::err_asm_tying_incompatible_types
)
1607 << InTy
<< OutTy
<< OutputExpr
->getSourceRange()
1608 << InputExpr
->getSourceRange();
1616 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc
,
1617 SourceLocation RParen
, Decl
*Parm
,
1619 VarDecl
*Var
= cast_or_null
<VarDecl
>(Parm
);
1620 if (Var
&& Var
->isInvalidDecl())
1623 return Owned(new (Context
) ObjCAtCatchStmt(AtLoc
, RParen
, Var
, Body
));
1627 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc
, Stmt
*Body
) {
1628 return Owned(new (Context
) ObjCAtFinallyStmt(AtLoc
, Body
));
1632 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc
, Stmt
*Try
,
1633 MultiStmtArg CatchStmts
, Stmt
*Finally
) {
1634 getCurFunction()->setHasBranchProtectedScope();
1635 unsigned NumCatchStmts
= CatchStmts
.size();
1636 return Owned(ObjCAtTryStmt::Create(Context
, AtLoc
, Try
,
1637 CatchStmts
.release(),
1642 StmtResult
Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc
,
1645 DefaultLvalueConversion(Throw
);
1647 QualType ThrowType
= Throw
->getType();
1648 // Make sure the expression type is an ObjC pointer or "void *".
1649 if (!ThrowType
->isDependentType() &&
1650 !ThrowType
->isObjCObjectPointerType()) {
1651 const PointerType
*PT
= ThrowType
->getAs
<PointerType
>();
1652 if (!PT
|| !PT
->getPointeeType()->isVoidType())
1653 return StmtError(Diag(AtLoc
, diag::error_objc_throw_expects_object
)
1654 << Throw
->getType() << Throw
->getSourceRange());
1658 return Owned(new (Context
) ObjCAtThrowStmt(AtLoc
, Throw
));
1662 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
,
1665 // @throw without an expression designates a rethrow (which much occur
1666 // in the context of an @catch clause).
1667 Scope
*AtCatchParent
= CurScope
;
1668 while (AtCatchParent
&& !AtCatchParent
->isAtCatchScope())
1669 AtCatchParent
= AtCatchParent
->getParent();
1671 return StmtError(Diag(AtLoc
, diag::error_rethrow_used_outside_catch
));
1674 return BuildObjCAtThrowStmt(AtLoc
, Throw
);
1678 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc
, Expr
*SyncExpr
,
1680 getCurFunction()->setHasBranchProtectedScope();
1682 DefaultLvalueConversion(SyncExpr
);
1684 // Make sure the expression type is an ObjC pointer or "void *".
1685 if (!SyncExpr
->getType()->isDependentType() &&
1686 !SyncExpr
->getType()->isObjCObjectPointerType()) {
1687 const PointerType
*PT
= SyncExpr
->getType()->getAs
<PointerType
>();
1688 if (!PT
|| !PT
->getPointeeType()->isVoidType())
1689 return StmtError(Diag(AtLoc
, diag::error_objc_synchronized_expects_object
)
1690 << SyncExpr
->getType() << SyncExpr
->getSourceRange());
1693 return Owned(new (Context
) ObjCAtSynchronizedStmt(AtLoc
, SyncExpr
, SyncBody
));
1696 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1697 /// and creates a proper catch handler from them.
1699 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc
, Decl
*ExDecl
,
1700 Stmt
*HandlerBlock
) {
1701 // There's nothing to test that ActOnExceptionDecl didn't already test.
1702 return Owned(new (Context
) CXXCatchStmt(CatchLoc
,
1703 cast_or_null
<VarDecl
>(ExDecl
),
1709 class TypeWithHandler
{
1713 TypeWithHandler(const QualType
&type
, CXXCatchStmt
*statement
)
1714 : t(type
), stmt(statement
) {}
1716 // An arbitrary order is fine as long as it places identical
1717 // types next to each other.
1718 bool operator<(const TypeWithHandler
&y
) const {
1719 if (t
.getAsOpaquePtr() < y
.t
.getAsOpaquePtr())
1721 if (t
.getAsOpaquePtr() > y
.t
.getAsOpaquePtr())
1724 return getTypeSpecStartLoc() < y
.getTypeSpecStartLoc();
1727 bool operator==(const TypeWithHandler
& other
) const {
1728 return t
== other
.t
;
1731 CXXCatchStmt
*getCatchStmt() const { return stmt
; }
1732 SourceLocation
getTypeSpecStartLoc() const {
1733 return stmt
->getExceptionDecl()->getTypeSpecStartLoc();
1739 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1740 /// handlers and creates a try statement from them.
1742 Sema::ActOnCXXTryBlock(SourceLocation TryLoc
, Stmt
*TryBlock
,
1743 MultiStmtArg RawHandlers
) {
1744 unsigned NumHandlers
= RawHandlers
.size();
1745 assert(NumHandlers
> 0 &&
1746 "The parser shouldn't call this if there are no handlers.");
1747 Stmt
**Handlers
= RawHandlers
.get();
1749 llvm::SmallVector
<TypeWithHandler
, 8> TypesWithHandlers
;
1751 for (unsigned i
= 0; i
< NumHandlers
; ++i
) {
1752 CXXCatchStmt
*Handler
= llvm::cast
<CXXCatchStmt
>(Handlers
[i
]);
1753 if (!Handler
->getExceptionDecl()) {
1754 if (i
< NumHandlers
- 1)
1755 return StmtError(Diag(Handler
->getLocStart(),
1756 diag::err_early_catch_all
));
1761 const QualType CaughtType
= Handler
->getCaughtType();
1762 const QualType CanonicalCaughtType
= Context
.getCanonicalType(CaughtType
);
1763 TypesWithHandlers
.push_back(TypeWithHandler(CanonicalCaughtType
, Handler
));
1766 // Detect handlers for the same type as an earlier one.
1767 if (NumHandlers
> 1) {
1768 llvm::array_pod_sort(TypesWithHandlers
.begin(), TypesWithHandlers
.end());
1770 TypeWithHandler prev
= TypesWithHandlers
[0];
1771 for (unsigned i
= 1; i
< TypesWithHandlers
.size(); ++i
) {
1772 TypeWithHandler curr
= TypesWithHandlers
[i
];
1775 Diag(curr
.getTypeSpecStartLoc(),
1776 diag::warn_exception_caught_by_earlier_handler
)
1777 << curr
.getCatchStmt()->getCaughtType().getAsString();
1778 Diag(prev
.getTypeSpecStartLoc(),
1779 diag::note_previous_exception_handler
)
1780 << prev
.getCatchStmt()->getCaughtType().getAsString();
1787 getCurFunction()->setHasBranchProtectedScope();
1789 // FIXME: We should detect handlers that cannot catch anything because an
1790 // earlier handler catches a superclass. Need to find a method that is not
1791 // quadratic for this.
1792 // Neither of these are explicitly forbidden, but every compiler detects them
1795 return Owned(CXXTryStmt::Create(Context
, TryLoc
, TryBlock
,
1796 Handlers
, NumHandlers
));