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