SemaChecking.cpp revision 5caa370ea6f70bd3e7e4a9cc3b69ac1a849c8534
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Lex/Preprocessor.h"
22using namespace clang;
23
24/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex.  They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business.  This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32                                                    unsigned ByteNo) const {
33  assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
35  // Loop over all of the tokens in this string until we find the one that
36  // contains the byte we're looking for.
37  unsigned TokNo = 0;
38  while (1) {
39    assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40    SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42    // Get the spelling of the string so that we can get the data that makes up
43    // the string literal, not the identifier for the macro it is potentially
44    // expanded through.
45    SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47    // Re-lex the token to get its length and original spelling.
48    std::pair<FileID, unsigned> LocInfo =
49      SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50    std::pair<const char *,const char *> Buffer =
51      SourceMgr.getBufferData(LocInfo.first);
52    const char *StrData = Buffer.first+LocInfo.second;
53
54    // Create a langops struct and enable trigraphs.  This is sufficient for
55    // relexing tokens.
56    LangOptions LangOpts;
57    LangOpts.Trigraphs = true;
58
59    // Create a lexer starting at the beginning of this token.
60    Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61                   Buffer.second);
62    Token TheTok;
63    TheLexer.LexFromRawLexer(TheTok);
64
65    // Use the StringLiteralParser to compute the length of the string in bytes.
66    StringLiteralParser SLP(&TheTok, 1, PP);
67    unsigned TokNumBytes = SLP.GetStringLength();
68
69    // If the byte is in this token, return the location of the byte.
70    if (ByteNo < TokNumBytes ||
71        (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
72      unsigned Offset =
73        StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75      // Now that we know the offset of the token in the spelling, use the
76      // preprocessor to get the offset in the original source.
77      return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
78    }
79
80    // Move to the next string token.
81    ++TokNo;
82    ByteNo -= TokNumBytes;
83  }
84}
85
86
87/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
89Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91  OwningExprResult TheCallResult(Owned(TheCall));
92  // Get the IdentifierInfo* for the called function.
93  IdentifierInfo *FnInfo = FDecl->getIdentifier();
94
95  // None of the checks below are needed for functions that don't have
96  // simple names (e.g., C++ conversion functions).
97  if (!FnInfo)
98    return move(TheCallResult);
99
100  switch (FDecl->getBuiltinID(Context)) {
101  case Builtin::BI__builtin___CFStringMakeConstantString:
102    assert(TheCall->getNumArgs() == 1 &&
103           "Wrong # arguments to builtin CFStringMakeConstantString");
104    if (CheckObjCString(TheCall->getArg(0)))
105      return ExprError();
106    return move(TheCallResult);
107  case Builtin::BI__builtin_stdarg_start:
108  case Builtin::BI__builtin_va_start:
109    if (SemaBuiltinVAStart(TheCall))
110      return ExprError();
111    return move(TheCallResult);
112  case Builtin::BI__builtin_isgreater:
113  case Builtin::BI__builtin_isgreaterequal:
114  case Builtin::BI__builtin_isless:
115  case Builtin::BI__builtin_islessequal:
116  case Builtin::BI__builtin_islessgreater:
117  case Builtin::BI__builtin_isunordered:
118    if (SemaBuiltinUnorderedCompare(TheCall))
119      return ExprError();
120    return move(TheCallResult);
121  case Builtin::BI__builtin_return_address:
122  case Builtin::BI__builtin_frame_address:
123    if (SemaBuiltinStackAddress(TheCall))
124      return ExprError();
125    return move(TheCallResult);
126  case Builtin::BI__builtin_shufflevector:
127    return SemaBuiltinShuffleVector(TheCall);
128    // TheCall will be freed by the smart pointer here, but that's fine, since
129    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
130  case Builtin::BI__builtin_prefetch:
131    if (SemaBuiltinPrefetch(TheCall))
132      return ExprError();
133    return move(TheCallResult);
134  case Builtin::BI__builtin_object_size:
135    if (SemaBuiltinObjectSize(TheCall))
136      return ExprError();
137    return move(TheCallResult);
138  case Builtin::BI__builtin_longjmp:
139    if (SemaBuiltinLongjmp(TheCall))
140      return ExprError();
141    return move(TheCallResult);
142  case Builtin::BI__sync_fetch_and_add:
143  case Builtin::BI__sync_fetch_and_sub:
144  case Builtin::BI__sync_fetch_and_or:
145  case Builtin::BI__sync_fetch_and_and:
146  case Builtin::BI__sync_fetch_and_xor:
147  case Builtin::BI__sync_add_and_fetch:
148  case Builtin::BI__sync_sub_and_fetch:
149  case Builtin::BI__sync_and_and_fetch:
150  case Builtin::BI__sync_or_and_fetch:
151  case Builtin::BI__sync_xor_and_fetch:
152  case Builtin::BI__sync_val_compare_and_swap:
153  case Builtin::BI__sync_bool_compare_and_swap:
154  case Builtin::BI__sync_lock_test_and_set:
155  case Builtin::BI__sync_lock_release:
156    if (SemaBuiltinAtomicOverloaded(TheCall))
157      return ExprError();
158    return move(TheCallResult);
159  }
160
161  // FIXME: This mechanism should be abstracted to be less fragile and
162  // more efficient. For example, just map function ids to custom
163  // handlers.
164
165  // Printf checking.
166  if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
167    if (Format->getType() == "printf") {
168      bool HasVAListArg = Format->getFirstArg() == 0;
169      if (!HasVAListArg) {
170        if (const FunctionProtoType *Proto
171            = FDecl->getType()->getAsFunctionProtoType())
172        HasVAListArg = !Proto->isVariadic();
173      }
174      CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
175                           HasVAListArg ? 0 : Format->getFirstArg() - 1);
176    }
177  }
178
179  return move(TheCallResult);
180}
181
182/// SemaBuiltinAtomicOverloaded - We have a call to a function like
183/// __sync_fetch_and_add, which is an overloaded function based on the pointer
184/// type of its first argument.  The main ActOnCallExpr routines have already
185/// promoted the types of arguments because all of these calls are prototyped as
186/// void(...).
187///
188/// This function goes through and does final semantic checking for these
189/// builtins,
190bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
191  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
192  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
193
194  // Ensure that we have at least one argument to do type inference from.
195  if (TheCall->getNumArgs() < 1)
196    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
197              << 0 << TheCall->getCallee()->getSourceRange();
198
199  // Inspect the first argument of the atomic builtin.  This should always be
200  // a pointer type, whose element is an integral scalar or pointer type.
201  // Because it is a pointer type, we don't have to worry about any implicit
202  // casts here.
203  Expr *FirstArg = TheCall->getArg(0);
204  if (!FirstArg->getType()->isPointerType())
205    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
206             << FirstArg->getType() << FirstArg->getSourceRange();
207
208  QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
209  if (!ValType->isIntegerType() && !ValType->isPointerType() &&
210      !ValType->isBlockPointerType())
211    return Diag(DRE->getLocStart(),
212                diag::err_atomic_builtin_must_be_pointer_intptr)
213             << FirstArg->getType() << FirstArg->getSourceRange();
214
215  // We need to figure out which concrete builtin this maps onto.  For example,
216  // __sync_fetch_and_add with a 2 byte object turns into
217  // __sync_fetch_and_add_2.
218#define BUILTIN_ROW(x) \
219  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
220    Builtin::BI##x##_8, Builtin::BI##x##_16 }
221
222  static const unsigned BuiltinIndices[][5] = {
223    BUILTIN_ROW(__sync_fetch_and_add),
224    BUILTIN_ROW(__sync_fetch_and_sub),
225    BUILTIN_ROW(__sync_fetch_and_or),
226    BUILTIN_ROW(__sync_fetch_and_and),
227    BUILTIN_ROW(__sync_fetch_and_xor),
228
229    BUILTIN_ROW(__sync_add_and_fetch),
230    BUILTIN_ROW(__sync_sub_and_fetch),
231    BUILTIN_ROW(__sync_and_and_fetch),
232    BUILTIN_ROW(__sync_or_and_fetch),
233    BUILTIN_ROW(__sync_xor_and_fetch),
234
235    BUILTIN_ROW(__sync_val_compare_and_swap),
236    BUILTIN_ROW(__sync_bool_compare_and_swap),
237    BUILTIN_ROW(__sync_lock_test_and_set),
238    BUILTIN_ROW(__sync_lock_release)
239  };
240#undef BUILTIN_ROW
241
242  // Determine the index of the size.
243  unsigned SizeIndex;
244  switch (Context.getTypeSize(ValType)/8) {
245  case 1: SizeIndex = 0; break;
246  case 2: SizeIndex = 1; break;
247  case 4: SizeIndex = 2; break;
248  case 8: SizeIndex = 3; break;
249  case 16: SizeIndex = 4; break;
250  default:
251    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
252             << FirstArg->getType() << FirstArg->getSourceRange();
253  }
254
255  // Each of these builtins has one pointer argument, followed by some number of
256  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
257  // that we ignore.  Find out which row of BuiltinIndices to read from as well
258  // as the number of fixed args.
259  unsigned BuiltinID = FDecl->getBuiltinID(Context);
260  unsigned BuiltinIndex, NumFixed = 1;
261  switch (BuiltinID) {
262  default: assert(0 && "Unknown overloaded atomic builtin!");
263  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
264  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
265  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
266  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
267  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
268
269  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
270  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
271  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
272  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
273  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
274
275  case Builtin::BI__sync_val_compare_and_swap:
276    BuiltinIndex = 10;
277    NumFixed = 2;
278    break;
279  case Builtin::BI__sync_bool_compare_and_swap:
280    BuiltinIndex = 11;
281    NumFixed = 2;
282    break;
283  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
284  case Builtin::BI__sync_lock_release:
285    BuiltinIndex = 13;
286    NumFixed = 0;
287    break;
288  }
289
290  // Now that we know how many fixed arguments we expect, first check that we
291  // have at least that many.
292  if (TheCall->getNumArgs() < 1+NumFixed)
293    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
294            << 0 << TheCall->getCallee()->getSourceRange();
295
296  // Next, walk the valid ones promoting to the right type.
297  for (unsigned i = 0; i != NumFixed; ++i) {
298    Expr *Arg = TheCall->getArg(i+1);
299
300    // If the argument is an implicit cast, then there was a promotion due to
301    // "...", just remove it now.
302    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
303      Arg = ICE->getSubExpr();
304      ICE->setSubExpr(0);
305      ICE->Destroy(Context);
306      TheCall->setArg(i+1, Arg);
307    }
308
309    // GCC does an implicit conversion to the pointer or integer ValType.  This
310    // can fail in some cases (1i -> int**), check for this error case now.
311    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
312      return true;
313
314    // Okay, we have something that *can* be converted to the right type.  Check
315    // to see if there is a potentially weird extension going on here.  This can
316    // happen when you do an atomic operation on something like an char* and
317    // pass in 42.  The 42 gets converted to char.  This is even more strange
318    // for things like 45.123 -> char, etc.
319    // FIXME: Do this check.
320    ImpCastExprToType(Arg, ValType, false);
321    TheCall->setArg(i+1, Arg);
322  }
323
324  // Okay, if we get here, everything is good.  Get the decl for the concrete
325  // builtin.
326  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
327  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
328  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
329  FunctionDecl *NewBuiltinDecl =
330    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
331                                           TUScope, false, DRE->getLocStart()));
332  // Switch the DeclRefExpr to refer to the new decl.
333  DRE->setDecl(NewBuiltinDecl);
334  DRE->setType(NewBuiltinDecl->getType());
335
336  // Set the callee in the CallExpr.
337  // FIXME: This leaks the original parens and implicit casts.
338  Expr *PromotedCall = DRE;
339  UsualUnaryConversions(PromotedCall);
340  TheCall->setCallee(PromotedCall);
341
342
343  // Change the result type of the call to match the result type of the decl.
344  TheCall->setType(NewBuiltinDecl->getResultType());
345  return false;
346}
347
348
349/// CheckObjCString - Checks that the argument to the builtin
350/// CFString constructor is correct
351/// FIXME: GCC currently emits the following warning:
352/// "warning: input conversion stopped due to an input byte that does not
353///           belong to the input codeset UTF-8"
354/// Note: It might also make sense to do the UTF-16 conversion here (would
355/// simplify the backend).
356bool Sema::CheckObjCString(Expr *Arg) {
357  Arg = Arg->IgnoreParenCasts();
358  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
359
360  if (!Literal || Literal->isWide()) {
361    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
362      << Arg->getSourceRange();
363    return true;
364  }
365
366  const char *Data = Literal->getStrData();
367  unsigned Length = Literal->getByteLength();
368
369  for (unsigned i = 0; i < Length; ++i) {
370    if (!Data[i]) {
371      Diag(getLocationOfStringLiteralByte(Literal, i),
372           diag::warn_cfstring_literal_contains_nul_character)
373        << Arg->getSourceRange();
374      break;
375    }
376  }
377
378  return false;
379}
380
381/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
382/// Emit an error and return true on failure, return false on success.
383bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
384  Expr *Fn = TheCall->getCallee();
385  if (TheCall->getNumArgs() > 2) {
386    Diag(TheCall->getArg(2)->getLocStart(),
387         diag::err_typecheck_call_too_many_args)
388      << 0 /*function call*/ << Fn->getSourceRange()
389      << SourceRange(TheCall->getArg(2)->getLocStart(),
390                     (*(TheCall->arg_end()-1))->getLocEnd());
391    return true;
392  }
393
394  if (TheCall->getNumArgs() < 2) {
395    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
396      << 0 /*function call*/;
397  }
398
399  // Determine whether the current function is variadic or not.
400  bool isVariadic;
401  if (CurBlock)
402    isVariadic = CurBlock->isVariadic;
403  else if (getCurFunctionDecl()) {
404    if (FunctionProtoType* FTP =
405            dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
406      isVariadic = FTP->isVariadic();
407    else
408      isVariadic = false;
409  } else {
410    isVariadic = getCurMethodDecl()->isVariadic();
411  }
412
413  if (!isVariadic) {
414    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
415    return true;
416  }
417
418  // Verify that the second argument to the builtin is the last argument of the
419  // current function or method.
420  bool SecondArgIsLastNamedArgument = false;
421  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
422
423  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
424    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
425      // FIXME: This isn't correct for methods (results in bogus warning).
426      // Get the last formal in the current function.
427      const ParmVarDecl *LastArg;
428      if (CurBlock)
429        LastArg = *(CurBlock->TheDecl->param_end()-1);
430      else if (FunctionDecl *FD = getCurFunctionDecl())
431        LastArg = *(FD->param_end()-1);
432      else
433        LastArg = *(getCurMethodDecl()->param_end()-1);
434      SecondArgIsLastNamedArgument = PV == LastArg;
435    }
436  }
437
438  if (!SecondArgIsLastNamedArgument)
439    Diag(TheCall->getArg(1)->getLocStart(),
440         diag::warn_second_parameter_of_va_start_not_last_named_argument);
441  return false;
442}
443
444/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
445/// friends.  This is declared to take (...), so we have to check everything.
446bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
447  if (TheCall->getNumArgs() < 2)
448    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
449      << 0 /*function call*/;
450  if (TheCall->getNumArgs() > 2)
451    return Diag(TheCall->getArg(2)->getLocStart(),
452                diag::err_typecheck_call_too_many_args)
453      << 0 /*function call*/
454      << SourceRange(TheCall->getArg(2)->getLocStart(),
455                     (*(TheCall->arg_end()-1))->getLocEnd());
456
457  Expr *OrigArg0 = TheCall->getArg(0);
458  Expr *OrigArg1 = TheCall->getArg(1);
459
460  // Do standard promotions between the two arguments, returning their common
461  // type.
462  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
463
464  // Make sure any conversions are pushed back into the call; this is
465  // type safe since unordered compare builtins are declared as "_Bool
466  // foo(...)".
467  TheCall->setArg(0, OrigArg0);
468  TheCall->setArg(1, OrigArg1);
469
470  // If the common type isn't a real floating type, then the arguments were
471  // invalid for this operation.
472  if (!Res->isRealFloatingType())
473    return Diag(OrigArg0->getLocStart(),
474                diag::err_typecheck_call_invalid_ordered_compare)
475      << OrigArg0->getType() << OrigArg1->getType()
476      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
477
478  return false;
479}
480
481bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
482  // The signature for these builtins is exact; the only thing we need
483  // to check is that the argument is a constant.
484  SourceLocation Loc;
485  if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
486    return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
487
488  return false;
489}
490
491/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
492// This is declared to take (...), so we have to check everything.
493Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
494  if (TheCall->getNumArgs() < 3)
495    return ExprError(Diag(TheCall->getLocEnd(),
496                          diag::err_typecheck_call_too_few_args)
497      << 0 /*function call*/ << TheCall->getSourceRange());
498
499  QualType FAType = TheCall->getArg(0)->getType();
500  QualType SAType = TheCall->getArg(1)->getType();
501
502  if (!FAType->isVectorType() || !SAType->isVectorType()) {
503    Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
504      << SourceRange(TheCall->getArg(0)->getLocStart(),
505                     TheCall->getArg(1)->getLocEnd());
506    return ExprError();
507  }
508
509  if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
510      Context.getCanonicalType(SAType).getUnqualifiedType()) {
511    Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
512      << SourceRange(TheCall->getArg(0)->getLocStart(),
513                     TheCall->getArg(1)->getLocEnd());
514    return ExprError();
515  }
516
517  unsigned numElements = FAType->getAsVectorType()->getNumElements();
518  if (TheCall->getNumArgs() != numElements+2) {
519    if (TheCall->getNumArgs() < numElements+2)
520      return ExprError(Diag(TheCall->getLocEnd(),
521                            diag::err_typecheck_call_too_few_args)
522               << 0 /*function call*/ << TheCall->getSourceRange());
523    return ExprError(Diag(TheCall->getLocEnd(),
524                          diag::err_typecheck_call_too_many_args)
525             << 0 /*function call*/ << TheCall->getSourceRange());
526  }
527
528  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
529    llvm::APSInt Result(32);
530    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
531      return ExprError(Diag(TheCall->getLocStart(),
532                  diag::err_shufflevector_nonconstant_argument)
533                << TheCall->getArg(i)->getSourceRange());
534
535    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
536      return ExprError(Diag(TheCall->getLocStart(),
537                  diag::err_shufflevector_argument_too_large)
538               << TheCall->getArg(i)->getSourceRange());
539  }
540
541  llvm::SmallVector<Expr*, 32> exprs;
542
543  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
544    exprs.push_back(TheCall->getArg(i));
545    TheCall->setArg(i, 0);
546  }
547
548  return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
549                                            FAType,
550                                            TheCall->getCallee()->getLocStart(),
551                                            TheCall->getRParenLoc()));
552}
553
554/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
555// This is declared to take (const void*, ...) and can take two
556// optional constant int args.
557bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
558  unsigned NumArgs = TheCall->getNumArgs();
559
560  if (NumArgs > 3)
561    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
562             << 0 /*function call*/ << TheCall->getSourceRange();
563
564  // Argument 0 is checked for us and the remaining arguments must be
565  // constant integers.
566  for (unsigned i = 1; i != NumArgs; ++i) {
567    Expr *Arg = TheCall->getArg(i);
568    QualType RWType = Arg->getType();
569
570    const BuiltinType *BT = RWType->getAsBuiltinType();
571    llvm::APSInt Result;
572    if (!BT || BT->getKind() != BuiltinType::Int ||
573        !Arg->isIntegerConstantExpr(Result, Context))
574      return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
575              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
576
577    // FIXME: gcc issues a warning and rewrites these to 0. These
578    // seems especially odd for the third argument since the default
579    // is 3.
580    if (i == 1) {
581      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
582        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
583             << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
584    } else {
585      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
586        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
587            << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
588    }
589  }
590
591  return false;
592}
593
594/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
595/// int type). This simply type checks that type is one of the defined
596/// constants (0-3).
597bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
598  Expr *Arg = TheCall->getArg(1);
599  QualType ArgType = Arg->getType();
600  const BuiltinType *BT = ArgType->getAsBuiltinType();
601  llvm::APSInt Result(32);
602  if (!BT || BT->getKind() != BuiltinType::Int ||
603      !Arg->isIntegerConstantExpr(Result, Context)) {
604    return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
605             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
606  }
607
608  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
609    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
610             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
611  }
612
613  return false;
614}
615
616/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
617/// This checks that val is a constant 1.
618bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
619  Expr *Arg = TheCall->getArg(1);
620  llvm::APSInt Result(32);
621  if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
622    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
623             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
624
625  return false;
626}
627
628// Handle i > 1 ? "x" : "y", recursivelly
629bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
630                                  bool HasVAListArg,
631                                  unsigned format_idx, unsigned firstDataArg) {
632
633  switch (E->getStmtClass()) {
634  case Stmt::ConditionalOperatorClass: {
635    const ConditionalOperator *C = cast<ConditionalOperator>(E);
636    return SemaCheckStringLiteral(C->getLHS(), TheCall,
637                                  HasVAListArg, format_idx, firstDataArg)
638        && SemaCheckStringLiteral(C->getRHS(), TheCall,
639                                  HasVAListArg, format_idx, firstDataArg);
640  }
641
642  case Stmt::ImplicitCastExprClass: {
643    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
644    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
645                                  format_idx, firstDataArg);
646  }
647
648  case Stmt::ParenExprClass: {
649    const ParenExpr *Expr = cast<ParenExpr>(E);
650    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
651                                  format_idx, firstDataArg);
652  }
653
654  case Stmt::DeclRefExprClass: {
655    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
656
657    // As an exception, do not flag errors for variables binding to
658    // const string literals.
659    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
660      bool isConstant = false;
661      QualType T = DR->getType();
662
663      if (const ArrayType *AT = Context.getAsArrayType(T)) {
664        isConstant = AT->getElementType().isConstant(Context);
665      }
666      else if (const PointerType *PT = T->getAsPointerType()) {
667        isConstant = T.isConstant(Context) &&
668                     PT->getPointeeType().isConstant(Context);
669      }
670
671      if (isConstant) {
672        const VarDecl *Def = 0;
673        if (const Expr *Init = VD->getDefinition(Def))
674          return SemaCheckStringLiteral(Init, TheCall,
675                                        HasVAListArg, format_idx, firstDataArg);
676      }
677    }
678
679    return false;
680  }
681
682  case Stmt::ObjCStringLiteralClass:
683  case Stmt::StringLiteralClass: {
684    const StringLiteral *StrE = NULL;
685
686    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
687      StrE = ObjCFExpr->getString();
688    else
689      StrE = cast<StringLiteral>(E);
690
691    if (StrE) {
692      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
693                        firstDataArg);
694      return true;
695    }
696
697    return false;
698  }
699
700  default:
701    return false;
702  }
703}
704
705
706/// CheckPrintfArguments - Check calls to printf (and similar functions) for
707/// correct use of format strings.
708///
709///  HasVAListArg - A predicate indicating whether the printf-like
710///    function is passed an explicit va_arg argument (e.g., vprintf)
711///
712///  format_idx - The index into Args for the format string.
713///
714/// Improper format strings to functions in the printf family can be
715/// the source of bizarre bugs and very serious security holes.  A
716/// good source of information is available in the following paper
717/// (which includes additional references):
718///
719///  FormatGuard: Automatic Protection From printf Format String
720///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
721///
722/// Functionality implemented:
723///
724///  We can statically check the following properties for string
725///  literal format strings for non v.*printf functions (where the
726///  arguments are passed directly):
727//
728///  (1) Are the number of format conversions equal to the number of
729///      data arguments?
730///
731///  (2) Does each format conversion correctly match the type of the
732///      corresponding data argument?  (TODO)
733///
734/// Moreover, for all printf functions we can:
735///
736///  (3) Check for a missing format string (when not caught by type checking).
737///
738///  (4) Check for no-operation flags; e.g. using "#" with format
739///      conversion 'c'  (TODO)
740///
741///  (5) Check the use of '%n', a major source of security holes.
742///
743///  (6) Check for malformed format conversions that don't specify anything.
744///
745///  (7) Check for empty format strings.  e.g: printf("");
746///
747///  (8) Check that the format string is a wide literal.
748///
749///  (9) Also check the arguments of functions with the __format__ attribute.
750///      (TODO).
751///
752/// All of these checks can be done by parsing the format string.
753///
754/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
755void
756Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
757                           unsigned format_idx, unsigned firstDataArg) {
758  const Expr *Fn = TheCall->getCallee();
759
760  // CHECK: printf-like function is called with no format string.
761  if (format_idx >= TheCall->getNumArgs()) {
762    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
763      << Fn->getSourceRange();
764    return;
765  }
766
767  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
768
769  // CHECK: format string is not a string literal.
770  //
771  // Dynamically generated format strings are difficult to
772  // automatically vet at compile time.  Requiring that format strings
773  // are string literals: (1) permits the checking of format strings by
774  // the compiler and thereby (2) can practically remove the source of
775  // many format string exploits.
776
777  // Format string can be either ObjC string (e.g. @"%d") or
778  // C string (e.g. "%d")
779  // ObjC string uses the same format specifiers as C string, so we can use
780  // the same format string checking logic for both ObjC and C strings.
781  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
782                             firstDataArg))
783    return;  // Literal format string found, check done!
784
785  // For vprintf* functions (i.e., HasVAListArg==true), we add a
786  // special check to see if the format string is a function parameter
787  // of the function calling the printf function.  If the function
788  // has an attribute indicating it is a printf-like function, then we
789  // should suppress warnings concerning non-literals being used in a call
790  // to a vprintf function.  For example:
791  //
792  // void
793  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
794  //      va_list ap;
795  //      va_start(ap, fmt);
796  //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
797  //      ...
798  //
799  //
800  //  FIXME: We don't have full attribute support yet, so just check to see
801  //    if the argument is a DeclRefExpr that references a parameter.  We'll
802  //    add proper support for checking the attribute later.
803  if (HasVAListArg)
804    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
805      if (isa<ParmVarDecl>(DR->getDecl()))
806        return;
807
808  // If there are no arguments specified, warn with -Wformat-security, otherwise
809  // warn only with -Wformat-nonliteral.
810  if (TheCall->getNumArgs() == format_idx+1)
811    Diag(TheCall->getArg(format_idx)->getLocStart(),
812         diag::warn_printf_nonliteral_noargs)
813      << OrigFormatExpr->getSourceRange();
814  else
815    Diag(TheCall->getArg(format_idx)->getLocStart(),
816         diag::warn_printf_nonliteral)
817           << OrigFormatExpr->getSourceRange();
818}
819
820void Sema::CheckPrintfString(const StringLiteral *FExpr,
821                             const Expr *OrigFormatExpr,
822                             const CallExpr *TheCall, bool HasVAListArg,
823                             unsigned format_idx, unsigned firstDataArg) {
824
825  const ObjCStringLiteral *ObjCFExpr =
826    dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
827
828  // CHECK: is the format string a wide literal?
829  if (FExpr->isWide()) {
830    Diag(FExpr->getLocStart(),
831         diag::warn_printf_format_string_is_wide_literal)
832      << OrigFormatExpr->getSourceRange();
833    return;
834  }
835
836  // Str - The format string.  NOTE: this is NOT null-terminated!
837  const char *Str = FExpr->getStrData();
838
839  // CHECK: empty format string?
840  unsigned StrLen = FExpr->getByteLength();
841
842  if (StrLen == 0) {
843    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
844      << OrigFormatExpr->getSourceRange();
845    return;
846  }
847
848  // We process the format string using a binary state machine.  The
849  // current state is stored in CurrentState.
850  enum {
851    state_OrdChr,
852    state_Conversion
853  } CurrentState = state_OrdChr;
854
855  // numConversions - The number of conversions seen so far.  This is
856  //  incremented as we traverse the format string.
857  unsigned numConversions = 0;
858
859  // numDataArgs - The number of data arguments after the format
860  //  string.  This can only be determined for non vprintf-like
861  //  functions.  For those functions, this value is 1 (the sole
862  //  va_arg argument).
863  unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
864
865  // Inspect the format string.
866  unsigned StrIdx = 0;
867
868  // LastConversionIdx - Index within the format string where we last saw
869  //  a '%' character that starts a new format conversion.
870  unsigned LastConversionIdx = 0;
871
872  for (; StrIdx < StrLen; ++StrIdx) {
873
874    // Is the number of detected conversion conversions greater than
875    // the number of matching data arguments?  If so, stop.
876    if (!HasVAListArg && numConversions > numDataArgs) break;
877
878    // Handle "\0"
879    if (Str[StrIdx] == '\0') {
880      // The string returned by getStrData() is not null-terminated,
881      // so the presence of a null character is likely an error.
882      Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
883           diag::warn_printf_format_string_contains_null_char)
884        <<  OrigFormatExpr->getSourceRange();
885      return;
886    }
887
888    // Ordinary characters (not processing a format conversion).
889    if (CurrentState == state_OrdChr) {
890      if (Str[StrIdx] == '%') {
891        CurrentState = state_Conversion;
892        LastConversionIdx = StrIdx;
893      }
894      continue;
895    }
896
897    // Seen '%'.  Now processing a format conversion.
898    switch (Str[StrIdx]) {
899    // Handle dynamic precision or width specifier.
900    case '*': {
901      ++numConversions;
902
903      if (!HasVAListArg && numConversions > numDataArgs) {
904        SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
905
906        if (Str[StrIdx-1] == '.')
907          Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
908            << OrigFormatExpr->getSourceRange();
909        else
910          Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
911            << OrigFormatExpr->getSourceRange();
912
913        // Don't do any more checking.  We'll just emit spurious errors.
914        return;
915      }
916
917      // Perform type checking on width/precision specifier.
918      const Expr *E = TheCall->getArg(format_idx+numConversions);
919      if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
920        if (BT->getKind() == BuiltinType::Int)
921          break;
922
923      SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
924
925      if (Str[StrIdx-1] == '.')
926        Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
927          << E->getType() << E->getSourceRange();
928      else
929        Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
930          << E->getType() << E->getSourceRange();
931
932      break;
933    }
934
935    // Characters which can terminate a format conversion
936    // (e.g. "%d").  Characters that specify length modifiers or
937    // other flags are handled by the default case below.
938    //
939    // FIXME: additional checks will go into the following cases.
940    case 'i':
941    case 'd':
942    case 'o':
943    case 'u':
944    case 'x':
945    case 'X':
946    case 'D':
947    case 'O':
948    case 'U':
949    case 'e':
950    case 'E':
951    case 'f':
952    case 'F':
953    case 'g':
954    case 'G':
955    case 'a':
956    case 'A':
957    case 'c':
958    case 'C':
959    case 'S':
960    case 's':
961    case 'p':
962      ++numConversions;
963      CurrentState = state_OrdChr;
964      break;
965
966    // CHECK: Are we using "%n"?  Issue a warning.
967    case 'n': {
968      ++numConversions;
969      CurrentState = state_OrdChr;
970      SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
971                                                          LastConversionIdx);
972
973      Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
974      break;
975    }
976
977    // Handle "%@"
978    case '@':
979      // %@ is allowed in ObjC format strings only.
980      if(ObjCFExpr != NULL)
981        CurrentState = state_OrdChr;
982      else {
983        // Issue a warning: invalid format conversion.
984        SourceLocation Loc =
985          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
986
987        Diag(Loc, diag::warn_printf_invalid_conversion)
988          <<  std::string(Str+LastConversionIdx,
989                          Str+std::min(LastConversionIdx+2, StrLen))
990          << OrigFormatExpr->getSourceRange();
991      }
992      ++numConversions;
993      break;
994
995    // Handle "%%"
996    case '%':
997      // Sanity check: Was the first "%" character the previous one?
998      // If not, we will assume that we have a malformed format
999      // conversion, and that the current "%" character is the start
1000      // of a new conversion.
1001      if (StrIdx - LastConversionIdx == 1)
1002        CurrentState = state_OrdChr;
1003      else {
1004        // Issue a warning: invalid format conversion.
1005        SourceLocation Loc =
1006          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1007
1008        Diag(Loc, diag::warn_printf_invalid_conversion)
1009          << std::string(Str+LastConversionIdx, Str+StrIdx)
1010          << OrigFormatExpr->getSourceRange();
1011
1012        // This conversion is broken.  Advance to the next format
1013        // conversion.
1014        LastConversionIdx = StrIdx;
1015        ++numConversions;
1016      }
1017      break;
1018
1019    default:
1020      // This case catches all other characters: flags, widths, etc.
1021      // We should eventually process those as well.
1022      break;
1023    }
1024  }
1025
1026  if (CurrentState == state_Conversion) {
1027    // Issue a warning: invalid format conversion.
1028    SourceLocation Loc =
1029      getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1030
1031    Diag(Loc, diag::warn_printf_invalid_conversion)
1032      << std::string(Str+LastConversionIdx,
1033                     Str+std::min(LastConversionIdx+2, StrLen))
1034      << OrigFormatExpr->getSourceRange();
1035    return;
1036  }
1037
1038  if (!HasVAListArg) {
1039    // CHECK: Does the number of format conversions exceed the number
1040    //        of data arguments?
1041    if (numConversions > numDataArgs) {
1042      SourceLocation Loc =
1043        getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1044
1045      Diag(Loc, diag::warn_printf_insufficient_data_args)
1046        << OrigFormatExpr->getSourceRange();
1047    }
1048    // CHECK: Does the number of data arguments exceed the number of
1049    //        format conversions in the format string?
1050    else if (numConversions < numDataArgs)
1051      Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
1052           diag::warn_printf_too_many_data_args)
1053        << OrigFormatExpr->getSourceRange();
1054  }
1055}
1056
1057//===--- CHECK: Return Address of Stack Variable --------------------------===//
1058
1059static DeclRefExpr* EvalVal(Expr *E);
1060static DeclRefExpr* EvalAddr(Expr* E);
1061
1062/// CheckReturnStackAddr - Check if a return statement returns the address
1063///   of a stack variable.
1064void
1065Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1066                           SourceLocation ReturnLoc) {
1067
1068  // Perform checking for returned stack addresses.
1069  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1070    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1071      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1072       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1073
1074    // Skip over implicit cast expressions when checking for block expressions.
1075    if (ImplicitCastExpr *IcExpr =
1076          dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1077      RetValExp = IcExpr->getSubExpr();
1078
1079    if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
1080      if (C->hasBlockDeclRefExprs())
1081        Diag(C->getLocStart(), diag::err_ret_local_block)
1082          << C->getSourceRange();
1083  }
1084  // Perform checking for stack values returned by reference.
1085  else if (lhsType->isReferenceType()) {
1086    // Check for a reference to the stack
1087    if (DeclRefExpr *DR = EvalVal(RetValExp))
1088      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1089        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1090  }
1091}
1092
1093/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1094///  check if the expression in a return statement evaluates to an address
1095///  to a location on the stack.  The recursion is used to traverse the
1096///  AST of the return expression, with recursion backtracking when we
1097///  encounter a subexpression that (1) clearly does not lead to the address
1098///  of a stack variable or (2) is something we cannot determine leads to
1099///  the address of a stack variable based on such local checking.
1100///
1101///  EvalAddr processes expressions that are pointers that are used as
1102///  references (and not L-values).  EvalVal handles all other values.
1103///  At the base case of the recursion is a check for a DeclRefExpr* in
1104///  the refers to a stack variable.
1105///
1106///  This implementation handles:
1107///
1108///   * pointer-to-pointer casts
1109///   * implicit conversions from array references to pointers
1110///   * taking the address of fields
1111///   * arbitrary interplay between "&" and "*" operators
1112///   * pointer arithmetic from an address of a stack variable
1113///   * taking the address of an array element where the array is on the stack
1114static DeclRefExpr* EvalAddr(Expr *E) {
1115  // We should only be called for evaluating pointer expressions.
1116  assert((E->getType()->isPointerType() ||
1117          E->getType()->isBlockPointerType() ||
1118          E->getType()->isObjCQualifiedIdType()) &&
1119         "EvalAddr only works on pointers");
1120
1121  // Our "symbolic interpreter" is just a dispatch off the currently
1122  // viewed AST node.  We then recursively traverse the AST by calling
1123  // EvalAddr and EvalVal appropriately.
1124  switch (E->getStmtClass()) {
1125  case Stmt::ParenExprClass:
1126    // Ignore parentheses.
1127    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1128
1129  case Stmt::UnaryOperatorClass: {
1130    // The only unary operator that make sense to handle here
1131    // is AddrOf.  All others don't make sense as pointers.
1132    UnaryOperator *U = cast<UnaryOperator>(E);
1133
1134    if (U->getOpcode() == UnaryOperator::AddrOf)
1135      return EvalVal(U->getSubExpr());
1136    else
1137      return NULL;
1138  }
1139
1140  case Stmt::BinaryOperatorClass: {
1141    // Handle pointer arithmetic.  All other binary operators are not valid
1142    // in this context.
1143    BinaryOperator *B = cast<BinaryOperator>(E);
1144    BinaryOperator::Opcode op = B->getOpcode();
1145
1146    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1147      return NULL;
1148
1149    Expr *Base = B->getLHS();
1150
1151    // Determine which argument is the real pointer base.  It could be
1152    // the RHS argument instead of the LHS.
1153    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1154
1155    assert (Base->getType()->isPointerType());
1156    return EvalAddr(Base);
1157  }
1158
1159  // For conditional operators we need to see if either the LHS or RHS are
1160  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1161  case Stmt::ConditionalOperatorClass: {
1162    ConditionalOperator *C = cast<ConditionalOperator>(E);
1163
1164    // Handle the GNU extension for missing LHS.
1165    if (Expr *lhsExpr = C->getLHS())
1166      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1167        return LHS;
1168
1169     return EvalAddr(C->getRHS());
1170  }
1171
1172  // For casts, we need to handle conversions from arrays to
1173  // pointer values, and pointer-to-pointer conversions.
1174  case Stmt::ImplicitCastExprClass:
1175  case Stmt::CStyleCastExprClass:
1176  case Stmt::CXXFunctionalCastExprClass: {
1177    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1178    QualType T = SubExpr->getType();
1179
1180    if (SubExpr->getType()->isPointerType() ||
1181        SubExpr->getType()->isBlockPointerType() ||
1182        SubExpr->getType()->isObjCQualifiedIdType())
1183      return EvalAddr(SubExpr);
1184    else if (T->isArrayType())
1185      return EvalVal(SubExpr);
1186    else
1187      return 0;
1188  }
1189
1190  // C++ casts.  For dynamic casts, static casts, and const casts, we
1191  // are always converting from a pointer-to-pointer, so we just blow
1192  // through the cast.  In the case the dynamic cast doesn't fail (and
1193  // return NULL), we take the conservative route and report cases
1194  // where we return the address of a stack variable.  For Reinterpre
1195  // FIXME: The comment about is wrong; we're not always converting
1196  // from pointer to pointer. I'm guessing that this code should also
1197  // handle references to objects.
1198  case Stmt::CXXStaticCastExprClass:
1199  case Stmt::CXXDynamicCastExprClass:
1200  case Stmt::CXXConstCastExprClass:
1201  case Stmt::CXXReinterpretCastExprClass: {
1202      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1203      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1204        return EvalAddr(S);
1205      else
1206        return NULL;
1207  }
1208
1209  // Everything else: we simply don't reason about them.
1210  default:
1211    return NULL;
1212  }
1213}
1214
1215
1216///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1217///   See the comments for EvalAddr for more details.
1218static DeclRefExpr* EvalVal(Expr *E) {
1219
1220  // We should only be called for evaluating non-pointer expressions, or
1221  // expressions with a pointer type that are not used as references but instead
1222  // are l-values (e.g., DeclRefExpr with a pointer type).
1223
1224  // Our "symbolic interpreter" is just a dispatch off the currently
1225  // viewed AST node.  We then recursively traverse the AST by calling
1226  // EvalAddr and EvalVal appropriately.
1227  switch (E->getStmtClass()) {
1228  case Stmt::DeclRefExprClass:
1229  case Stmt::QualifiedDeclRefExprClass: {
1230    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1231    //  at code that refers to a variable's name.  We check if it has local
1232    //  storage within the function, and if so, return the expression.
1233    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1234
1235    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1236      if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1237
1238    return NULL;
1239  }
1240
1241  case Stmt::ParenExprClass:
1242    // Ignore parentheses.
1243    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1244
1245  case Stmt::UnaryOperatorClass: {
1246    // The only unary operator that make sense to handle here
1247    // is Deref.  All others don't resolve to a "name."  This includes
1248    // handling all sorts of rvalues passed to a unary operator.
1249    UnaryOperator *U = cast<UnaryOperator>(E);
1250
1251    if (U->getOpcode() == UnaryOperator::Deref)
1252      return EvalAddr(U->getSubExpr());
1253
1254    return NULL;
1255  }
1256
1257  case Stmt::ArraySubscriptExprClass: {
1258    // Array subscripts are potential references to data on the stack.  We
1259    // retrieve the DeclRefExpr* for the array variable if it indeed
1260    // has local storage.
1261    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1262  }
1263
1264  case Stmt::ConditionalOperatorClass: {
1265    // For conditional operators we need to see if either the LHS or RHS are
1266    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1267    ConditionalOperator *C = cast<ConditionalOperator>(E);
1268
1269    // Handle the GNU extension for missing LHS.
1270    if (Expr *lhsExpr = C->getLHS())
1271      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1272        return LHS;
1273
1274    return EvalVal(C->getRHS());
1275  }
1276
1277  // Accesses to members are potential references to data on the stack.
1278  case Stmt::MemberExprClass: {
1279    MemberExpr *M = cast<MemberExpr>(E);
1280
1281    // Check for indirect access.  We only want direct field accesses.
1282    if (!M->isArrow())
1283      return EvalVal(M->getBase());
1284    else
1285      return NULL;
1286  }
1287
1288  // Everything else: we simply don't reason about them.
1289  default:
1290    return NULL;
1291  }
1292}
1293
1294//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1295
1296/// Check for comparisons of floating point operands using != and ==.
1297/// Issue a warning if these are no self-comparisons, as they are not likely
1298/// to do what the programmer intended.
1299void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1300  bool EmitWarning = true;
1301
1302  Expr* LeftExprSansParen = lex->IgnoreParens();
1303  Expr* RightExprSansParen = rex->IgnoreParens();
1304
1305  // Special case: check for x == x (which is OK).
1306  // Do not emit warnings for such cases.
1307  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1308    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1309      if (DRL->getDecl() == DRR->getDecl())
1310        EmitWarning = false;
1311
1312
1313  // Special case: check for comparisons against literals that can be exactly
1314  //  represented by APFloat.  In such cases, do not emit a warning.  This
1315  //  is a heuristic: often comparison against such literals are used to
1316  //  detect if a value in a variable has not changed.  This clearly can
1317  //  lead to false negatives.
1318  if (EmitWarning) {
1319    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1320      if (FLL->isExact())
1321        EmitWarning = false;
1322    }
1323    else
1324      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1325        if (FLR->isExact())
1326          EmitWarning = false;
1327    }
1328  }
1329
1330  // Check for comparisons with builtin types.
1331  if (EmitWarning)
1332    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1333      if (CL->isBuiltinCall(Context))
1334        EmitWarning = false;
1335
1336  if (EmitWarning)
1337    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1338      if (CR->isBuiltinCall(Context))
1339        EmitWarning = false;
1340
1341  // Emit the diagnostic.
1342  if (EmitWarning)
1343    Diag(loc, diag::warn_floatingpoint_eq)
1344      << lex->getSourceRange() << rex->getSourceRange();
1345}
1346