blob: ee3a8e6a7fe0d59bcf54821095aa0df68ca60f80 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner3429a812007-08-23 05:46:52 +000015#include "clang/AST/ASTContext.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/Expr.h"
Chris Lattner3429a812007-08-23 05:46:52 +000017#include "clang/AST/Stmt.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/Parse/Scope.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Lex/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
24Sema::StmtResult Sema::ParseExprStmt(ExprTy *expr) {
25 Expr *E = static_cast<Expr*>(expr);
Steve Naroff1b8a46c2007-07-27 22:15:19 +000026 assert(E && "ParseExprStmt(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +000027
28 // Exprs are statements, so there is no need to do a conversion here. However,
29 // diagnose some potentially bad code.
30 if (!E->hasLocalSideEffect())
31 Diag(E->getExprLoc(), diag::warn_unused_expr, E->getSourceRange());
32
33 return E;
34}
35
36
37Sema::StmtResult Sema::ParseNullStmt(SourceLocation SemiLoc) {
38 return new NullStmt(SemiLoc);
39}
40
41Sema::StmtResult Sema::ParseDeclStmt(DeclTy *decl) {
42 if (decl)
43 return new DeclStmt(static_cast<Decl *>(decl));
44 else
45 return true; // error
46}
47
48Action::StmtResult
49Sema::ParseCompoundStmt(SourceLocation L, SourceLocation R,
50 StmtTy **Elts, unsigned NumElts) {
51 return new CompoundStmt((Stmt**)Elts, NumElts);
52}
53
54Action::StmtResult
55Sema::ParseCaseStmt(SourceLocation CaseLoc, ExprTy *lhsval,
56 SourceLocation DotDotDotLoc, ExprTy *rhsval,
57 SourceLocation ColonLoc, StmtTy *subStmt) {
58 Stmt *SubStmt = static_cast<Stmt*>(subStmt);
59 Expr *LHSVal = ((Expr *)lhsval), *RHSVal = ((Expr *)rhsval);
60 assert((LHSVal != 0) && "missing expression in case statement");
61
62 SourceLocation ExpLoc;
63 // C99 6.8.4.2p3: The expression shall be an integer constant.
64 if (!LHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
65 Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
66 LHSVal->getSourceRange());
67 return SubStmt;
68 }
69
70 // GCC extension: The expression shall be an integer constant.
71 if (RHSVal && !RHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
72 Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
73 RHSVal->getSourceRange());
Chris Lattner3429a812007-08-23 05:46:52 +000074 RHSVal = 0; // Recover by just forgetting about it.
Chris Lattner4b009652007-07-25 00:24:17 +000075 }
76
77 if (SwitchStack.empty()) {
78 Diag(CaseLoc, diag::err_case_not_in_switch);
79 return SubStmt;
80 }
81
82 CaseStmt *CS = new CaseStmt(LHSVal, RHSVal, SubStmt);
83 SwitchStack.back()->addSwitchCase(CS);
84 return CS;
85}
86
87Action::StmtResult
88Sema::ParseDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
89 StmtTy *subStmt, Scope *CurScope) {
90 Stmt *SubStmt = static_cast<Stmt*>(subStmt);
91
92 if (SwitchStack.empty()) {
93 Diag(DefaultLoc, diag::err_default_not_in_switch);
94 return SubStmt;
95 }
96
97 DefaultStmt *DS = new DefaultStmt(DefaultLoc, SubStmt);
98 SwitchStack.back()->addSwitchCase(DS);
99
100 return DS;
101}
102
103Action::StmtResult
104Sema::ParseLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
105 SourceLocation ColonLoc, StmtTy *subStmt) {
106 Stmt *SubStmt = static_cast<Stmt*>(subStmt);
107 // Look up the record for this label identifier.
108 LabelStmt *&LabelDecl = LabelMap[II];
109
110 // If not forward referenced or defined already, just create a new LabelStmt.
111 if (LabelDecl == 0)
112 return LabelDecl = new LabelStmt(IdentLoc, II, SubStmt);
113
114 assert(LabelDecl->getID() == II && "Label mismatch!");
115
116 // Otherwise, this label was either forward reference or multiply defined. If
117 // multiply defined, reject it now.
118 if (LabelDecl->getSubStmt()) {
119 Diag(IdentLoc, diag::err_redefinition_of_label, LabelDecl->getName());
120 Diag(LabelDecl->getIdentLoc(), diag::err_previous_definition);
121 return SubStmt;
122 }
123
124 // Otherwise, this label was forward declared, and we just found its real
125 // definition. Fill in the forward definition and return it.
126 LabelDecl->setIdentLoc(IdentLoc);
127 LabelDecl->setSubStmt(SubStmt);
128 return LabelDecl;
129}
130
131Action::StmtResult
132Sema::ParseIfStmt(SourceLocation IfLoc, ExprTy *CondVal,
133 StmtTy *ThenVal, SourceLocation ElseLoc,
134 StmtTy *ElseVal) {
135 Expr *condExpr = (Expr *)CondVal;
136 assert(condExpr && "ParseIfStmt(): missing expression");
137
138 DefaultFunctionArrayConversion(condExpr);
139 QualType condType = condExpr->getType();
140
141 if (!condType->isScalarType()) // C99 6.8.4.1p1
142 return Diag(IfLoc, diag::err_typecheck_statement_requires_scalar,
143 condType.getAsString(), condExpr->getSourceRange());
144
145 return new IfStmt(condExpr, (Stmt*)ThenVal, (Stmt*)ElseVal);
146}
147
148Action::StmtResult
Chris Lattner3429a812007-08-23 05:46:52 +0000149Sema::StartSwitchStmt(ExprTy *cond) {
150 Expr *Cond = static_cast<Expr*>(cond);
151
152 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
153 UsualUnaryConversions(Cond);
154
155 SwitchStmt *SS = new SwitchStmt(Cond);
Chris Lattner4b009652007-07-25 00:24:17 +0000156 SwitchStack.push_back(SS);
157 return SS;
158}
159
Chris Lattner3429a812007-08-23 05:46:52 +0000160/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
161/// the specified width and sign. If an overflow occurs, detect it and emit
162/// the specified diagnostic.
163void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
164 unsigned NewWidth, bool NewSign,
165 SourceLocation Loc,
166 unsigned DiagID) {
167 // Perform a conversion to the promoted condition type if needed.
168 if (NewWidth > Val.getBitWidth()) {
169 // If this is an extension, just do it.
170 llvm::APSInt OldVal(Val);
171 Val.extend(NewWidth);
172
173 // If the input was signed and negative and the output is unsigned,
174 // warn.
175 if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
176 Diag(Loc, DiagID, OldVal.toString(), Val.toString());
177
178 Val.setIsSigned(NewSign);
179 } else if (NewWidth < Val.getBitWidth()) {
180 // If this is a truncation, check for overflow.
181 llvm::APSInt ConvVal(Val);
182 ConvVal.trunc(NewWidth);
183 ConvVal.extend(Val.getBitWidth());
184 if (ConvVal != Val)
185 Diag(Loc, DiagID, Val.toString(), ConvVal.toString());
186
187 // Regardless of whether a diagnostic was emitted, really do the
188 // truncation.
189 Val.trunc(NewWidth);
190 } else if (NewSign != Val.isSigned()) {
191 // Convert the sign to match the sign of the condition. This can cause
192 // overflow as well: unsigned(INTMIN)
193 llvm::APSInt OldVal(Val);
194 Val.setIsSigned(NewSign);
195
196 if (Val.isNegative()) // Sign bit changes meaning.
197 Diag(Loc, DiagID, OldVal.toString(), Val.toString());
198 }
199}
200
Chris Lattner4b009652007-07-25 00:24:17 +0000201Action::StmtResult
202Sema::FinishSwitchStmt(SourceLocation SwitchLoc, StmtTy *Switch, ExprTy *Body) {
203 Stmt *BodyStmt = (Stmt*)Body;
204
205 SwitchStmt *SS = SwitchStack.back();
206 assert(SS == (SwitchStmt*)Switch && "switch stack missing push/pop!");
207
208 SS->setBody(BodyStmt);
209 SwitchStack.pop_back();
210
Chris Lattner3429a812007-08-23 05:46:52 +0000211 Expr *CondExpr = SS->getCond();
212 QualType CondType = CondExpr->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000213
Chris Lattner3429a812007-08-23 05:46:52 +0000214 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
Chris Lattner4b009652007-07-25 00:24:17 +0000215 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer,
Chris Lattner3429a812007-08-23 05:46:52 +0000216 CondType.getAsString(), CondExpr->getSourceRange());
217 return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000218 }
Chris Lattner3429a812007-08-23 05:46:52 +0000219
220 // Get the bitwidth of the switched-on value before promotions. We must
221 // convert the integer case values to this width before comparison.
222 unsigned CondWidth = Context.getTypeSize(CondType, SwitchLoc);
223 bool CondIsSigned = CondType->isSignedIntegerType();
224
225 // Accumulate all of the case values in a vector so that we can sort them
226 // and detect duplicates. This vector contains the APInt for the case after
227 // it has been converted to the condition type.
228 llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseVals;
229
230 // Keep track of any GNU case ranges we see. The APSInt is the low value.
231 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
232
233 DefaultStmt *TheDefaultStmt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000234
Chris Lattner1a4066d2007-08-23 06:23:56 +0000235 bool CaseListIsErroneous = false;
236
237 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
Chris Lattner4b009652007-07-25 00:24:17 +0000238 SC = SC->getNextSwitchCase()) {
Chris Lattner1a4066d2007-08-23 06:23:56 +0000239
Chris Lattner4b009652007-07-25 00:24:17 +0000240 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
Chris Lattner3429a812007-08-23 05:46:52 +0000241 if (TheDefaultStmt) {
242 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
243 Diag(TheDefaultStmt->getDefaultLoc(), diag::err_first_label);
Chris Lattner4b009652007-07-25 00:24:17 +0000244
Chris Lattner3429a812007-08-23 05:46:52 +0000245 // FIXME: Remove the default statement from the switch block so that
246 // we'll return a valid AST. This requires recursing down the
247 // AST and finding it, not something we are set up to do right now. For
248 // now, just lop the entire switch stmt out of the AST.
Chris Lattner1a4066d2007-08-23 06:23:56 +0000249 CaseListIsErroneous = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000250 }
Chris Lattner3429a812007-08-23 05:46:52 +0000251 TheDefaultStmt = DS;
Chris Lattner4b009652007-07-25 00:24:17 +0000252
Chris Lattner3429a812007-08-23 05:46:52 +0000253 } else {
254 CaseStmt *CS = cast<CaseStmt>(SC);
255
256 // We already verified that the expression has a i-c-e value (C99
257 // 6.8.4.2p3) - get that value now.
258 llvm::APSInt LoVal(32);
259 CS->getLHS()->isIntegerConstantExpr(LoVal, Context);
260
261 // Convert the value to the same width/sign as the condition.
262 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
263 CS->getLHS()->getLocStart(),
264 diag::warn_case_value_overflow);
Chris Lattner4b009652007-07-25 00:24:17 +0000265
Chris Lattner1a4066d2007-08-23 06:23:56 +0000266 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
Chris Lattner3429a812007-08-23 05:46:52 +0000267 if (CS->getRHS())
268 CaseRanges.push_back(std::make_pair(LoVal, CS));
Chris Lattner1a4066d2007-08-23 06:23:56 +0000269 else
270 CaseVals.push_back(std::make_pair(LoVal, CS));
Chris Lattner3429a812007-08-23 05:46:52 +0000271 }
272 }
273
Chris Lattner1a4066d2007-08-23 06:23:56 +0000274 // Sort all the scalar case values so we can easily detect duplicates.
275 std::stable_sort(CaseVals.begin(), CaseVals.end());
Chris Lattner3429a812007-08-23 05:46:52 +0000276
Chris Lattner2b1b9a82007-08-23 14:29:07 +0000277 if (!CaseVals.empty()) {
278 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
279 if (CaseVals[i].first == CaseVals[i+1].first) {
280 // If we have a duplicate, report it.
281 Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
282 diag::err_duplicate_case, CaseVals[i].first.toString());
283 Diag(CaseVals[i].second->getLHS()->getLocStart(),
284 diag::err_duplicate_case_prev);
285 // FIXME: We really want to remove the bogus case stmt from the substmt,
286 // but we have no way to do this right now.
287 CaseListIsErroneous = true;
288 }
Chris Lattner1a4066d2007-08-23 06:23:56 +0000289 }
290 }
Chris Lattner3429a812007-08-23 05:46:52 +0000291
Chris Lattner1a4066d2007-08-23 06:23:56 +0000292 // Detect duplicate case ranges, which usually don't exist at all in the first
293 // place.
294 if (!CaseRanges.empty()) {
295 // Sort all the case ranges by their low value so we can easily detect
296 // overlaps between ranges.
297 std::stable_sort(CaseVals.begin(), CaseVals.end());
298
299 // Scan the ranges, computing the high values and removing empty ranges.
300 std::vector<llvm::APSInt> HiVals;
301 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
302 CaseStmt *CR = CaseRanges[i].second;
303 llvm::APSInt HiVal(32);
304 CR->getRHS()->isIntegerConstantExpr(HiVal, Context);
305
306 // Convert the value to the same width/sign as the condition.
307 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
308 CR->getRHS()->getLocStart(),
309 diag::warn_case_value_overflow);
310
311 // FIXME: if the low value is bigger than the high value, the case is
312 // empty: emit "empty range specified" warning and drop it.
313
314 HiVals.push_back(HiVal);
315 }
316
317 // Rescan the ranges, looking for overlap with singleton values and other
318 // ranges.
319 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
320 //llvm::APSInt &CRLow = CaseRanges[i].first;
321 //CaseStmt *CR = CaseRanges[i].second;
322
323 // FIXME: TODO.
324 }
325 }
Chris Lattner3429a812007-08-23 05:46:52 +0000326
Chris Lattner1a4066d2007-08-23 06:23:56 +0000327 // FIXME: If the case list was broken is some way, we don't have a good system
328 // to patch it up. Instead, just return the whole substmt as broken.
329 if (CaseListIsErroneous)
330 return true;
Chris Lattner3429a812007-08-23 05:46:52 +0000331
Chris Lattner4b009652007-07-25 00:24:17 +0000332 return SS;
333}
334
335Action::StmtResult
336Sema::ParseWhileStmt(SourceLocation WhileLoc, ExprTy *Cond, StmtTy *Body) {
337 Expr *condExpr = (Expr *)Cond;
338 assert(condExpr && "ParseWhileStmt(): missing expression");
339
340 DefaultFunctionArrayConversion(condExpr);
341 QualType condType = condExpr->getType();
342
343 if (!condType->isScalarType()) // C99 6.8.5p2
344 return Diag(WhileLoc, diag::err_typecheck_statement_requires_scalar,
345 condType.getAsString(), condExpr->getSourceRange());
346
347 return new WhileStmt(condExpr, (Stmt*)Body);
348}
349
350Action::StmtResult
351Sema::ParseDoStmt(SourceLocation DoLoc, StmtTy *Body,
352 SourceLocation WhileLoc, ExprTy *Cond) {
353 Expr *condExpr = (Expr *)Cond;
354 assert(condExpr && "ParseDoStmt(): missing expression");
355
356 DefaultFunctionArrayConversion(condExpr);
357 QualType condType = condExpr->getType();
358
359 if (!condType->isScalarType()) // C99 6.8.5p2
360 return Diag(DoLoc, diag::err_typecheck_statement_requires_scalar,
361 condType.getAsString(), condExpr->getSourceRange());
362
363 return new DoStmt((Stmt*)Body, condExpr);
364}
365
366Action::StmtResult
367Sema::ParseForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
368 StmtTy *First, ExprTy *Second, ExprTy *Third,
369 SourceLocation RParenLoc, StmtTy *Body) {
370 if (First) {
371 // C99 6.8.5p3: FIXME. Need to hack Parser::ParseForStatement() and
372 // declaration support to create a DeclStmt node. Once this is done,
373 // we can test for DeclStmt vs. Expr (already a sub-class of Stmt).
374 }
375 if (Second) {
376 Expr *testExpr = (Expr *)Second;
377 DefaultFunctionArrayConversion(testExpr);
378 QualType testType = testExpr->getType();
379
380 if (!testType->isScalarType()) // C99 6.8.5p2
381 return Diag(ForLoc, diag::err_typecheck_statement_requires_scalar,
382 testType.getAsString(), testExpr->getSourceRange());
383 }
384 return new ForStmt((Stmt*)First, (Expr*)Second, (Expr*)Third, (Stmt*)Body);
385}
386
387
388Action::StmtResult
389Sema::ParseGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
390 IdentifierInfo *LabelII) {
391 // Look up the record for this label identifier.
392 LabelStmt *&LabelDecl = LabelMap[LabelII];
393
394 // If we haven't seen this label yet, create a forward reference.
395 if (LabelDecl == 0)
396 LabelDecl = new LabelStmt(LabelLoc, LabelII, 0);
397
398 return new GotoStmt(LabelDecl);
399}
400
401Action::StmtResult
402Sema::ParseIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,
403 ExprTy *DestExp) {
404 // FIXME: Verify that the operand is convertible to void*.
405
406 return new IndirectGotoStmt((Expr*)DestExp);
407}
408
409Action::StmtResult
410Sema::ParseContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
411 Scope *S = CurScope->getContinueParent();
412 if (!S) {
413 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
414 Diag(ContinueLoc, diag::err_continue_not_in_loop);
415 return true;
416 }
417
418 return new ContinueStmt();
419}
420
421Action::StmtResult
422Sema::ParseBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
423 Scope *S = CurScope->getBreakParent();
424 if (!S) {
425 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
426 Diag(BreakLoc, diag::err_break_not_in_loop_or_switch);
427 return true;
428 }
429
430 return new BreakStmt();
431}
432
433
434Action::StmtResult
435Sema::ParseReturnStmt(SourceLocation ReturnLoc, ExprTy *rex) {
436 Expr *RetValExp = static_cast<Expr *>(rex);
437 QualType lhsType = CurFunctionDecl->getResultType();
438
439 if (lhsType->isVoidType()) {
440 if (RetValExp) // C99 6.8.6.4p1 (ext_ since GCC warns)
441 Diag(ReturnLoc, diag::ext_return_has_expr,
442 CurFunctionDecl->getIdentifier()->getName(),
443 RetValExp->getSourceRange());
444 return new ReturnStmt(RetValExp);
445 } else {
446 if (!RetValExp) {
447 const char *funcName = CurFunctionDecl->getIdentifier()->getName();
448 if (getLangOptions().C99) // C99 6.8.6.4p1 (ext_ since GCC warns)
449 Diag(ReturnLoc, diag::ext_return_missing_expr, funcName);
450 else // C90 6.6.6.4p4
451 Diag(ReturnLoc, diag::warn_return_missing_expr, funcName);
452 return new ReturnStmt((Expr*)0);
453 }
454 }
455 // we have a non-void function with an expression, continue checking
456 QualType rhsType = RetValExp->getType();
457
458 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
459 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
460 // function return.
461 AssignmentCheckResult result = CheckSingleAssignmentConstraints(lhsType,
462 RetValExp);
Ted Kremenek235e1ad2007-08-14 18:14:14 +0000463
Chris Lattner4b009652007-07-25 00:24:17 +0000464 // decode the result (notice that extensions still return a type).
465 switch (result) {
466 case Compatible:
467 break;
468 case Incompatible:
469 Diag(ReturnLoc, diag::err_typecheck_return_incompatible,
470 lhsType.getAsString(), rhsType.getAsString(),
471 RetValExp->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000472 break;
473 case PointerFromInt:
474 // check for null pointer constant (C99 6.3.2.3p3)
475 if (!RetValExp->isNullPointerConstant(Context)) {
476 Diag(ReturnLoc, diag::ext_typecheck_return_pointer_int,
477 lhsType.getAsString(), rhsType.getAsString(),
478 RetValExp->getSourceRange());
479 }
480 break;
481 case IntFromPointer:
482 Diag(ReturnLoc, diag::ext_typecheck_return_pointer_int,
483 lhsType.getAsString(), rhsType.getAsString(),
484 RetValExp->getSourceRange());
485 break;
486 case IncompatiblePointer:
487 Diag(ReturnLoc, diag::ext_typecheck_return_incompatible_pointer,
488 lhsType.getAsString(), rhsType.getAsString(),
489 RetValExp->getSourceRange());
490 break;
491 case CompatiblePointerDiscardsQualifiers:
492 Diag(ReturnLoc, diag::ext_typecheck_return_discards_qualifiers,
493 lhsType.getAsString(), rhsType.getAsString(),
494 RetValExp->getSourceRange());
495 break;
496 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000497
498 if (RetValExp) CheckReturnStackAddr(RetValExp, lhsType, ReturnLoc);
499
Chris Lattner4b009652007-07-25 00:24:17 +0000500 return new ReturnStmt((Expr*)RetValExp);
501}
502