]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaChecking.cpp
Vendor import of clang trunk r126079:
[FreeBSD/FreeBSD.git] / lib / Sema / SemaChecking.cpp
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 "clang/Sema/Sema.h"
16 #include "clang/Sema/SemaInternal.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Analysis/Analyses/FormatString.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "clang/Basic/TargetBuiltins.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/ConvertUTF.h"
35 #include <limits>
36 using namespace clang;
37 using namespace sema;
38
39 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40                                                     unsigned ByteNo) const {
41   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42                                PP.getLangOptions(), PP.getTargetInfo());
43 }
44   
45
46 /// CheckablePrintfAttr - does a function call have a "printf" attribute
47 /// and arguments that merit checking?
48 bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49   if (Format->getType() == "printf") return true;
50   if (Format->getType() == "printf0") {
51     // printf0 allows null "format" string; if so don't check format/args
52     unsigned format_idx = Format->getFormatIdx() - 1;
53     // Does the index refer to the implicit object argument?
54     if (isa<CXXMemberCallExpr>(TheCall)) {
55       if (format_idx == 0)
56         return false;
57       --format_idx;
58     }
59     if (format_idx < TheCall->getNumArgs()) {
60       Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
61       if (!Format->isNullPointerConstant(Context,
62                                          Expr::NPC_ValueDependentIsNull))
63         return true;
64     }
65   }
66   return false;
67 }
68
69 ExprResult
70 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
71   ExprResult TheCallResult(Owned(TheCall));
72
73   // Find out if any arguments are required to be integer constant expressions.
74   unsigned ICEArguments = 0;
75   ASTContext::GetBuiltinTypeError Error;
76   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
77   if (Error != ASTContext::GE_None)
78     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
79   
80   // If any arguments are required to be ICE's, check and diagnose.
81   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
82     // Skip arguments not required to be ICE's.
83     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
84     
85     llvm::APSInt Result;
86     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
87       return true;
88     ICEArguments &= ~(1 << ArgNo);
89   }
90   
91   switch (BuiltinID) {
92   case Builtin::BI__builtin___CFStringMakeConstantString:
93     assert(TheCall->getNumArgs() == 1 &&
94            "Wrong # arguments to builtin CFStringMakeConstantString");
95     if (CheckObjCString(TheCall->getArg(0)))
96       return ExprError();
97     break;
98   case Builtin::BI__builtin_stdarg_start:
99   case Builtin::BI__builtin_va_start:
100     if (SemaBuiltinVAStart(TheCall))
101       return ExprError();
102     break;
103   case Builtin::BI__builtin_isgreater:
104   case Builtin::BI__builtin_isgreaterequal:
105   case Builtin::BI__builtin_isless:
106   case Builtin::BI__builtin_islessequal:
107   case Builtin::BI__builtin_islessgreater:
108   case Builtin::BI__builtin_isunordered:
109     if (SemaBuiltinUnorderedCompare(TheCall))
110       return ExprError();
111     break;
112   case Builtin::BI__builtin_fpclassify:
113     if (SemaBuiltinFPClassification(TheCall, 6))
114       return ExprError();
115     break;
116   case Builtin::BI__builtin_isfinite:
117   case Builtin::BI__builtin_isinf:
118   case Builtin::BI__builtin_isinf_sign:
119   case Builtin::BI__builtin_isnan:
120   case Builtin::BI__builtin_isnormal:
121     if (SemaBuiltinFPClassification(TheCall, 1))
122       return ExprError();
123     break;
124   case Builtin::BI__builtin_shufflevector:
125     return SemaBuiltinShuffleVector(TheCall);
126     // TheCall will be freed by the smart pointer here, but that's fine, since
127     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
128   case Builtin::BI__builtin_prefetch:
129     if (SemaBuiltinPrefetch(TheCall))
130       return ExprError();
131     break;
132   case Builtin::BI__builtin_object_size:
133     if (SemaBuiltinObjectSize(TheCall))
134       return ExprError();
135     break;
136   case Builtin::BI__builtin_longjmp:
137     if (SemaBuiltinLongjmp(TheCall))
138       return ExprError();
139     break;
140   case Builtin::BI__builtin_constant_p:
141     if (TheCall->getNumArgs() == 0)
142       return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
143         << 0 /*function call*/ << 1 << 0 << TheCall->getSourceRange();
144     if (TheCall->getNumArgs() > 1)
145       return Diag(TheCall->getArg(1)->getLocStart(),
146                   diag::err_typecheck_call_too_many_args)
147         << 0 /*function call*/ << 1 << TheCall->getNumArgs()
148         << TheCall->getArg(1)->getSourceRange();
149     break;
150   case Builtin::BI__sync_fetch_and_add:
151   case Builtin::BI__sync_fetch_and_sub:
152   case Builtin::BI__sync_fetch_and_or:
153   case Builtin::BI__sync_fetch_and_and:
154   case Builtin::BI__sync_fetch_and_xor:
155   case Builtin::BI__sync_add_and_fetch:
156   case Builtin::BI__sync_sub_and_fetch:
157   case Builtin::BI__sync_and_and_fetch:
158   case Builtin::BI__sync_or_and_fetch:
159   case Builtin::BI__sync_xor_and_fetch:
160   case Builtin::BI__sync_val_compare_and_swap:
161   case Builtin::BI__sync_bool_compare_and_swap:
162   case Builtin::BI__sync_lock_test_and_set:
163   case Builtin::BI__sync_lock_release:
164     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
165   }
166   
167   // Since the target specific builtins for each arch overlap, only check those
168   // of the arch we are compiling for.
169   if (BuiltinID >= Builtin::FirstTSBuiltin) {
170     switch (Context.Target.getTriple().getArch()) {
171       case llvm::Triple::arm:
172       case llvm::Triple::thumb:
173         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
174           return ExprError();
175         break;
176       default:
177         break;
178     }
179   }
180
181   return move(TheCallResult);
182 }
183
184 // Get the valid immediate range for the specified NEON type code.
185 static unsigned RFT(unsigned t, bool shift = false) {
186   bool quad = t & 0x10;
187   
188   switch (t & 0x7) {
189     case 0: // i8
190       return shift ? 7 : (8 << (int)quad) - 1;
191     case 1: // i16
192       return shift ? 15 : (4 << (int)quad) - 1;
193     case 2: // i32
194       return shift ? 31 : (2 << (int)quad) - 1;
195     case 3: // i64
196       return shift ? 63 : (1 << (int)quad) - 1;
197     case 4: // f32
198       assert(!shift && "cannot shift float types!");
199       return (2 << (int)quad) - 1;
200     case 5: // poly8
201       return shift ? 7 : (8 << (int)quad) - 1;
202     case 6: // poly16
203       return shift ? 15 : (4 << (int)quad) - 1;
204     case 7: // float16
205       assert(!shift && "cannot shift float types!");
206       return (4 << (int)quad) - 1;
207   }
208   return 0;
209 }
210
211 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
212   llvm::APSInt Result;
213
214   unsigned mask = 0;
215   unsigned TV = 0;
216   switch (BuiltinID) {
217 #define GET_NEON_OVERLOAD_CHECK
218 #include "clang/Basic/arm_neon.inc"
219 #undef GET_NEON_OVERLOAD_CHECK
220   }
221   
222   // For NEON intrinsics which are overloaded on vector element type, validate
223   // the immediate which specifies which variant to emit.
224   if (mask) {
225     unsigned ArgNo = TheCall->getNumArgs()-1;
226     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
227       return true;
228     
229     TV = Result.getLimitedValue(32);
230     if ((TV > 31) || (mask & (1 << TV)) == 0)
231       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
232         << TheCall->getArg(ArgNo)->getSourceRange();
233   }
234   
235   // For NEON intrinsics which take an immediate value as part of the 
236   // instruction, range check them here.
237   unsigned i = 0, l = 0, u = 0;
238   switch (BuiltinID) {
239   default: return false;
240   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
241   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
242   case ARM::BI__builtin_arm_vcvtr_f:
243   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
244 #define GET_NEON_IMMEDIATE_CHECK
245 #include "clang/Basic/arm_neon.inc"
246 #undef GET_NEON_IMMEDIATE_CHECK
247   };
248
249   // Check that the immediate argument is actually a constant.
250   if (SemaBuiltinConstantArg(TheCall, i, Result))
251     return true;
252
253   // Range check against the upper/lower values for this isntruction.
254   unsigned Val = Result.getZExtValue();
255   if (Val < l || Val > (u + l))
256     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
257       << l << u+l << TheCall->getArg(i)->getSourceRange();
258
259   // FIXME: VFP Intrinsics should error if VFP not present.
260   return false;
261 }
262
263 /// CheckFunctionCall - Check a direct function call for various correctness
264 /// and safety properties not strictly enforced by the C type system.
265 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
266   // Get the IdentifierInfo* for the called function.
267   IdentifierInfo *FnInfo = FDecl->getIdentifier();
268
269   // None of the checks below are needed for functions that don't have
270   // simple names (e.g., C++ conversion functions).
271   if (!FnInfo)
272     return false;
273
274   // FIXME: This mechanism should be abstracted to be less fragile and
275   // more efficient. For example, just map function ids to custom
276   // handlers.
277
278   // Printf and scanf checking.
279   for (specific_attr_iterator<FormatAttr>
280          i = FDecl->specific_attr_begin<FormatAttr>(),
281          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
282
283     const FormatAttr *Format = *i;
284     const bool b = Format->getType() == "scanf";
285     if (b || CheckablePrintfAttr(Format, TheCall)) {
286       bool HasVAListArg = Format->getFirstArg() == 0;
287       CheckPrintfScanfArguments(TheCall, HasVAListArg,
288                                 Format->getFormatIdx() - 1,
289                                 HasVAListArg ? 0 : Format->getFirstArg() - 1,
290                                 !b);
291     }
292   }
293
294   for (specific_attr_iterator<NonNullAttr>
295          i = FDecl->specific_attr_begin<NonNullAttr>(),
296          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
297     CheckNonNullArguments(*i, TheCall);
298   }
299
300   return false;
301 }
302
303 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
304   // Printf checking.
305   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
306   if (!Format)
307     return false;
308
309   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
310   if (!V)
311     return false;
312
313   QualType Ty = V->getType();
314   if (!Ty->isBlockPointerType())
315     return false;
316
317   const bool b = Format->getType() == "scanf";
318   if (!b && !CheckablePrintfAttr(Format, TheCall))
319     return false;
320
321   bool HasVAListArg = Format->getFirstArg() == 0;
322   CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
323                             HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
324
325   return false;
326 }
327
328 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
329 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
330 /// type of its first argument.  The main ActOnCallExpr routines have already
331 /// promoted the types of arguments because all of these calls are prototyped as
332 /// void(...).
333 ///
334 /// This function goes through and does final semantic checking for these
335 /// builtins,
336 ExprResult
337 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
338   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
339   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
340   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
341
342   // Ensure that we have at least one argument to do type inference from.
343   if (TheCall->getNumArgs() < 1) {
344     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
345       << 0 << 1 << TheCall->getNumArgs()
346       << TheCall->getCallee()->getSourceRange();
347     return ExprError();
348   }
349
350   // Inspect the first argument of the atomic builtin.  This should always be
351   // a pointer type, whose element is an integral scalar or pointer type.
352   // Because it is a pointer type, we don't have to worry about any implicit
353   // casts here.
354   // FIXME: We don't allow floating point scalars as input.
355   Expr *FirstArg = TheCall->getArg(0);
356   if (!FirstArg->getType()->isPointerType()) {
357     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
358       << FirstArg->getType() << FirstArg->getSourceRange();
359     return ExprError();
360   }
361
362   QualType ValType =
363     FirstArg->getType()->getAs<PointerType>()->getPointeeType();
364   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
365       !ValType->isBlockPointerType()) {
366     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
367       << FirstArg->getType() << FirstArg->getSourceRange();
368     return ExprError();
369   }
370
371   // The majority of builtins return a value, but a few have special return
372   // types, so allow them to override appropriately below.
373   QualType ResultType = ValType;
374
375   // We need to figure out which concrete builtin this maps onto.  For example,
376   // __sync_fetch_and_add with a 2 byte object turns into
377   // __sync_fetch_and_add_2.
378 #define BUILTIN_ROW(x) \
379   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
380     Builtin::BI##x##_8, Builtin::BI##x##_16 }
381
382   static const unsigned BuiltinIndices[][5] = {
383     BUILTIN_ROW(__sync_fetch_and_add),
384     BUILTIN_ROW(__sync_fetch_and_sub),
385     BUILTIN_ROW(__sync_fetch_and_or),
386     BUILTIN_ROW(__sync_fetch_and_and),
387     BUILTIN_ROW(__sync_fetch_and_xor),
388
389     BUILTIN_ROW(__sync_add_and_fetch),
390     BUILTIN_ROW(__sync_sub_and_fetch),
391     BUILTIN_ROW(__sync_and_and_fetch),
392     BUILTIN_ROW(__sync_or_and_fetch),
393     BUILTIN_ROW(__sync_xor_and_fetch),
394
395     BUILTIN_ROW(__sync_val_compare_and_swap),
396     BUILTIN_ROW(__sync_bool_compare_and_swap),
397     BUILTIN_ROW(__sync_lock_test_and_set),
398     BUILTIN_ROW(__sync_lock_release)
399   };
400 #undef BUILTIN_ROW
401
402   // Determine the index of the size.
403   unsigned SizeIndex;
404   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
405   case 1: SizeIndex = 0; break;
406   case 2: SizeIndex = 1; break;
407   case 4: SizeIndex = 2; break;
408   case 8: SizeIndex = 3; break;
409   case 16: SizeIndex = 4; break;
410   default:
411     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
412       << FirstArg->getType() << FirstArg->getSourceRange();
413     return ExprError();
414   }
415
416   // Each of these builtins has one pointer argument, followed by some number of
417   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
418   // that we ignore.  Find out which row of BuiltinIndices to read from as well
419   // as the number of fixed args.
420   unsigned BuiltinID = FDecl->getBuiltinID();
421   unsigned BuiltinIndex, NumFixed = 1;
422   switch (BuiltinID) {
423   default: assert(0 && "Unknown overloaded atomic builtin!");
424   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
425   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
426   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
427   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
428   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
429
430   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
431   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
432   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
433   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
434   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
435
436   case Builtin::BI__sync_val_compare_and_swap:
437     BuiltinIndex = 10;
438     NumFixed = 2;
439     break;
440   case Builtin::BI__sync_bool_compare_and_swap:
441     BuiltinIndex = 11;
442     NumFixed = 2;
443     ResultType = Context.BoolTy;
444     break;
445   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
446   case Builtin::BI__sync_lock_release:
447     BuiltinIndex = 13;
448     NumFixed = 0;
449     ResultType = Context.VoidTy;
450     break;
451   }
452
453   // Now that we know how many fixed arguments we expect, first check that we
454   // have at least that many.
455   if (TheCall->getNumArgs() < 1+NumFixed) {
456     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
457       << 0 << 1+NumFixed << TheCall->getNumArgs()
458       << TheCall->getCallee()->getSourceRange();
459     return ExprError();
460   }
461
462   // Get the decl for the concrete builtin from this, we can tell what the
463   // concrete integer type we should convert to is.
464   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
465   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
466   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
467   FunctionDecl *NewBuiltinDecl =
468     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
469                                            TUScope, false, DRE->getLocStart()));
470
471   // The first argument --- the pointer --- has a fixed type; we
472   // deduce the types of the rest of the arguments accordingly.  Walk
473   // the remaining arguments, converting them to the deduced value type.
474   for (unsigned i = 0; i != NumFixed; ++i) {
475     Expr *Arg = TheCall->getArg(i+1);
476
477     // If the argument is an implicit cast, then there was a promotion due to
478     // "...", just remove it now.
479     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
480       Arg = ICE->getSubExpr();
481       ICE->setSubExpr(0);
482       TheCall->setArg(i+1, Arg);
483     }
484
485     // GCC does an implicit conversion to the pointer or integer ValType.  This
486     // can fail in some cases (1i -> int**), check for this error case now.
487     CastKind Kind = CK_Invalid;
488     ExprValueKind VK = VK_RValue;
489     CXXCastPath BasePath;
490     if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
491       return ExprError();
492
493     // Okay, we have something that *can* be converted to the right type.  Check
494     // to see if there is a potentially weird extension going on here.  This can
495     // happen when you do an atomic operation on something like an char* and
496     // pass in 42.  The 42 gets converted to char.  This is even more strange
497     // for things like 45.123 -> char, etc.
498     // FIXME: Do this check.
499     ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
500     TheCall->setArg(i+1, Arg);
501   }
502
503   // Switch the DeclRefExpr to refer to the new decl.
504   DRE->setDecl(NewBuiltinDecl);
505   DRE->setType(NewBuiltinDecl->getType());
506
507   // Set the callee in the CallExpr.
508   // FIXME: This leaks the original parens and implicit casts.
509   Expr *PromotedCall = DRE;
510   UsualUnaryConversions(PromotedCall);
511   TheCall->setCallee(PromotedCall);
512
513   // Change the result type of the call to match the original value type. This
514   // is arbitrary, but the codegen for these builtins ins design to handle it
515   // gracefully.
516   TheCall->setType(ResultType);
517
518   return move(TheCallResult);
519 }
520
521
522 /// CheckObjCString - Checks that the argument to the builtin
523 /// CFString constructor is correct
524 /// Note: It might also make sense to do the UTF-16 conversion here (would
525 /// simplify the backend).
526 bool Sema::CheckObjCString(Expr *Arg) {
527   Arg = Arg->IgnoreParenCasts();
528   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
529
530   if (!Literal || Literal->isWide()) {
531     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
532       << Arg->getSourceRange();
533     return true;
534   }
535
536   size_t NulPos = Literal->getString().find('\0');
537   if (NulPos != llvm::StringRef::npos) {
538     Diag(getLocationOfStringLiteralByte(Literal, NulPos),
539          diag::warn_cfstring_literal_contains_nul_character)
540       << Arg->getSourceRange();
541   }
542   if (Literal->containsNonAsciiOrNull()) {
543     llvm::StringRef String = Literal->getString();
544     unsigned NumBytes = String.size();
545     llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
546     const UTF8 *FromPtr = (UTF8 *)String.data();
547     UTF16 *ToPtr = &ToBuf[0];
548     
549     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
550                                                  &ToPtr, ToPtr + NumBytes,
551                                                  strictConversion);
552     // Check for conversion failure.
553     if (Result != conversionOK)
554       Diag(Arg->getLocStart(),
555            diag::warn_cfstring_truncated) << Arg->getSourceRange();
556   }
557   return false;
558 }
559
560 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
561 /// Emit an error and return true on failure, return false on success.
562 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
563   Expr *Fn = TheCall->getCallee();
564   if (TheCall->getNumArgs() > 2) {
565     Diag(TheCall->getArg(2)->getLocStart(),
566          diag::err_typecheck_call_too_many_args)
567       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
568       << Fn->getSourceRange()
569       << SourceRange(TheCall->getArg(2)->getLocStart(),
570                      (*(TheCall->arg_end()-1))->getLocEnd());
571     return true;
572   }
573
574   if (TheCall->getNumArgs() < 2) {
575     return Diag(TheCall->getLocEnd(),
576       diag::err_typecheck_call_too_few_args_at_least)
577       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
578   }
579
580   // Determine whether the current function is variadic or not.
581   BlockScopeInfo *CurBlock = getCurBlock();
582   bool isVariadic;
583   if (CurBlock)
584     isVariadic = CurBlock->TheDecl->isVariadic();
585   else if (FunctionDecl *FD = getCurFunctionDecl())
586     isVariadic = FD->isVariadic();
587   else
588     isVariadic = getCurMethodDecl()->isVariadic();
589
590   if (!isVariadic) {
591     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
592     return true;
593   }
594
595   // Verify that the second argument to the builtin is the last argument of the
596   // current function or method.
597   bool SecondArgIsLastNamedArgument = false;
598   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
599
600   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
601     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
602       // FIXME: This isn't correct for methods (results in bogus warning).
603       // Get the last formal in the current function.
604       const ParmVarDecl *LastArg;
605       if (CurBlock)
606         LastArg = *(CurBlock->TheDecl->param_end()-1);
607       else if (FunctionDecl *FD = getCurFunctionDecl())
608         LastArg = *(FD->param_end()-1);
609       else
610         LastArg = *(getCurMethodDecl()->param_end()-1);
611       SecondArgIsLastNamedArgument = PV == LastArg;
612     }
613   }
614
615   if (!SecondArgIsLastNamedArgument)
616     Diag(TheCall->getArg(1)->getLocStart(),
617          diag::warn_second_parameter_of_va_start_not_last_named_argument);
618   return false;
619 }
620
621 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
622 /// friends.  This is declared to take (...), so we have to check everything.
623 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
624   if (TheCall->getNumArgs() < 2)
625     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
626       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
627   if (TheCall->getNumArgs() > 2)
628     return Diag(TheCall->getArg(2)->getLocStart(),
629                 diag::err_typecheck_call_too_many_args)
630       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
631       << SourceRange(TheCall->getArg(2)->getLocStart(),
632                      (*(TheCall->arg_end()-1))->getLocEnd());
633
634   Expr *OrigArg0 = TheCall->getArg(0);
635   Expr *OrigArg1 = TheCall->getArg(1);
636
637   // Do standard promotions between the two arguments, returning their common
638   // type.
639   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
640
641   // Make sure any conversions are pushed back into the call; this is
642   // type safe since unordered compare builtins are declared as "_Bool
643   // foo(...)".
644   TheCall->setArg(0, OrigArg0);
645   TheCall->setArg(1, OrigArg1);
646
647   if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
648     return false;
649
650   // If the common type isn't a real floating type, then the arguments were
651   // invalid for this operation.
652   if (!Res->isRealFloatingType())
653     return Diag(OrigArg0->getLocStart(),
654                 diag::err_typecheck_call_invalid_ordered_compare)
655       << OrigArg0->getType() << OrigArg1->getType()
656       << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
657
658   return false;
659 }
660
661 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
662 /// __builtin_isnan and friends.  This is declared to take (...), so we have
663 /// to check everything. We expect the last argument to be a floating point
664 /// value.
665 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
666   if (TheCall->getNumArgs() < NumArgs)
667     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
668       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
669   if (TheCall->getNumArgs() > NumArgs)
670     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
671                 diag::err_typecheck_call_too_many_args)
672       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
673       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
674                      (*(TheCall->arg_end()-1))->getLocEnd());
675
676   Expr *OrigArg = TheCall->getArg(NumArgs-1);
677
678   if (OrigArg->isTypeDependent())
679     return false;
680
681   // This operation requires a non-_Complex floating-point number.
682   if (!OrigArg->getType()->isRealFloatingType())
683     return Diag(OrigArg->getLocStart(),
684                 diag::err_typecheck_call_invalid_unary_fp)
685       << OrigArg->getType() << OrigArg->getSourceRange();
686
687   // If this is an implicit conversion from float -> double, remove it.
688   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
689     Expr *CastArg = Cast->getSubExpr();
690     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
691       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
692              "promotion from float to double is the only expected cast here");
693       Cast->setSubExpr(0);
694       TheCall->setArg(NumArgs-1, CastArg);
695       OrigArg = CastArg;
696     }
697   }
698   
699   return false;
700 }
701
702 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
703 // This is declared to take (...), so we have to check everything.
704 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
705   if (TheCall->getNumArgs() < 2)
706     return ExprError(Diag(TheCall->getLocEnd(),
707                           diag::err_typecheck_call_too_few_args_at_least)
708       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
709       << TheCall->getSourceRange());
710
711   // Determine which of the following types of shufflevector we're checking:
712   // 1) unary, vector mask: (lhs, mask)
713   // 2) binary, vector mask: (lhs, rhs, mask)
714   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
715   QualType resType = TheCall->getArg(0)->getType();
716   unsigned numElements = 0;
717   
718   if (!TheCall->getArg(0)->isTypeDependent() &&
719       !TheCall->getArg(1)->isTypeDependent()) {
720     QualType LHSType = TheCall->getArg(0)->getType();
721     QualType RHSType = TheCall->getArg(1)->getType();
722     
723     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
724       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
725         << SourceRange(TheCall->getArg(0)->getLocStart(),
726                        TheCall->getArg(1)->getLocEnd());
727       return ExprError();
728     }
729     
730     numElements = LHSType->getAs<VectorType>()->getNumElements();
731     unsigned numResElements = TheCall->getNumArgs() - 2;
732
733     // Check to see if we have a call with 2 vector arguments, the unary shuffle
734     // with mask.  If so, verify that RHS is an integer vector type with the
735     // same number of elts as lhs.
736     if (TheCall->getNumArgs() == 2) {
737       if (!RHSType->hasIntegerRepresentation() || 
738           RHSType->getAs<VectorType>()->getNumElements() != numElements)
739         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
740           << SourceRange(TheCall->getArg(1)->getLocStart(),
741                          TheCall->getArg(1)->getLocEnd());
742       numResElements = numElements;
743     }
744     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
745       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
746         << SourceRange(TheCall->getArg(0)->getLocStart(),
747                        TheCall->getArg(1)->getLocEnd());
748       return ExprError();
749     } else if (numElements != numResElements) {
750       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
751       resType = Context.getVectorType(eltType, numResElements,
752                                       VectorType::GenericVector);
753     }
754   }
755
756   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
757     if (TheCall->getArg(i)->isTypeDependent() ||
758         TheCall->getArg(i)->isValueDependent())
759       continue;
760
761     llvm::APSInt Result(32);
762     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
763       return ExprError(Diag(TheCall->getLocStart(),
764                   diag::err_shufflevector_nonconstant_argument)
765                 << TheCall->getArg(i)->getSourceRange());
766
767     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
768       return ExprError(Diag(TheCall->getLocStart(),
769                   diag::err_shufflevector_argument_too_large)
770                << TheCall->getArg(i)->getSourceRange());
771   }
772
773   llvm::SmallVector<Expr*, 32> exprs;
774
775   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
776     exprs.push_back(TheCall->getArg(i));
777     TheCall->setArg(i, 0);
778   }
779
780   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
781                                             exprs.size(), resType,
782                                             TheCall->getCallee()->getLocStart(),
783                                             TheCall->getRParenLoc()));
784 }
785
786 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
787 // This is declared to take (const void*, ...) and can take two
788 // optional constant int args.
789 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
790   unsigned NumArgs = TheCall->getNumArgs();
791
792   if (NumArgs > 3)
793     return Diag(TheCall->getLocEnd(),
794              diag::err_typecheck_call_too_many_args_at_most)
795              << 0 /*function call*/ << 3 << NumArgs
796              << TheCall->getSourceRange();
797
798   // Argument 0 is checked for us and the remaining arguments must be
799   // constant integers.
800   for (unsigned i = 1; i != NumArgs; ++i) {
801     Expr *Arg = TheCall->getArg(i);
802     
803     llvm::APSInt Result;
804     if (SemaBuiltinConstantArg(TheCall, i, Result))
805       return true;
806
807     // FIXME: gcc issues a warning and rewrites these to 0. These
808     // seems especially odd for the third argument since the default
809     // is 3.
810     if (i == 1) {
811       if (Result.getLimitedValue() > 1)
812         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
813              << "0" << "1" << Arg->getSourceRange();
814     } else {
815       if (Result.getLimitedValue() > 3)
816         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
817             << "0" << "3" << Arg->getSourceRange();
818     }
819   }
820
821   return false;
822 }
823
824 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
825 /// TheCall is a constant expression.
826 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
827                                   llvm::APSInt &Result) {
828   Expr *Arg = TheCall->getArg(ArgNum);
829   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
830   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
831   
832   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
833   
834   if (!Arg->isIntegerConstantExpr(Result, Context))
835     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
836                 << FDecl->getDeclName() <<  Arg->getSourceRange();
837   
838   return false;
839 }
840
841 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
842 /// int type). This simply type checks that type is one of the defined
843 /// constants (0-3).
844 // For compatability check 0-3, llvm only handles 0 and 2.
845 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
846   llvm::APSInt Result;
847   
848   // Check constant-ness first.
849   if (SemaBuiltinConstantArg(TheCall, 1, Result))
850     return true;
851
852   Expr *Arg = TheCall->getArg(1);
853   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
854     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
855              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
856   }
857
858   return false;
859 }
860
861 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
862 /// This checks that val is a constant 1.
863 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
864   Expr *Arg = TheCall->getArg(1);
865   llvm::APSInt Result;
866
867   // TODO: This is less than ideal. Overload this to take a value.
868   if (SemaBuiltinConstantArg(TheCall, 1, Result))
869     return true;
870   
871   if (Result != 1)
872     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
873              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
874
875   return false;
876 }
877
878 // Handle i > 1 ? "x" : "y", recursivelly
879 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
880                                   bool HasVAListArg,
881                                   unsigned format_idx, unsigned firstDataArg,
882                                   bool isPrintf) {
883  tryAgain:
884   if (E->isTypeDependent() || E->isValueDependent())
885     return false;
886
887   switch (E->getStmtClass()) {
888   case Stmt::BinaryConditionalOperatorClass:
889   case Stmt::ConditionalOperatorClass: {
890     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
891     return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
892                                   format_idx, firstDataArg, isPrintf)
893         && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
894                                   format_idx, firstDataArg, isPrintf);
895   }
896
897   case Stmt::IntegerLiteralClass:
898     // Technically -Wformat-nonliteral does not warn about this case.
899     // The behavior of printf and friends in this case is implementation
900     // dependent.  Ideally if the format string cannot be null then
901     // it should have a 'nonnull' attribute in the function prototype.
902     return true;
903
904   case Stmt::ImplicitCastExprClass: {
905     E = cast<ImplicitCastExpr>(E)->getSubExpr();
906     goto tryAgain;
907   }
908
909   case Stmt::ParenExprClass: {
910     E = cast<ParenExpr>(E)->getSubExpr();
911     goto tryAgain;
912   }
913
914   case Stmt::OpaqueValueExprClass:
915     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
916       E = src;
917       goto tryAgain;
918     }
919     return false;
920
921   case Stmt::DeclRefExprClass: {
922     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
923
924     // As an exception, do not flag errors for variables binding to
925     // const string literals.
926     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
927       bool isConstant = false;
928       QualType T = DR->getType();
929
930       if (const ArrayType *AT = Context.getAsArrayType(T)) {
931         isConstant = AT->getElementType().isConstant(Context);
932       } else if (const PointerType *PT = T->getAs<PointerType>()) {
933         isConstant = T.isConstant(Context) &&
934                      PT->getPointeeType().isConstant(Context);
935       }
936
937       if (isConstant) {
938         if (const Expr *Init = VD->getAnyInitializer())
939           return SemaCheckStringLiteral(Init, TheCall,
940                                         HasVAListArg, format_idx, firstDataArg,
941                                         isPrintf);
942       }
943
944       // For vprintf* functions (i.e., HasVAListArg==true), we add a
945       // special check to see if the format string is a function parameter
946       // of the function calling the printf function.  If the function
947       // has an attribute indicating it is a printf-like function, then we
948       // should suppress warnings concerning non-literals being used in a call
949       // to a vprintf function.  For example:
950       //
951       // void
952       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
953       //      va_list ap;
954       //      va_start(ap, fmt);
955       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
956       //      ...
957       //
958       //
959       //  FIXME: We don't have full attribute support yet, so just check to see
960       //    if the argument is a DeclRefExpr that references a parameter.  We'll
961       //    add proper support for checking the attribute later.
962       if (HasVAListArg)
963         if (isa<ParmVarDecl>(VD))
964           return true;
965     }
966
967     return false;
968   }
969
970   case Stmt::CallExprClass: {
971     const CallExpr *CE = cast<CallExpr>(E);
972     if (const ImplicitCastExpr *ICE
973           = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
974       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
975         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
976           if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
977             unsigned ArgIndex = FA->getFormatIdx();
978             const Expr *Arg = CE->getArg(ArgIndex - 1);
979
980             return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
981                                           format_idx, firstDataArg, isPrintf);
982           }
983         }
984       }
985     }
986
987     return false;
988   }
989   case Stmt::ObjCStringLiteralClass:
990   case Stmt::StringLiteralClass: {
991     const StringLiteral *StrE = NULL;
992
993     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
994       StrE = ObjCFExpr->getString();
995     else
996       StrE = cast<StringLiteral>(E);
997
998     if (StrE) {
999       CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1000                         firstDataArg, isPrintf);
1001       return true;
1002     }
1003
1004     return false;
1005   }
1006
1007   default:
1008     return false;
1009   }
1010 }
1011
1012 void
1013 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1014                             const CallExpr *TheCall) {
1015   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1016                                   e = NonNull->args_end();
1017        i != e; ++i) {
1018     const Expr *ArgExpr = TheCall->getArg(*i);
1019     if (ArgExpr->isNullPointerConstant(Context,
1020                                        Expr::NPC_ValueDependentIsNotNull))
1021       Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1022         << ArgExpr->getSourceRange();
1023   }
1024 }
1025
1026 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1027 /// functions) for correct use of format strings.
1028 void
1029 Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1030                                 unsigned format_idx, unsigned firstDataArg,
1031                                 bool isPrintf) {
1032
1033   const Expr *Fn = TheCall->getCallee();
1034
1035   // The way the format attribute works in GCC, the implicit this argument
1036   // of member functions is counted. However, it doesn't appear in our own
1037   // lists, so decrement format_idx in that case.
1038   if (isa<CXXMemberCallExpr>(TheCall)) {
1039     const CXXMethodDecl *method_decl =
1040       dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1041     if (method_decl && method_decl->isInstance()) {
1042       // Catch a format attribute mistakenly referring to the object argument.
1043       if (format_idx == 0)
1044         return;
1045       --format_idx;
1046       if(firstDataArg != 0)
1047         --firstDataArg;
1048     }
1049   }
1050
1051   // CHECK: printf/scanf-like function is called with no format string.
1052   if (format_idx >= TheCall->getNumArgs()) {
1053     Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1054       << Fn->getSourceRange();
1055     return;
1056   }
1057
1058   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1059
1060   // CHECK: format string is not a string literal.
1061   //
1062   // Dynamically generated format strings are difficult to
1063   // automatically vet at compile time.  Requiring that format strings
1064   // are string literals: (1) permits the checking of format strings by
1065   // the compiler and thereby (2) can practically remove the source of
1066   // many format string exploits.
1067
1068   // Format string can be either ObjC string (e.g. @"%d") or
1069   // C string (e.g. "%d")
1070   // ObjC string uses the same format specifiers as C string, so we can use
1071   // the same format string checking logic for both ObjC and C strings.
1072   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1073                              firstDataArg, isPrintf))
1074     return;  // Literal format string found, check done!
1075
1076   // If there are no arguments specified, warn with -Wformat-security, otherwise
1077   // warn only with -Wformat-nonliteral.
1078   if (TheCall->getNumArgs() == format_idx+1)
1079     Diag(TheCall->getArg(format_idx)->getLocStart(),
1080          diag::warn_format_nonliteral_noargs)
1081       << OrigFormatExpr->getSourceRange();
1082   else
1083     Diag(TheCall->getArg(format_idx)->getLocStart(),
1084          diag::warn_format_nonliteral)
1085            << OrigFormatExpr->getSourceRange();
1086 }
1087
1088 namespace {
1089 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1090 protected:
1091   Sema &S;
1092   const StringLiteral *FExpr;
1093   const Expr *OrigFormatExpr;
1094   const unsigned FirstDataArg;
1095   const unsigned NumDataArgs;
1096   const bool IsObjCLiteral;
1097   const char *Beg; // Start of format string.
1098   const bool HasVAListArg;
1099   const CallExpr *TheCall;
1100   unsigned FormatIdx;
1101   llvm::BitVector CoveredArgs;
1102   bool usesPositionalArgs;
1103   bool atFirstArg;
1104 public:
1105   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1106                      const Expr *origFormatExpr, unsigned firstDataArg,
1107                      unsigned numDataArgs, bool isObjCLiteral,
1108                      const char *beg, bool hasVAListArg,
1109                      const CallExpr *theCall, unsigned formatIdx)
1110     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1111       FirstDataArg(firstDataArg),
1112       NumDataArgs(numDataArgs),
1113       IsObjCLiteral(isObjCLiteral), Beg(beg),
1114       HasVAListArg(hasVAListArg),
1115       TheCall(theCall), FormatIdx(formatIdx),
1116       usesPositionalArgs(false), atFirstArg(true) {
1117         CoveredArgs.resize(numDataArgs);
1118         CoveredArgs.reset();
1119       }
1120
1121   void DoneProcessing();
1122
1123   void HandleIncompleteSpecifier(const char *startSpecifier,
1124                                  unsigned specifierLen);
1125     
1126   virtual void HandleInvalidPosition(const char *startSpecifier,
1127                                      unsigned specifierLen,
1128                                      analyze_format_string::PositionContext p);
1129
1130   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1131
1132   void HandleNullChar(const char *nullCharacter);
1133
1134 protected:
1135   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1136                                         const char *startSpec,
1137                                         unsigned specifierLen,
1138                                         const char *csStart, unsigned csLen);
1139   
1140   SourceRange getFormatStringRange();
1141   CharSourceRange getSpecifierRange(const char *startSpecifier,
1142                                     unsigned specifierLen);
1143   SourceLocation getLocationOfByte(const char *x);
1144
1145   const Expr *getDataArg(unsigned i) const;
1146   
1147   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1148                     const analyze_format_string::ConversionSpecifier &CS,
1149                     const char *startSpecifier, unsigned specifierLen,
1150                     unsigned argIndex);
1151 };
1152 }
1153
1154 SourceRange CheckFormatHandler::getFormatStringRange() {
1155   return OrigFormatExpr->getSourceRange();
1156 }
1157
1158 CharSourceRange CheckFormatHandler::
1159 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1160   SourceLocation Start = getLocationOfByte(startSpecifier);
1161   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1162
1163   // Advance the end SourceLocation by one due to half-open ranges.
1164   End = End.getFileLocWithOffset(1);
1165
1166   return CharSourceRange::getCharRange(Start, End);
1167 }
1168
1169 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1170   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1171 }
1172
1173 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1174                                                    unsigned specifierLen){
1175   SourceLocation Loc = getLocationOfByte(startSpecifier);
1176   S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1177     << getSpecifierRange(startSpecifier, specifierLen);
1178 }
1179
1180 void
1181 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1182                                      analyze_format_string::PositionContext p) {
1183   SourceLocation Loc = getLocationOfByte(startPos);
1184   S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1185     << (unsigned) p << getSpecifierRange(startPos, posLen);
1186 }
1187
1188 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1189                                             unsigned posLen) {
1190   SourceLocation Loc = getLocationOfByte(startPos);
1191   S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1192     << getSpecifierRange(startPos, posLen);
1193 }
1194
1195 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1196   // The presence of a null character is likely an error.
1197   S.Diag(getLocationOfByte(nullCharacter),
1198          diag::warn_printf_format_string_contains_null_char)
1199     << getFormatStringRange();
1200 }
1201
1202 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1203   return TheCall->getArg(FirstDataArg + i);
1204 }
1205
1206 void CheckFormatHandler::DoneProcessing() {
1207     // Does the number of data arguments exceed the number of
1208     // format conversions in the format string?
1209   if (!HasVAListArg) {
1210       // Find any arguments that weren't covered.
1211     CoveredArgs.flip();
1212     signed notCoveredArg = CoveredArgs.find_first();
1213     if (notCoveredArg >= 0) {
1214       assert((unsigned)notCoveredArg < NumDataArgs);
1215       S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1216              diag::warn_printf_data_arg_not_used)
1217       << getFormatStringRange();
1218     }
1219   }
1220 }
1221
1222 bool
1223 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1224                                                      SourceLocation Loc,
1225                                                      const char *startSpec,
1226                                                      unsigned specifierLen,
1227                                                      const char *csStart,
1228                                                      unsigned csLen) {
1229   
1230   bool keepGoing = true;
1231   if (argIndex < NumDataArgs) {
1232     // Consider the argument coverered, even though the specifier doesn't
1233     // make sense.
1234     CoveredArgs.set(argIndex);
1235   }
1236   else {
1237     // If argIndex exceeds the number of data arguments we
1238     // don't issue a warning because that is just a cascade of warnings (and
1239     // they may have intended '%%' anyway). We don't want to continue processing
1240     // the format string after this point, however, as we will like just get
1241     // gibberish when trying to match arguments.
1242     keepGoing = false;
1243   }
1244   
1245   S.Diag(Loc, diag::warn_format_invalid_conversion)
1246     << llvm::StringRef(csStart, csLen)
1247     << getSpecifierRange(startSpec, specifierLen);
1248   
1249   return keepGoing;
1250 }
1251
1252 bool
1253 CheckFormatHandler::CheckNumArgs(
1254   const analyze_format_string::FormatSpecifier &FS,
1255   const analyze_format_string::ConversionSpecifier &CS,
1256   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1257
1258   if (argIndex >= NumDataArgs) {
1259     if (FS.usesPositionalArg())  {
1260       S.Diag(getLocationOfByte(CS.getStart()),
1261              diag::warn_printf_positional_arg_exceeds_data_args)
1262       << (argIndex+1) << NumDataArgs
1263       << getSpecifierRange(startSpecifier, specifierLen);
1264     }
1265     else {
1266       S.Diag(getLocationOfByte(CS.getStart()),
1267              diag::warn_printf_insufficient_data_args)
1268       << getSpecifierRange(startSpecifier, specifierLen);
1269     }
1270     
1271     return false;
1272   }
1273   return true;
1274 }
1275
1276 //===--- CHECK: Printf format string checking ------------------------------===//
1277
1278 namespace {
1279 class CheckPrintfHandler : public CheckFormatHandler {
1280 public:
1281   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1282                      const Expr *origFormatExpr, unsigned firstDataArg,
1283                      unsigned numDataArgs, bool isObjCLiteral,
1284                      const char *beg, bool hasVAListArg,
1285                      const CallExpr *theCall, unsigned formatIdx)
1286   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1287                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1288                        theCall, formatIdx) {}
1289   
1290   
1291   bool HandleInvalidPrintfConversionSpecifier(
1292                                       const analyze_printf::PrintfSpecifier &FS,
1293                                       const char *startSpecifier,
1294                                       unsigned specifierLen);
1295   
1296   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1297                              const char *startSpecifier,
1298                              unsigned specifierLen);
1299   
1300   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1301                     const char *startSpecifier, unsigned specifierLen);
1302   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1303                            const analyze_printf::OptionalAmount &Amt,
1304                            unsigned type,
1305                            const char *startSpecifier, unsigned specifierLen);
1306   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1307                   const analyze_printf::OptionalFlag &flag,
1308                   const char *startSpecifier, unsigned specifierLen);
1309   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1310                          const analyze_printf::OptionalFlag &ignoredFlag,
1311                          const analyze_printf::OptionalFlag &flag,
1312                          const char *startSpecifier, unsigned specifierLen);
1313 };  
1314 }
1315
1316 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1317                                       const analyze_printf::PrintfSpecifier &FS,
1318                                       const char *startSpecifier,
1319                                       unsigned specifierLen) {
1320   const analyze_printf::PrintfConversionSpecifier &CS =
1321     FS.getConversionSpecifier();
1322   
1323   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1324                                           getLocationOfByte(CS.getStart()),
1325                                           startSpecifier, specifierLen,
1326                                           CS.getStart(), CS.getLength());
1327 }
1328
1329 bool CheckPrintfHandler::HandleAmount(
1330                                const analyze_format_string::OptionalAmount &Amt,
1331                                unsigned k, const char *startSpecifier,
1332                                unsigned specifierLen) {
1333
1334   if (Amt.hasDataArgument()) {
1335     if (!HasVAListArg) {
1336       unsigned argIndex = Amt.getArgIndex();
1337       if (argIndex >= NumDataArgs) {
1338         S.Diag(getLocationOfByte(Amt.getStart()),
1339                diag::warn_printf_asterisk_missing_arg)
1340           << k << getSpecifierRange(startSpecifier, specifierLen);
1341         // Don't do any more checking.  We will just emit
1342         // spurious errors.
1343         return false;
1344       }
1345
1346       // Type check the data argument.  It should be an 'int'.
1347       // Although not in conformance with C99, we also allow the argument to be
1348       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1349       // doesn't emit a warning for that case.
1350       CoveredArgs.set(argIndex);
1351       const Expr *Arg = getDataArg(argIndex);
1352       QualType T = Arg->getType();
1353
1354       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1355       assert(ATR.isValid());
1356
1357       if (!ATR.matchesType(S.Context, T)) {
1358         S.Diag(getLocationOfByte(Amt.getStart()),
1359                diag::warn_printf_asterisk_wrong_type)
1360           << k
1361           << ATR.getRepresentativeType(S.Context) << T
1362           << getSpecifierRange(startSpecifier, specifierLen)
1363           << Arg->getSourceRange();
1364         // Don't do any more checking.  We will just emit
1365         // spurious errors.
1366         return false;
1367       }
1368     }
1369   }
1370   return true;
1371 }
1372
1373 void CheckPrintfHandler::HandleInvalidAmount(
1374                                       const analyze_printf::PrintfSpecifier &FS,
1375                                       const analyze_printf::OptionalAmount &Amt,
1376                                       unsigned type,
1377                                       const char *startSpecifier,
1378                                       unsigned specifierLen) {
1379   const analyze_printf::PrintfConversionSpecifier &CS =
1380     FS.getConversionSpecifier();
1381   switch (Amt.getHowSpecified()) {
1382   case analyze_printf::OptionalAmount::Constant:
1383     S.Diag(getLocationOfByte(Amt.getStart()),
1384         diag::warn_printf_nonsensical_optional_amount)
1385       << type
1386       << CS.toString()
1387       << getSpecifierRange(startSpecifier, specifierLen)
1388       << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1389           Amt.getConstantLength()));
1390     break;
1391
1392   default:
1393     S.Diag(getLocationOfByte(Amt.getStart()),
1394         diag::warn_printf_nonsensical_optional_amount)
1395       << type
1396       << CS.toString()
1397       << getSpecifierRange(startSpecifier, specifierLen);
1398     break;
1399   }
1400 }
1401
1402 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1403                                     const analyze_printf::OptionalFlag &flag,
1404                                     const char *startSpecifier,
1405                                     unsigned specifierLen) {
1406   // Warn about pointless flag with a fixit removal.
1407   const analyze_printf::PrintfConversionSpecifier &CS =
1408     FS.getConversionSpecifier();
1409   S.Diag(getLocationOfByte(flag.getPosition()),
1410       diag::warn_printf_nonsensical_flag)
1411     << flag.toString() << CS.toString()
1412     << getSpecifierRange(startSpecifier, specifierLen)
1413     << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
1414 }
1415
1416 void CheckPrintfHandler::HandleIgnoredFlag(
1417                                 const analyze_printf::PrintfSpecifier &FS,
1418                                 const analyze_printf::OptionalFlag &ignoredFlag,
1419                                 const analyze_printf::OptionalFlag &flag,
1420                                 const char *startSpecifier,
1421                                 unsigned specifierLen) {
1422   // Warn about ignored flag with a fixit removal.
1423   S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1424       diag::warn_printf_ignored_flag)
1425     << ignoredFlag.toString() << flag.toString()
1426     << getSpecifierRange(startSpecifier, specifierLen)
1427     << FixItHint::CreateRemoval(getSpecifierRange(
1428         ignoredFlag.getPosition(), 1));
1429 }
1430
1431 bool
1432 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1433                                             &FS,
1434                                           const char *startSpecifier,
1435                                           unsigned specifierLen) {
1436
1437   using namespace analyze_format_string;
1438   using namespace analyze_printf;  
1439   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1440
1441   if (FS.consumesDataArgument()) {
1442     if (atFirstArg) {
1443         atFirstArg = false;
1444         usesPositionalArgs = FS.usesPositionalArg();
1445     }
1446     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1447       // Cannot mix-and-match positional and non-positional arguments.
1448       S.Diag(getLocationOfByte(CS.getStart()),
1449              diag::warn_format_mix_positional_nonpositional_args)
1450         << getSpecifierRange(startSpecifier, specifierLen);
1451       return false;
1452     }
1453   }
1454
1455   // First check if the field width, precision, and conversion specifier
1456   // have matching data arguments.
1457   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1458                     startSpecifier, specifierLen)) {
1459     return false;
1460   }
1461
1462   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1463                     startSpecifier, specifierLen)) {
1464     return false;
1465   }
1466
1467   if (!CS.consumesDataArgument()) {
1468     // FIXME: Technically specifying a precision or field width here
1469     // makes no sense.  Worth issuing a warning at some point.
1470     return true;
1471   }
1472
1473   // Consume the argument.
1474   unsigned argIndex = FS.getArgIndex();
1475   if (argIndex < NumDataArgs) {
1476     // The check to see if the argIndex is valid will come later.
1477     // We set the bit here because we may exit early from this
1478     // function if we encounter some other error.
1479     CoveredArgs.set(argIndex);
1480   }
1481
1482   // Check for using an Objective-C specific conversion specifier
1483   // in a non-ObjC literal.
1484   if (!IsObjCLiteral && CS.isObjCArg()) {
1485     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1486                                                   specifierLen);
1487   }
1488
1489   // Check for invalid use of field width
1490   if (!FS.hasValidFieldWidth()) {
1491     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1492         startSpecifier, specifierLen);
1493   }
1494
1495   // Check for invalid use of precision
1496   if (!FS.hasValidPrecision()) {
1497     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1498         startSpecifier, specifierLen);
1499   }
1500
1501   // Check each flag does not conflict with any other component.
1502   if (!FS.hasValidThousandsGroupingPrefix())
1503     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1504   if (!FS.hasValidLeadingZeros())
1505     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1506   if (!FS.hasValidPlusPrefix())
1507     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1508   if (!FS.hasValidSpacePrefix())
1509     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1510   if (!FS.hasValidAlternativeForm())
1511     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1512   if (!FS.hasValidLeftJustified())
1513     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1514
1515   // Check that flags are not ignored by another flag
1516   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1517     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1518         startSpecifier, specifierLen);
1519   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1520     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1521             startSpecifier, specifierLen);
1522
1523   // Check the length modifier is valid with the given conversion specifier.
1524   const LengthModifier &LM = FS.getLengthModifier();
1525   if (!FS.hasValidLengthModifier())
1526     S.Diag(getLocationOfByte(LM.getStart()),
1527         diag::warn_format_nonsensical_length)
1528       << LM.toString() << CS.toString()
1529       << getSpecifierRange(startSpecifier, specifierLen)
1530       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1531           LM.getLength()));
1532
1533   // Are we using '%n'?
1534   if (CS.getKind() == ConversionSpecifier::nArg) {
1535     // Issue a warning about this being a possible security issue.
1536     S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1537       << getSpecifierRange(startSpecifier, specifierLen);
1538     // Continue checking the other format specifiers.
1539     return true;
1540   }
1541
1542   // The remaining checks depend on the data arguments.
1543   if (HasVAListArg)
1544     return true;
1545
1546   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1547     return false;
1548
1549   // Now type check the data expression that matches the
1550   // format specifier.
1551   const Expr *Ex = getDataArg(argIndex);
1552   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1553   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1554     // Check if we didn't match because of an implicit cast from a 'char'
1555     // or 'short' to an 'int'.  This is done because printf is a varargs
1556     // function.
1557     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1558       if (ICE->getType() == S.Context.IntTy) {
1559         // All further checking is done on the subexpression.
1560         Ex = ICE->getSubExpr();
1561         if (ATR.matchesType(S.Context, Ex->getType()))
1562           return true;
1563       }
1564
1565     // We may be able to offer a FixItHint if it is a supported type.
1566     PrintfSpecifier fixedFS = FS;
1567     bool success = fixedFS.fixType(Ex->getType());
1568
1569     if (success) {
1570       // Get the fix string from the fixed format specifier
1571       llvm::SmallString<128> buf;
1572       llvm::raw_svector_ostream os(buf);
1573       fixedFS.toString(os);
1574
1575       // FIXME: getRepresentativeType() perhaps should return a string
1576       // instead of a QualType to better handle when the representative
1577       // type is 'wint_t' (which is defined in the system headers).
1578       S.Diag(getLocationOfByte(CS.getStart()),
1579           diag::warn_printf_conversion_argument_type_mismatch)
1580         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1581         << getSpecifierRange(startSpecifier, specifierLen)
1582         << Ex->getSourceRange()
1583         << FixItHint::CreateReplacement(
1584             getSpecifierRange(startSpecifier, specifierLen),
1585             os.str());
1586     }
1587     else {
1588       S.Diag(getLocationOfByte(CS.getStart()),
1589              diag::warn_printf_conversion_argument_type_mismatch)
1590         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1591         << getSpecifierRange(startSpecifier, specifierLen)
1592         << Ex->getSourceRange();
1593     }
1594   }
1595
1596   return true;
1597 }
1598
1599 //===--- CHECK: Scanf format string checking ------------------------------===//
1600
1601 namespace {  
1602 class CheckScanfHandler : public CheckFormatHandler {
1603 public:
1604   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1605                     const Expr *origFormatExpr, unsigned firstDataArg,
1606                     unsigned numDataArgs, bool isObjCLiteral,
1607                     const char *beg, bool hasVAListArg,
1608                     const CallExpr *theCall, unsigned formatIdx)
1609   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1610                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1611                        theCall, formatIdx) {}
1612   
1613   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1614                             const char *startSpecifier,
1615                             unsigned specifierLen);
1616   
1617   bool HandleInvalidScanfConversionSpecifier(
1618           const analyze_scanf::ScanfSpecifier &FS,
1619           const char *startSpecifier,
1620           unsigned specifierLen);
1621
1622   void HandleIncompleteScanList(const char *start, const char *end);
1623 };
1624 }
1625
1626 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1627                                                  const char *end) {
1628   S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1629     << getSpecifierRange(start, end - start);
1630 }
1631
1632 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1633                                         const analyze_scanf::ScanfSpecifier &FS,
1634                                         const char *startSpecifier,
1635                                         unsigned specifierLen) {
1636
1637   const analyze_scanf::ScanfConversionSpecifier &CS =
1638     FS.getConversionSpecifier();
1639
1640   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1641                                           getLocationOfByte(CS.getStart()),
1642                                           startSpecifier, specifierLen,
1643                                           CS.getStart(), CS.getLength());
1644 }
1645
1646 bool CheckScanfHandler::HandleScanfSpecifier(
1647                                        const analyze_scanf::ScanfSpecifier &FS,
1648                                        const char *startSpecifier,
1649                                        unsigned specifierLen) {
1650   
1651   using namespace analyze_scanf;
1652   using namespace analyze_format_string;  
1653
1654   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
1655
1656   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
1657   // be used to decide if we are using positional arguments consistently.
1658   if (FS.consumesDataArgument()) {
1659     if (atFirstArg) {
1660       atFirstArg = false;
1661       usesPositionalArgs = FS.usesPositionalArg();
1662     }
1663     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1664       // Cannot mix-and-match positional and non-positional arguments.
1665       S.Diag(getLocationOfByte(CS.getStart()),
1666              diag::warn_format_mix_positional_nonpositional_args)
1667         << getSpecifierRange(startSpecifier, specifierLen);
1668       return false;
1669     }
1670   }
1671   
1672   // Check if the field with is non-zero.
1673   const OptionalAmount &Amt = FS.getFieldWidth();
1674   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1675     if (Amt.getConstantAmount() == 0) {
1676       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1677                                                    Amt.getConstantLength());
1678       S.Diag(getLocationOfByte(Amt.getStart()),
1679              diag::warn_scanf_nonzero_width)
1680         << R << FixItHint::CreateRemoval(R);
1681     }
1682   }
1683   
1684   if (!FS.consumesDataArgument()) {
1685     // FIXME: Technically specifying a precision or field width here
1686     // makes no sense.  Worth issuing a warning at some point.
1687     return true;
1688   }
1689   
1690   // Consume the argument.
1691   unsigned argIndex = FS.getArgIndex();
1692   if (argIndex < NumDataArgs) {
1693       // The check to see if the argIndex is valid will come later.
1694       // We set the bit here because we may exit early from this
1695       // function if we encounter some other error.
1696     CoveredArgs.set(argIndex);
1697   }
1698   
1699   // Check the length modifier is valid with the given conversion specifier.
1700   const LengthModifier &LM = FS.getLengthModifier();
1701   if (!FS.hasValidLengthModifier()) {
1702     S.Diag(getLocationOfByte(LM.getStart()),
1703            diag::warn_format_nonsensical_length)
1704       << LM.toString() << CS.toString()
1705       << getSpecifierRange(startSpecifier, specifierLen)
1706       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1707                                                     LM.getLength()));
1708   }
1709
1710   // The remaining checks depend on the data arguments.
1711   if (HasVAListArg)
1712     return true;
1713   
1714   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1715     return false;
1716   
1717   // FIXME: Check that the argument type matches the format specifier.
1718   
1719   return true;
1720 }
1721
1722 void Sema::CheckFormatString(const StringLiteral *FExpr,
1723                              const Expr *OrigFormatExpr,
1724                              const CallExpr *TheCall, bool HasVAListArg,
1725                              unsigned format_idx, unsigned firstDataArg,
1726                              bool isPrintf) {
1727   
1728   // CHECK: is the format string a wide literal?
1729   if (FExpr->isWide()) {
1730     Diag(FExpr->getLocStart(),
1731          diag::warn_format_string_is_wide_literal)
1732     << OrigFormatExpr->getSourceRange();
1733     return;
1734   }
1735   
1736   // Str - The format string.  NOTE: this is NOT null-terminated!
1737   llvm::StringRef StrRef = FExpr->getString();
1738   const char *Str = StrRef.data();
1739   unsigned StrLen = StrRef.size();
1740   
1741   // CHECK: empty format string?
1742   if (StrLen == 0) {
1743     Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
1744     << OrigFormatExpr->getSourceRange();
1745     return;
1746   }
1747   
1748   if (isPrintf) {
1749     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1750                          TheCall->getNumArgs() - firstDataArg,
1751                          isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1752                          HasVAListArg, TheCall, format_idx);
1753   
1754     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1755       H.DoneProcessing();
1756   }
1757   else {
1758     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1759                         TheCall->getNumArgs() - firstDataArg,
1760                         isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1761                         HasVAListArg, TheCall, format_idx);
1762     
1763     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1764       H.DoneProcessing();
1765   }
1766 }
1767
1768 //===--- CHECK: Return Address of Stack Variable --------------------------===//
1769
1770 static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1771 static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1772
1773 /// CheckReturnStackAddr - Check if a return statement returns the address
1774 ///   of a stack variable.
1775 void
1776 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1777                            SourceLocation ReturnLoc) {
1778
1779   Expr *stackE = 0;
1780   llvm::SmallVector<DeclRefExpr *, 8> refVars;
1781
1782   // Perform checking for returned stack addresses, local blocks,
1783   // label addresses or references to temporaries.
1784   if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1785     stackE = EvalAddr(RetValExp, refVars);
1786   } else if (lhsType->isReferenceType()) {
1787     stackE = EvalVal(RetValExp, refVars);
1788   }
1789
1790   if (stackE == 0)
1791     return; // Nothing suspicious was found.
1792
1793   SourceLocation diagLoc;
1794   SourceRange diagRange;
1795   if (refVars.empty()) {
1796     diagLoc = stackE->getLocStart();
1797     diagRange = stackE->getSourceRange();
1798   } else {
1799     // We followed through a reference variable. 'stackE' contains the
1800     // problematic expression but we will warn at the return statement pointing
1801     // at the reference variable. We will later display the "trail" of
1802     // reference variables using notes.
1803     diagLoc = refVars[0]->getLocStart();
1804     diagRange = refVars[0]->getSourceRange();
1805   }
1806
1807   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1808     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1809                                              : diag::warn_ret_stack_addr)
1810      << DR->getDecl()->getDeclName() << diagRange;
1811   } else if (isa<BlockExpr>(stackE)) { // local block.
1812     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1813   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1814     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1815   } else { // local temporary.
1816     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1817                                              : diag::warn_ret_local_temp_addr)
1818      << diagRange;
1819   }
1820
1821   // Display the "trail" of reference variables that we followed until we
1822   // found the problematic expression using notes.
1823   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1824     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1825     // If this var binds to another reference var, show the range of the next
1826     // var, otherwise the var binds to the problematic expression, in which case
1827     // show the range of the expression.
1828     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1829                                   : stackE->getSourceRange();
1830     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1831       << VD->getDeclName() << range;
1832   }
1833 }
1834
1835 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1836 ///  check if the expression in a return statement evaluates to an address
1837 ///  to a location on the stack, a local block, an address of a label, or a
1838 ///  reference to local temporary. The recursion is used to traverse the
1839 ///  AST of the return expression, with recursion backtracking when we
1840 ///  encounter a subexpression that (1) clearly does not lead to one of the
1841 ///  above problematic expressions (2) is something we cannot determine leads to
1842 ///  a problematic expression based on such local checking.
1843 ///
1844 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
1845 ///  the expression that they point to. Such variables are added to the
1846 ///  'refVars' vector so that we know what the reference variable "trail" was.
1847 ///
1848 ///  EvalAddr processes expressions that are pointers that are used as
1849 ///  references (and not L-values).  EvalVal handles all other values.
1850 ///  At the base case of the recursion is a check for the above problematic
1851 ///  expressions.
1852 ///
1853 ///  This implementation handles:
1854 ///
1855 ///   * pointer-to-pointer casts
1856 ///   * implicit conversions from array references to pointers
1857 ///   * taking the address of fields
1858 ///   * arbitrary interplay between "&" and "*" operators
1859 ///   * pointer arithmetic from an address of a stack variable
1860 ///   * taking the address of an array element where the array is on the stack
1861 static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1862   if (E->isTypeDependent())
1863       return NULL;
1864
1865   // We should only be called for evaluating pointer expressions.
1866   assert((E->getType()->isAnyPointerType() ||
1867           E->getType()->isBlockPointerType() ||
1868           E->getType()->isObjCQualifiedIdType()) &&
1869          "EvalAddr only works on pointers");
1870
1871   // Our "symbolic interpreter" is just a dispatch off the currently
1872   // viewed AST node.  We then recursively traverse the AST by calling
1873   // EvalAddr and EvalVal appropriately.
1874   switch (E->getStmtClass()) {
1875   case Stmt::ParenExprClass:
1876     // Ignore parentheses.
1877     return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1878
1879   case Stmt::DeclRefExprClass: {
1880     DeclRefExpr *DR = cast<DeclRefExpr>(E);
1881
1882     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1883       // If this is a reference variable, follow through to the expression that
1884       // it points to.
1885       if (V->hasLocalStorage() &&
1886           V->getType()->isReferenceType() && V->hasInit()) {
1887         // Add the reference variable to the "trail".
1888         refVars.push_back(DR);
1889         return EvalAddr(V->getInit(), refVars);
1890       }
1891
1892     return NULL;
1893   }
1894
1895   case Stmt::UnaryOperatorClass: {
1896     // The only unary operator that make sense to handle here
1897     // is AddrOf.  All others don't make sense as pointers.
1898     UnaryOperator *U = cast<UnaryOperator>(E);
1899
1900     if (U->getOpcode() == UO_AddrOf)
1901       return EvalVal(U->getSubExpr(), refVars);
1902     else
1903       return NULL;
1904   }
1905
1906   case Stmt::BinaryOperatorClass: {
1907     // Handle pointer arithmetic.  All other binary operators are not valid
1908     // in this context.
1909     BinaryOperator *B = cast<BinaryOperator>(E);
1910     BinaryOperatorKind op = B->getOpcode();
1911
1912     if (op != BO_Add && op != BO_Sub)
1913       return NULL;
1914
1915     Expr *Base = B->getLHS();
1916
1917     // Determine which argument is the real pointer base.  It could be
1918     // the RHS argument instead of the LHS.
1919     if (!Base->getType()->isPointerType()) Base = B->getRHS();
1920
1921     assert (Base->getType()->isPointerType());
1922     return EvalAddr(Base, refVars);
1923   }
1924
1925   // For conditional operators we need to see if either the LHS or RHS are
1926   // valid DeclRefExpr*s.  If one of them is valid, we return it.
1927   case Stmt::ConditionalOperatorClass: {
1928     ConditionalOperator *C = cast<ConditionalOperator>(E);
1929
1930     // Handle the GNU extension for missing LHS.
1931     if (Expr *lhsExpr = C->getLHS()) {
1932     // In C++, we can have a throw-expression, which has 'void' type.
1933       if (!lhsExpr->getType()->isVoidType())
1934         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
1935           return LHS;
1936     }
1937
1938     // In C++, we can have a throw-expression, which has 'void' type.
1939     if (C->getRHS()->getType()->isVoidType())
1940       return NULL;
1941
1942     return EvalAddr(C->getRHS(), refVars);
1943   }
1944   
1945   case Stmt::BlockExprClass:
1946     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
1947       return E; // local block.
1948     return NULL;
1949
1950   case Stmt::AddrLabelExprClass:
1951     return E; // address of label.
1952
1953   // For casts, we need to handle conversions from arrays to
1954   // pointer values, and pointer-to-pointer conversions.
1955   case Stmt::ImplicitCastExprClass:
1956   case Stmt::CStyleCastExprClass:
1957   case Stmt::CXXFunctionalCastExprClass: {
1958     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1959     QualType T = SubExpr->getType();
1960
1961     if (SubExpr->getType()->isPointerType() ||
1962         SubExpr->getType()->isBlockPointerType() ||
1963         SubExpr->getType()->isObjCQualifiedIdType())
1964       return EvalAddr(SubExpr, refVars);
1965     else if (T->isArrayType())
1966       return EvalVal(SubExpr, refVars);
1967     else
1968       return 0;
1969   }
1970
1971   // C++ casts.  For dynamic casts, static casts, and const casts, we
1972   // are always converting from a pointer-to-pointer, so we just blow
1973   // through the cast.  In the case the dynamic cast doesn't fail (and
1974   // return NULL), we take the conservative route and report cases
1975   // where we return the address of a stack variable.  For Reinterpre
1976   // FIXME: The comment about is wrong; we're not always converting
1977   // from pointer to pointer. I'm guessing that this code should also
1978   // handle references to objects.
1979   case Stmt::CXXStaticCastExprClass:
1980   case Stmt::CXXDynamicCastExprClass:
1981   case Stmt::CXXConstCastExprClass:
1982   case Stmt::CXXReinterpretCastExprClass: {
1983       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1984       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1985         return EvalAddr(S, refVars);
1986       else
1987         return NULL;
1988   }
1989
1990   // Everything else: we simply don't reason about them.
1991   default:
1992     return NULL;
1993   }
1994 }
1995
1996
1997 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1998 ///   See the comments for EvalAddr for more details.
1999 static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
2000 do {
2001   // We should only be called for evaluating non-pointer expressions, or
2002   // expressions with a pointer type that are not used as references but instead
2003   // are l-values (e.g., DeclRefExpr with a pointer type).
2004
2005   // Our "symbolic interpreter" is just a dispatch off the currently
2006   // viewed AST node.  We then recursively traverse the AST by calling
2007   // EvalAddr and EvalVal appropriately.
2008   switch (E->getStmtClass()) {
2009   case Stmt::ImplicitCastExprClass: {
2010     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2011     if (IE->getValueKind() == VK_LValue) {
2012       E = IE->getSubExpr();
2013       continue;
2014     }
2015     return NULL;
2016   }
2017
2018   case Stmt::DeclRefExprClass: {
2019     // When we hit a DeclRefExpr we are looking at code that refers to a
2020     // variable's name. If it's not a reference variable we check if it has
2021     // local storage within the function, and if so, return the expression.
2022     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2023
2024     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2025       if (V->hasLocalStorage()) {
2026         if (!V->getType()->isReferenceType())
2027           return DR;
2028
2029         // Reference variable, follow through to the expression that
2030         // it points to.
2031         if (V->hasInit()) {
2032           // Add the reference variable to the "trail".
2033           refVars.push_back(DR);
2034           return EvalVal(V->getInit(), refVars);
2035         }
2036       }
2037
2038     return NULL;
2039   }
2040
2041   case Stmt::ParenExprClass: {
2042     // Ignore parentheses.
2043     E = cast<ParenExpr>(E)->getSubExpr();
2044     continue;
2045   }
2046
2047   case Stmt::UnaryOperatorClass: {
2048     // The only unary operator that make sense to handle here
2049     // is Deref.  All others don't resolve to a "name."  This includes
2050     // handling all sorts of rvalues passed to a unary operator.
2051     UnaryOperator *U = cast<UnaryOperator>(E);
2052
2053     if (U->getOpcode() == UO_Deref)
2054       return EvalAddr(U->getSubExpr(), refVars);
2055
2056     return NULL;
2057   }
2058
2059   case Stmt::ArraySubscriptExprClass: {
2060     // Array subscripts are potential references to data on the stack.  We
2061     // retrieve the DeclRefExpr* for the array variable if it indeed
2062     // has local storage.
2063     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2064   }
2065
2066   case Stmt::ConditionalOperatorClass: {
2067     // For conditional operators we need to see if either the LHS or RHS are
2068     // non-NULL Expr's.  If one is non-NULL, we return it.
2069     ConditionalOperator *C = cast<ConditionalOperator>(E);
2070
2071     // Handle the GNU extension for missing LHS.
2072     if (Expr *lhsExpr = C->getLHS())
2073       if (Expr *LHS = EvalVal(lhsExpr, refVars))
2074         return LHS;
2075
2076     return EvalVal(C->getRHS(), refVars);
2077   }
2078
2079   // Accesses to members are potential references to data on the stack.
2080   case Stmt::MemberExprClass: {
2081     MemberExpr *M = cast<MemberExpr>(E);
2082
2083     // Check for indirect access.  We only want direct field accesses.
2084     if (M->isArrow())
2085       return NULL;
2086
2087     // Check whether the member type is itself a reference, in which case
2088     // we're not going to refer to the member, but to what the member refers to.
2089     if (M->getMemberDecl()->getType()->isReferenceType())
2090       return NULL;
2091
2092     return EvalVal(M->getBase(), refVars);
2093   }
2094
2095   default:
2096     // Check that we don't return or take the address of a reference to a
2097     // temporary. This is only useful in C++.
2098     if (!E->isTypeDependent() && E->isRValue())
2099       return E;
2100
2101     // Everything else: we simply don't reason about them.
2102     return NULL;
2103   }
2104 } while (true);
2105 }
2106
2107 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2108
2109 /// Check for comparisons of floating point operands using != and ==.
2110 /// Issue a warning if these are no self-comparisons, as they are not likely
2111 /// to do what the programmer intended.
2112 void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2113   bool EmitWarning = true;
2114
2115   Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2116   Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
2117
2118   // Special case: check for x == x (which is OK).
2119   // Do not emit warnings for such cases.
2120   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2121     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2122       if (DRL->getDecl() == DRR->getDecl())
2123         EmitWarning = false;
2124
2125
2126   // Special case: check for comparisons against literals that can be exactly
2127   //  represented by APFloat.  In such cases, do not emit a warning.  This
2128   //  is a heuristic: often comparison against such literals are used to
2129   //  detect if a value in a variable has not changed.  This clearly can
2130   //  lead to false negatives.
2131   if (EmitWarning) {
2132     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2133       if (FLL->isExact())
2134         EmitWarning = false;
2135     } else
2136       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2137         if (FLR->isExact())
2138           EmitWarning = false;
2139     }
2140   }
2141
2142   // Check for comparisons with builtin types.
2143   if (EmitWarning)
2144     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2145       if (CL->isBuiltinCall(Context))
2146         EmitWarning = false;
2147
2148   if (EmitWarning)
2149     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2150       if (CR->isBuiltinCall(Context))
2151         EmitWarning = false;
2152
2153   // Emit the diagnostic.
2154   if (EmitWarning)
2155     Diag(loc, diag::warn_floatingpoint_eq)
2156       << lex->getSourceRange() << rex->getSourceRange();
2157 }
2158
2159 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2160 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2161
2162 namespace {
2163
2164 /// Structure recording the 'active' range of an integer-valued
2165 /// expression.
2166 struct IntRange {
2167   /// The number of bits active in the int.
2168   unsigned Width;
2169
2170   /// True if the int is known not to have negative values.
2171   bool NonNegative;
2172
2173   IntRange(unsigned Width, bool NonNegative)
2174     : Width(Width), NonNegative(NonNegative)
2175   {}
2176
2177   /// Returns the range of the bool type.
2178   static IntRange forBoolType() {
2179     return IntRange(1, true);
2180   }
2181
2182   /// Returns the range of an opaque value of the given integral type.
2183   static IntRange forValueOfType(ASTContext &C, QualType T) {
2184     return forValueOfCanonicalType(C,
2185                           T->getCanonicalTypeInternal().getTypePtr());
2186   }
2187
2188   /// Returns the range of an opaque value of a canonical integral type.
2189   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2190     assert(T->isCanonicalUnqualified());
2191
2192     if (const VectorType *VT = dyn_cast<VectorType>(T))
2193       T = VT->getElementType().getTypePtr();
2194     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2195       T = CT->getElementType().getTypePtr();
2196
2197     // For enum types, use the known bit width of the enumerators.
2198     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2199       EnumDecl *Enum = ET->getDecl();
2200       if (!Enum->isDefinition())
2201         return IntRange(C.getIntWidth(QualType(T, 0)), false);
2202
2203       unsigned NumPositive = Enum->getNumPositiveBits();
2204       unsigned NumNegative = Enum->getNumNegativeBits();
2205
2206       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2207     }
2208
2209     const BuiltinType *BT = cast<BuiltinType>(T);
2210     assert(BT->isInteger());
2211
2212     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2213   }
2214
2215   /// Returns the "target" range of a canonical integral type, i.e.
2216   /// the range of values expressible in the type.
2217   ///
2218   /// This matches forValueOfCanonicalType except that enums have the
2219   /// full range of their type, not the range of their enumerators.
2220   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2221     assert(T->isCanonicalUnqualified());
2222
2223     if (const VectorType *VT = dyn_cast<VectorType>(T))
2224       T = VT->getElementType().getTypePtr();
2225     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2226       T = CT->getElementType().getTypePtr();
2227     if (const EnumType *ET = dyn_cast<EnumType>(T))
2228       T = ET->getDecl()->getIntegerType().getTypePtr();
2229
2230     const BuiltinType *BT = cast<BuiltinType>(T);
2231     assert(BT->isInteger());
2232
2233     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2234   }
2235
2236   /// Returns the supremum of two ranges: i.e. their conservative merge.
2237   static IntRange join(IntRange L, IntRange R) {
2238     return IntRange(std::max(L.Width, R.Width),
2239                     L.NonNegative && R.NonNegative);
2240   }
2241
2242   /// Returns the infinum of two ranges: i.e. their aggressive merge.
2243   static IntRange meet(IntRange L, IntRange R) {
2244     return IntRange(std::min(L.Width, R.Width),
2245                     L.NonNegative || R.NonNegative);
2246   }
2247 };
2248
2249 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2250   if (value.isSigned() && value.isNegative())
2251     return IntRange(value.getMinSignedBits(), false);
2252
2253   if (value.getBitWidth() > MaxWidth)
2254     value = value.trunc(MaxWidth);
2255
2256   // isNonNegative() just checks the sign bit without considering
2257   // signedness.
2258   return IntRange(value.getActiveBits(), true);
2259 }
2260
2261 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2262                        unsigned MaxWidth) {
2263   if (result.isInt())
2264     return GetValueRange(C, result.getInt(), MaxWidth);
2265
2266   if (result.isVector()) {
2267     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2268     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2269       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2270       R = IntRange::join(R, El);
2271     }
2272     return R;
2273   }
2274
2275   if (result.isComplexInt()) {
2276     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2277     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2278     return IntRange::join(R, I);
2279   }
2280
2281   // This can happen with lossless casts to intptr_t of "based" lvalues.
2282   // Assume it might use arbitrary bits.
2283   // FIXME: The only reason we need to pass the type in here is to get
2284   // the sign right on this one case.  It would be nice if APValue
2285   // preserved this.
2286   assert(result.isLValue());
2287   return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
2288 }
2289
2290 /// Pseudo-evaluate the given integer expression, estimating the
2291 /// range of values it might take.
2292 ///
2293 /// \param MaxWidth - the width to which the value will be truncated
2294 IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2295   E = E->IgnoreParens();
2296
2297   // Try a full evaluation first.
2298   Expr::EvalResult result;
2299   if (E->Evaluate(result, C))
2300     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2301
2302   // I think we only want to look through implicit casts here; if the
2303   // user has an explicit widening cast, we should treat the value as
2304   // being of the new, wider type.
2305   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2306     if (CE->getCastKind() == CK_NoOp)
2307       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2308
2309     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
2310
2311     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2312
2313     // Assume that non-integer casts can span the full range of the type.
2314     if (!isIntegerCast)
2315       return OutputTypeRange;
2316
2317     IntRange SubRange
2318       = GetExprRange(C, CE->getSubExpr(),
2319                      std::min(MaxWidth, OutputTypeRange.Width));
2320
2321     // Bail out if the subexpr's range is as wide as the cast type.
2322     if (SubRange.Width >= OutputTypeRange.Width)
2323       return OutputTypeRange;
2324
2325     // Otherwise, we take the smaller width, and we're non-negative if
2326     // either the output type or the subexpr is.
2327     return IntRange(SubRange.Width,
2328                     SubRange.NonNegative || OutputTypeRange.NonNegative);
2329   }
2330
2331   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2332     // If we can fold the condition, just take that operand.
2333     bool CondResult;
2334     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2335       return GetExprRange(C, CondResult ? CO->getTrueExpr()
2336                                         : CO->getFalseExpr(),
2337                           MaxWidth);
2338
2339     // Otherwise, conservatively merge.
2340     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2341     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2342     return IntRange::join(L, R);
2343   }
2344
2345   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2346     switch (BO->getOpcode()) {
2347
2348     // Boolean-valued operations are single-bit and positive.
2349     case BO_LAnd:
2350     case BO_LOr:
2351     case BO_LT:
2352     case BO_GT:
2353     case BO_LE:
2354     case BO_GE:
2355     case BO_EQ:
2356     case BO_NE:
2357       return IntRange::forBoolType();
2358
2359     // The type of these compound assignments is the type of the LHS,
2360     // so the RHS is not necessarily an integer.
2361     case BO_MulAssign:
2362     case BO_DivAssign:
2363     case BO_RemAssign:
2364     case BO_AddAssign:
2365     case BO_SubAssign:
2366       return IntRange::forValueOfType(C, E->getType());
2367
2368     // Operations with opaque sources are black-listed.
2369     case BO_PtrMemD:
2370     case BO_PtrMemI:
2371       return IntRange::forValueOfType(C, E->getType());
2372
2373     // Bitwise-and uses the *infinum* of the two source ranges.
2374     case BO_And:
2375     case BO_AndAssign:
2376       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2377                             GetExprRange(C, BO->getRHS(), MaxWidth));
2378
2379     // Left shift gets black-listed based on a judgement call.
2380     case BO_Shl:
2381       // ...except that we want to treat '1 << (blah)' as logically
2382       // positive.  It's an important idiom.
2383       if (IntegerLiteral *I
2384             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2385         if (I->getValue() == 1) {
2386           IntRange R = IntRange::forValueOfType(C, E->getType());
2387           return IntRange(R.Width, /*NonNegative*/ true);
2388         }
2389       }
2390       // fallthrough
2391
2392     case BO_ShlAssign:
2393       return IntRange::forValueOfType(C, E->getType());
2394
2395     // Right shift by a constant can narrow its left argument.
2396     case BO_Shr:
2397     case BO_ShrAssign: {
2398       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2399
2400       // If the shift amount is a positive constant, drop the width by
2401       // that much.
2402       llvm::APSInt shift;
2403       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2404           shift.isNonNegative()) {
2405         unsigned zext = shift.getZExtValue();
2406         if (zext >= L.Width)
2407           L.Width = (L.NonNegative ? 0 : 1);
2408         else
2409           L.Width -= zext;
2410       }
2411
2412       return L;
2413     }
2414
2415     // Comma acts as its right operand.
2416     case BO_Comma:
2417       return GetExprRange(C, BO->getRHS(), MaxWidth);
2418
2419     // Black-list pointer subtractions.
2420     case BO_Sub:
2421       if (BO->getLHS()->getType()->isPointerType())
2422         return IntRange::forValueOfType(C, E->getType());
2423       // fallthrough
2424
2425     default:
2426       break;
2427     }
2428
2429     // Treat every other operator as if it were closed on the
2430     // narrowest type that encompasses both operands.
2431     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2432     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2433     return IntRange::join(L, R);
2434   }
2435
2436   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2437     switch (UO->getOpcode()) {
2438     // Boolean-valued operations are white-listed.
2439     case UO_LNot:
2440       return IntRange::forBoolType();
2441
2442     // Operations with opaque sources are black-listed.
2443     case UO_Deref:
2444     case UO_AddrOf: // should be impossible
2445       return IntRange::forValueOfType(C, E->getType());
2446
2447     default:
2448       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2449     }
2450   }
2451   
2452   if (dyn_cast<OffsetOfExpr>(E)) {
2453     IntRange::forValueOfType(C, E->getType());
2454   }
2455
2456   FieldDecl *BitField = E->getBitField();
2457   if (BitField) {
2458     llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2459     unsigned BitWidth = BitWidthAP.getZExtValue();
2460
2461     return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2462   }
2463
2464   return IntRange::forValueOfType(C, E->getType());
2465 }
2466
2467 IntRange GetExprRange(ASTContext &C, Expr *E) {
2468   return GetExprRange(C, E, C.getIntWidth(E->getType()));
2469 }
2470
2471 /// Checks whether the given value, which currently has the given
2472 /// source semantics, has the same value when coerced through the
2473 /// target semantics.
2474 bool IsSameFloatAfterCast(const llvm::APFloat &value,
2475                           const llvm::fltSemantics &Src,
2476                           const llvm::fltSemantics &Tgt) {
2477   llvm::APFloat truncated = value;
2478
2479   bool ignored;
2480   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2481   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2482
2483   return truncated.bitwiseIsEqual(value);
2484 }
2485
2486 /// Checks whether the given value, which currently has the given
2487 /// source semantics, has the same value when coerced through the
2488 /// target semantics.
2489 ///
2490 /// The value might be a vector of floats (or a complex number).
2491 bool IsSameFloatAfterCast(const APValue &value,
2492                           const llvm::fltSemantics &Src,
2493                           const llvm::fltSemantics &Tgt) {
2494   if (value.isFloat())
2495     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2496
2497   if (value.isVector()) {
2498     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2499       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2500         return false;
2501     return true;
2502   }
2503
2504   assert(value.isComplexFloat());
2505   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2506           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2507 }
2508
2509 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
2510
2511 static bool IsZero(Sema &S, Expr *E) {
2512   // Suppress cases where we are comparing against an enum constant.
2513   if (const DeclRefExpr *DR =
2514       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2515     if (isa<EnumConstantDecl>(DR->getDecl()))
2516       return false;
2517
2518   // Suppress cases where the '0' value is expanded from a macro.
2519   if (E->getLocStart().isMacroID())
2520     return false;
2521
2522   llvm::APSInt Value;
2523   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2524 }
2525
2526 static bool HasEnumType(Expr *E) {
2527   // Strip off implicit integral promotions.
2528   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2529     if (ICE->getCastKind() != CK_IntegralCast &&
2530         ICE->getCastKind() != CK_NoOp)
2531       break;
2532     E = ICE->getSubExpr();
2533   }
2534
2535   return E->getType()->isEnumeralType();
2536 }
2537
2538 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2539   BinaryOperatorKind op = E->getOpcode();
2540   if (E->isValueDependent())
2541     return;
2542
2543   if (op == BO_LT && IsZero(S, E->getRHS())) {
2544     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2545       << "< 0" << "false" << HasEnumType(E->getLHS())
2546       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2547   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
2548     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2549       << ">= 0" << "true" << HasEnumType(E->getLHS())
2550       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2551   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
2552     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2553       << "0 >" << "false" << HasEnumType(E->getRHS())
2554       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2555   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
2556     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2557       << "0 <=" << "true" << HasEnumType(E->getRHS())
2558       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2559   }
2560 }
2561
2562 /// Analyze the operands of the given comparison.  Implements the
2563 /// fallback case from AnalyzeComparison.
2564 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2565   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2566   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2567 }
2568
2569 /// \brief Implements -Wsign-compare.
2570 ///
2571 /// \param lex the left-hand expression
2572 /// \param rex the right-hand expression
2573 /// \param OpLoc the location of the joining operator
2574 /// \param BinOpc binary opcode or 0
2575 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2576   // The type the comparison is being performed in.
2577   QualType T = E->getLHS()->getType();
2578   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2579          && "comparison with mismatched types");
2580
2581   // We don't do anything special if this isn't an unsigned integral
2582   // comparison:  we're only interested in integral comparisons, and
2583   // signed comparisons only happen in cases we don't care to warn about.
2584   //
2585   // We also don't care about value-dependent expressions or expressions
2586   // whose result is a constant.
2587   if (!T->hasUnsignedIntegerRepresentation()
2588       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
2589     return AnalyzeImpConvsInComparison(S, E);
2590
2591   Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2592   Expr *rex = E->getRHS()->IgnoreParenImpCasts();
2593
2594   // Check to see if one of the (unmodified) operands is of different
2595   // signedness.
2596   Expr *signedOperand, *unsignedOperand;
2597   if (lex->getType()->hasSignedIntegerRepresentation()) {
2598     assert(!rex->getType()->hasSignedIntegerRepresentation() &&
2599            "unsigned comparison between two signed integer expressions?");
2600     signedOperand = lex;
2601     unsignedOperand = rex;
2602   } else if (rex->getType()->hasSignedIntegerRepresentation()) {
2603     signedOperand = rex;
2604     unsignedOperand = lex;
2605   } else {
2606     CheckTrivialUnsignedComparison(S, E);
2607     return AnalyzeImpConvsInComparison(S, E);
2608   }
2609
2610   // Otherwise, calculate the effective range of the signed operand.
2611   IntRange signedRange = GetExprRange(S.Context, signedOperand);
2612
2613   // Go ahead and analyze implicit conversions in the operands.  Note
2614   // that we skip the implicit conversions on both sides.
2615   AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2616   AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
2617
2618   // If the signed range is non-negative, -Wsign-compare won't fire,
2619   // but we should still check for comparisons which are always true
2620   // or false.
2621   if (signedRange.NonNegative)
2622     return CheckTrivialUnsignedComparison(S, E);
2623
2624   // For (in)equality comparisons, if the unsigned operand is a
2625   // constant which cannot collide with a overflowed signed operand,
2626   // then reinterpreting the signed operand as unsigned will not
2627   // change the result of the comparison.
2628   if (E->isEqualityOp()) {
2629     unsigned comparisonWidth = S.Context.getIntWidth(T);
2630     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
2631
2632     // We should never be unable to prove that the unsigned operand is
2633     // non-negative.
2634     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2635
2636     if (unsignedRange.Width < comparisonWidth)
2637       return;
2638   }
2639
2640   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2641     << lex->getType() << rex->getType()
2642     << lex->getSourceRange() << rex->getSourceRange();
2643 }
2644
2645 /// Analyzes an attempt to assign the given value to a bitfield.
2646 ///
2647 /// Returns true if there was something fishy about the attempt.
2648 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2649                                SourceLocation InitLoc) {
2650   assert(Bitfield->isBitField());
2651   if (Bitfield->isInvalidDecl())
2652     return false;
2653
2654   // White-list bool bitfields.
2655   if (Bitfield->getType()->isBooleanType())
2656     return false;
2657
2658   // Ignore value- or type-dependent expressions.
2659   if (Bitfield->getBitWidth()->isValueDependent() ||
2660       Bitfield->getBitWidth()->isTypeDependent() ||
2661       Init->isValueDependent() ||
2662       Init->isTypeDependent())
2663     return false;
2664
2665   Expr *OriginalInit = Init->IgnoreParenImpCasts();
2666
2667   llvm::APSInt Width(32);
2668   Expr::EvalResult InitValue;
2669   if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
2670       !OriginalInit->Evaluate(InitValue, S.Context) ||
2671       !InitValue.Val.isInt())
2672     return false;
2673
2674   const llvm::APSInt &Value = InitValue.Val.getInt();
2675   unsigned OriginalWidth = Value.getBitWidth();
2676   unsigned FieldWidth = Width.getZExtValue();
2677
2678   if (OriginalWidth <= FieldWidth)
2679     return false;
2680
2681   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
2682
2683   // It's fairly common to write values into signed bitfields
2684   // that, if sign-extended, would end up becoming a different
2685   // value.  We don't want to warn about that.
2686   if (Value.isSigned() && Value.isNegative())
2687     TruncatedValue = TruncatedValue.sext(OriginalWidth);
2688   else
2689     TruncatedValue = TruncatedValue.zext(OriginalWidth);
2690
2691   if (Value == TruncatedValue)
2692     return false;
2693
2694   std::string PrettyValue = Value.toString(10);
2695   std::string PrettyTrunc = TruncatedValue.toString(10);
2696
2697   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2698     << PrettyValue << PrettyTrunc << OriginalInit->getType()
2699     << Init->getSourceRange();
2700
2701   return true;
2702 }
2703
2704 /// Analyze the given simple or compound assignment for warning-worthy
2705 /// operations.
2706 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2707   // Just recurse on the LHS.
2708   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2709
2710   // We want to recurse on the RHS as normal unless we're assigning to
2711   // a bitfield.
2712   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
2713     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2714                                   E->getOperatorLoc())) {
2715       // Recurse, ignoring any implicit conversions on the RHS.
2716       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2717                                         E->getOperatorLoc());
2718     }
2719   }
2720
2721   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2722 }
2723
2724 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2725 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2726                      unsigned diag) {
2727   S.Diag(E->getExprLoc(), diag)
2728     << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
2729 }
2730
2731 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2732   if (!Range.Width) return "0";
2733
2734   llvm::APSInt ValueInRange = Value;
2735   ValueInRange.setIsSigned(!Range.NonNegative);
2736   ValueInRange = ValueInRange.trunc(Range.Width);
2737   return ValueInRange.toString(10);
2738 }
2739
2740 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2741                              SourceLocation CC, bool *ICContext = 0) {
2742   if (E->isTypeDependent() || E->isValueDependent()) return;
2743
2744   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2745   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2746   if (Source == Target) return;
2747   if (Target->isDependentType()) return;
2748
2749   // If the conversion context location is invalid or instantiated
2750   // from a system macro, don't complain.
2751   if (CC.isInvalid() ||
2752       (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2753                            S.Context.getSourceManager().getSpellingLoc(CC))))
2754     return;
2755
2756   // Never diagnose implicit casts to bool.
2757   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2758     return;
2759
2760   // Strip vector types.
2761   if (isa<VectorType>(Source)) {
2762     if (!isa<VectorType>(Target))
2763       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
2764
2765     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2766     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2767   }
2768
2769   // Strip complex types.
2770   if (isa<ComplexType>(Source)) {
2771     if (!isa<ComplexType>(Target))
2772       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
2773
2774     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2775     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2776   }
2777
2778   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2779   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2780
2781   // If the source is floating point...
2782   if (SourceBT && SourceBT->isFloatingPoint()) {
2783     // ...and the target is floating point...
2784     if (TargetBT && TargetBT->isFloatingPoint()) {
2785       // ...then warn if we're dropping FP rank.
2786
2787       // Builtin FP kinds are ordered by increasing FP rank.
2788       if (SourceBT->getKind() > TargetBT->getKind()) {
2789         // Don't warn about float constants that are precisely
2790         // representable in the target type.
2791         Expr::EvalResult result;
2792         if (E->Evaluate(result, S.Context)) {
2793           // Value might be a float, a float vector, or a float complex.
2794           if (IsSameFloatAfterCast(result.Val,
2795                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2796                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2797             return;
2798         }
2799
2800         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
2801       }
2802       return;
2803     }
2804
2805     // If the target is integral, always warn.
2806     if ((TargetBT && TargetBT->isInteger())) {
2807       Expr *InnerE = E->IgnoreParenImpCasts();
2808       if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2809         DiagnoseImpCast(S, LiteralExpr, T, CC,
2810                         diag::warn_impcast_literal_float_to_integer);
2811       } else {
2812         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2813       }
2814     }
2815
2816     return;
2817   }
2818
2819   if (!Source->isIntegerType() || !Target->isIntegerType())
2820     return;
2821
2822   IntRange SourceRange = GetExprRange(S.Context, E);
2823   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
2824
2825   if (SourceRange.Width > TargetRange.Width) {
2826     // If the source is a constant, use a default-on diagnostic.
2827     // TODO: this should happen for bitfield stores, too.
2828     llvm::APSInt Value(32);
2829     if (E->isIntegerConstantExpr(Value, S.Context)) {
2830       std::string PrettySourceValue = Value.toString(10);
2831       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2832
2833       S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2834         << PrettySourceValue << PrettyTargetValue
2835         << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2836       return;
2837     }
2838
2839     // People want to build with -Wshorten-64-to-32 and not -Wconversion
2840     // and by god we'll let them.
2841     if (SourceRange.Width == 64 && TargetRange.Width == 32)
2842       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2843     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
2844   }
2845
2846   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2847       (!TargetRange.NonNegative && SourceRange.NonNegative &&
2848        SourceRange.Width == TargetRange.Width)) {
2849     unsigned DiagID = diag::warn_impcast_integer_sign;
2850
2851     // Traditionally, gcc has warned about this under -Wsign-compare.
2852     // We also want to warn about it in -Wconversion.
2853     // So if -Wconversion is off, use a completely identical diagnostic
2854     // in the sign-compare group.
2855     // The conditional-checking code will 
2856     if (ICContext) {
2857       DiagID = diag::warn_impcast_integer_sign_conditional;
2858       *ICContext = true;
2859     }
2860
2861     return DiagnoseImpCast(S, E, T, CC, DiagID);
2862   }
2863
2864   return;
2865 }
2866
2867 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2868
2869 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2870                              SourceLocation CC, bool &ICContext) {
2871   E = E->IgnoreParenImpCasts();
2872
2873   if (isa<ConditionalOperator>(E))
2874     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2875
2876   AnalyzeImplicitConversions(S, E, CC);
2877   if (E->getType() != T)
2878     return CheckImplicitConversion(S, E, T, CC, &ICContext);
2879   return;
2880 }
2881
2882 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2883   SourceLocation CC = E->getQuestionLoc();
2884
2885   AnalyzeImplicitConversions(S, E->getCond(), CC);
2886
2887   bool Suspicious = false;
2888   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2889   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
2890
2891   // If -Wconversion would have warned about either of the candidates
2892   // for a signedness conversion to the context type...
2893   if (!Suspicious) return;
2894
2895   // ...but it's currently ignored...
2896   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2897                                  CC))
2898     return;
2899
2900   // ...and -Wsign-compare isn't...
2901   if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
2902     return;
2903
2904   // ...then check whether it would have warned about either of the
2905   // candidates for a signedness conversion to the condition type.
2906   if (E->getType() != T) {
2907     Suspicious = false;
2908     CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2909                             E->getType(), CC, &Suspicious);
2910     if (!Suspicious)
2911       CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2912                               E->getType(), CC, &Suspicious);
2913     if (!Suspicious)
2914       return;
2915   }
2916
2917   // If so, emit a diagnostic under -Wsign-compare.
2918   Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2919   Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2920   S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2921     << lex->getType() << rex->getType()
2922     << lex->getSourceRange() << rex->getSourceRange();
2923 }
2924
2925 /// AnalyzeImplicitConversions - Find and report any interesting
2926 /// implicit conversions in the given expression.  There are a couple
2927 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
2928 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
2929   QualType T = OrigE->getType();
2930   Expr *E = OrigE->IgnoreParenImpCasts();
2931
2932   // For conditional operators, we analyze the arguments as if they
2933   // were being fed directly into the output.
2934   if (isa<ConditionalOperator>(E)) {
2935     ConditionalOperator *CO = cast<ConditionalOperator>(E);
2936     CheckConditionalOperator(S, CO, T);
2937     return;
2938   }
2939
2940   // Go ahead and check any implicit conversions we might have skipped.
2941   // The non-canonical typecheck is just an optimization;
2942   // CheckImplicitConversion will filter out dead implicit conversions.
2943   if (E->getType() != T)
2944     CheckImplicitConversion(S, E, T, CC);
2945
2946   // Now continue drilling into this expression.
2947
2948   // Skip past explicit casts.
2949   if (isa<ExplicitCastExpr>(E)) {
2950     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2951     return AnalyzeImplicitConversions(S, E, CC);
2952   }
2953
2954   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2955     // Do a somewhat different check with comparison operators.
2956     if (BO->isComparisonOp())
2957       return AnalyzeComparison(S, BO);
2958
2959     // And with assignments and compound assignments.
2960     if (BO->isAssignmentOp())
2961       return AnalyzeAssignment(S, BO);
2962   }
2963
2964   // These break the otherwise-useful invariant below.  Fortunately,
2965   // we don't really need to recurse into them, because any internal
2966   // expressions should have been analyzed already when they were
2967   // built into statements.
2968   if (isa<StmtExpr>(E)) return;
2969
2970   // Don't descend into unevaluated contexts.
2971   if (isa<SizeOfAlignOfExpr>(E)) return;
2972
2973   // Now just recurse over the expression's children.
2974   CC = E->getExprLoc();
2975   for (Stmt::child_range I = E->children(); I; ++I)
2976     AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
2977 }
2978
2979 } // end anonymous namespace
2980
2981 /// Diagnoses "dangerous" implicit conversions within the given
2982 /// expression (which is a full expression).  Implements -Wconversion
2983 /// and -Wsign-compare.
2984 ///
2985 /// \param CC the "context" location of the implicit conversion, i.e.
2986 ///   the most location of the syntactic entity requiring the implicit
2987 ///   conversion
2988 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
2989   // Don't diagnose in unevaluated contexts.
2990   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2991     return;
2992
2993   // Don't diagnose for value- or type-dependent expressions.
2994   if (E->isTypeDependent() || E->isValueDependent())
2995     return;
2996
2997   // This is not the right CC for (e.g.) a variable initialization.
2998   AnalyzeImplicitConversions(*this, E, CC);
2999 }
3000
3001 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3002                                        FieldDecl *BitField,
3003                                        Expr *Init) {
3004   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3005 }
3006
3007 /// CheckParmsForFunctionDef - Check that the parameters of the given
3008 /// function are appropriate for the definition of a function. This
3009 /// takes care of any checks that cannot be performed on the
3010 /// declaration itself, e.g., that the types of each of the function
3011 /// parameters are complete.
3012 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3013                                     bool CheckParameterNames) {
3014   bool HasInvalidParm = false;
3015   for (; P != PEnd; ++P) {
3016     ParmVarDecl *Param = *P;
3017     
3018     // C99 6.7.5.3p4: the parameters in a parameter type list in a
3019     // function declarator that is part of a function definition of
3020     // that function shall not have incomplete type.
3021     //
3022     // This is also C++ [dcl.fct]p6.
3023     if (!Param->isInvalidDecl() &&
3024         RequireCompleteType(Param->getLocation(), Param->getType(),
3025                                diag::err_typecheck_decl_incomplete_type)) {
3026       Param->setInvalidDecl();
3027       HasInvalidParm = true;
3028     }
3029
3030     // C99 6.9.1p5: If the declarator includes a parameter type list, the
3031     // declaration of each parameter shall include an identifier.
3032     if (CheckParameterNames &&
3033         Param->getIdentifier() == 0 &&
3034         !Param->isImplicit() &&
3035         !getLangOptions().CPlusPlus)
3036       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3037
3038     // C99 6.7.5.3p12:
3039     //   If the function declarator is not part of a definition of that
3040     //   function, parameters may have incomplete type and may use the [*]
3041     //   notation in their sequences of declarator specifiers to specify
3042     //   variable length array types.
3043     QualType PType = Param->getOriginalType();
3044     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3045       if (AT->getSizeModifier() == ArrayType::Star) {
3046         // FIXME: This diagnosic should point the the '[*]' if source-location
3047         // information is added for it.
3048         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3049       }
3050     }
3051   }
3052
3053   return HasInvalidParm;
3054 }
3055
3056 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3057 /// pointer cast increases the alignment requirements.
3058 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3059   // This is actually a lot of work to potentially be doing on every
3060   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3061   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3062                                           TRange.getBegin())
3063         == Diagnostic::Ignored)
3064     return;
3065
3066   // Ignore dependent types.
3067   if (T->isDependentType() || Op->getType()->isDependentType())
3068     return;
3069
3070   // Require that the destination be a pointer type.
3071   const PointerType *DestPtr = T->getAs<PointerType>();
3072   if (!DestPtr) return;
3073
3074   // If the destination has alignment 1, we're done.
3075   QualType DestPointee = DestPtr->getPointeeType();
3076   if (DestPointee->isIncompleteType()) return;
3077   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3078   if (DestAlign.isOne()) return;
3079
3080   // Require that the source be a pointer type.
3081   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3082   if (!SrcPtr) return;
3083   QualType SrcPointee = SrcPtr->getPointeeType();
3084
3085   // Whitelist casts from cv void*.  We already implicitly
3086   // whitelisted casts to cv void*, since they have alignment 1.
3087   // Also whitelist casts involving incomplete types, which implicitly
3088   // includes 'void'.
3089   if (SrcPointee->isIncompleteType()) return;
3090
3091   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3092   if (SrcAlign >= DestAlign) return;
3093
3094   Diag(TRange.getBegin(), diag::warn_cast_align)
3095     << Op->getType() << T
3096     << static_cast<unsigned>(SrcAlign.getQuantity())
3097     << static_cast<unsigned>(DestAlign.getQuantity())
3098     << TRange << Op->getSourceRange();
3099 }
3100
3101 void Sema::CheckArrayAccess(const clang::ArraySubscriptExpr *E) {
3102   const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
3103   const ConstantArrayType *ArrayTy =
3104     Context.getAsConstantArrayType(BaseExpr->getType());
3105   if (!ArrayTy)
3106     return;
3107
3108   const Expr *IndexExpr = E->getIdx();
3109   if (IndexExpr->isValueDependent())
3110     return;
3111   llvm::APSInt index;
3112   if (!IndexExpr->isIntegerConstantExpr(index, Context))
3113     return;
3114
3115   if (!index.isNegative()) {
3116     llvm::APInt size = ArrayTy->getSize();
3117     if (!size.isStrictlyPositive())
3118       return;
3119     if (size.getBitWidth() > index.getBitWidth())
3120       index = index.sext(size.getBitWidth());
3121     else if (size.getBitWidth() < index.getBitWidth())
3122       size = size.sext(index.getBitWidth());
3123
3124     if (index.slt(size))
3125       return;
3126
3127     Diag(E->getBase()->getLocStart(), diag::warn_array_index_exceeds_bounds)
3128       << index.toString(10, true) << size.toString(10, true)
3129       << IndexExpr->getSourceRange();
3130   } else {
3131     Diag(E->getBase()->getLocStart(), diag::warn_array_index_precedes_bounds)
3132       << index.toString(10, true) << IndexExpr->getSourceRange();
3133   }
3134
3135   const NamedDecl *ND = NULL;
3136   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3137     ND = dyn_cast<NamedDecl>(DRE->getDecl());
3138   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3139     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3140   if (ND)
3141     Diag(ND->getLocStart(), diag::note_array_index_out_of_bounds)
3142       << ND->getDeclName();
3143 }
3144