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